From b2e0662d78f5afc3188c681cb4e0707c4f416fea Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:46:04 -0700 Subject: [PATCH 0001/1441] fix(provider): take a child's exit from its termination handler, not waitUntilExit Process.waitUntilExit() runs the calling thread's run loop in 62.5 ms slices. Once the child is reaped it keeps doing so until a block that Foundation queued on the starting thread's run loop has run, whenever it takes the caller for the starting thread. It decides that from a per-thread list of task addresses that is never pruned. Seven provider sites waited that way. Each starts and waits on one thread, so none could hang; the hang needs a second thread that once started a Process at the same address (103 of 300 sessions lost in a standalone probe on macOS 27.2). What they paid was time. BoundedProcess polled isRunning every 50 ms and then called waitUntilExit() on a child that was already gone: 121 to 125 ms for a child that exits at once, on every call, with the caller's run loop serviced meanwhile. Update staging runs five such children on the ProviderLoop actor while the provider serves. The six unbounded sites serviced the run loop on every call and lost a slice in about 0.6% of them. ProcessExitObserver installs terminationHandler before the launch and latches the report, so an exit that precedes the first wait is kept and later waits return. BoundedProcess waits on it with the same three deadlines; a child reaped as a deadline passes counts as exited, so SIGTERM and SIGKILL still go only to a running process. The six unbounded sites gain no timeout. No signal is added or moved. Tests: a run-loop probe shows BoundedProcess and LaunchctlControl no longer service their caller's run loop, and the fastest of ten bounded runs must beat the 62.5 ms slice. Two tests pin the unchanged SIGTERM and SIGKILL escalation. The observer has its own suite, including 60 sessions started on one dispatch thread and waited for on another. open, codesign, profiles and log cannot be run from a test, so a source check keeps waitUntilExit() out of provider sources. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + .../ProviderCore/Auth/Enrollment.swift | 5 +- .../ProviderCore/Process/BoundedProcess.swift | 26 ++-- .../Process/ProcessExitObserver.swift | 70 +++++++++++ .../Security/DarkbloomMDMRemoval.swift | 5 +- .../Security/SecurityHardening.swift | 5 +- .../Service/LaunchctlControl.swift | 5 +- .../Sources/darkbloom/LogsCommand.swift | 5 +- .../Sources/darkbloom/ReportCommand.swift | 5 +- .../Helpers/RunLoopServiceProbe.swift | 24 ++++ .../Process/BoundedProcessTests.swift | 80 +++++++++++++ .../ChildExitWaitConventionTests.swift | 39 ++++++ .../Process/ProcessExitObserverTests.swift | 111 ++++++++++++++++++ .../Service/LaunchctlControlTests.swift | 27 +++++ 14 files changed, 385 insertions(+), 26 deletions(-) create mode 100644 provider-swift/Sources/ProviderCore/Process/ProcessExitObserver.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Helpers/RunLoopServiceProbe.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Process/BoundedProcessTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Process/ChildExitWaitConventionTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Process/ProcessExitObserverTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Service/LaunchctlControlTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e8611f769..f1a5f187cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased — child process exit waits + +- Report a finished child process without the former polling and run-loop delay. Bounded children (the paged-kernel preflight, update staging, runtime smoke and signature checks, `darkbloom doctor` and `verify` probes) are reported up to about 120 ms sooner each, and waiting for `launchctl`, `codesign`, `profiles`, `open` and `log` no longer runs the calling thread's run loop. Timeouts and the SIGTERM-then-SIGKILL escalation are unchanged. + ## Unreleased — provider cache storage controls - Add `darkbloom cache set --daily-write-gb ... --directory ...` and `cache status` for persistent write limits and optional external cache storage. Validate local APFS storage, require encryption for external volumes, pin the volume UUID and refuse unavailable or replaced disks without falling back. Keep encryption keys and the rolling-day write ledger on the Mac; switching disks does not reset usage. Changes apply after restart. diff --git a/provider-swift/Sources/ProviderCore/Auth/Enrollment.swift b/provider-swift/Sources/ProviderCore/Auth/Enrollment.swift index 72b6fd990c..72bed16804 100644 --- a/provider-swift/Sources/ProviderCore/Auth/Enrollment.swift +++ b/provider-swift/Sources/ProviderCore/Auth/Enrollment.swift @@ -235,8 +235,9 @@ public struct EnrollmentService: Sendable { process.arguments = arguments process.standardOutput = FileHandle.nullDevice process.standardError = FileHandle.nullDevice - try process.run() - process.waitUntilExit() + let childExit = ProcessExitObserver() + try childExit.run(process) + childExit.wait() return process.terminationStatus } } diff --git a/provider-swift/Sources/ProviderCore/Process/BoundedProcess.swift b/provider-swift/Sources/ProviderCore/Process/BoundedProcess.swift index 5ca07c1685..ffb34a851e 100644 --- a/provider-swift/Sources/ProviderCore/Process/BoundedProcess.swift +++ b/provider-swift/Sources/ProviderCore/Process/BoundedProcess.swift @@ -124,7 +124,7 @@ public enum BoundedProcess { } else { process.standardError = FileHandle.nullDevice } - // Drain to EOF before anyone reads the tail. `waitUntilExit()` says + // Drain to EOF before anyone reads the tail. A reported exit says // the CHILD is gone, not that the readability handler has consumed // the pipe -- a child that writes a short diagnostic and exits fast // can be reaped before its bytes are delivered, and then the tail @@ -136,20 +136,19 @@ public enum BoundedProcess { stderrPipe?.fileHandleForReading.readabilityHandler = nil try? stderrPipe?.fileHandleForReading.close() } - try process.run() + let childExit = ProcessExitObserver() + try childExit.run(process) - guard waitForExit(process, timeout: timeout) else { + guard waitForExit(process, reportedBy: childExit, timeout: timeout) else { process.terminate() - if !waitForExit(process, timeout: 2) { + if !waitForExit(process, reportedBy: childExit, timeout: 2) { forceKill(process) - guard waitForExit(process, timeout: 2) else { + guard waitForExit(process, reportedBy: childExit, timeout: 2) else { throw Failure.wouldNotTerminate } } - process.waitUntilExit() throw Failure.timedOut(seconds: timeout) } - process.waitUntilExit() guard requireSuccessfulExit else { return } guard process.terminationReason == .exit else { @@ -162,17 +161,16 @@ public enum BoundedProcess { } } + /// Waits up to `timeout` seconds for the exit report; true means the child + /// has exited. A child that is reaped as the deadline passes counts as + /// exited even if its report is still in flight, so a signal is only ever + /// sent to a process that is running. private static func waitForExit( _ process: Process, + reportedBy childExit: ProcessExitObserver, timeout: TimeInterval ) -> Bool { - let deadline = ProcessInfo.processInfo.systemUptime + max(0, timeout) - while process.isRunning, - ProcessInfo.processInfo.systemUptime < deadline - { - Thread.sleep(forTimeInterval: 0.05) - } - return !process.isRunning + childExit.wait(timeout: timeout) || !process.isRunning } private static func forceKill(_ process: Process) { diff --git a/provider-swift/Sources/ProviderCore/Process/ProcessExitObserver.swift b/provider-swift/Sources/ProviderCore/Process/ProcessExitObserver.swift new file mode 100644 index 0000000000..f48530ab20 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Process/ProcessExitObserver.swift @@ -0,0 +1,70 @@ +import Foundation + +/// Observes the exit of a Foundation `Process` without a run loop. +/// +/// `Process.waitUntilExit()` runs the calling thread's run loop in 62.5 ms +/// slices. Once the child is reaped it keeps doing so until a block that +/// Foundation queued on the run loop of the thread that called `run()` has +/// executed, whenever it believes the caller is that thread. Measured on +/// macOS 27.2: +/// +/// - Same thread starts and waits, child already gone: one whole slice is +/// spent first, about 66 ms, on every call. +/// - Another thread waits: the exit is noticed only at a slice boundary. If +/// that thread once started a `Process` whose address the current one +/// reuses, Foundation takes it for the starting thread and waits for a +/// block only the real starting thread's run loop can execute. On a +/// dispatch or cooperative thread nobody runs that loop, so the call never +/// returns. +/// +/// Foundation calls `terminationHandler` from its own exit source with no run +/// loop involved, so this latch is released by that alone. +/// +/// Once released the latch stays released: an exit that precedes the first +/// wait is kept, and every later wait returns at once. +public final class ProcessExitObserver: @unchecked Sendable { + /// Thrown by a second `run(_:)`: one observer reports one child. + public struct AlreadyStarted: Error {} + + private enum Phase { case unstarted, awaitingExit, settled } + + private let observed = DispatchGroup() + private let lock = NSLock() + private var phase = Phase.unstarted + + public init() {} + + /// Installs the exit handler and then starts `process`; use it in place of + /// `process.run()`. The handler has to be in place before the launch, or a + /// child that exits at once would never be reported; it replaces any + /// `terminationHandler` already set. A launch that throws settles the + /// latch, because no exit will ever follow it. + public func run(_ process: Process) throws { + try lock.withLock { + guard phase == .unstarted else { throw AlreadyStarted() } + phase = .awaitingExit + observed.enter() + } + process.terminationHandler = { [self] _ in settle() } + do { try process.run() } catch { settle(); throw error } + } + + /// Blocks until Foundation has reported the exit; `terminationStatus` and + /// `terminationReason` are valid from then on. Returns at once if it + /// already was, if the launch threw, or if nothing was ever started. + public func wait() { observed.wait() } + + /// As `wait()`, but gives up after `timeout` seconds; false means not yet + /// reported. + public func wait(timeout: TimeInterval) -> Bool { + observed.wait(timeout: .now() + max(0, timeout)) == .success + } + + private func settle() { + lock.withLock { + guard phase == .awaitingExit else { return } + phase = .settled + observed.leave() + } + } +} diff --git a/provider-swift/Sources/ProviderCore/Security/DarkbloomMDMRemoval.swift b/provider-swift/Sources/ProviderCore/Security/DarkbloomMDMRemoval.swift index bb72d96132..7a5d29045d 100644 --- a/provider-swift/Sources/ProviderCore/Security/DarkbloomMDMRemoval.swift +++ b/provider-swift/Sources/ProviderCore/Security/DarkbloomMDMRemoval.swift @@ -99,9 +99,10 @@ public enum DarkbloomMDMRemoval { let output = Pipe() process.standardOutput = output process.standardError = showErrors ? FileHandle.standardError : FileHandle.nullDevice - do { try process.run() } catch { return nil } + let childExit = ProcessExitObserver() + do { try childExit.run(process) } catch { return nil } let data = output.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() + childExit.wait() guard process.terminationStatus == 0 else { return nil } return data } diff --git a/provider-swift/Sources/ProviderCore/Security/SecurityHardening.swift b/provider-swift/Sources/ProviderCore/Security/SecurityHardening.swift index bba1f4d6a7..dbeb3f2e6d 100644 --- a/provider-swift/Sources/ProviderCore/Security/SecurityHardening.swift +++ b/provider-swift/Sources/ProviderCore/Security/SecurityHardening.swift @@ -229,15 +229,16 @@ public func verifyBundleSignature() throws { process.standardOutput = FileHandle.nullDevice process.standardError = errPipe + let childExit = ProcessExitObserver() do { - try process.run() + try childExit.run(process) } catch { logger.warning("Could not verify bundle signature: \(error)") return // Don't fail if codesign isn't available } // Drain the captured stream before waiting; stdout is deliberately discarded. let data = errPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() + childExit.wait() if process.terminationStatus == 0 { logger.info("App bundle signature valid") diff --git a/provider-swift/Sources/ProviderCore/Service/LaunchctlControl.swift b/provider-swift/Sources/ProviderCore/Service/LaunchctlControl.swift index 412a67f549..8f0781748d 100644 --- a/provider-swift/Sources/ProviderCore/Service/LaunchctlControl.swift +++ b/provider-swift/Sources/ProviderCore/Service/LaunchctlControl.swift @@ -65,10 +65,11 @@ enum LaunchctlControl { process.standardError = errPipe ?? FileHandle.nullDevice process.standardInput = FileHandle.nullDevice - try process.run() + let childExit = ProcessExitObserver() + try childExit.run(process) let outData = outPipe?.fileHandleForReading.readDataToEndOfFile() ?? Data() let errData = errPipe?.fileHandleForReading.readDataToEndOfFile() ?? Data() - process.waitUntilExit() + childExit.wait() return Output( status: process.terminationStatus, stdout: String(data: outData, encoding: .utf8) ?? "", diff --git a/provider-swift/Sources/darkbloom/LogsCommand.swift b/provider-swift/Sources/darkbloom/LogsCommand.swift index 17c9be9887..cf1f6297fa 100644 --- a/provider-swift/Sources/darkbloom/LogsCommand.swift +++ b/provider-swift/Sources/darkbloom/LogsCommand.swift @@ -126,13 +126,14 @@ struct Logs: AsyncParsableCommand { process.standardError = FileHandle.standardError process.standardInput = FileHandle.standardInput + let childExit = ProcessExitObserver() do { - try process.run() + try childExit.run(process) } catch { printError("failed to run log: \(error.localizedDescription)") throw ExitCode.failure } - process.waitUntilExit() + childExit.wait() // Mirror `--last` alone: if the historical `log show` failed (e.g. a // malformed duration), surface its exit status instead of silently diff --git a/provider-swift/Sources/darkbloom/ReportCommand.swift b/provider-swift/Sources/darkbloom/ReportCommand.swift index da7d317d9c..75e739e848 100644 --- a/provider-swift/Sources/darkbloom/ReportCommand.swift +++ b/provider-swift/Sources/darkbloom/ReportCommand.swift @@ -184,7 +184,8 @@ struct Report: AsyncParsableCommand { process.standardOutput = pipe process.standardError = errors - try process.run() + let childExit = ProcessExitObserver() + try childExit.run(process) // Drain stderr concurrently so a chatty failure cannot block stdout. let errorText = LockedText() let drained = DispatchSemaphore(value: 0) @@ -193,7 +194,7 @@ struct Report: AsyncParsableCommand { drained.signal() } let data = pipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() + childExit.wait() drained.wait() if DeviceCheckEvidence.isAccessDenied(status: process.terminationStatus, stderr: errorText.value) { diff --git a/provider-swift/Tests/ProviderCoreTests/Helpers/RunLoopServiceProbe.swift b/provider-swift/Tests/ProviderCoreTests/Helpers/RunLoopServiceProbe.swift new file mode 100644 index 0000000000..f60809d5d5 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Helpers/RunLoopServiceProbe.swift @@ -0,0 +1,24 @@ +import Foundation + +/// A timer that is due at once on the run loop of the thread that creates it. +/// It fires only if something runs that run loop, which is how a test sees +/// whether a synchronous call serviced its caller's run loop. +final class RunLoopServiceProbe: @unchecked Sendable { + private let lock = NSLock() + private var fired = false + private var timer: CFRunLoopTimer? + + init() { + let timer = CFRunLoopTimerCreateWithHandler(nil, CFAbsoluteTimeGetCurrent(), 0, 0, 0) { [self] _ in + lock.withLock { fired = true } + } + CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, .defaultMode) + self.timer = timer + } + + var runLoopWasServiced: Bool { lock.withLock { fired } } + + func cancel() { + if let timer { CFRunLoopTimerInvalidate(timer) } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Process/BoundedProcessTests.swift b/provider-swift/Tests/ProviderCoreTests/Process/BoundedProcessTests.swift new file mode 100644 index 0000000000..3dca3e82d1 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Process/BoundedProcessTests.swift @@ -0,0 +1,80 @@ +import Foundation +import Testing +@testable import ProviderCore + +@Suite("Bounded child process") +struct BoundedProcessTests { + private let exitsAtOnce = URL(fileURLWithPath: "/usr/bin/true") + + /// `Process.waitUntilExit()` runs the calling thread's run loop for at + /// least one 62.5 ms slice once the child is gone. Anything scheduled on + /// that run loop then fires inside the call, and the call returns late. + @Test("Waiting for a child does not run the calling thread's run loop") + func callersRunLoopIsLeftAlone() throws { + let probe = RunLoopServiceProbe() + defer { probe.cancel() } + + try BoundedProcess.run(exitsAtOnce, arguments: [], timeout: 10) + + #expect(!probe.runLoopWasServiced) + } + + /// Polling `isRunning` every 50 ms and then calling `waitUntilExit()` took + /// about 120 ms to report an exited child, and never less than the 62.5 ms + /// run-loop slice. Taking the fastest of several runs keeps a busy + /// machine from failing this. + @Test("A child that has exited is reported without a polling or run-loop delay") + func exitedChildIsReportedPromptly() { + let fastest = (0..<10).map { _ in + outcome(of: { try BoundedProcess.run(exitsAtOnce, arguments: [], timeout: 10) }).seconds + }.min() ?? .infinity + #expect(fastest < 0.06) + } + + @Test("A child that outlives its timeout is sent SIGTERM and reported as timed out") + func timeoutSendsSIGTERM() { + let run = outcome(of: { + try BoundedProcess.run(URL(fileURLWithPath: "/bin/sleep"), arguments: ["30"], timeout: 0.3) + }) + #expect(run.timeoutLimit == 0.3) + // SIGTERM ended it, so the two-second wait before SIGKILL never ran out. + #expect(run.seconds >= 0.3 && run.seconds < 2) + } + + @Test("A child that ignores SIGTERM gets it once and SIGKILL two seconds later") + func ignoredSIGTERMEscalatesToSIGKILL() throws { + let received = FileManager.default.temporaryDirectory + .appendingPathComponent("darkbloom-bounded-process-\(UUID().uuidString).signals") + defer { try? FileManager.default.removeItem(at: received) } + // `$0` is the file the shell appends to each time SIGTERM arrives. + let script = "trap 'echo TERM >> \"$0\"' TERM; while :; do /bin/sleep 0.05; done" + + // One second lets a slow machine start the shell and set the trap first. + let run = outcome(of: { + try BoundedProcess.run( + URL(fileURLWithPath: "/bin/sh"), arguments: ["-c", script, received.path], timeout: 1) + }) + + #expect(run.timeoutLimit == 1) + #expect(run.seconds >= 3 && run.seconds < 5) + #expect(try String(contentsOf: received, encoding: .utf8) == "TERM\n") + } + + private struct Outcome { + var failure: (any Error)? + var seconds: TimeInterval + + /// The limit carried by a `.timedOut` failure; nil for anything else. + var timeoutLimit: TimeInterval? { + guard case .timedOut(let limit)? = failure as? BoundedProcess.Failure else { return nil } + return limit + } + } + + private func outcome(of body: () throws -> Void) -> Outcome { + let started = ProcessInfo.processInfo.systemUptime + var failure: (any Error)? + do { try body() } catch { failure = error } + return Outcome(failure: failure, seconds: ProcessInfo.processInfo.systemUptime - started) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Process/ChildExitWaitConventionTests.swift b/provider-swift/Tests/ProviderCoreTests/Process/ChildExitWaitConventionTests.swift new file mode 100644 index 0000000000..4bd0593e1e --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Process/ChildExitWaitConventionTests.swift @@ -0,0 +1,39 @@ +import Foundation +import Testing + +/// Provider code waits for a child through its termination handler, with +/// `ProcessExitObserver`, never with `Process.waitUntilExit()`. Several of the +/// places that start a child (`open`, `codesign`, `profiles`, `log`) cannot be +/// run from a test, so this reads the sources instead. +@Suite("Child exit wait convention") +struct ChildExitWaitConventionTests { + @Test("No provider source waits with Process.waitUntilExit()") + func sourcesDoNotCallWaitUntilExit() throws { + let sources = try providerPackageRoot().appendingPathComponent("Sources") + let paths = try #require(FileManager.default.enumerator(atPath: sources.path)) + var calls: [String] = [] + for case let path as String in paths where path.hasSuffix(".swift") { + let source = try String(contentsOf: sources.appendingPathComponent(path), encoding: .utf8) + for (index, line) in source.split(separator: "\n", omittingEmptySubsequences: false).enumerated() { + let code = line.trimmingCharacters(in: .whitespaces) + if code.contains(".waitUntilExit(") && !code.hasPrefix("//") { + calls.append("\(path):\(index + 1)") + } + } + } + #expect(calls.isEmpty, "use ProcessExitObserver instead of waitUntilExit() in: \(calls.sorted().joined(separator: ", "))") + } + + private func providerPackageRoot() throws -> URL { + var root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + while root != root.deletingLastPathComponent() { + if FileManager.default.fileExists(atPath: root.appendingPathComponent("Package.swift").path) { + return root + } + root.deleteLastPathComponent() + } + throw PackageLocationError.packageRootNotFound + } + + private enum PackageLocationError: Error { case packageRootNotFound } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Process/ProcessExitObserverTests.swift b/provider-swift/Tests/ProviderCoreTests/Process/ProcessExitObserverTests.swift new file mode 100644 index 0000000000..db9ac4a7ac --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Process/ProcessExitObserverTests.swift @@ -0,0 +1,111 @@ +import Foundation +import Testing +@testable import ProviderCore + +@Suite("Child process exit observation") +struct ProcessExitObserverTests { + @Test("An exit that precedes the first wait is kept, and every later wait returns") + func exitBeforeTheFirstWaitIsKept() throws { + let process = child("/usr/bin/true") + let childExit = ProcessExitObserver() + try childExit.run(process) + while process.isRunning { usleep(1_000) } + + #expect(childExit.wait(timeout: 5)) + childExit.wait() + #expect(childExit.wait(timeout: 0)) + #expect(process.terminationStatus == 0) + } + + @Test("A timed wait reports a running child as not exited, then its exit") + func timedWaitFollowsTheChild() throws { + let process = child("/bin/sleep", "30") + let childExit = ProcessExitObserver() + try childExit.run(process) + + #expect(!childExit.wait(timeout: 0.05)) + process.terminate() + #expect(childExit.wait(timeout: 5)) + #expect(process.terminationReason == .uncaughtSignal) + } + + @Test("A launch that fails leaves nothing to wait for") + func failedLaunchSettles() { + let childExit = ProcessExitObserver() + #expect(throws: (any Error).self) { + try childExit.run(child("/nonexistent/darkbloom-test-command")) + } + #expect(childExit.wait(timeout: 0)) + } + + @Test("One observer reports one child") + func secondStartIsRefused() throws { + let childExit = ProcessExitObserver() + try childExit.run(child("/usr/bin/true")) + #expect(throws: ProcessExitObserver.AlreadyStarted.self) { + try childExit.run(child("/usr/bin/true")) + } + #expect(childExit.wait(timeout: 5)) + } + + /// One thread starts the child, another reads its output to the end and + /// then waits for the exit, session after session on recycled dispatch + /// threads. This is the shape in which `Process.waitUntilExit()` never + /// returns: measured on macOS 27.2, 103 of 300 such sessions were lost + /// when the waiting thread called it. The share depends on which earlier + /// `Process` addresses the waiting thread happens to hold, so one session + /// proves nothing; this many do. + @Test("An exit is reported in every session when another thread waits") + func exitIsReportedToAnotherThreadInEverySession() throws { + let sessions = 60 + for number in 1...sessions { + let session = CrossThreadSession(child("/bin/sleep", "0.02")) + session.run() + try session.launch?.get() + // Stop at the first loss: each one waits out the whole five seconds. + try #require(session.exitReported, "Session \(number) of \(sessions): exit not reported within 5 s") + } + } + + private func child(_ path: String, _ arguments: String...) -> Process { + let process = Process() + process.executableURL = URL(fileURLWithPath: path) + process.arguments = arguments + process.standardInput = FileHandle.nullDevice + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + return process + } +} + +/// One child started on one dispatch thread and waited for on another. Both +/// results are written before `finished` is signalled and read only after +/// `run()` has returned, which is what makes the unlocked state safe. +private final class CrossThreadSession: @unchecked Sendable { + private let process: Process + private let output = Pipe() + private let childExit = ProcessExitObserver() + private let finished = DispatchSemaphore(value: 0) + private(set) var launch: Result? + private(set) var exitReported = false + + init(_ process: Process) { + self.process = process + process.standardOutput = output + } + + func run() { + DispatchQueue(label: "process-exit-observer-tests.start").async { [self] in + launch = Result { try childExit.run(process) } + try? output.fileHandleForWriting.close() + DispatchQueue(label: "process-exit-observer-tests.wait").async { [self] in + _ = output.fileHandleForReading.readDataToEndOfFile() + exitReported = childExit.wait(timeout: 5) + finished.signal() + } + // The starting thread stays busy, so the waiter gets another. + usleep(5_000) + } + finished.wait() + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Service/LaunchctlControlTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/LaunchctlControlTests.swift new file mode 100644 index 0000000000..4c99726762 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Service/LaunchctlControlTests.swift @@ -0,0 +1,27 @@ +import Foundation +import Testing +@testable import ProviderCore + +/// The real spawn path of `LaunchctlControl`. `launchctl help` prints its +/// usage and exits; it reads and changes no launchd state. +@Suite("launchctl invocation") +struct LaunchctlControlTests { + @Test("Output and exit status of a real launchctl run are returned") + func capturesOutputAndStatus() throws { + let help = try LaunchctlControl.runThrowing(["help"], captureStdout: true) + #expect(help.succeeded) + #expect(help.stdout.contains("bootstrap")) + } + + /// `Process.waitUntilExit()` runs the calling thread's run loop even when, + /// as here, the child's output has already been read to its end. + @Test("Waiting for launchctl does not run the calling thread's run loop") + func callersRunLoopIsLeftAlone() throws { + let probe = RunLoopServiceProbe() + defer { probe.cancel() } + + _ = try LaunchctlControl.runThrowing(["help"], captureStdout: true) + + #expect(!probe.runLoopWasServiced) + } +} From 518a9b62cd1e4eeb673b05d9c1e28fc6f0180da8 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Fri, 9 Oct 2026 14:57:56 -0700 Subject: [PATCH 0002/1441] fix(provider): keep status on an unexpired App Attest lease `darkbloom status` and `darkbloom doctor` showed App Attest authorization only when the coordinator's latest lease renewal was at most 10 s old. Renewals arrive every few seconds, so a late one switched the output to legacy `Trust: self_signed / online` while the lease was still valid. Keep displaying an unexpired App Attest lease; MDM removal in `darkbloom unenroll` still requires a renewal inside 10 s. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + docs/reference/provider-authorization.md | 4 +- .../ProviderAuthorizationReadiness.swift | 76 +++++++++++++++++-- .../darkbloom/Diagnostics/DoctorRunner.swift | 2 +- .../Sources/darkbloom/DoctorCommand.swift | 2 +- .../Sources/darkbloom/StatusCommand.swift | 2 +- .../StatusCommandRunTests.swift | 24 ++++++ .../ProviderAuthorizationReadinessTests.swift | 35 +++++++++ 8 files changed, 137 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f505e3365..25b4e5ac8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased — provider status App Attest lease + +- Keep `darkbloom status` and `darkbloom doctor` reporting App Attest authorization until the coordinator lease expires. They required a renewal within the last 10 seconds, so one delayed renewal showed `Trust: self_signed / online` although serving continued. `darkbloom unenroll` still requires a renewal within 10 seconds before offering MDM removal. + ## Unreleased — provider build environment - A dev provider release now defaults to the dev coordinator `wss://api.dev.darkbloom.dev/ws/provider`. It does not fall back to the production coordinator. Dev and prod builds read models from `https://models.darkbloom.ai`. Local builds, tests and production releases keep the production defaults. `provider.toml`, CLI flags and `DARKBLOOM_R2_CDN_URL` still override the defaults. diff --git a/docs/reference/provider-authorization.md b/docs/reference/provider-authorization.md index 5ebf139b24..6e33365802 100644 --- a/docs/reference/provider-authorization.md +++ b/docs/reference/provider-authorization.md @@ -1,6 +1,6 @@ # Provider serving authorization -> Last updated: 2026-10-04 +> Last updated: 2026-10-09 The coordinator can authorize private inference through complete legacy verification or a qualified App Attest connection. These are separate evidence paths; App Attest never sets legacy MDA/APNs flags. The [rollout runbook](../operations/mdm-optional-rollout.md) separates code availability from activation qualification. @@ -82,6 +82,8 @@ The additive `trust_status.authorization` object is coordinator-to-provider only `darkbloom status` and `darkbloom doctor` distinguish App Attest authorization from legacy verification. `darkbloom unenroll` offers full exit or App Attest migration. The migration option and direct `--keep-serving` shortcut require macOS 27 or later and a fresh running-provider snapshot, matching coordinator and process identity, and an unexpired removal-ready authorization. Both the state-file write and receipt of the coordinator decision must be at most `snapshotMaxAge = 10` seconds old (`provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift`, `currentStatus`); periodic local writes cannot refresh an old removal decision. It preserves account/config/key data and opens System Settings only after identifying the exact Darkbloom enrollment. It never removes a company profile or the app's embedded signing profile. Full exit stops the provider service before offering profile removal and optional cleanup. Enter/EOF cancels; noninteractive use requires an explicit mode flag. Code: `provider-swift/Sources/darkbloom/UnenrollCommand+KeepServing.swift` and `provider-swift/Sources/ProviderCore/Security/DarkbloomMDMRemoval.swift`. +`darkbloom status` and `darkbloom doctor` apply the same snapshot, process, coordinator, `online` and protocol checks, but keep showing an App Attest authorization until its `expires_at` when the latest renewal arrived more than `snapshotMaxAge` ago (`provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift`, `displayedStatus`). The coordinator sends a renewal after each successful `authorization.RefreshInterval` refresh and bounds the lease by `RevocationFreshness = 30 * time.Second` (`coordinator/internal/appattest/authorization/controller.go`), so one delayed renewal does not end the grant. `none` and `legacy` decisions still need a renewal inside `snapshotMaxAge`. + ## Owner dashboard and upgrade guidance The setup page prominently explains macOS 27 and planned MDM deactivation. diff --git a/provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift b/provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift index 276e89ff5e..72fb4a872a 100644 --- a/provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift +++ b/provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift @@ -5,17 +5,52 @@ import Foundation public enum ProviderAuthorizationReadiness { public static let snapshotMaxAge: Double = 10 + /// Removal guidance: the coordinator decision itself must be fresh, so a + /// delayed revocation cannot be hidden behind a lease that has time left. public static func currentStatus( _ authorization: ProviderAuthorizationStatus?, status: String?, writtenAt: Double, receivedAt: Double, startedAt: Double, now: Double, processMatches: Bool, coordinatorMatches: Bool + ) -> ProviderAuthorizationStatus? { + guard let live = liveDecision(authorization, status: status, writtenAt: writtenAt, + receivedAt: receivedAt, startedAt: startedAt, now: now, + processMatches: processMatches, coordinatorMatches: coordinatorMatches), + now - receivedAt <= snapshotMaxAge + else { return nil } + return live + } + + /// Status and doctor: an unexpired App Attest lease is still the + /// coordinator's grant when its latest renewal arrived more than + /// `snapshotMaxAge` ago, so one delayed renewal does not show legacy trust. + /// Other decisions keep the renewal window. + public static func displayedStatus( + _ authorization: ProviderAuthorizationStatus?, + status: String?, writtenAt: Double, receivedAt: Double, + startedAt: Double, now: Double, processMatches: Bool, + coordinatorMatches: Bool + ) -> ProviderAuthorizationStatus? { + guard let live = liveDecision(authorization, status: status, writtenAt: writtenAt, + receivedAt: receivedAt, startedAt: startedAt, now: now, + processMatches: processMatches, coordinatorMatches: coordinatorMatches), + now - receivedAt <= snapshotMaxAge || live.hasCurrentAppAttestAuthorization(now: now) + else { return nil } + return live + } + + /// The latest decision this live process received from the expected + /// coordinator, written by a daemon that is still updating its snapshot. + private static func liveDecision( + _ authorization: ProviderAuthorizationStatus?, + status: String?, writtenAt: Double, receivedAt: Double, + startedAt: Double, now: Double, processMatches: Bool, + coordinatorMatches: Bool ) -> ProviderAuthorizationStatus? { guard processMatches, coordinatorMatches, now.isFinite, writtenAt.isFinite, receivedAt.isFinite, startedAt.isFinite, writtenAt <= now + 2, now - writtenAt <= snapshotMaxAge, receivedAt >= startedAt, receivedAt <= now + 2, - now - receivedAt <= snapshotMaxAge, status == "online", let authorization, authorization.protocolVersion == 1 else { return nil } @@ -64,16 +99,41 @@ extension DaemonState { now: Double = Date().timeIntervalSince1970, readProcessIdentity: (Int32) -> ProcessIdentity? = ProcessIdentity.read ) -> ProviderAuthorizationStatus? { - let processMatches = processIdentity.map { - $0.pid == pid && readProcessIdentity(pid) == $0 - } ?? false - let coordinatorMatches = coordinatorUrl.map { - coordinatorHTTPBase($0) == coordinatorHTTPBase(expectedCoordinator) - } ?? false + let matches = snapshotMatches(coordinatorURL: expectedCoordinator, readProcessIdentity: readProcessIdentity) return ProviderAuthorizationReadiness.currentStatus( trust?.authorization, status: trust?.status, writtenAt: writtenAt, receivedAt: trust?.receivedAt ?? 0, startedAt: startedAt, now: now, - processMatches: processMatches, coordinatorMatches: coordinatorMatches) + processMatches: matches.process, coordinatorMatches: matches.coordinator) + } + + /// For `status` and `doctor` output; removal decisions use + /// `currentProviderAuthorization`. + public func displayedProviderAuthorization( + coordinatorURL expectedCoordinator: String, + now: Double = Date().timeIntervalSince1970, + readProcessIdentity: (Int32) -> ProcessIdentity? = ProcessIdentity.read + ) -> ProviderAuthorizationStatus? { + let matches = snapshotMatches(coordinatorURL: expectedCoordinator, readProcessIdentity: readProcessIdentity) + return ProviderAuthorizationReadiness.displayedStatus( + trust?.authorization, status: trust?.status, + writtenAt: writtenAt, receivedAt: trust?.receivedAt ?? 0, + startedAt: startedAt, now: now, + processMatches: matches.process, coordinatorMatches: matches.coordinator) + } + + /// Whether this snapshot was written by the still-running daemon process + /// and describes a connection to the expected coordinator. + private func snapshotMatches( + coordinatorURL expectedCoordinator: String, + readProcessIdentity: (Int32) -> ProcessIdentity? + ) -> (process: Bool, coordinator: Bool) { + let process = processIdentity.map { + $0.pid == pid && readProcessIdentity(pid) == $0 + } ?? false + let coordinator = coordinatorUrl.map { + coordinatorHTTPBase($0) == coordinatorHTTPBase(expectedCoordinator) + } ?? false + return (process, coordinator) } } diff --git a/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift b/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift index 78c264aad6..7c5aab913d 100644 --- a/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift +++ b/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift @@ -17,7 +17,7 @@ enum DoctorRunner { // "Fresh" = the daemon is running AND its state snapshot isn't stale, so // its live fields (trust level, current model, capacity) are trustworthy. let stateFresh = daemonUp && !(state?.isStale(now: now) ?? true) - let authorization = state?.currentProviderAuthorization(coordinatorURL: coordinatorURL, now: now) + let authorization = state?.displayedProviderAuthorization(coordinatorURL: coordinatorURL, now: now) let appAttestAuthorized = authorization?.hasCurrentAppAttestAuthorization(now: now) == true // ---- Attestation key (read-only daemon state) ---- diff --git a/provider-swift/Sources/darkbloom/DoctorCommand.swift b/provider-swift/Sources/darkbloom/DoctorCommand.swift index 8d69587e17..16b4b4b25c 100644 --- a/provider-swift/Sources/darkbloom/DoctorCommand.swift +++ b/provider-swift/Sources/darkbloom/DoctorCommand.swift @@ -332,7 +332,7 @@ func buildCoordinatorDoctorChecks( let base = coordinatorHTTPBase(coordinatorOverride ?? snapshot.config.coordinator.url) var checks: [DoctorCheck] = [] let now = Date().timeIntervalSince1970 - let authorization = DaemonStateFile.read()?.currentProviderAuthorization( + let authorization = DaemonStateFile.read()?.displayedProviderAuthorization( coordinatorURL: coordinatorOverride ?? snapshot.config.coordinator.url, now: now) let appAttestAuthorized = authorization?.hasCurrentAppAttestAuthorization(now: now) == true diff --git a/provider-swift/Sources/darkbloom/StatusCommand.swift b/provider-swift/Sources/darkbloom/StatusCommand.swift index 2612ff8b2e..b4cf632ddc 100644 --- a/provider-swift/Sources/darkbloom/StatusCommand.swift +++ b/provider-swift/Sources/darkbloom/StatusCommand.swift @@ -131,7 +131,7 @@ struct Status: AsyncParsableCommand { print(" Selection: \(status.models.joined(separator: ", "))") } - let authorization = state.currentProviderAuthorization( + let authorization = state.displayedProviderAuthorization( coordinatorURL: config.coordinator.url, now: now) if let authorization { print("Authorization: \(ProviderAuthorizationReadiness.summary(authorization, now: now))") diff --git a/provider-swift/Tests/DarkbloomCLITests/StatusCommandRunTests.swift b/provider-swift/Tests/DarkbloomCLITests/StatusCommandRunTests.swift index 8890781c2e..7c4ad0e512 100644 --- a/provider-swift/Tests/DarkbloomCLITests/StatusCommandRunTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/StatusCommandRunTests.swift @@ -113,4 +113,28 @@ struct StatusCommandRunTests { #expect(lines.dropFirst(daemon + 1).first == Status.lifecycleDrainLine( ProviderDrainStatus(outcome: .timedOut, remaining: 0))) } + + /// Renewals of the ~30 s App Attest lease arrive every few seconds with + /// jitter; one that is 15 s late must not turn status into legacy trust. + @Test("status keeps reporting App Attest while the lease is unexpired and a renewal is late") + func lateLeaseRenewalStillAuthorizes() async throws { + let result = try await #require( + processExitsWith: .success, observing: [\.standardOutputContent] + ) { + let sandbox = try CLICommandSandbox.enter(autoRestart: false) + defer { sandbox.remove() } + let now = Date().timeIntervalSince1970 + var authorization = CLICommandSandbox.appAttestAuthorization(now: now) + authorization.expiresAt = now + 15 + sandbox.writeState(try CLICommandSandbox.runningState( + now: now, + trust: .init(trustLevel: "self_signed", status: "online", reason: "Provider authorization updated", + receivedAt: now - 15, authorization: authorization))) + try await runCLICommand(Status.self, ["status", "--config", sandbox.config.path]) + } + let output = decodedText(result.standardOutputContent) + + #expect(output.contains("\nAuthorization: App Attest authorizes this connection. ")) + #expect(!output.contains("\nTrust: self_signed / online\n")) + } } diff --git a/provider-swift/Tests/ProviderCoreTests/Diagnostics/ProviderAuthorizationReadinessTests.swift b/provider-swift/Tests/ProviderCoreTests/Diagnostics/ProviderAuthorizationReadinessTests.swift index fac162e710..afe4470017 100644 --- a/provider-swift/Tests/ProviderCoreTests/Diagnostics/ProviderAuthorizationReadinessTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Diagnostics/ProviderAuthorizationReadinessTests.swift @@ -97,6 +97,41 @@ import Testing #expect(ProviderAuthorizationReadiness.removalReady(current(receivedAt: 99), now: 100)) } + /// The coordinator renews a ~30 s App Attest lease every few seconds with + /// jitter. A renewal older than `snapshotMaxAge` is still the coordinator's + /// grant until `expiresAt`; status and doctor must not drop to legacy trust. + @Test func displayKeepsAnUnexpiredLeaseWhoseRenewalIsLate() { + let identity = ProcessIdentity(pid: 41, startTimeMicros: 9) + func state(receivedAt: Double, expiresAt: Double, path: String = "app_attest", + online: String = "online") -> DaemonState { + DaemonState( + pid: 41, processIdentity: identity, version: "test", + writtenAt: 100, startedAt: 50, + trust: .init(trustLevel: "self_signed", status: online, reason: "", + receivedAt: receivedAt, authorization: status(path: path, expiresAt: expiresAt)), + coordinatorURL: "wss://api.darkbloom.dev/ws/provider") + } + func displayed(_ state: DaemonState, coordinator: String = "https://api.darkbloom.dev", + identity: ProcessIdentity? = identity, now: Double = 100) -> ProviderAuthorizationStatus? { + state.displayedProviderAuthorization( + coordinatorURL: coordinator, now: now, readProcessIdentity: { _ in identity }) + } + let late = state(receivedAt: 85, expiresAt: 115) + #expect(displayed(late) == late.trust?.authorization) + // Unenroll keeps requiring a renewal inside snapshotMaxAge. + #expect(late.currentProviderAuthorization( + coordinatorURL: "https://api.darkbloom.dev", now: 100, readProcessIdentity: { _ in identity }) == nil) + + #expect(displayed(state(receivedAt: 85, expiresAt: 100)) == nil) + #expect(displayed(state(receivedAt: 85, expiresAt: 115, path: "none")) == nil) + #expect(displayed(state(receivedAt: 40, expiresAt: 115)) == nil) + #expect(displayed(late, coordinator: "https://other.example") == nil) + #expect(displayed(late, identity: nil) == nil) + #expect(displayed(state(receivedAt: 85, expiresAt: 115, online: "untrusted")) == nil) + // The lease cannot outlive a daemon that stopped writing its snapshot. + #expect(displayed(late, now: 110.001) == nil) + } + @Test func expiredStatusNeverClaimsThatRemovalIsAvailable() { let description = ProviderAuthorizationReadiness.summary(status(expiresAt: 100), now: 100) #expect(!description.contains("removal is available")) From 473eca97becdfbdfd014536f2839344e47758438 Mon Sep 17 00:00:00 2001 From: darkbloombugs Date: Sun, 11 Oct 2026 16:24:37 -0700 Subject: [PATCH 0003/1441] fix(provider): require fresh readiness for MDM removal advice (#1433) Co-authored-by: darkbloombugs <338864726+darkbloombugs@users.noreply.github.com> --- CHANGELOG.md | 4 + docs/developer/build.md | 8 +- docs/developer/test.md | 14 +- docs/provider/attestation.md | 4 +- docs/provider/cli-reference.md | 3 +- docs/reference/provider-authorization.md | 4 +- .../ProviderAuthorizationReadiness.swift | 17 ++- .../darkbloom/Diagnostics/DoctorRunner.swift | 4 +- .../Sources/darkbloom/DoctorCommand.swift | 8 +- .../Sources/darkbloom/StatusCommand.swift | 4 +- .../UnenrollCommand+KeepServing.swift | 3 +- .../ProviderAuthorizationReadinessTests.swift | 127 +++++++++++++++++- 12 files changed, 184 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 25b4e5ac8c..38637be166 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased — fresh MDM removal guidance + +- Keep `darkbloom status` and both `darkbloom doctor` authorization summaries from offering MDM removal when the coordinator decision is too old for removal readiness. An unexpired App Attest serving lease stays visible; removal advice asks for fresh readiness and keeps existing profiles installed. The `darkbloom unenroll` checks are unchanged. + ## Unreleased — provider status App Attest lease - Keep `darkbloom status` and `darkbloom doctor` reporting App Attest authorization until the coordinator lease expires. They required a renewal within the last 10 seconds, so one delayed renewal showed `Trust: self_signed / online` although serving continued. `darkbloom unenroll` still requires a renewal within 10 seconds before offering MDM removal. diff --git a/docs/developer/build.md b/docs/developer/build.md index e8a14d9373..985f1af176 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build -> Last updated: 2026-10-08 +> Last updated: 2026-10-10 Stack maintenance uses Python 3, Git, authenticated `gh`, and a configured commit signer; it requires no product build. Follow [Maintain a pull-request stack](pull-requests.md) @@ -236,6 +236,12 @@ Go/Swift fixture and focused checks are described in [test.md](test.md) and The `ProviderAppAttest` Swift target uses public DeviceCheck/Security APIs. Its [shadow packaging and live-validation requirements](../reference/app-attest-shadow.md#packaging-and-live-acceptance) are separate from a successful local compile. +After changing provider authorization summaries, rebuild the provider test +product before running the [authorization guidance tests](test.md#provider-authorization-guidance). +They exercise shared production decisions without invoking status/doctor's +host probes or native Apple operations; signed-release qualification remains +separate. + The provider email operator command builds separately with `go build -o /tmp/provider-emails ./coordinator/cmd/provider-emails`. It is not part of the coordinator server process. See the [provider email runbook](../operations/provider-emails.md). diff --git a/docs/developer/test.md b/docs/developer/test.md index 492ed0196b..ae0437b7ba 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test -> Last updated: 2026-10-08 +> Last updated: 2026-10-10 ## Autopilot rewards @@ -1275,6 +1275,18 @@ source/dependency/binary/metallib/artifact tuple: The [App Attest shadow validation commands](../reference/app-attest-shadow.md#validation) cover cryptography, protocol symmetry, counter races, unchanged routing, and coexistence signing. Live macOS 27 acceptance remains separate. +### Provider authorization guidance + +After rebuilding the provider test product, run +`swift test --skip-build --no-parallel --filter ProviderAuthorizationReadinessTests` +from `provider-swift/`. The suite exercises the production freshness checks and +summary used by status and both doctor paths: a late but unexpired serving lease +stays visible while removal advice requires the matching fresh decision. It +covers the receipt-window boundary, disabled rollout, missing or mismatched +decisions and exact lease expiry. These checks use fixed snapshots and injected +process identity; they do not run the CLI's host probes, change profiles or +establish native App Attest acceptance. + ## Cache attempt ownership during model replacement Run the real Registry publication/accounting regression after changing model diff --git a/docs/provider/attestation.md b/docs/provider/attestation.md index 6ab7cfaed7..bf56416abb 100644 --- a/docs/provider/attestation.md +++ b/docs/provider/attestation.md @@ -1,6 +1,6 @@ # Reaching and keeping `hardware` trust -> Last updated: 2026-10-08 +> Last updated: 2026-10-10 How to check provider verification and retain legacy `hardware` trust where eligible. New providers require macOS 27 or later and current qualified App @@ -83,6 +83,8 @@ qualified; do not delete a working credential to bypass that check. New setup on macOS 27 or later skips MDM profile download in both the installer and `darkbloom enroll`. Darkbloom MDM will be deactivated soon; upgrade to macOS 27 to avoid legacy enrollment. A qualified macOS 27 provider can use [App Attest authorization](../reference/provider-authorization.md) when the coordinator explicitly enables it. Start the signed provider and check `darkbloom status` / `darkbloom doctor` for current App Attest authorization. Company-managed Macs keep their employer profile; they do not enroll into Darkbloom MDM for this path. +When `darkbloom status` or `darkbloom doctor` says App Attest authorizes the connection but MDM removal needs fresh coordinator readiness, keep existing profiles installed and wait for a fresh decision. The displayed serving lease can remain valid after removal readiness becomes stale. Both doctor summaries and status use the separate decisions in `provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift` (`summary`); see the [authorization reference](../reference/provider-authorization.md). + After the coordinator enables removal and reports readiness, run `darkbloom unenroll` and choose the App Attest option. Removal guidance requires a coordinator decision received within the last 10 seconds, as well as a current daemon snapshot and unexpired authorization; a local state-file rewrite cannot extend readiness. It requires macOS 27 or later; `--keep-serving` remains a direct shortcut. The command preserves credentials/account data, validates the exact Darkbloom enrollment and guides removal in System Settings. If the read-only administrator inventory is needed, run the command in the foreground of an interactive terminal: `sudo` reads the password with terminal echo disabled. Refusing authentication, running without a terminal, or running as a background job withholds guidance; no profile is removed by the CLI. The full-exit option stops the provider and offers identity cleanup, so choose App Attest to retain provider identity. New setup remains pending if App Attest is unavailable or unqualified; diagnose diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 3e0e4a490a..3cb158d82b 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1,6 +1,6 @@ # Provider CLI reference -> Last updated: 2026-10-08 +> Last updated: 2026-10-10 Reference for the `darkbloom` command-line tool: every subcommand and flag, the files and identifiers it creates, the `provider.toml` keys it reads with their @@ -783,6 +783,7 @@ Output includes: - `Inference memory` is the nominal hardware budget, **not** live free RAM. - Schedule state (active/inactive). - Live daemon PID, uptime, trust verdict, and last model-load error. +- App Attest serving authorization can remain visible through its unexpired lease, while MDM removal advice requires a matching fresh coordinator decision. The same distinction applies to both doctor summaries; see [provider authorization](../reference/provider-authorization.md). - `Not serving:` when the daemon is alive but a graceful drain has closed admission — draining, a drain that did not finish, or a drain whose relaunch never happened — with the commands that finish or interrupt it diff --git a/docs/reference/provider-authorization.md b/docs/reference/provider-authorization.md index 6e33365802..ff508cfaed 100644 --- a/docs/reference/provider-authorization.md +++ b/docs/reference/provider-authorization.md @@ -1,6 +1,6 @@ # Provider serving authorization -> Last updated: 2026-10-09 +> Last updated: 2026-10-10 The coordinator can authorize private inference through complete legacy verification or a qualified App Attest connection. These are separate evidence paths; App Attest never sets legacy MDA/APNs flags. The [rollout runbook](../operations/mdm-optional-rollout.md) separates code availability from activation qualification. @@ -84,6 +84,8 @@ The additive `trust_status.authorization` object is coordinator-to-provider only `darkbloom status` and `darkbloom doctor` apply the same snapshot, process, coordinator, `online` and protocol checks, but keep showing an App Attest authorization until its `expires_at` when the latest renewal arrived more than `snapshotMaxAge` ago (`provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift`, `displayedStatus`). The coordinator sends a renewal after each successful `authorization.RefreshInterval` refresh and bounds the lease by `RevocationFreshness = 30 * time.Second` (`coordinator/internal/appattest/authorization/controller.go`), so one delayed renewal does not end the grant. `none` and `legacy` decisions still need a renewal inside `snapshotMaxAge`. +The serving-authorization summary takes the displayed lease and the strict removal decision separately (`ProviderAuthorizationReadiness.summary`). Status and both doctor paths derive them from the same daemon snapshot and observation time. Positive removal advice requires the matching fresh decision and `mdm_removal_ready`; a late but unexpired lease remains visible while the summary asks for fresh readiness and retains existing profiles. These are local guidance checks; `unenroll` still performs its existing readiness checks before and after profile inspection. + ## Owner dashboard and upgrade guidance The setup page prominently explains macOS 27 and planned MDM deactivation. diff --git a/provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift b/provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift index 72fb4a872a..4051cd5102 100644 --- a/provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift +++ b/provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift @@ -63,17 +63,26 @@ public enum ProviderAuthorizationReadiness { && authorization.hasCurrentAppAttestAuthorization(now: now) } + /// Displayed serving leases can outlast removal readiness. Callers provide + /// the strict current decision from the same snapshot and time separately. public static func summary( - _ authorization: ProviderAuthorizationStatus?, now: Double, + _ authorization: ProviderAuthorizationStatus?, + removalAuthorization: ProviderAuthorizationStatus?, now: Double, macOSMajorVersion: Int = ProcessInfo.processInfo.operatingSystemVersion.majorVersion ) -> String { guard let authorization else { return "App Attest authorization is unconfirmed; keep any existing management profiles installed until this running provider receives fresh coordinator readiness." } if authorization.hasCurrentAppAttestAuthorization(now: now) { - return "App Attest authorizes this connection. " + (authorization.mdmRemovalReady - ? "Darkbloom MDM removal is available: run darkbloom unenroll and choose App Attest." - : "Darkbloom MDM removal is not enabled for this machine yet.") + let serving = "App Attest authorizes this connection. " + guard authorization.mdmRemovalReady else { + return serving + "Darkbloom MDM removal is not enabled for this machine yet." + } + guard removalAuthorization == authorization, + removalReady(removalAuthorization, now: now) else { + return serving + "Darkbloom MDM removal needs fresh coordinator readiness; keep existing management profiles installed." + } + return serving + "Darkbloom MDM removal is available: run darkbloom unenroll and choose App Attest." } if authorization.path == "legacy" { return "Serving through legacy verification; keep the Darkbloom MDM profile." diff --git a/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift b/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift index 7c5aab913d..83cf63cb46 100644 --- a/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift +++ b/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift @@ -18,6 +18,7 @@ enum DoctorRunner { // its live fields (trust level, current model, capacity) are trustworthy. let stateFresh = daemonUp && !(state?.isStale(now: now) ?? true) let authorization = state?.displayedProviderAuthorization(coordinatorURL: coordinatorURL, now: now) + let removalAuthorization = state?.currentProviderAuthorization(coordinatorURL: coordinatorURL, now: now) let appAttestAuthorized = authorization?.hasCurrentAppAttestAuthorization(now: now) == true // ---- Attestation key (read-only daemon state) ---- @@ -57,7 +58,8 @@ enum DoctorRunner { if let authorization { out.append(Diagnostic(section: .trust, name: "serving authorization", level: appAttestAuthorized || authorization.path == "legacy" ? .pass : .warn, - message: ProviderAuthorizationReadiness.summary(authorization, now: now), + message: ProviderAuthorizationReadiness.summary( + authorization, removalAuthorization: removalAuthorization, now: now), fix: nil)) } else if let state, let trust = state.trust, daemonUp, !state.isStale(now: now) { let advice = TrustReasonCatalog.advice(level: trust.trustLevel, status: trust.status, reason: trust.reason) diff --git a/provider-swift/Sources/darkbloom/DoctorCommand.swift b/provider-swift/Sources/darkbloom/DoctorCommand.swift index 16b4b4b25c..5c0756b740 100644 --- a/provider-swift/Sources/darkbloom/DoctorCommand.swift +++ b/provider-swift/Sources/darkbloom/DoctorCommand.swift @@ -332,7 +332,10 @@ func buildCoordinatorDoctorChecks( let base = coordinatorHTTPBase(coordinatorOverride ?? snapshot.config.coordinator.url) var checks: [DoctorCheck] = [] let now = Date().timeIntervalSince1970 - let authorization = DaemonStateFile.read()?.displayedProviderAuthorization( + let state = DaemonStateFile.read() + let authorization = state?.displayedProviderAuthorization( + coordinatorURL: coordinatorOverride ?? snapshot.config.coordinator.url, now: now) + let removalAuthorization = state?.currentProviderAuthorization( coordinatorURL: coordinatorOverride ?? snapshot.config.coordinator.url, now: now) let appAttestAuthorized = authorization?.hasCurrentAppAttestAuthorization(now: now) == true @@ -381,7 +384,8 @@ func buildCoordinatorDoctorChecks( if let authorization { checks.append(.init(name: "serving authorization", status: appAttestAuthorized || authorization.path == "legacy" ? .pass : .warn, - detail: ProviderAuthorizationReadiness.summary(authorization, now: now))) + detail: ProviderAuthorizationReadiness.summary( + authorization, removalAuthorization: removalAuthorization, now: now))) return checks } diff --git a/provider-swift/Sources/darkbloom/StatusCommand.swift b/provider-swift/Sources/darkbloom/StatusCommand.swift index b4cf632ddc..f852df9552 100644 --- a/provider-swift/Sources/darkbloom/StatusCommand.swift +++ b/provider-swift/Sources/darkbloom/StatusCommand.swift @@ -133,8 +133,10 @@ struct Status: AsyncParsableCommand { let authorization = state.displayedProviderAuthorization( coordinatorURL: config.coordinator.url, now: now) + let removalAuthorization = state.currentProviderAuthorization( + coordinatorURL: config.coordinator.url, now: now) if let authorization { - print("Authorization: \(ProviderAuthorizationReadiness.summary(authorization, now: now))") + print("Authorization: \(ProviderAuthorizationReadiness.summary(authorization, removalAuthorization: removalAuthorization, now: now))") if !authorization.machineID.isEmpty { print("Machine ID: \(authorization.machineID)") } } else if let trust = state.trust { let advice = TrustReasonCatalog.advice(level: trust.trustLevel, status: trust.status, reason: trust.reason) diff --git a/provider-swift/Sources/darkbloom/UnenrollCommand+KeepServing.swift b/provider-swift/Sources/darkbloom/UnenrollCommand+KeepServing.swift index 612c1392fa..7f481118cc 100644 --- a/provider-swift/Sources/darkbloom/UnenrollCommand+KeepServing.swift +++ b/provider-swift/Sources/darkbloom/UnenrollCommand+KeepServing.swift @@ -21,7 +21,8 @@ extension Unenroll { let authorization = DaemonStateFile.read()?.currentProviderAuthorization( coordinatorURL: coordinator, now: now) guard ProviderAuthorizationReadiness.removalReady(authorization, now: now) else { - printError(ProviderAuthorizationReadiness.summary(authorization, now: now)) + printError(ProviderAuthorizationReadiness.summary( + authorization, removalAuthorization: authorization, now: now)) throw ExitCode.failure } diff --git a/provider-swift/Tests/ProviderCoreTests/Diagnostics/ProviderAuthorizationReadinessTests.swift b/provider-swift/Tests/ProviderCoreTests/Diagnostics/ProviderAuthorizationReadinessTests.swift index afe4470017..5ceea7b21c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Diagnostics/ProviderAuthorizationReadinessTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Diagnostics/ProviderAuthorizationReadinessTests.swift @@ -133,15 +133,138 @@ import Testing } @Test func expiredStatusNeverClaimsThatRemovalIsAvailable() { - let description = ProviderAuthorizationReadiness.summary(status(expiresAt: 100), now: 100) + let expired = status(expiresAt: 100) + let description = ProviderAuthorizationReadiness.summary( + expired, removalAuthorization: expired, now: 100) #expect(!description.contains("removal is available")) #expect(description.contains("not currently qualified")) } + @Test func lateLeaseDoesNotOfferRemovalWithoutFreshReadiness() throws { + let identity = ProcessIdentity(pid: 41, startTimeMicros: 9) + let state = DaemonState( + pid: 41, processIdentity: identity, version: "test", + writtenAt: 100, startedAt: 50, + trust: .init(trustLevel: "self_signed", status: "online", reason: "Provider authorization updated", + receivedAt: 85, authorization: status(expiresAt: 115)), + coordinatorURL: "wss://fixture.invalid/ws/provider") + let displayed = try #require(state.displayedProviderAuthorization( + coordinatorURL: "https://fixture.invalid", now: 100, readProcessIdentity: { _ in identity })) + let current = state.currentProviderAuthorization( + coordinatorURL: "https://fixture.invalid", now: 100, readProcessIdentity: { _ in identity }) + #expect(current == nil) + #expect(!ProviderAuthorizationReadiness.removalReady(current, now: 100)) + // This is the production summary called by status and both doctor paths. + let summary = ProviderAuthorizationReadiness.summary( + displayed, removalAuthorization: current, now: 100, macOSMajorVersion: 27) + print("APP_ATTEST_LATE_LEASE_WITNESS displayed=\(displayed.path) fresh_removal=\(current != nil) summary=\(summary)") + #expect(summary.contains("App Attest authorizes this connection")) + #expect(!summary.contains("removal is available")) + #expect(!summary.contains("run darkbloom unenroll")) + #expect(summary.contains("needs fresh coordinator readiness")) + #expect(summary.contains("keep existing management profiles installed")) + } + + @Test func displayAndRemovalKeepTheirDistinctTimeBoundaries() { + func decisions(receivedAt: Double = 90, expiresAt: Double = 115, + writtenAt: Double = 100) -> (ProviderAuthorizationStatus?, ProviderAuthorizationStatus?) { + let authorization = status(expiresAt: expiresAt) + return ( + ProviderAuthorizationReadiness.displayedStatus( + authorization, status: "online", writtenAt: writtenAt, receivedAt: receivedAt, + startedAt: 50, now: 100, processMatches: true, coordinatorMatches: true), + ProviderAuthorizationReadiness.currentStatus( + authorization, status: "online", writtenAt: writtenAt, receivedAt: receivedAt, + startedAt: 50, now: 100, processMatches: true, coordinatorMatches: true)) + } + #expect(decisions().0 != nil) + #expect(ProviderAuthorizationReadiness.removalReady(decisions().1, now: 100)) + #expect(decisions(receivedAt: 89.999).0 != nil) + #expect(decisions(receivedAt: 89.999).1 == nil) + #expect(decisions(receivedAt: 85, expiresAt: 100).0 == nil) + #expect(decisions(receivedAt: 85, expiresAt: 100.001).0 != nil) + for expiry in [Double.nan, .infinity] { + #expect(decisions(receivedAt: 85, expiresAt: expiry).0 == nil) + } + #expect(decisions(writtenAt: 89.999).0 == nil) + #expect(decisions(writtenAt: 102.001).0 == nil) + } + + @Test func summaryOffersRemovalOnlyWithinTheReceiptWindow() { + for receivedAt in [90.0, 89.999] { + let grant = status(expiresAt: 115) + let displayed = ProviderAuthorizationReadiness.displayedStatus( + grant, status: "online", writtenAt: 100, receivedAt: receivedAt, + startedAt: 50, now: 100, processMatches: true, coordinatorMatches: true) + let current = ProviderAuthorizationReadiness.currentStatus( + grant, status: "online", writtenAt: 100, receivedAt: receivedAt, + startedAt: 50, now: 100, processMatches: true, coordinatorMatches: true) + let summary = ProviderAuthorizationReadiness.summary( + displayed, removalAuthorization: current, now: 100) + + #expect(summary.contains("App Attest authorizes this connection")) + #expect(summary.contains("removal is available") == (receivedAt == 90)) + #expect(summary.contains("run darkbloom unenroll") == (receivedAt == 90)) + #expect(summary.contains("needs fresh coordinator readiness") == (receivedAt == 89.999)) + } + } + + @Test func summaryKeepsDisabledRemovalSeparateFromMissingReadiness() { + var grant = status() + grant.mdmRemovalReady = false + for current: ProviderAuthorizationStatus? in [grant, nil] { + let summary = ProviderAuthorizationReadiness.summary( + grant, removalAuthorization: current, now: 100) + #expect(summary.contains("App Attest authorizes this connection")) + #expect(summary.contains("removal is not enabled")) + #expect(!summary.contains("needs fresh coordinator readiness")) + #expect(!summary.contains("run darkbloom unenroll")) + } + } + + @Test func summaryRejectsMissingOrDifferentRemovalDecisions() { + let grant = status() + var otherSession = grant + otherSession.sessionID = "other-session" + var otherMachine = grant + otherMachine.machineID = "other-machine" + var differentDecision = grant + differentDecision.reason = "different-decision" + var disabled = grant + disabled.mdmRemovalReady = false + var malformed = grant + malformed.protocolVersion = 2 + let invalid: [ProviderAuthorizationStatus?] = [ + nil, otherSession, otherMachine, differentDecision, disabled, malformed, + status(expiresAt: 100), status(path: "none"), status(path: "legacy"), + ] + for current in invalid { + let summary = ProviderAuthorizationReadiness.summary( + grant, removalAuthorization: current, now: 100) + #expect(summary.contains("App Attest authorizes this connection")) + #expect(summary.contains("needs fresh coordinator readiness")) + #expect(summary.contains("keep existing management profiles installed")) + #expect(!summary.contains("removal is available")) + #expect(!summary.contains("run darkbloom unenroll")) + } + } + + @Test func removalDecisionCannotRestoreMissingOrExpiredDisplayedAuthorization() { + let unavailable: [ProviderAuthorizationStatus?] = [nil, status(expiresAt: 100), status(path: "none")] + for displayed in unavailable { + let summary = ProviderAuthorizationReadiness.summary( + displayed, removalAuthorization: status(), now: 100) + #expect(!summary.contains("App Attest authorizes this connection")) + #expect(!summary.contains("removal is available")) + #expect(!summary.contains("run darkbloom unenroll")) + } + } + @Test func disabledCoordinatorLeavesMacOS27SetupPendingWithoutMDMFallback() { var disabled = status(path: "none") disabled.appAttestAvailable = false - let summary = ProviderAuthorizationReadiness.summary(disabled, now: 100, macOSMajorVersion: 27) + let summary = ProviderAuthorizationReadiness.summary( + disabled, removalAuthorization: disabled, now: 100, macOSMajorVersion: 27) #expect(summary.contains("setup remains pending")) #expect(!summary.contains("enrollment is still required")) #expect(!ProviderAuthorizationReadiness.removalReady(disabled, now: 100)) From 5dc4f7ae1ddd2c755ffaffb35c1d0a535c1e705b Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 27 Oct 2026 22:34:47 -0700 Subject: [PATCH 0004/1441] perf(provider): restore dense Qwen conversations from just below the prompt end A dense Qwen 3.5/3.8 request served alone prefills in 4,096-token stripes, so its deepest SSD checkpoint was the last full stripe end, up to 4,095 tokens before the prompt end. The next turn of the conversation re-prefilled that gap. With its paged complete store, the engine now sets the SDK's demandedLatestCheckpointMinimumTokens to the store floor. A request the store would write then also ends a prefill range at the deepest 256-aligned boundary at least 64 tokens below its prompt end, when that saves at least the floor. Busy providers, which prefill in 512-token chunks beside decoding requests, keep the ordinary geometry. Six-turn conversation from 30K to 55K tokens, Qwen3.5-9B, M3 Ultra, two runs per arm: the mean summed time to first token of the five follow-up turns fell from 57.38 s to 47.88 s (-16.5%), with outputs identical to master on every turn. SSD bytes rose 2.6% (2.71 GB to 2.78 GB) for the same 7 files. Requires mlx-swift-lm 05c7ca7e (feat/demanded-latest-checkpoint). Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen-end-of-prompt-checkpoints.md | 13 ++++++++ docs/architecture/inference.md | 3 +- docs/architecture/prefix-cache.md | 23 ++++++++++++- libs/mlx-swift-lm | 2 +- .../EngineV2Factory+DemandedCheckpoint.swift | 19 +++++++++++ .../Factory/EngineV2Factory+Production.swift | 2 ++ .../Qwen35CheckpointRetentionLiveTests.swift | 12 +++++-- .../Vision/QwenVLMTargetExtractionTests.swift | 32 +++++++++++++++++++ 8 files changed, 100 insertions(+), 6 deletions(-) create mode 100644 changelog.d/qwen-end-of-prompt-checkpoints.md diff --git a/changelog.d/qwen-end-of-prompt-checkpoints.md b/changelog.d/qwen-end-of-prompt-checkpoints.md new file mode 100644 index 0000000000..21cc42efd2 --- /dev/null +++ b/changelog.d/qwen-end-of-prompt-checkpoints.md @@ -0,0 +1,13 @@ +### Dense Qwen conversations restore almost all of the previous turn + +- A dense Qwen 3.5/3.8 request served alone prefills in 4,096-token stripes, + so its deepest SSD checkpoint was the last full stripe end, up to 4,095 + tokens before the prompt end. The next turn of the conversation + re-prefilled that gap. Such a request now also ends a prefill range just + below its prompt end (at least 64 tokens before it, on the 256-token grid) + when that saves at least 1,024 tokens, and the next turn restores from + there. In a six-turn conversation from 30K to 55K tokens on Qwen3.5-9B (M3 + Ultra), the summed time to first token of the five follow-up turns fell + from 57.4 s to 47.9 s, with identical outputs. Busy providers, which + prefill in 512-token chunks beside decoding requests, and the short-prompt + fork checkpoint are unchanged. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 5e51121117..8eabe90de2 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-27 +> Last updated: 2026-10-28 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -1384,6 +1384,7 @@ elapsed nanoseconds. Numerics only — never tokens, text or hashes | `maxWaiting` | 64 (`CBv2SchedulerConfig` init default) | `CBv2Contracts.swift`, `CBv2SchedulerConfig` | | `soloPrefillStripeTokens` | 4096 for dense Qwen3.5/3.8 (`Qwen35Model`, not `Qwen35MoEModel`); 2048 (`defaultSoloPrefillStripeTokens`) for families on the 512-token chunk; none for Gemma 4, because a stripe arms only above the plain chunk; `DARKBLOOM_CBV2_SOLO_PREFILL_STRIPE` | `EngineV2Factory+Configuration.swift` (`soloPrefillStripeTokens`) | | `bidirectionalMediaPrefillChunkCeiling` | 512 whenever the plain chunk is wider, otherwise unset | `EngineV2Factory+Configuration.swift` (`prefillGeometry`); `CBv2Contracts.swift` (`plainPrefillChunkSize`) | +| `demandedLatestCheckpointMinimumTokens` | The paged complete store's effective-token floor for dense Qwen3.5/3.8 (`Qwen35Model`, not `Qwen35MoEModel`), otherwise unset: a range ends just below the prompt end when that saves at least the floor ([end-of-prompt boundary](prefix-cache.md#streamed-complete-checkpoints)) | `EngineV2Factory+DemandedCheckpoint.swift` (`demandedLatestCheckpointMinimumTokens`) | | `maxConcurrentPartialPrefills` | 1; `DARKBLOOM_CBV2_MAX_PARTIAL_PREFILLS` | `EngineV2Factory+Configuration.swift`, `maxPartialPrefillsKey` | | Prompt-chunk attention | 128-query blocks (`DARKBLOOM_CBV2_ATTN_QUERY_BLOCK`; paged blocks other than Qwen4 QSA build an absolute mask), bounding the composed score tensor. A full-attention chunk with no window, softcap, vision span or bidirectional mask, whose head_dim MLX fuses (64/72/80/96/128; 256 on NAX from 1024 queries in bf16/fp16), is one `.causal` call on either KV backend (live packed paged KV keeps its own path); `DARKBLOOM_TTFT_FUSED_CAUSAL_PREFILL=0` restores blocks | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/AttentionV1.swift` (`usesFusedCausalPrefill`), `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedLayerCache.swift` (`prefillAttend`) | | `enablePrefixCache` | true when the slot has an effective SSD cache, enabled paged resident cache, or recurrent checkpoint-bank configuration, or complete SSD checkpoint store; engine capability gates still apply | `EngineV2Factory+Production.swift` (`assembleProductionBuild`), `EngineV2.swift` | diff --git a/docs/architecture/prefix-cache.md b/docs/architecture/prefix-cache.md index 379aed6f07..7c6a00be4f 100644 --- a/docs/architecture/prefix-cache.md +++ b/docs/architecture/prefix-cache.md @@ -1,6 +1,6 @@ # KV cache layouts and prefix caching -> Last updated: 2026-10-24 +> Last updated: 2026-10-28 How the provider lays out a request's KV cache, how it decides whether a previously computed prefix can be reused, and where reusable state lives: @@ -667,6 +667,27 @@ live in `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/Dem `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift` (`executeMixed`). Existing checkpoint count/byte and storage floors remain. +A dense Qwen donor's deepest boundary is otherwise the last full solo stripe +end, up to 4,095 tokens below the prompt end. The next turn of a growing +conversation re-prefills that gap. The engine with its paged complete store +therefore also sets +`CBv2SchedulerConfig.demandedLatestCheckpointMinimumTokens` to the store floor +(`EngineV2Factory.demandedLatestCheckpointMinimumTokens`). A request the store +would write then ends one range at the deepest aligned boundary at least +`demandedLatestPromptEndMarginTokens = 64` tokens below its prompt end. The +margin keeps the boundary inside the prefix the next turn shares even after +the template re-renders the generation prompt. The cut is made only when it +saves at least the floor over the start of the range it shortens. Beside +decoding requests (512-token chunks) no cut qualifies at the default floor, so +the ordinary geometry stays. The short-prompt fork target, the retained +first/target/latest roles and fleet-novel refusal are unchanged; the cut +boundary becomes the rolling latest. Dense Qwen restores token-exactly under +any partition, as the parity rule above records. The partition is +`demandedLatestCheckpointRange` in +`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/DemandedShortCheckpointRange.swift`; +scheduling and the first-token projection share it through +`demandedCheckpointRange`. + GLM-5.3-Flash captures its KDA state under the same range-end rule, but it has no solo stripe and its prefill chunk shares one 2,048-token step budget with the decode rows of other requests (`EngineV2Factory.glm5NextMaximumStepTokens`). diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index aee6ebb683..05c7ca7eaa 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit aee6ebb6835c62feda80000c83f81f2788cc9822 +Subproject commit 05c7ca7eaa65f018eec7154e8683913e9b6ae060 diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+DemandedCheckpoint.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+DemandedCheckpoint.swift index 3acfbb3035..7959ee7d7f 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+DemandedCheckpoint.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+DemandedCheckpoint.swift @@ -58,6 +58,25 @@ extension EngineV2Factory { return store.config.minEffectiveTokens } + /// Dense Qwen's deepest boundary is otherwise the last full stripe or chunk + /// end, up to 4,095 tokens below the prompt end that the next turn of a + /// growing conversation extends. Its restore is exact under any prefill + /// partition, so with its paged complete store a range also ends just below + /// the prompt end (SDK `CBv2SchedulerConfig.demandedLatestCheckpointMinimumTokens`). + /// GLM's capture-boundary partition is not reused: its cut at the fork + /// hint would replace the retained stripe end below it, which a shorter + /// fork restores. + static func demandedLatestCheckpointMinimumTokens( + model: any LanguageModel, backend: EngineV2KVBackendKind, + store: (any CBv2CompletePrefixCache)? + ) -> Int? { + guard backend == .paged, isDenseQwen35(model), let store = store as? SSDHybridCheckpointStore, + store.config.backendLayout == CBv2CompleteCheckpointManifest.pagedLayout + || store.config.backendLayout == CBv2CompleteCheckpointManifest.nativeQuantizedPagedLayout + else { return nil } + return store.config.minEffectiveTokens + } + /// Host-only policy shared by the actual assembly and qualification tests. /// A benchmark request cannot qualify another backend or lower a floor. static func benchmarkRecurrentShortCheckpointMinimumTokens( diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+Production.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+Production.swift index f47ba432ae..523f05e8f2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+Production.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+Production.swift @@ -307,6 +307,8 @@ extension EngineV2Factory { constructionPurpose: constructionPurpose, checkpointPartition: checkpointPartition) schedulerConfig.demandedCaptureBoundaryMinimumTokens = demandedCaptureBoundaryMinimumTokens( model: model, store: completePrefixCache) + schedulerConfig.demandedLatestCheckpointMinimumTokens = demandedLatestCheckpointMinimumTokens( + model: model, backend: preparedBackend.kind, store: completePrefixCache) let processOwner: (any CBv2ProcessMemoryOwner)? if let glmNative { guard glmNative.resources.backend === backend, diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen35CheckpointRetentionLiveTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen35CheckpointRetentionLiveTests.swift index a709c81124..3f3dfb5ffe 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen35CheckpointRetentionLiveTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen35CheckpointRetentionLiveTests.swift @@ -110,8 +110,9 @@ struct Qwen35CheckpointRetentionLiveTests { } } - /// A ~6.2k donor with the same fork hint: 4,096 is one 2,048 chunk - /// below its 6,144 deepest, is kept beside the first and the deepest. + /// A donor whose last full 2,048 chunk ends at 6,144, with the same fork + /// hint: 4,096 is kept beside the first and the deepest, the end-of-prompt + /// boundary above that chunk end. @Test("a fork target one 2,048 chunk below the deepest is kept", .timeLimit(.minutes(10)), .enabled(if: enabled)) func targetOneChunkBelowDeepestIsKept() async throws { @@ -127,7 +128,12 @@ struct Qwen35CheckpointRetentionLiveTests { try await requireQwen35CheckpointIdle(bridge) await store.waitForWritesForTesting() let kept = try fixture.positions(scope: "tenant-b", prefixOf: tokens) - #expect(kept.positions == [2_048, 4_096, 6_144], "the demanded fork and deepest serve different continuations") + // `CBv2SchedulerConfig.demandedLatestPromptEndMarginTokens`; the + // cut saves at least the 1,024-token floor over the 6,144 chunk end. + let promptEndMargin = 64 + let latest = (tokens.count - 1 - promptEndMargin) / PrefixCachePolicy.blockSize * PrefixCachePolicy.blockSize + try #require(latest - 6_144 >= 1_024, "fixture geometry: donor \(tokens.count) tokens") + #expect(kept.positions == [2_048, 4_096, latest], "the demanded fork and deepest serve different continuations") #expect(store.stats().filesWritten == 3) print("[qwen35-retention-adjacent] prompt=\(tokens.count) hint=5120 positions=\(kept.positions) " + "tensorBytes=\(kept.bytes) bytesWritten=\(store.stats().bytesWritten) mtp=\(fixture.mtpActive)") diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Vision/QwenVLMTargetExtractionTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Vision/QwenVLMTargetExtractionTests.swift index 6f3e2798a5..d573705242 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Vision/QwenVLMTargetExtractionTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Vision/QwenVLMTargetExtractionTests.swift @@ -334,6 +334,38 @@ struct QwenVLMTargetExtractionTests { await store.closeAndWait() } + @Test("end-of-prompt boundaries require the actual dense paged SSD store and keep its floor") + func endOfPromptBoundaryRequiresDensePagedSSD() async throws { + let config = try EngineV2VLMTextExtraction.decodeQwenConfiguration( + configData: qwenTargetFixtureJSON(fullAttentionInterval: 2)) + let dense = Qwen35Model(config) + let moe = Qwen35MoEModel(config) + let fixture = try SSDHybridCheckpointTestFixture(paged: true) + defer { fixture.remove() } + let store = try fixture.makeStore() + defer { store.close() } + #expect(EngineV2Factory.demandedLatestCheckpointMinimumTokens( + model: dense, backend: .paged, store: store) == store.config.minEffectiveTokens) + // The MoE target's prefill depends on its partition. + #expect(EngineV2Factory.demandedLatestCheckpointMinimumTokens( + model: moe, backend: .paged, store: store) == nil) + #expect(EngineV2Factory.demandedLatestCheckpointMinimumTokens( + model: dense, backend: .contiguous, store: store) == nil) + #expect(EngineV2Factory.demandedLatestCheckpointMinimumTokens( + model: dense, backend: .paged, store: nil) == nil) + // The capture-boundary partition stays GLM's. + #expect(EngineV2Factory.demandedCaptureBoundaryMinimumTokens(model: dense, store: store) == nil) + await store.closeAndWait() + + let contiguousFixture = try SSDHybridCheckpointTestFixture(paged: false) + defer { contiguousFixture.remove() } + let contiguousStore = try contiguousFixture.makeStore() + defer { contiguousStore.close() } + #expect(EngineV2Factory.demandedLatestCheckpointMinimumTokens( + model: dense, backend: .paged, store: contiguousStore) == nil) + await contiguousStore.closeAndWait() + } + @Test("benchmark resolution uses the same extracted Qwen target") func benchmarkServingModelUsesQwenExtraction() throws { let configData = qwenTargetFixtureJSON() From 41dd24f49f919c7bbfd768712e519788fc6894ed Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:24:44 -0700 Subject: [PATCH 0005/1441] GPT-OSS: match client stop sequences in the Harmony final message only The engine matched `stop` against every generated character, including the private Harmony analysis. A sequence that appeared while gpt-oss reasoned ended the request before any answer: finish_reason "stop", reasoning only, empty content. On provider 0.10.4 with production gpt-oss-20b weights, stop ["."] did this to 36/36 requests and ["\n\n"] to 14/36 (0/36 without a stop); each cut reasoning is an exact prefix of its same-seed no-stop twin, which went on to answer. ModelEOSPolicy.stopStringScope gives GPT-OSS the Harmony final-channel scope (<|channel|>final ... <|message|> up to <|end|>/<|return|>/<|call|>/<|start|>). It travels with the EOS policy: EngineV2SlotFactory -> makeBridge -> EngineV2Bridge -> CBv2Request.stopStringScope, and the matched-sequence replay uses the same scope. Other models keep whole-output matching. Bumps libs/mlx-swift-lm to 38b90ed1 (fix/harmony-final-stop-scope), which adds the scope to StopHoldback. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gptoss-stop-in-final-channel.md | 9 +++++ docs/architecture/inference.md | 2 +- libs/mlx-swift-lm | 2 +- .../Bridge/EngineV2Bridge+StopSequence.swift | 17 ++++++++-- .../Bridge/EngineV2Bridge+Submission.swift | 3 +- .../Bridge/EngineV2Bridge+Translation.swift | 6 ++-- .../Engine/Bridge/EngineV2Bridge.swift | 5 +++ .../Engine/Factory/EngineV2Config.swift | 2 ++ .../Engine/Factory/EngineV2SlotFactory.swift | 1 + .../Prompting/ChatTemplateFixes.swift | 6 ++++ .../GPTOSSHarmonyTemplateFixes.swift | 9 +++++ .../Inference/Prompting/ModelEOSPolicy.swift | 10 ++++++ .../Engine/EngineV2BridgeTests.swift | 33 +++++++++++++++++++ .../MultiModelBatchSchedulerEngineTests.swift | 11 +++++++ 14 files changed, 109 insertions(+), 7 deletions(-) create mode 100644 changelog.d/gptoss-stop-in-final-channel.md diff --git a/changelog.d/gptoss-stop-in-final-channel.md b/changelog.d/gptoss-stop-in-final-channel.md new file mode 100644 index 0000000000..da591a38d6 --- /dev/null +++ b/changelog.d/gptoss-stop-in-final-channel.md @@ -0,0 +1,9 @@ +### GPT-OSS stop sequences apply to the answer only + +- A client `stop` sequence on GPT-OSS models such as `gpt-oss-20b` now + matches only the Harmony `final` message, the text returned as `content`. + It used to match the private analysis too, so a sequence that appeared + while the model reasoned (for example `"\n\n"` or `"."`) ended the request + before any answer: `finish_reason` `stop`, reasoning only, empty content. + Tool-call arguments are never cut either. Other models keep whole-output + matching. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 5e51121117..4f24a26f5d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1843,7 +1843,7 @@ disabled for this hybrid model. | `logit_bias` | `logitBias` — string keys parsed to non-negative `Int`; invalid keys dropped and counted | `[:]` | | `logprobs` + `top_logprobs` | `topLogprobs = logprobs ? min(20, max(1, top_logprobs ?? 0)) : 0` | `0` | | `max_tokens` | `maxTokens = max_tokens ?? 4096` | 4096 | -| `stop` | `stopStrings`, matched on held-back detokenised text (`EngineV2Bridge+StopSequence.swift`) | `[]` | +| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match; the reported sequence replays the same scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | | `min_p`, `priority` | **Ignored**: always `0` | — | | `n`, `best_of` | **Not represented**: one alternative | — | diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index aee6ebb683..38b90ed185 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit aee6ebb6835c62feda80000c83f81f2788cc9822 +Subproject commit 38b90ed185d883bd5f54c355b8eab9df5fd0919a diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift index 5ddaf77813..6fb0f4c4c7 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift @@ -1,4 +1,5 @@ import Foundation +import MLXLMCommon extension EngineV2Bridge { func matchedStopSequence( @@ -10,13 +11,25 @@ extension EngineV2Bridge { tokenIds: generatedTokens, skipSpecialTokens: false ) - return Self.matchedStopSequence(candidates: candidates, generatedText: generatedText) + return Self.matchedStopSequence( + candidates: candidates, generatedText: generatedText, scope: stopStringScope) } + /// The candidate that ended generation. A scoped model matched stops only + /// inside its scope, so a candidate seen elsewhere (Harmony analysis) did + /// not stop it. static func matchedStopSequence( candidates: [String], - generatedText: String + generatedText: String, + scope: CBv2StopStringScope? = nil ) -> String? { + if let scope { + let holdback = StopHoldback(stopStrings: candidates, scope: scope) + let scan = holdback.ingest(generatedText) + guard scan.stopped else { return nil } + let tail = generatedText.unicodeScalars.dropFirst(scan.text.unicodeScalars.count) + return candidates.first { !$0.isEmpty && tail.starts(with: $0.unicodeScalars) } + } let generatedScalars = Array(generatedText.unicodeScalars) var best: (position: Int, candidateIndex: Int, value: String)? for (candidateIndex, candidate) in candidates.enumerated() where !candidate.isEmpty { diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift index 39116e8c83..1abc162e03 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift @@ -246,7 +246,8 @@ extension EngineV2Bridge { samplingDefaults: samplingDefaults, // The same coordinator hint that gates the write also tells the // engine which fork boundary is worth staging. - prefixCheckpointTargetTokens: donationDemand?.repeatedPrefixTokens + prefixCheckpointTargetTokens: donationDemand?.repeatedPrefixTokens, + stopStringScope: stopStringScope ) cbv2Request.positionState = positionState ?? multimodal?.positionState cbv2Request.hybridPrefixIdentity = hybridPrefixIdentity diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift index 3a33336bb5..da8a5bd87c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift @@ -65,7 +65,8 @@ enum EngineV2Translation { multimodal: CBv2MultimodalInput? = nil, tokenConstraint: (any CBv2TokenConstraint)? = nil, samplingDefaults: EngineV2SamplingDefaults = .legacy, - prefixCheckpointTargetTokens: Int? = nil + prefixCheckpointTargetTokens: Int? = nil, + stopStringScope: CBv2StopStringScope? = nil ) -> CBv2Request { CBv2Request( id: id, @@ -79,7 +80,8 @@ enum EngineV2Translation { prefixCacheEnabled: cacheEnabled, multimodal: multimodal, tokenConstraint: tokenConstraint, - prefixCheckpointTargetTokens: cacheEnabled ? prefixCheckpointTargetTokens : nil + prefixCheckpointTargetTokens: cacheEnabled ? prefixCheckpointTargetTokens : nil, + stopStringScope: stopStringScope ) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift index eda037ee03..1d2eae904b 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift @@ -106,6 +106,9 @@ public actor EngineV2Bridge { /// tokens) — `buildStopTokenIds` semantics, computed ONCE at bridge /// construction so B=1 and batched behavior stay identical. let stopTokenIds: Set + /// Where client stop strings apply (`ModelEOSPolicy.stopStringScope`); + /// nil matches the whole generated text. + let stopStringScope: CBv2StopStringScope? /// Artifact sampling defaults resolved once at construction /// (`EngineV2SamplingDefaults.resolve`); `.legacy` for every family /// that has not been admitted. @@ -368,6 +371,7 @@ public actor EngineV2Bridge { tokenizer: TokenizerHandle, eosTokenIds: Set, extraEOSTokens: [String] = [], + stopStringScope: CBv2StopStringScope? = nil, samplingDefaults: EngineV2SamplingDefaults = .legacy, defaultMaxTokens: Int = 4096, maxConcurrentRequests: Int = 4, @@ -428,6 +432,7 @@ public actor EngineV2Bridge { extraEOSTokens: extraEOSTokens, convertTokenToId: { [inner = tokenizer.inner] in inner.convertTokenToId($0) } ) + self.stopStringScope = stopStringScope self.samplingDefaults = samplingDefaults self.defaultMaxTokens = defaultMaxTokens self.maxConcurrentRequests = maxConcurrentRequests diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Config.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Config.swift index e587d969fc..4641bbfd99 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Config.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Config.swift @@ -154,6 +154,7 @@ public enum EngineV2Factory { tokenizer: TokenizerHandle, eosTokenIds: Set, extraEOSTokens: [String] = [], + stopStringScope: CBv2StopStringScope? = nil, samplingDefaults: EngineV2SamplingDefaults = .legacy, defaultMaxTokens: Int = 4096, maxConcurrentRequests: Int = 4, @@ -204,6 +205,7 @@ public enum EngineV2Factory { tokenizer: tokenizer, eosTokenIds: eosTokenIds, extraEOSTokens: extraEOSTokens, + stopStringScope: stopStringScope, samplingDefaults: samplingDefaults, defaultMaxTokens: defaultMaxTokens, maxConcurrentRequests: maxConcurrentRequests, diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift index ab3f5e7e95..faec07ae75 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift @@ -571,6 +571,7 @@ enum EngineV2SlotFactory { tokenizer: tokenizer, eosTokenIds: eosTokenIds, extraEOSTokens: snapshot.extraEOSTokens, + stopStringScope: ModelEOSPolicy.stopStringScope(modelId: modelId, modelType: modelType), samplingDefaults: samplingDefaults, defaultMaxTokens: sizing.defaultMaxTokens, maxConcurrentRequests: effectiveMaxConcurrentRequests, diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatTemplateFixes.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatTemplateFixes.swift index a7fbe46dd6..66ef982671 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatTemplateFixes.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatTemplateFixes.swift @@ -5,6 +5,7 @@ // after the model family so future fixes do not bleed across templates. import Foundation +import MLXLMCommon import MLXLMServer struct ChatTemplateFixContext: Sendable { @@ -132,6 +133,11 @@ enum ChatTemplateFixes { return ids } + static func stopStringScope(context: ChatTemplateFixContext) -> CBv2StopStringScope? { + GPTOSSHarmonyTemplateFix.applies(to: context) + ? GPTOSSHarmonyTemplateFix.finalChannelStopScope : nil + } + static func validateGenericToolHistory( _ messages: [[String: any Sendable]] ) throws { diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/GPTOSSHarmonyTemplateFixes.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/GPTOSSHarmonyTemplateFixes.swift index ed312169f1..de294d465c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/GPTOSSHarmonyTemplateFixes.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/GPTOSSHarmonyTemplateFixes.swift @@ -5,6 +5,7 @@ // templates without changing other model families. import Foundation +import MLXLMCommon enum GPTOSSHarmonyTemplateFix { static func applies(to context: ChatTemplateFixContext) -> Bool { @@ -37,6 +38,14 @@ enum GPTOSSHarmonyTemplateFix { Set(["<|return|>", "<|endoftext|>", "<|call|>"].compactMap(tokenToId)) } + /// Client stop strings apply to the final channel, the text clients + /// receive as `content`. Matching them in analysis ended requests before + /// any answer existed (finish_reason "stop", reasoning only); tool-call + /// arguments are not answer text either. + static let finalChannelStopScope = CBv2StopStringScope( + opener: "<|channel|>final", openerEnd: "<|message|>", + closers: ["<|end|>", "<|return|>", "<|call|>", "<|start|>"]) + private static func isHarmonyModelHint(_ value: String?) -> Bool { guard let value else { return false } let normalized = value.lowercased() diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ModelEOSPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ModelEOSPolicy.swift index 707593cce7..f7c5d80cf0 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ModelEOSPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ModelEOSPolicy.swift @@ -6,6 +6,7 @@ // slot construction has one scheduler-independent stop-token policy. import Foundation +import MLXLMCommon public enum ModelEOSPolicy { /// Return model-specific EOS tokens at the engine boundary. Most models @@ -24,4 +25,13 @@ public enum ModelEOSPolicy { tokenToId: tokenToId ) } + + /// Where client stop strings apply; nil keeps whole-output matching. + public static func stopStringScope( + modelId: String, + modelType: String? = nil + ) -> CBv2StopStringScope? { + ChatTemplateFixes.stopStringScope( + context: ChatTemplateFixContext(modelId: modelId, modelType: modelType)) + } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift index 5cb3ce2e73..b320bb793b 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift @@ -804,6 +804,39 @@ struct EngineV2MatchedStopSequenceTests { ) == nil) } + @Test("a scoped model reports only the stop that ended its answer") + func scopedMatchedSequence() { + let scope = ModelEOSPolicy.stopStringScope(modelId: "gpt-oss-20b") + let analysis = "<|channel|>analysis<|message|>The answer: Canberra. Done.<|end|>" + #expect(EngineV2Bridge.matchedStopSequence( + candidates: ["."], + generatedText: analysis + "<|start|>assistant<|channel|>final<|message|>It is Canberra", + scope: scope + ) == nil, "a period in the analysis did not stop the request") + #expect(EngineV2Bridge.matchedStopSequence( + candidates: ["!", "."], + generatedText: analysis + "<|start|>assistant<|channel|>final<|message|>It is Canberra. More", + scope: scope + ) == ".") + } + + @Test("GPT-OSS requests carry the bridge's stop-string scope") + func translationCarriesStopScope() { + let scope = ModelEOSPolicy.stopStringScope(modelId: "gpt-oss-20b") + let request = ChatCompletionRequest( + model: "gpt-oss-20b", messages: [ChatMessage(role: "user", content: "hi")], + stop: .multiple(["\n\n"])) + let scoped = EngineV2Translation.cbv2Request( + id: CBv2RequestID(1), promptTokens: [1], request: request, defaultMaxTokens: 16, + stopTokenIds: [], stopStringScope: scope) + #expect(scoped.stopStrings == ["\n\n"]) + #expect(scoped.stopStringScope == scope) + let unscoped = EngineV2Translation.cbv2Request( + id: CBv2RequestID(2), promptTokens: [1], request: request, defaultMaxTokens: 16, + stopTokenIds: []) + #expect(unscoped.stopStringScope == nil) + } + @Test("compares Unicode scalars exactly rather than canonically") func unicodeScalarExactness() { #expect(EngineV2Bridge.matchedStopSequence( diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/MultiModelBatchSchedulerEngineTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/MultiModelBatchSchedulerEngineTests.swift index 50875deaf8..f30f4074cd 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/MultiModelBatchSchedulerEngineTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/MultiModelBatchSchedulerEngineTests.swift @@ -622,6 +622,17 @@ func harmonyEOSUsesModelTypeForAliasedModels() { #expect(ids == [199999, 200002, 200012]) } +@Test("GPT-OSS client stop strings apply to the Harmony final channel only") +func gptOssStopStringsAreScopedToTheFinalChannel() { + let scope = ModelEOSPolicy.stopStringScope(modelId: "gpt-oss-20b") + #expect(scope == CBv2StopStringScope( + opener: "<|channel|>final", openerEnd: "<|message|>", + closers: ["<|end|>", "<|return|>", "<|call|>", "<|start|>"])) + #expect(ModelEOSPolicy.stopStringScope(modelId: "local-alias", modelType: "gpt_oss") == scope) + #expect(ModelEOSPolicy.stopStringScope(modelId: "gemma-4-26b-qat-4bit") == nil) + #expect(ModelEOSPolicy.stopStringScope(modelId: "qwen3.6-35b-a3b-vl-mtp-mxfp8") == nil) +} + @Test("non-Harmony EOS set is unchanged") func nonHarmonyEOSIsUnchanged() { let ids = ModelEOSPolicy.effectiveEOSTokenIds( From ac39dada16ca0e37a8f38ae973ea27af1c1999ca Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:06:24 -0700 Subject: [PATCH 0006/1441] Gemma 4 and models: client stop sequences skip reasoning and tool calls With reasoning on, a client stop string matched the model's private reasoning too, so one that appeared while the model reasoned (for example "." or "\n\n") ended the request before any answer: finish_reason "stop", reasoning only, empty content. GPT-OSS got an answer-channel scope in the previous commit; Gemma 4 and parsers need the opposite shape. ReasoningStopScope picks the scope per request from its reasoning parser: - gemma4: exclude <|channel>... and <|tool_call>...; - qwen3/deepseek_r1: exclude ... and ... , starting inside when the prompt probe left a think block open (Qwen's "\n" prefill); - Harmony and no parser keep the model's scope. submitTokenized(stopStringScope:) overrides the bridge's model scope, the text, media and MiMo-media paths pass it (media now probes its prompt before submit), and the reported stop_sequence replays the request's scope. Pins mlx-swift-lm fix/reasoning-stop-scope-exclude (95e1d2b9). Recorded on provider 0.10.4 with gemma-4-26b-qat-4bit, reasoning on, 36 prompts at temperature 0: stop ["."] and ["\n\n"] each gave 36/36 empty answers, all proven cut inside the thought. With this change: 0/36 for every stop set, no answer holds a stop, and each "."/"\n\n" answer equals the full answer cut at its first stop with identical reasoning (36/36 each). Co-Authored-By: Claude Opus 5.5 --- .../reasoning-stop-outside-reasoning.md | 12 +++ docs/architecture/inference.md | 2 +- libs/mlx-swift-lm | 2 +- .../Engine/Bridge/EngineV2Bridge+Events.swift | 6 +- .../Bridge/EngineV2Bridge+StopSequence.swift | 11 +-- .../Bridge/EngineV2Bridge+Submission.swift | 8 +- .../Engine/Bridge/EngineV2Bridge.swift | 4 +- .../MultiModelBatchSchedulerEngine.swift | 32 +++++--- .../Prompting/ReasoningStopScope.swift | 39 +++++++++ .../Engine/EngineV2BridgeTests.swift | 47 ++++++++++- .../Prompting/ReasoningStopScopeTests.swift | 82 +++++++++++++++++++ 11 files changed, 220 insertions(+), 25 deletions(-) create mode 100644 changelog.d/reasoning-stop-outside-reasoning.md create mode 100644 provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift diff --git a/changelog.d/reasoning-stop-outside-reasoning.md b/changelog.d/reasoning-stop-outside-reasoning.md new file mode 100644 index 0000000000..f4ea63b319 --- /dev/null +++ b/changelog.d/reasoning-stop-outside-reasoning.md @@ -0,0 +1,12 @@ +### Stop sequences no longer match Gemma 4 or `` reasoning + +- A client `stop` sequence on Gemma 4 models such as `gemma-4-26b-qat-4bit`, + and on models that reason in `` blocks (Qwen 3.5, 3.6 and 3.8, + among others), now matches only the text returned as `content`. With + reasoning on, it used to match the reasoning too, so a sequence that + appeared while the model reasoned (for example `"."` or `"\n\n"`) ended the + request before any answer: `finish_reason` `stop`, reasoning only, empty + content. +- Tool-call frames are never cut either, and whitespace before the answer's + first character (the blank line after ``) cannot complete a stop + sequence on its own. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 4f24a26f5d..b6ff026bcf 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1843,7 +1843,7 @@ disabled for this hybrid model. | `logit_bias` | `logitBias` — string keys parsed to non-negative `Int`; invalid keys dropped and counted | `[:]` | | `logprobs` + `top_logprobs` | `topLogprobs = logprobs ? min(20, max(1, top_logprobs ?? 0)) : 0` | `0` | | `max_tokens` | `maxTokens = max_tokens ?? 4096` | 4096 | -| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match; the reported sequence replays the same scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | +| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match. Gemma 4 and `` parsers exclude their reasoning and tool-call spans per request instead, starting inside reasoning when the prompt opened a think block (`ReasoningStopScope`). The reported sequence replays the request's scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | | `min_p`, `priority` | **Ignored**: always `0` | — | | `n`, `best_of` | **Not represented**: one alternative | — | diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 38b90ed185..95e1d2b9c3 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 38b90ed185d883bd5f54c355b8eab9df5fd0919a +Subproject commit 95e1d2b9c39849cad31fcf0a53b916ea6c7fc474 diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift index e2286bd6ab..a23470e478 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Events.swift @@ -12,6 +12,7 @@ extension EngineV2Bridge { continuation: AsyncStream.Continuation, holdsSharedReservation: Bool, stopSequences: [String] = [], + stopStringScope: CBv2StopStringScope? = nil, logprobsChannel: EngineV2LogprobsChannel? = nil, usageSignal: EngineV2RequestUsageSignal? = nil, prefixCacheReceiptID: CBv2RequestID? = nil, @@ -28,6 +29,7 @@ extension EngineV2Bridge { id: id, events: events, continuation: continuation, holdsSharedReservation: holdsSharedReservation, stopSequences: stopSequences, + stopStringScope: stopStringScope, logprobsChannel: logprobsChannel, usageSignal: usageSignal, prefixCacheReceiptID: prefixCacheReceiptID, @@ -59,6 +61,7 @@ extension EngineV2Bridge { continuation: AsyncStream.Continuation, holdsSharedReservation: Bool, stopSequences: [String] = [], + stopStringScope: CBv2StopStringScope? = nil, logprobsChannel: EngineV2LogprobsChannel? = nil, usageSignal: EngineV2RequestUsageSignal? = nil, prefixCacheReceiptID: CBv2RequestID? = nil, @@ -144,7 +147,8 @@ extension EngineV2Bridge { if reason == .stop || reason == .length { usageSignal?.record(matchedStopSequence: matchedStopSequence( candidates: stopSequences, - generatedTokens: generatedTokens + generatedTokens: generatedTokens, + scope: stopStringScope )) } // Out-of-band usage detail (logprobs-channel pattern): the diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift index 6fb0f4c4c7..fd94acb8a4 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift @@ -4,7 +4,8 @@ import MLXLMCommon extension EngineV2Bridge { func matchedStopSequence( candidates: [String], - generatedTokens: [Int] + generatedTokens: [Int], + scope: CBv2StopStringScope? ) -> String? { guard !candidates.isEmpty, !generatedTokens.isEmpty else { return nil } let generatedText = tokenizer.inner.decode( @@ -12,12 +13,12 @@ extension EngineV2Bridge { skipSpecialTokens: false ) return Self.matchedStopSequence( - candidates: candidates, generatedText: generatedText, scope: stopStringScope) + candidates: candidates, generatedText: generatedText, scope: scope) } - /// The candidate that ended generation. A scoped model matched stops only - /// inside its scope, so a candidate seen elsewhere (Harmony analysis) did - /// not stop it. + /// The candidate that ended generation. A scoped request matched stops + /// only inside its scope, so a candidate seen elsewhere (Harmony analysis, + /// reasoning) did not stop it. static func matchedStopSequence( candidates: [String], generatedText: String, diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift index 1abc162e03..87810208eb 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift @@ -58,6 +58,7 @@ extension EngineV2Bridge { hybridPrefixIdentity: CBv2HybridPrefixIdentity? = nil, mediaKind: EngineV2MediaKind? = nil, tokenConstraint: (any CBv2TokenConstraint)? = nil, + stopStringScope: CBv2StopStringScope? = nil, donationDemand: SSDCheckpointDonationDemand? = nil, promptWork: PromptWork? = nil, measurementPurpose: EngineMeasurementPurpose = .serving @@ -76,6 +77,7 @@ extension EngineV2Bridge { hybridPrefixIdentity: hybridPrefixIdentity, mediaKind: mediaKind, tokenConstraint: tokenConstraint, + stopStringScope: stopStringScope, donationDemand: donationDemand, firstContentDeadline: nil, promptWork: promptWork, measurementPurpose: measurementPurpose) @@ -124,6 +126,9 @@ extension EngineV2Bridge { hybridPrefixIdentity: CBv2HybridPrefixIdentity? = nil, mediaKind: EngineV2MediaKind? = nil, tokenConstraint: (any CBv2TokenConstraint)? = nil, + /// Where this request's stop strings apply (`ReasoningStopScope`); nil + /// keeps the model's scope (`ModelEOSPolicy.stopStringScope`). + stopStringScope: CBv2StopStringScope? = nil, /// Coordinator repeat-demand hint for the complete-checkpoint write /// gate; nil keeps the legacy write-every-checkpoint behaviour. donationDemand: SSDCheckpointDonationDemand? = nil, @@ -247,7 +252,7 @@ extension EngineV2Bridge { // The same coordinator hint that gates the write also tells the // engine which fork boundary is worth staging. prefixCheckpointTargetTokens: donationDemand?.repeatedPrefixTokens, - stopStringScope: stopStringScope + stopStringScope: stopStringScope ?? self.stopStringScope ) cbv2Request.positionState = positionState ?? multimodal?.positionState cbv2Request.hybridPrefixIdentity = hybridPrefixIdentity @@ -936,6 +941,7 @@ extension EngineV2Bridge { id: id, events: events, continuation: continuation, holdsSharedReservation: sharedKVReserved, stopSequences: cbv2Request.stopStrings, + stopStringScope: cbv2Request.stopStringScope, logprobsChannel: logprobsChannel, usageSignal: usageSignal, prefixCacheReceiptID: prefixCacheReceiptID, diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift index 1d2eae904b..7aad822919 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift @@ -106,8 +106,8 @@ public actor EngineV2Bridge { /// tokens) — `buildStopTokenIds` semantics, computed ONCE at bridge /// construction so B=1 and batched behavior stay identical. let stopTokenIds: Set - /// Where client stop strings apply (`ModelEOSPolicy.stopStringScope`); - /// nil matches the whole generated text. + /// Where client stop strings apply (`ModelEOSPolicy.stopStringScope`) + /// unless a request brings its own; nil matches the whole generated text. let stopStringScope: CBv2StopStringScope? /// Artifact sampling defaults resolved once at construction /// (`EngineV2SamplingDefaults.resolve`); `.legacy` for every family diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index 1207bdc816..30f58e376d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -711,6 +711,17 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { // failures) stay correct as written. await mediaGate.release(requestId: mediaReqId) try checkFirstContentDeadline() + // Initialize the think parser from the rendered media + // prompt: reasoning for an open block, content for a + // pre-closed block (thinking-disabled media). The stop + // scope starts in the same state. + let reasoningPrefix = ReasoningPromptProbe.streamingPrefix( + reasoningParser: visionRequest.reasoningParser, + stream: visionRequest.stream, + promptTokens: visionPrepared.promptTokens, + modelType: modelType, + decodeTail: { tokenizer.inner.decode(tokenIds: $0, skipSpecialTokens: false) } + ) ?? contentSeed(parser: visionRequest.reasoningParser, stream: visionRequest.stream) // Qualified native media shares text's request-owned // parser. Other VLMs retain their legacy media behavior. let upstream = try await bridge.submitTokenized( @@ -733,6 +744,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { multimodal: visionPrepared.multimodalInput(), hybridPrefixIdentity: mediaPrefixIdentity, mediaKind: visionPrepared.mediaKind, + stopStringScope: ReasoningStopScope.scope( + reasoningParser: visionRequest.reasoningParser, + reasoningPrefix: reasoningPrefix), donationDemand: donationDemand, firstContentDeadline: firstContentDeadline, profile: profile, @@ -747,18 +761,6 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { await bridge.cancel(requestId: visionRequestId) throw error } - // Initialize the think parser from the rendered media - // prompt: reasoning for an open block, content for a - // pre-closed block (thinking-disabled media). - try checkFirstContentDeadline() - let reasoningPrefix = ReasoningPromptProbe.streamingPrefix( - reasoningParser: visionRequest.reasoningParser, - stream: visionRequest.stream, - promptTokens: visionPrepared.promptTokens, - modelType: modelType, - decodeTail: { tokenizer.inner.decode(tokenIds: $0, skipSpecialTokens: false) } - ) ?? contentSeed(parser: visionRequest.reasoningParser, stream: visionRequest.stream) - try checkFirstContentDeadline() return try await makeDeadlineCheckedEventStream( upstream: upstream, cancelUpstream: { await bridge.cancel(requestId: visionRequestId) }, @@ -970,6 +972,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { logprobsChannel: engineV2Logprobs?.channel, usageSignal: requestUsage, tokenConstraint: tokenConstraint, + stopStringScope: ReasoningStopScope.scope( + reasoningParser: request.reasoningParser, reasoningPrefix: reasoningPrefix), donationDemand: donationDemand, firstContentDeadline: firstContentDeadline, profile: profile, @@ -1099,7 +1103,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { request:Self.translate(openAIRequest:request,defaultMaxTokens:maximumOutput, logitBias:engineV2Sampling?.logitBias,seed:engineV2Sampling?.seed), requestId:id,cacheScope:cacheScope,cacheEnabled:false,usageSignal:requestUsage, - multimodal:native.request.multimodal,firstContentDeadline:firstContentDeadline,profile:profile, + multimodal:native.request.multimodal, + stopStringScope:ReasoningStopScope.scope(reasoningParser:request.reasoningParser,reasoningPrefix:nil), + firstContentDeadline:firstContentDeadline,profile:profile, measurementPurpose:measurementPurpose) // Install the ONE existing router/forwarder before any post-submit // cancellation veto. Its protected mode drains actual terminal/error. diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift new file mode 100644 index 0000000000..ee0eddee8d --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift @@ -0,0 +1,39 @@ +// Copyright © 2026 Eigen Labs. +// +// Client stop strings end the answer, never the reasoning before it. Matched +// against all generated text, a stop the model happened to write while it +// reasoned ended the request before any answer: finish_reason "stop", +// reasoning only, empty content. Each scope mirrors the request's reasoning +// parser, so text it returns as reasoning, and tool-call frames, never match. + +import Foundation +import MLXLMCommon +import MLXLMServer + +enum ReasoningStopScope { + static let think = CBv2StopStringScope.Span(opener: "", closers: [""]) + static let thinkToolCall = CBv2StopStringScope.Span( + opener: "", closers: [""]) + static let gemmaThought = CBv2StopStringScope.Span(opener: "<|channel>", closers: [""]) + static let gemmaToolCall = CBv2StopStringScope.Span( + opener: "<|tool_call>", closers: [""]) + + /// The scope for one request. `reasoningPrefix` is the prompt's + /// `ReasoningPromptProbe` state: an open think block means output starts + /// inside reasoning. nil keeps the model's scope (GPT-OSS's Harmony final + /// channel) or, without a reasoning parser, whole-output matching. + static func scope( + reasoningParser: ReasoningParserFormat?, reasoningPrefix: String? + ) -> CBv2StopStringScope? { + switch reasoningParser { + case .qwen3?, .deepseekR1?: + return CBv2StopStringScope( + excluding: [think, thinkToolCall], + startingInside: reasoningPrefix == ReasoningPromptProbe.thinkOpen) + case .gemma4?: + return CBv2StopStringScope(excluding: [gemmaThought, gemmaToolCall]) + default: + return nil + } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift index b320bb793b..55d565c59e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift @@ -143,6 +143,8 @@ private struct StubTokenizer: MLXLMCommon.Tokenizer { var tokenTable: [String: Int] = ["": 2, "<|eot|>": 7] var eosTokenString: String? = "" var failTemplate = false + /// Text for chosen ids; every other id decodes as "t". + var decodeTable: [Int: String] = [:] func encode(text: String, addSpecialTokens: Bool) -> [Int] { Array(repeating: 0, count: text.count) @@ -150,7 +152,7 @@ private struct StubTokenizer: MLXLMCommon.Tokenizer { /// Deterministic per-id text ("t") so logprob-entry conversion /// (token string + UTF-8 bytes) is assertable. func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { - tokenIds.map { "t\($0)" }.joined() + tokenIds.map { decodeTable[$0] ?? "t\($0)" }.joined() } func convertTokenToId(_ token: String) -> Int? { tokenTable[token] } func convertIdToToken(_ id: Int) -> String? { nil } @@ -435,6 +437,7 @@ private func makeBridge( modelId: String = "gemma-4-27b-it", eosTokenIds: Set = [2], extraEOSTokens: [String] = [], + stopStringScope: CBv2StopStringScope? = nil, defaultMaxTokens: Int = 4096, kvBytesPerToken: Int = 0, fixedRequestBytes: Int = 0, @@ -453,6 +456,7 @@ private func makeBridge( tokenizer: TokenizerHandle(tokenizer), eosTokenIds: eosTokenIds, extraEOSTokens: extraEOSTokens, + stopStringScope: stopStringScope, defaultMaxTokens: defaultMaxTokens, maxConcurrentRequests: 4, kvBytesPerToken: kvBytesPerToken, @@ -837,6 +841,47 @@ struct EngineV2MatchedStopSequenceTests { #expect(unscoped.stopStringScope == nil) } + @Test("a request's stop scope reaches the engine and the reported sequence") + func requestScopeReachesEngineAndReport() async { + // Gemma 4 with reasoning on: a period in the thought, "!" in the answer. + let tokenizer = StubTokenizer(decodeTable: [ + 20: "<|channel>", 21: "thought\nIt is A.", 22: "", 23: "A!", + ]) + let engine = ScriptedCBv2Engine(script: .stream([ + .delta(text: "", tokens: [20, 21, 22, 23], logprobs: nil), + .finished(reason: .stop, usage: CBv2Usage(promptTokens: 5, completionTokens: 4)), + ])) + let bridge = makeBridge(engine: engine, tokenizer: tokenizer) + let scope = ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil) + let signal = EngineV2RequestUsageSignal() + _ = await record(await bridge.submitTokenized( + promptTokens: [1, 2, 3], + request: makeRequest(stop: .multiple([".", "!"])), + usageSignal: signal, + stopStringScope: scope + )) + #expect(engine.submitted.first?.stopStringScope == scope) + #expect(signal.matchedStopSequence == "!", "the thought's period did not stop it") + } + + @Test("a request's scope replaces the model's, which applies otherwise") + func modelScopeIsTheDefault() async { + let harmony = ModelEOSPolicy.stopStringScope(modelId: "gpt-oss-20b") + let think = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "") + for (modelScope, requestScope, expected) in [ + (harmony, nil, harmony), (nil, nil, nil), (harmony, think, think), + ] { + let engine = ScriptedCBv2Engine(script: .stream([ + .finished(reason: .stop, usage: CBv2Usage(promptTokens: 5, completionTokens: 0)), + ])) + let bridge = makeBridge(engine: engine, stopStringScope: modelScope) + _ = await record(await bridge.submitTokenized( + promptTokens: [1, 2, 3], request: makeRequest(stop: .single(".")), + stopStringScope: requestScope)) + #expect(engine.submitted.first?.stopStringScope == expected) + } + } + @Test("compares Unicode scalars exactly rather than canonically") func unicodeScalarExactness() { #expect(EngineV2Bridge.matchedStopSequence( diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift new file mode 100644 index 0000000000..65e457d5ae --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift @@ -0,0 +1,82 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon +import MLXLMServer +import Testing + +@testable import ProviderCore + +@Suite("Reasoning stop scope") +struct ReasoningStopScopeTests { + private func run(_ output: String, stops: [String], scope: CBv2StopStringScope?) -> String { + let holdback = StopHoldback(stopStrings: stops, scope: scope) + let scan = holdback.ingest(output) + return scan.stopped ? scan.text : scan.text + holdback.flush() + } + + @Test("think parsers exclude reasoning and tool calls from where the prompt left off") + func thinkParsers() { + for parser in [ReasoningParserFormat.qwen3, .deepseekR1] { + #expect( + ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: "") + == CBv2StopStringScope( + excluding: [ReasoningStopScope.think, ReasoningStopScope.thinkToolCall], + startingInside: true)) + for prefix in ["", nil] { + #expect( + ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: prefix) + == CBv2StopStringScope( + excluding: [ReasoningStopScope.think, ReasoningStopScope.thinkToolCall])) + } + } + } + + @Test("Gemma 4 excludes its thought channel and tool calls") + func gemma() { + #expect( + ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil) + == CBv2StopStringScope(excluding: [ + .init(opener: "<|channel>", closers: [""]), + .init(opener: "<|tool_call>", closers: [""]), + ])) + } + + @Test("Harmony keeps the model's scope; no parser keeps whole-output matching") + func otherParsers() { + for parser in [ReasoningParserFormat.harmony, ReasoningParserFormat.none, nil] { + #expect(ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: "") == nil) + } + } + + @Test("a stop in a Qwen thinking prompt's reasoning no longer ends the request") + func qwenThinking() { + // The template prefilled "\n"; the model writes "\n\n" after "". + let output = + "Capital of Australia. Canberra.\n\nKeep it short.\n\n\n" + + "The capital of Australia is Canberra.\n\nIt is in the ACT." + let scope = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "") + #expect(run(output, stops: ["."], scope: nil) == "Capital of Australia") + #expect( + run(output, stops: ["."], scope: scope) + == "Capital of Australia. Canberra.\n\nKeep it short.\n\n\n" + + "The capital of Australia is Canberra") + #expect( + run(output, stops: ["\n\n"], scope: scope) + == "Capital of Australia. Canberra.\n\nKeep it short.\n\n\n" + + "The capital of Australia is Canberra.") + } + + @Test("a stop in a Gemma 4 thought no longer ends the request") + func gemmaThinking() { + let output = + "<|channel>thought\nCapital of Australia. Canberra.\n\nKeep it short." + + "The capital of Australia is Canberra.\n\nIt is in the ACT." + let scope = ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil) + #expect(run(output, stops: ["."], scope: nil) == "<|channel>thought\nCapital of Australia") + #expect( + run(output, stops: ["\n\n"], scope: scope) + == "<|channel>thought\nCapital of Australia. Canberra.\n\nKeep it short." + + "The capital of Australia is Canberra.") + } +} From 5e56f05157f79f934c31487536800a3cbfabb688 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:46:57 -0700 Subject: [PATCH 0007/1441] Stop scope: native block engine stays unscoped; report the stop that matched From the review pass: - The native block engine (diffusion Gemma) builds its stop matcher without a scope, so it still matches the whole output. Its requests now carry no scope either, so the reported stop_sequence is the one that matched instead of nil. - A scoped report could name a candidate that only starts where the matching one does: "\n" for "\nUser:" right after , or a stop reaching into a span. It now names the first candidate that alone stops at the same place. - Pins mlx-swift-lm b5d4c754 (simpler excluded-span release, identical behavior). Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 2 +- libs/mlx-swift-lm | 2 +- .../Bridge/EngineV2Bridge+StopSequence.swift | 11 +++-- .../Bridge/EngineV2Bridge+Submission.swift | 6 ++- .../Engine/EngineV2BridgeTests.swift | 12 +++++ .../NativeBlockRetirementBridgeTests.swift | 49 +++++++++++++++++++ 6 files changed, 75 insertions(+), 7 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index b6ff026bcf..562fc16deb 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1843,7 +1843,7 @@ disabled for this hybrid model. | `logit_bias` | `logitBias` — string keys parsed to non-negative `Int`; invalid keys dropped and counted | `[:]` | | `logprobs` + `top_logprobs` | `topLogprobs = logprobs ? min(20, max(1, top_logprobs ?? 0)) : 0` | `0` | | `max_tokens` | `maxTokens = max_tokens ?? 4096` | 4096 | -| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match. Gemma 4 and `` parsers exclude their reasoning and tool-call spans per request instead, starting inside reasoning when the prompt opened a think block (`ReasoningStopScope`). The reported sequence replays the request's scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | +| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match. Gemma 4 and `` parsers exclude their reasoning and tool-call spans per request instead, starting inside reasoning when the prompt opened a think block (`ReasoningStopScope`). The native block engine (diffusion Gemma) matches the whole output, so its requests carry no scope. The reported sequence replays the request's scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | | `min_p`, `priority` | **Ignored**: always `0` | — | | `n`, `best_of` | **Not represented**: one alternative | — | diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 95e1d2b9c3..b5d4c75495 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 95e1d2b9c39849cad31fcf0a53b916ea6c7fc474 +Subproject commit b5d4c754953c621c7fd27f787e32718d4078c2dc diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift index fd94acb8a4..c038b63c5a 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+StopSequence.swift @@ -25,11 +25,14 @@ extension EngineV2Bridge { scope: CBv2StopStringScope? = nil ) -> String? { if let scope { - let holdback = StopHoldback(stopStrings: candidates, scope: scope) - let scan = holdback.ingest(generatedText) + let scan = StopHoldback(stopStrings: candidates, scope: scope).ingest(generatedText) guard scan.stopped else { return nil } - let tail = generatedText.unicodeScalars.dropFirst(scan.text.unicodeScalars.count) - return candidates.first { !$0.isEmpty && tail.starts(with: $0.unicodeScalars) } + // The first candidate that alone stops at the same place: one that + // merely starts there may not count (whitespace before an answer). + return candidates.first { + !$0.isEmpty + && StopHoldback(stopStrings: [$0], scope: scope).ingest(generatedText) == scan + } } let generatedScalars = Array(generatedText.unicodeScalars) var best: (position: Int, candidateIndex: Int, value: String)? diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift index 87810208eb..6aa9e87851 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift @@ -252,7 +252,11 @@ extension EngineV2Bridge { // The same coordinator hint that gates the write also tells the // engine which fork boundary is worth staging. prefixCheckpointTargetTokens: donationDemand?.repeatedPrefixTokens, - stopStringScope: stopStringScope ?? self.stopStringScope + // The native block engine's decoder matches stops over the whole + // output, so its requests carry no scope and the reported stop + // agrees with the one that matched. + stopStringScope: ownedEngine is CBv2NativeBlockEngine + ? nil : stopStringScope ?? self.stopStringScope ) cbv2Request.positionState = positionState ?? multimodal?.positionState cbv2Request.hybridPrefixIdentity = hybridPrefixIdentity diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift index 55d565c59e..8a39de94a2 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift @@ -841,6 +841,18 @@ struct EngineV2MatchedStopSequenceTests { #expect(unscoped.stopStringScope == nil) } + @Test("a scoped report names the stop that matched, not one that only starts there") + func scopedReportNamesTheMatchingCandidate() { + let inside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "") + #expect(EngineV2Bridge.matchedStopSequence( + candidates: ["\n", "\nUser:"], generatedText: "r\n\nUser: hi", scope: inside + ) == "\nUser:", "a bare newline before the answer does not stop it") + let outside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: nil) + #expect(EngineV2Bridge.matchedStopSequence( + candidates: ["Ar", scope: outside + ) == "A", "a stop never matches into a span") + } + @Test("a request's stop scope reaches the engine and the reported sequence") func requestScopeReachesEngineAndReport() async { // Gemma 4 with reasoning on: a period in the thought, "!" in the answer. diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift index 4aef6707df..fb1087619b 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift @@ -47,6 +47,28 @@ struct NativeBlockRetirementBridgeTests { return .committed(tokens: [64 + index], stopToken: nil, finishReason: index == 2 ? .length : nil) } } + /// Commits one block of output, then stops at the token limit. + private final class TextSession: CBv2NativeBlockSession { + let tokens: [Int] + let cancellation: CBv2NativeBlockCancellation + var index = 0, generatedTokenCount = 0 + var retainedBytes: Int { 64 } + var activeTokenCount: Int { 1 + generatedTokenCount } + init(tokens: [Int], cancellation: CBv2NativeBlockCancellation) { + self.tokens = tokens; self.cancellation = cancellation + } + func cancel() {} + func advanceNative() throws -> CBv2NativeBlockStep { + defer { index += 1 } + if index == 0 { return .prefill(computedTokens: 1, complete: true) } + if cancellation.isCancelled { throw CancellationError() } + if index == 1 { + generatedTokenCount = tokens.count + return .committed(tokens: tokens, stopToken: nil, finishReason: nil) + } + return .committed(tokens: [], stopToken: nil, finishReason: .length) + } + } private struct Result: Sendable { var text = "", error = ""; var cause: InferenceTerminalCause?; var completion = 0 } private func collect(_ stream: AsyncStream) async -> Result { var result = Result() @@ -66,6 +88,33 @@ struct NativeBlockRetirementBridgeTests { try #require(await predicate()) } + /// The native block decoder matches stops over the whole output, so a + /// request's reasoning scope is not sent there and the reported stop is + /// the one that matched. + @Test func nativeBlockRequestsCarryNoStopScope() async throws { + let tokenizer = Tokens() + let output = Array("<|channel>thought\nIt is A.Yes!".utf8).map(Int.init) + let engine = try CBv2NativeBlockEngine(tokenizer: tokenizer, kvBytesCapacity: 300, + shutdownGraceSeconds: 0, loopConfig: .init(stepTimeout: 60, watchdogInterval: 0.01), + reservationForRequest: { _ in 100 }, makeSession: { _, cancellation in + TextSession(tokens: output, cancellation: cancellation) + }) + let budget = GlobalKVCacheBudget(capFraction: 1, activationReserveBytes: 0) { + .init(total: 8 << 30, active: 0, cache: 0, systemAvailable: 1_000) + } + let bridge = EngineV2Bridge(engine: engine, modelId: "native-fixture", tokenizer: TokenizerHandle(tokenizer), + eosTokenIds: [], defaultMaxTokens: 64, kvBytesPerToken: 1, kvBudget: budget) + let request = ChatCompletionRequest(model: "native-fixture", messages: [], temperature: 1, max_tokens: 64, + stop: .multiple([".", "!"])) + let signal = EngineV2RequestUsageSignal() + let result = await collect(await bridge.submitTokenized(promptTokens: [1], request: request, + requestId: "scoped", cacheEnabled: false, usageSignal: signal, + stopStringScope: ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil))) + #expect(result.text == "<|channel>thought\nIt is A" && result.error.isEmpty) + #expect(signal.matchedStopSequence == ".") + await bridge.shutdown() + } + @Test func watchdogReturnsTypedErrorWithoutRefundingBlockedNativeMemory() async throws { try await exercise(cancelConsumer: false) } From a4f27cfd8861dd0fd9aa4f8694d71de5fcf35a7f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:26:25 -0700 Subject: [PATCH 0008/1441] chore(provider): pin mlx-swift-lm 76ff231b (docs for the end-of-prompt boundary) The SDK change adds demandedLatestCheckpointMinimumTokens to the retention doc and shortens its code comments. No code changes. Co-Authored-By: Claude Opus 5.5 --- libs/mlx-swift-lm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 05c7ca7eaa..76ff231bbf 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 05c7ca7eaa65f018eec7154e8683913e9b6ae060 +Subproject commit 76ff231bbf73a7a5e54d07d860d6f629d59fdc92 From 46f7ae9c5d35ca5be5296596c8faec4f02b06cd1 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:04:15 -0700 Subject: [PATCH 0009/1441] Pin the merged mlx-swift-lm (#369) and the MLX stack it builds on libs/mlx-swift-lm moves to main 25bcd63f, the squash merge of Layr-Labs/mlx-swift-lm#369 (the Harmony final-channel stop scope this PR depends on). SDK main calls mlx-swift APIs newer than the pinned M5 hotfix (MLXFast fencedInputs), so the stack moves with it to the revision SDK main declares, as #1596 did: libs/mlx-swift c633d221 (nested mlx 72dffa2d, mlx-c 2ac897e3) and libs/mlx 72dffa2d. All three are on their repos' main. 72dffa2d carries the NAX head-dim split attention JIT fix (mlx main 6bc9de5b), the same get_steel_attention_nax_kernel change as the 0.10.3 hotfix 31f550af. Provider adaptations for the new SDK enum cases, behavior-preserving: - MLXServerGenerationEvent.logprobs is token metadata, handled like .info by the GLM and JSON answer-format observers (the provider streams logprobs through its own channel and emits no such events today). - MLXOpenAIServiceError.responseFormatCutOffByMaxTokens is the case the SDK split out of invalidResponseFormatOutput for a structured answer cut off by max_tokens; it keeps that case's 422 and retryable classification. Verified on M5 Max: Gemma 4 26B QAT serves an 8,204-token prompt (the 0.10.2 crash path) with an 8,192-token prefix hit on repeat; gpt-oss-20b stop ["."] still returns "The capital of Australia is Canberra". Co-Authored-By: Claude Opus 5.5 --- libs/mlx | 2 +- libs/mlx-swift | 2 +- libs/mlx-swift-lm | 2 +- .../Inference/Engine/InferenceErrorClassifier.swift | 2 +- .../Inference/Prompting/GLM5NextResponseFormat.swift | 2 +- .../ProviderCore/Inference/Prompting/JSONAnswerFormat.swift | 2 +- .../Sources/ProviderCore/ProviderLoop+ErrorMapping.swift | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/libs/mlx b/libs/mlx index 31f550af4d..72dffa2dbb 160000 --- a/libs/mlx +++ b/libs/mlx @@ -1 +1 @@ -Subproject commit 31f550af4df734c1296143b556dad624db3985fc +Subproject commit 72dffa2dbbdce95601fd84f5e8b6d7b4ec97a11b diff --git a/libs/mlx-swift b/libs/mlx-swift index 4926d3d977..c633d221d6 160000 --- a/libs/mlx-swift +++ b/libs/mlx-swift @@ -1 +1 @@ -Subproject commit 4926d3d977d691d2828231d8808058c57c63c874 +Subproject commit c633d221d627898502046714dcca677d9374a1ab diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 38b90ed185..25bcd63f18 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 38b90ed185d883bd5f54c355b8eab9df5fd0919a +Subproject commit 25bcd63f187b96ecf55796c93e104d20c9852d6a diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceErrorClassifier.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceErrorClassifier.swift index 9f5ed4be4c..76230786cd 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceErrorClassifier.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceErrorClassifier.swift @@ -39,7 +39,7 @@ func classifyTypedInferenceErrorReason(_ error: Error) -> InferenceErrorReason? } if let serviceError = error as? MLXOpenAIServiceError { switch serviceError { - case .invalidResponseFormatOutput, .multipleToolCallsNotAllowed: + case .invalidResponseFormatOutput, .responseFormatCutOffByMaxTokens, .multipleToolCallsNotAllowed: // Response-format validation and parallel-tool enforcement inspect // sampled model output. Another sample/provider can comply, so // these share the retryable non-provider-fault reason above. diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift index 2ae6daa37f..9f282a1b49 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift @@ -98,7 +98,7 @@ struct GLM5NextResponseFormatOutput { content += parsed.content guard let reasoning = parsed.reasoningContent, !reasoning.isEmpty else { return nil } return .parsed(.init(content: "", reasoningContent: reasoning)) - case .toolCall, .toolCallDelta, .info: + case .toolCall, .toolCallDelta, .info, .logprobs: return event } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift index a93497091e..2e8bb5ba9f 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift @@ -78,7 +78,7 @@ struct JSONAnswerOutput { switch event { case .content(let text): content += text case .parsed(let parsed): content += parsed.content - case .toolCall, .toolCallDelta, .info: break + case .toolCall, .toolCallDelta, .info, .logprobs: break } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift index ba44ca7431..024bcedf20 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift @@ -246,7 +246,7 @@ extension ProviderLoop { } if let svcErr = error as? MLXOpenAIServiceError { switch svcErr { - case .invalidResponseFormatOutput, .multipleToolCallsNotAllowed: + case .invalidResponseFormatOutput, .responseFormatCutOffByMaxTokens, .multipleToolCallsNotAllowed: return 422 case .embeddingsNotConfigured: return 501 From 2185dfe93cb60aa95ece16449f30d936b26dcb2a Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Wed, 28 Oct 2026 12:37:56 -0700 Subject: [PATCH 0010/1441] Handle the SDK's .logprobs event in provider test switches The re-pinned mlx-swift-lm adds MLXServerGenerationEvent.logprobs. Seven test helpers switch exhaustively over events; each treats it like its existing non-content cases (.info / skipped). No assertion changes. Co-Authored-By: Claude Opus 5.5 --- .../Inference/Engine/EngineV2ProductionWiringTests.swift | 2 +- .../Inference/Live/Gemma/GemmaToolCallLiveTests.swift | 2 +- .../Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift | 2 ++ .../Inference/Tools/FlintAnswerStopTests.swift | 1 + .../Inference/Tools/FlintResponseFormatTests.swift | 2 +- .../Inference/Tools/QwenJSONAnswerServingTests.swift | 2 +- .../Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift | 1 + 7 files changed, 8 insertions(+), 4 deletions(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ProductionWiringTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ProductionWiringTests.swift index 5ba94ab9b2..157337c61e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ProductionWiringTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ProductionWiringTests.swift @@ -310,7 +310,7 @@ private func recordServerStream( events.append(.parsed(parsed)) case .info(let info): events.append(.info(prompt: info.promptTokens, completion: info.completionTokens)) - case .toolCall, .toolCallDelta: + case .toolCall, .toolCallDelta, .logprobs: continue } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Gemma/GemmaToolCallLiveTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Gemma/GemmaToolCallLiveTests.swift index c2510f1f03..1bd15374ec 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Gemma/GemmaToolCallLiveTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Gemma/GemmaToolCallLiveTests.swift @@ -261,7 +261,7 @@ struct GemmaToolCallLiveTests { case .toolCall(let call): calls.append(call) case .content(let text): visible += text case .parsed(let parsed): visible += parsed.content - case .info: break + case .info, .logprobs: break case .toolCallDelta: Issue.record("a named tool_choice call is never streamed") } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift index 97864fb0de..126037d353 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift @@ -391,6 +391,8 @@ private enum Qwen36ProductionCanary { if let call = delta.completed { result.toolCalls.append(call) } case .info(let info): result.info = info + case .logprobs: + break } } return result diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintAnswerStopTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintAnswerStopTests.swift index 0eb4a9b83f..353513fcdf 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintAnswerStopTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintAnswerStopTests.swift @@ -127,6 +127,7 @@ private struct FlintStreamOutcome { case .toolCall(let call): calls.append(call) case .toolCallDelta(let delta): if let call = delta.completed { calls.append(call) } case .info(let info): self.info = info + case .logprobs: break } } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintResponseFormatTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintResponseFormatTests.swift index 513ce9b551..7f097a8a3c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintResponseFormatTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintResponseFormatTests.swift @@ -359,7 +359,7 @@ struct FlintResponseFormatOutputTests { case .content(let text): outcome.content += text case .toolCall: outcome.calls += 1 case .toolCallDelta(let delta): if delta.completed != nil { outcome.calls += 1 } - case .info: break + case .info, .logprobs: break } } } catch { outcome.error = error } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift index 2bc354f374..1e9786d650 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift @@ -104,7 +104,7 @@ private struct QwenAnswerOutcome { case .content(let text): parser.parse(text).forEach { apply($0) } case .parsed(let parsed): apply(parsed) case .info(let info): self.info = info - case .toolCall, .toolCallDelta: break + case .toolCall, .toolCallDelta, .logprobs: break } } diff --git a/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift b/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift index ff2fe52951..d883ce4a82 100644 --- a/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift @@ -34,6 +34,7 @@ final class NemotronSuperLocalOutputTests: XCTestCase { return "F:" + call.function.name + String(decoding: try encoder.encode(call.function.arguments), as: UTF8.self) case .info: return "I" + case .logprobs: return "L" case .toolCallDelta: XCTFail("the Super output holds calls until validation; it never streams fragments") return "D" From 2841c6fe59741189d352a6bde934291a53f2aaa4 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:10:42 -0700 Subject: [PATCH 0011/1441] ci: fresh run for Release Integrity Attempt 2 of run 40756992782 failed test_cli_result_write_failure_preserves_original_error_and_findings: the test inherits the runner's GITHUB_RUN_ATTEMPT=2, so the budget runner reports MANUAL_SCAN_RERUN_DISABLED. Attempt 1 on the same tree passed. No code change. Co-Authored-By: Claude Opus 5.5 From 0b083721f4d5b07917b7fb8e6ebe202fa233c708 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:14:05 -0700 Subject: [PATCH 0012/1441] Repin the SDK to the merged #368 (2beb401f) and the MLX stack it declares Layr-Labs/mlx-swift-lm#368 was squash-merged as 2beb401f, so this branch's former SDK pin 76ff231b (#368's head) is not on SDK main. Every gitlink now points at a commit on its fork's main: - libs/mlx-swift-lm 76ff231b -> 2beb401f, the tip of SDK main and the #368 squash. Merging 76ff231b into the previous main (25bcd63f) gives exactly 2beb401f's tree, so #368 (demandedLatestCheckpointMinimumTokens) is unchanged. The pin also brings what SDK main gained since master's aee6ebb6: the tensor-parallel engine (#308), Qwen tensor batching (#352) and the optional stop-string scope (#369). - libs/mlx-swift 4926d3d9 -> c633d221, the revision 2beb401f's Package.swift declares; mlx-swift main (52c36f86) has the same tree. SDK main calls mlx-swift APIs that 4926d3d9 lacks (MLXArray.sharingArray, the fencedInputs argument of MLXFast.metalKernel). The nested mlx-c moves from 004c735f to 2ac897e3 with it. - libs/mlx 31f550af -> 72dffa2d, the nested copy that Cmlx compiles at c633d221 (Source/Cmlx/mlx); mlx main (f24d7e63) has the same tree. 72dffa2d keeps the 0.10.3 M5 NAX head-dim split JIT fix: 31f550af is not its ancestor, but that fix's squash on mlx main (6bc9de5b, Layr-Labs/mlx#48, identical patch ID) is, and its jit_kernels.cpp change is intact. #1645 pins the same mlx-swift and mlx commits. Provider follow-ups for the SDK's new enum cases, identical to #1645's (46f7ae9c5 and 2185dfe93) so the two branches merge without conflicts: - MLXServerGenerationEvent.logprobs is token metadata. The GLM and JSON answer-format observers and seven test helpers treat it like .info. No SDK engine or provider bridge emits it today; the provider sends logprobs through EngineV2LogprobsChannel. - MLXOpenAIServiceError.responseFormatCutOffByMaxTokens, which the SDK split from invalidResponseFormatOutput for a structured answer cut off by max_tokens, keeps that case's 422 and retryable classification. Co-Authored-By: Claude Opus 5.5 --- libs/mlx | 2 +- libs/mlx-swift | 2 +- libs/mlx-swift-lm | 2 +- .../Inference/Engine/InferenceErrorClassifier.swift | 2 +- .../Inference/Prompting/GLM5NextResponseFormat.swift | 2 +- .../ProviderCore/Inference/Prompting/JSONAnswerFormat.swift | 2 +- .../Sources/ProviderCore/ProviderLoop+ErrorMapping.swift | 2 +- .../Inference/Engine/EngineV2ProductionWiringTests.swift | 2 +- .../Inference/Live/Gemma/GemmaToolCallLiveTests.swift | 2 +- .../Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift | 2 ++ .../Inference/Tools/FlintAnswerStopTests.swift | 1 + .../Inference/Tools/FlintResponseFormatTests.swift | 2 +- .../Inference/Tools/QwenJSONAnswerServingTests.swift | 2 +- .../Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift | 1 + 14 files changed, 15 insertions(+), 11 deletions(-) diff --git a/libs/mlx b/libs/mlx index 31f550af4d..72dffa2dbb 160000 --- a/libs/mlx +++ b/libs/mlx @@ -1 +1 @@ -Subproject commit 31f550af4df734c1296143b556dad624db3985fc +Subproject commit 72dffa2dbbdce95601fd84f5e8b6d7b4ec97a11b diff --git a/libs/mlx-swift b/libs/mlx-swift index 4926d3d977..c633d221d6 160000 --- a/libs/mlx-swift +++ b/libs/mlx-swift @@ -1 +1 @@ -Subproject commit 4926d3d977d691d2828231d8808058c57c63c874 +Subproject commit c633d221d627898502046714dcca677d9374a1ab diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 76ff231bbf..2beb401f99 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 76ff231bbf73a7a5e54d07d860d6f629d59fdc92 +Subproject commit 2beb401f99db736e2c7128234a2e9d969d750c77 diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceErrorClassifier.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceErrorClassifier.swift index 9f5ed4be4c..76230786cd 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceErrorClassifier.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceErrorClassifier.swift @@ -39,7 +39,7 @@ func classifyTypedInferenceErrorReason(_ error: Error) -> InferenceErrorReason? } if let serviceError = error as? MLXOpenAIServiceError { switch serviceError { - case .invalidResponseFormatOutput, .multipleToolCallsNotAllowed: + case .invalidResponseFormatOutput, .responseFormatCutOffByMaxTokens, .multipleToolCallsNotAllowed: // Response-format validation and parallel-tool enforcement inspect // sampled model output. Another sample/provider can comply, so // these share the retryable non-provider-fault reason above. diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift index 2ae6daa37f..9f282a1b49 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift @@ -98,7 +98,7 @@ struct GLM5NextResponseFormatOutput { content += parsed.content guard let reasoning = parsed.reasoningContent, !reasoning.isEmpty else { return nil } return .parsed(.init(content: "", reasoningContent: reasoning)) - case .toolCall, .toolCallDelta, .info: + case .toolCall, .toolCallDelta, .info, .logprobs: return event } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift index a93497091e..2e8bb5ba9f 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift @@ -78,7 +78,7 @@ struct JSONAnswerOutput { switch event { case .content(let text): content += text case .parsed(let parsed): content += parsed.content - case .toolCall, .toolCallDelta, .info: break + case .toolCall, .toolCallDelta, .info, .logprobs: break } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift index ba44ca7431..024bcedf20 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift @@ -246,7 +246,7 @@ extension ProviderLoop { } if let svcErr = error as? MLXOpenAIServiceError { switch svcErr { - case .invalidResponseFormatOutput, .multipleToolCallsNotAllowed: + case .invalidResponseFormatOutput, .responseFormatCutOffByMaxTokens, .multipleToolCallsNotAllowed: return 422 case .embeddingsNotConfigured: return 501 diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ProductionWiringTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ProductionWiringTests.swift index 5ba94ab9b2..157337c61e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ProductionWiringTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ProductionWiringTests.swift @@ -310,7 +310,7 @@ private func recordServerStream( events.append(.parsed(parsed)) case .info(let info): events.append(.info(prompt: info.promptTokens, completion: info.completionTokens)) - case .toolCall, .toolCallDelta: + case .toolCall, .toolCallDelta, .logprobs: continue } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Gemma/GemmaToolCallLiveTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Gemma/GemmaToolCallLiveTests.swift index c2510f1f03..1bd15374ec 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Gemma/GemmaToolCallLiveTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Gemma/GemmaToolCallLiveTests.swift @@ -261,7 +261,7 @@ struct GemmaToolCallLiveTests { case .toolCall(let call): calls.append(call) case .content(let text): visible += text case .parsed(let parsed): visible += parsed.content - case .info: break + case .info, .logprobs: break case .toolCallDelta: Issue.record("a named tool_choice call is never streamed") } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift index 97864fb0de..126037d353 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Live/Qwen/Qwen36ProductionCanaryTests.swift @@ -391,6 +391,8 @@ private enum Qwen36ProductionCanary { if let call = delta.completed { result.toolCalls.append(call) } case .info(let info): result.info = info + case .logprobs: + break } } return result diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintAnswerStopTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintAnswerStopTests.swift index 0eb4a9b83f..353513fcdf 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintAnswerStopTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintAnswerStopTests.swift @@ -127,6 +127,7 @@ private struct FlintStreamOutcome { case .toolCall(let call): calls.append(call) case .toolCallDelta(let delta): if let call = delta.completed { calls.append(call) } case .info(let info): self.info = info + case .logprobs: break } } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintResponseFormatTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintResponseFormatTests.swift index 513ce9b551..7f097a8a3c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintResponseFormatTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/FlintResponseFormatTests.swift @@ -359,7 +359,7 @@ struct FlintResponseFormatOutputTests { case .content(let text): outcome.content += text case .toolCall: outcome.calls += 1 case .toolCallDelta(let delta): if delta.completed != nil { outcome.calls += 1 } - case .info: break + case .info, .logprobs: break } } } catch { outcome.error = error } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift index 2bc354f374..1e9786d650 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift @@ -104,7 +104,7 @@ private struct QwenAnswerOutcome { case .content(let text): parser.parse(text).forEach { apply($0) } case .parsed(let parsed): apply(parsed) case .info(let info): self.info = info - case .toolCall, .toolCallDelta: break + case .toolCall, .toolCallDelta, .logprobs: break } } diff --git a/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift b/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift index ff2fe52951..d883ce4a82 100644 --- a/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift @@ -34,6 +34,7 @@ final class NemotronSuperLocalOutputTests: XCTestCase { return "F:" + call.function.name + String(decoding: try encoder.encode(call.function.arguments), as: UTF8.self) case .info: return "I" + case .logprobs: return "L" case .toolCallDelta: XCTFail("the Super output holds calls until validation; it never streams fragments") return "D" From 56c68e30bf55f254fb81997db3c5aafa52a1e1be Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Wed, 28 Oct 2026 19:34:40 -0700 Subject: [PATCH 0013/1441] test(provider): stop the paused-sweep telemetry test hanging the SSD suites "heartbeat snapshot remains available during a paused filesystem sweep" paused a Task.detached sweep inside SSDDiskBudget.shared.retireActiveEntries, holding the process-wide budget lock on a cooperative-pool thread until the async test body signalled it. Parallel suites take that lock from pool threads (store init and close, enforce, totalBytes); once they fill the pool the test body never resumes and the run hangs. With a probe that floods the pool with SSDDiskBudget.shared calls, master hangs 3 of 3 runs. The sweep now runs on GCD (onGCD, now shared with the epoch test from #1653) and the paused store takes the snapshot itself on a dedicated Thread, waiting at most 5 s, so ending the pause never needs a pool thread. GCD is not enough for the snapshot: with the pool full of threads blocked on the lock, a default-QoS GCD block did not start within 5 s in 5 of 5 runs. A snapshot that waits for the sweep still fails the test, now in 5 s instead of hanging. Co-Authored-By: Claude Opus 5.5 --- .../SSDCooperativePoolTestSupport.swift | 12 +++ .../KVCacheSSD/SSDCacheEpochStoreTests.swift | 9 --- ...SDWholeRootTelemetryConcurrencyTests.swift | 79 ++++++++++--------- 3 files changed, 54 insertions(+), 46 deletions(-) create mode 100644 provider-swift/Tests/ProviderCoreTests/KVCacheSSD/Fixtures/SSDCooperativePoolTestSupport.swift diff --git a/provider-swift/Tests/ProviderCoreTests/KVCacheSSD/Fixtures/SSDCooperativePoolTestSupport.swift b/provider-swift/Tests/ProviderCoreTests/KVCacheSSD/Fixtures/SSDCooperativePoolTestSupport.swift new file mode 100644 index 0000000000..1b51a11c4c --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/KVCacheSSD/Fixtures/SSDCooperativePoolTestSupport.swift @@ -0,0 +1,12 @@ +import Foundation + +/// Runs blocking work on a GCD thread. While a test holds a process-wide lock +/// (the epoch record lock, `SSDDiskBudget.shared`'s lock), parallel suites +/// blocked on it can fill the cooperative pool, so nothing that releases the +/// lock may need a pool thread. GCD may not start new work while the pool is +/// saturated, so work that must start during the hold needs its own `Thread`. +func onGCD(_ work: @escaping @Sendable () throws -> T) async throws -> T { + try await withCheckedThrowingContinuation { continuation in + DispatchQueue.global().async { continuation.resume(with: Result(catching: work)) } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/KVCacheSSD/SSDCacheEpochStoreTests.swift b/provider-swift/Tests/ProviderCoreTests/KVCacheSSD/SSDCacheEpochStoreTests.swift index 1defeed873..df31e1a87b 100644 --- a/provider-swift/Tests/ProviderCoreTests/KVCacheSSD/SSDCacheEpochStoreTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/KVCacheSSD/SSDCacheEpochStoreTests.swift @@ -5,15 +5,6 @@ import Testing @testable import ProviderCore -/// Runs blocking work on a GCD thread. While a test holds the process-wide -/// epoch record lock, parallel suites blocked on it can fill the cooperative -/// pool, so nothing that releases the lock may need a pool thread. -private func onGCD(_ work: @escaping @Sendable () throws -> T) async throws -> T { - try await withCheckedThrowingContinuation { continuation in - DispatchQueue.global().async { continuation.resume(with: Result(catching: work)) } - } -} - @Suite("SSD cache epoch persistence") struct SSDCacheEpochStoreTests { @Test("epoch persists, rotates durably, and binding drift wipes blocks") diff --git a/provider-swift/Tests/ProviderCoreTests/KVCacheSSD/SSDWholeRootTelemetryConcurrencyTests.swift b/provider-swift/Tests/ProviderCoreTests/KVCacheSSD/SSDWholeRootTelemetryConcurrencyTests.swift index 900fe0c711..2e59a86288 100644 --- a/provider-swift/Tests/ProviderCoreTests/KVCacheSSD/SSDWholeRootTelemetryConcurrencyTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/KVCacheSSD/SSDWholeRootTelemetryConcurrencyTests.swift @@ -3,12 +3,22 @@ import Testing @testable import ProviderCore /// Pauses a real sweep at the existing active-store mutation barrier, without -/// adding a production hook or requiring a large/slow filesystem fixture. -private final class PausedMaintenanceStore: SSDEvictableStore, @unchecked Sendable { +/// adding a production hook or requiring a large/slow filesystem fixture, and +/// takes a heartbeat snapshot there. The paused sweep holds +/// `SSDDiskBudget.shared`'s lock, which parallel suites take on cooperative-pool +/// threads, so the snapshot runs on its own thread and the pause is bounded: +/// nothing that ends it needs a pool thread. +private final class SnapshotDuringSweepStore: SSDEvictableStore, @unchecked Sendable { let evictionRoot: URL - let entered = DispatchSemaphore(value: 0) - let release = DispatchSemaphore(value: 0) - init(root: URL) { evictionRoot = root } + private let maintainer: SSDWholeRootMaintainer + private let lock = NSLock() + private var pauses = 0 + private var snapshotWasAvailable = false + private var snapshot: SSDWholeRootMaintainer.Stats? + init(root: URL, maintainer: SSDWholeRootMaintainer) { + evictionRoot = root + self.maintainer = maintainer + } var ownsEvictionRoot: Bool { true } var diskBytesOnDisk: Int { 0 } func oldestEntryAccess() -> Int64? { nil } @@ -24,11 +34,27 @@ private final class PausedMaintenanceStore: SSDEvictableStore, @unchecked Sendab return removed } func performExternalDestructiveChange(_ body: () -> Void) -> Bool { - entered.signal() - release.wait() + let returned = DispatchSemaphore(value: 0) + // Its own thread, not a GCD worker: while the pool is full of threads + // blocked on the budget lock, GCD did not start default-QoS work for 5 s. + Thread { [self] in + let stats = maintainer.statsSnapshot() + lock.withLock { snapshot = stats } + returned.signal() + }.start() + // A snapshot that waits for the sweep fails the test here instead of + // holding the shared budget lock until the run's watchdog. + let available = returned.wait(timeout: .now() + 5) == .success + lock.withLock { + pauses += 1 + snapshotWasAvailable = available + } body() return true } + var observed: (pauses: Int, snapshotWasAvailable: Bool, snapshot: SSDWholeRootMaintainer.Stats?) { + lock.withLock { (pauses, snapshotWasAvailable, snapshot) } + } } @Suite("Whole-root telemetry concurrency") @@ -41,41 +67,20 @@ struct SSDWholeRootTelemetryConcurrencyTests { #expect(try await fixture.donate(donor) == [256]) await donor.closeAndWait() - let paused = PausedMaintenanceStore(root: fixture.modelRoot) - SSDDiskBudget.shared.register(paused) - defer { paused.release.signal(); SSDDiskBudget.shared.deregister(paused) } let maintainer = SSDWholeRootMaintainer() - let sweep = Task.detached { + let paused = SnapshotDuringSweepStore(root: fixture.modelRoot, maintainer: maintainer) + SSDDiskBudget.shared.register(paused) + defer { SSDDiskBudget.shared.deregister(paused) } + let swept = try await onGCD { maintainer.maintain(root: fixture.root, ttlSeconds: 1, nowSeconds: Int64(Date().timeIntervalSince1970) + 7200, budgetBytes: Int.max) } - // Poll rather than blocking a cooperative executor thread. - func signalled(_ semaphore: DispatchSemaphore) -> Bool { - semaphore.wait(timeout: .now()) == .success - } - func waitForSignal(_ semaphore: DispatchSemaphore) async -> Bool { - let deadline = ContinuousClock.now.advanced(by: .seconds(5)) - while ContinuousClock.now < deadline { - if signalled(semaphore) { return true } - try? await Task.sleep(for: .milliseconds(1)) - } - return false - } - let sweepPaused = await waitForSignal(paused.entered) - #expect(sweepPaused) - let snapshotFinished = DispatchSemaphore(value: 0) - let snapshot = Task.detached { - let result = maintainer.statsSnapshot() - snapshotFinished.signal() - return result - } - let snapshotWasAvailable = await waitForSignal(snapshotFinished) - #expect(snapshotWasAvailable, "capacity heartbeat must not wait for the sweep") - paused.release.signal() - #expect(await sweep.value.ttlExpired == 1) - let duringSweep = await snapshot.value - if snapshotWasAvailable { #expect(duringSweep.ttlExpired == 0) } + #expect(swept.ttlExpired == 1) + let observed = paused.observed + try #require(observed.pauses == 1) + #expect(observed.snapshotWasAvailable, "capacity heartbeat must not wait for the sweep") + if observed.snapshotWasAvailable { #expect(observed.snapshot?.ttlExpired == 0) } #expect(maintainer.statsSnapshot().ttlExpired == 1) } } From 823ac618457fcdfc7ead8bce56d66fa641f0f4db Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 29 Oct 2026 00:56:39 -0700 Subject: [PATCH 0014/1441] perf(provider): prepare the checkpoint row encoder once per segment Repin libs/mlx-swift-lm 2beb401f -> 9c2f47b6 (one commit on SDK main, branch perf/prepared-checkpoint-row-encoder). Checkpoint export at a quantized checkpoint precision now encodes each older KV row with an encoder prepared once per segment read, which reuses its row buffers and one representability decoder and writes the scalar codec's exact bytes. Gemma 4 26B QAT on an M3 Ultra, default balanced precision: a donating request's end of stream 1.72/1.85/2.02 s -> 1.01/1.10/1.19 s (-41%, 10/10 interleaved pairs), summed time of the 11-request replay -10.8%, outputs identical on 110/110 requests. Docs: the SSD reference's conversion row and an export note in the inference architecture. Changelog: changelog.d/checkpoint-row-encoder.md. Co-Authored-By: Claude Opus 5.5 --- changelog.d/checkpoint-row-encoder.md | 8 ++++++++ docs/architecture/inference.md | 10 +++++++++- docs/reference/ssd-kv-cache.md | 4 ++-- libs/mlx-swift-lm | 2 +- 4 files changed, 20 insertions(+), 4 deletions(-) create mode 100644 changelog.d/checkpoint-row-encoder.md diff --git a/changelog.d/checkpoint-row-encoder.md b/changelog.d/checkpoint-row-encoder.md new file mode 100644 index 0000000000..0779a093f3 --- /dev/null +++ b/changelog.d/checkpoint-row-encoder.md @@ -0,0 +1,8 @@ +### Responses that save a cache checkpoint finish sooner + +- Saving a prefix-cache checkpoint encodes its older attention rows at the default + `balanced` checkpoint precision. That encoding now prepares its buffers and its + check once per segment instead of once per row and writes the same bytes. On a + Gemma 4 26B request that saves a checkpoint, the end of the response arrived + about 0.7 s sooner (1.7–2.0 s → 1.0–1.2 s on an M3 Ultra), with identical + output. Requests that save no checkpoint are unchanged. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index b9261f04e6..6943b76d72 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-28 +> Last updated: 2026-10-29 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -1339,6 +1339,14 @@ or fences them, so staging does not wait for that chunk `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTransfer.swift` (`CBv2CompleteCheckpointImport`)). +A donor's stream retires only after its complete checkpoint is published +(`EngineLoopV2.finishAfterCompletePrefixPublication`), so export time is added +to the donating response's end. At a quantized checkpoint precision, export +encodes each older attention row on the CPU with one prepared row encoder per +segment read, which writes the scalar codec's exact bytes +([conversion](../reference/ssd-kv-cache.md#complete-checkpoint-payload), +`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/NativeQuantizedCheckpointTensorSource.swift`). + Segmented paged admission no longer waits for queued GPU work. A released row's free 64 MiB segments are parked per pool, up to `min(2 GiB, slot grant / 8)`, outside the grant, floor and ledger charge, and the next admission of the same diff --git a/docs/reference/ssd-kv-cache.md b/docs/reference/ssd-kv-cache.md index 113234b679..2c73117a8b 100644 --- a/docs/reference/ssd-kv-cache.md +++ b/docs/reference/ssd-kv-cache.md @@ -1,6 +1,6 @@ # SSD KV cache reference -> Last updated: 2026-10-28 +> Last updated: 2026-10-29 Exact on-disk format, paths, identity binding, environment knobs, size and eviction rules, and per-family reuse capability of the provider's encrypted SSD @@ -123,7 +123,7 @@ and MTP codec. No public header field exposes those token boundaries | Initial read admission | Metadata-only candidate match precedes any file read. Shared mode reserves `ioScratchBytes = 20 << 20` once in the provider ledger; its native IO lease does not duplicate that charge. Contiguous compatibility keeps its existing two-ledger path | `SSDHybridCheckpointStore+Read.swift` (`stage`), `EngineV2+CompleteCheckpoint.swift` (`reserveCompleteCheckpointReadScratch`) | | Import admission | Authenticate manifest → allocation-free import plan → native per-buffer destination, scratch and metadata admission → bounded whole-file read. Shared native ownership is separate from provider host IO | `SSDHybridCheckpointStore+ReadAttempt.swift` (`readCheckpoint`), `CompleteCheckpointImportPlan.swift` (`allocate`) | | Provider-staged destinations | The provider-staged (non-native-bound) import creates contiguous destinations, paged segment storage and recent rows already available from zeroed host bytes, then skips `eval` and stream fences for them. Staging therefore never waits for MLX-Swift's process-wide `evalLock`, which the engine holds for a whole prefill chunk. The zero source is read by the copy and can briefly commit up to one destination outside the MLX allocator, so the import plan charges the largest as staging scratch. Native-bound imports and engine pool growth keep device allocation | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CheckpointHostZeros.swift` (`MLXArray.cbv2HostZeros`), `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTransfer.swift` (`CBv2CompleteCheckpointImport`), `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointStorage.swift` (`CBv2PagedCheckpointStorage`, `hostMaterialized`), `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointImportPlan.swift` (`CBv2CompleteCheckpointImportPlan.scratchBytes`, `evaluateUnavailable`) | -| Lossy-to-native conversion | CPU row encoding/decoding; `64 << 10` bytes of conversion scratch, reserved per export read and in the import plan. Import reuses row buffers, retains at most one fragmented input row, and batches validated native writes up to `16 << 10` bytes within that allowance. Native destination sizes, not encoded bytes, price restored state | `NativeCheckpointRowCodec.swift`, `NativeQuantizedCheckpointTensorSource.swift`, `CompleteCheckpointImportPlan.swift`, `NativeQuantizedCheckpointRestore.swift` | +| Lossy-to-native conversion | CPU row encoding/decoding; `64 << 10` bytes of conversion scratch, reserved per export read and in the import plan. Each export read prepares one row encoder (`CBv2PreparedNativeCheckpointRowEncoder`): it reuses its row buffers and one representability decoder and writes the scalar codec's exact bytes. Import reuses row buffers, retains at most one fragmented input row, and batches validated native writes up to `16 << 10` bytes within that allowance. Native destination sizes, not encoded bytes, price restored state | `NativeCheckpointRowCodec.swift`, `NativeQuantizedCheckpointTensorSource.swift`, `CompleteCheckpointImportPlan.swift`, `NativeQuantizedCheckpointRestore.swift` | | Idle state | Metadata index only; no resident tensor bank or persistent slot carve | `SSDHybridCheckpointStore.swift`, `provider-swift/Sources/ProviderCore/Inference/PrefixCache/PrefixCachePolicy.swift` (`isMemoryEnabled`) | | Imported lifetime | Single-use staged state retains native owners through aliases. Paged adoption replaces temporary staging with the full request promise and actual backing; recurrent/MTP auxiliary state has its own charge | `CompleteCheckpointTransfer.swift` | | Host IO lifetime | Read/decrypt aliases retire before the read charge returns; writers claim host buffers before encoding and release them after the complete write stack drains | `SSDHybridCheckpointStore+ReadAttempt.swift` (`readCheckpoint`), `SSDHybridCheckpointStore+Write.swift` (`write`) | diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 2beb401f99..9c2f47b640 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 2beb401f99db736e2c7128234a2e9d969d750c77 +Subproject commit 9c2f47b64003d56fdc4944a13af57f34a3a8c2cd From bd5f7f1b573f588cf73c395f07a5cd998b3a2fd6 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 29 Oct 2026 03:19:26 -0700 Subject: [PATCH 0015/1441] perf(provider): check each restored checkpoint row once for non-finite values Repin libs/mlx-swift-lm 2beb401f -> 5febd8a4 (one commit on SDK main, branch perf/decoder-row-finite-check). Restoring a complete checkpoint stored at a quantized checkpoint precision decodes each older KV row on the CPU; the decoder now tests each row once for values its native dtype cannot hold instead of running SIMD mask reductions per eight values, with the same bytes and the same refusals. Gemma 4 26B QAT on an M3 Ultra, default balanced precision: summed follow-up TTFT of the 11-request replay 8.740 -> 6.501 s (-25.6%, 10/10 interleaved pairs), about 0.2 s less per SSD restore at 1-3k cached tokens, donating requests' stream ends 0.20-0.25 s sooner, outputs identical on 110/110 requests. Docs: a restore-decode note in the inference architecture. Changelog: changelog.d/checkpoint-row-decoder.md. Co-Authored-By: Claude Opus 5.5 --- changelog.d/checkpoint-row-decoder.md | 10 ++++++++++ docs/architecture/inference.md | 6 ++++-- libs/mlx-swift-lm | 2 +- 3 files changed, 15 insertions(+), 3 deletions(-) create mode 100644 changelog.d/checkpoint-row-decoder.md diff --git a/changelog.d/checkpoint-row-decoder.md b/changelog.d/checkpoint-row-decoder.md new file mode 100644 index 0000000000..96ee68c9b4 --- /dev/null +++ b/changelog.d/checkpoint-row-decoder.md @@ -0,0 +1,10 @@ +### Cache restores finish sooner + +- Restoring a prefix-cache checkpoint decodes its older attention rows from the + default `balanced` checkpoint precision on the CPU. The decoder now checks each + row for values its native type cannot hold once per row instead of once per + eight values, with the same bytes and the same refusals. On Gemma 4 26B + follow-up requests served from the SSD cache, time to first token fell by about + 0.2 s per restore (about 25% over an 11-request conversation on an M3 Ultra), + and responses that save a checkpoint also end about 0.2 s sooner. Output is + unchanged. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index b9261f04e6..270514d85b 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-28 +> Last updated: 2026-10-29 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -1334,7 +1334,9 @@ The SSD stage runs before `engine.submit`, off the engine queue, while the engine may be evaluating another request's prefill chunk under MLX-Swift's process-wide `evalLock`. A provider-staged complete-checkpoint import therefore creates its destinations already available from host bytes and never evaluates -or fences them, so staging does not wait for that chunk +or fences them, so staging does not wait for that chunk; its CPU decode tests each +restored row once for values the native dtype cannot hold, and a refused row never +reaches a destination ([destination contract](../reference/ssd-kv-cache.md#complete-checkpoint-payload), `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTransfer.swift` (`CBv2CompleteCheckpointImport`)). diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 2beb401f99..5febd8a451 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 2beb401f99db736e2c7128234a2e9d969d750c77 +Subproject commit 5febd8a4514e6a54e4acd83193f9f224886c5b73 From 2b94b08fd52afdff04cce6bc7525e5f4ca5950ce Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:53:21 -0700 Subject: [PATCH 0016/1441] Repin the SDK to aabf0189 (direct test of the BF16 check before rounding) Repin libs/mlx-swift-lm 5febd8a4 -> aabf0189 (branch perf/decoder-row-finite-check, Layr-Labs/mlx-swift-lm#371). The new SDK commit adds a test that passes the four NaN words rounding would turn into a signed zero to writeNative in every lane and requires a refusal, and makes the prepared decoder and writeNative internal so the test can call it. The decoder's code is unchanged. Co-Authored-By: Claude Opus 5.5 --- libs/mlx-swift-lm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 5febd8a451..aabf018969 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 5febd8a4514e6a54e4acd83193f9f224886c5b73 +Subproject commit aabf0189692e0ad03e18041db2351663ffb00cd5 From 908cff5e0c911d5e8ab2fba8e5ad166f71d86cae Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Fri, 30 Oct 2026 23:40:09 -0700 Subject: [PATCH 0017/1441] Gemma 4 text keeps its spaces before punctuation Gemma 4 replies, reasoning and tool arguments lost the space before punctuation and could repeat a quote: `git add .` came back as `git add.`, and a streamed `role = 'start'` as `role = ''start'`. Gemma 4's published tokenizer_config.json omits clean_up_tokenization_spaces. swift-transformers reads a missing key as cleanup on; Python Transformers reads it as off. LocalTokenizerLoader now resolves a missing key to off in memory, for every model. An explicit Boolean is kept. Token IDs, sampling, model state and cache keys do not change. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-decode-keeps-spaces.md | 5 + docs/architecture/inference.md | 11 +- docs/architecture/native-block-inference.md | 14 +-- docs/developer/test.md | 8 +- .../Prompting/LocalTokenizerLoader.swift | 31 ++++-- .../LocalTokenizerDecodeSpacingTests.swift | 102 ++++++++++++++++++ 6 files changed, 152 insertions(+), 19 deletions(-) create mode 100644 changelog.d/gemma-decode-keeps-spaces.md create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerDecodeSpacingTests.swift diff --git a/changelog.d/gemma-decode-keeps-spaces.md b/changelog.d/gemma-decode-keeps-spaces.md new file mode 100644 index 0000000000..7b902c5121 --- /dev/null +++ b/changelog.d/gemma-decode-keeps-spaces.md @@ -0,0 +1,5 @@ +### Gemma 4 text keeps its spaces before punctuation + +- Gemma 4 replies, reasoning and tool arguments no longer lose the space before `.`, `,`, `?` and `!`, or repeat a quote. `git add .` came back as `git add.`, `bash ./run.sh` as `bash./run.sh`, `x != y` as `x!= y`, and, when streamed, `role = 'start'` as `role = ''start'`. +- Gemma 4's published `tokenizer_config.json` omits `clean_up_tokenization_spaces`, and the Swift tokenizer library reads a missing key as cleanup on, where Python Transformers reads it as off. The provider now resolves a missing key to off in memory for every model. An explicit Boolean is kept. +- Token IDs, sampling, model state and cache keys do not change. Only the text decoded from the same tokens does. Stop strings match the text as spelled: one with a space before punctuation can now match, and one that matched only the cleaned text (`add.` for `add .`) no longer does. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 45c07ff127..7ab4377f78 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-30 +> Last updated: 2026-10-31 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -1577,6 +1577,15 @@ never crosses a cache scope; `DARKBLOOM_TTFT_PROMPT_CACHE=0` restores the unchanged path ([configuration](../reference/configuration.md#prompt-preparation-and-admission)). +Decoded text keeps the spacing the tokens spell, unless the tokenizer config sets +`clean_up_tokenization_spaces` to true. swift-transformers reads an absent key as +true, which drops the space in sequences such as ` .`, ` ,`, ` ?`, ` !` and ` 's`, +and can make a streamed decode repeat bytes it already sent. Gemma 4's published +config omits the key. `LocalTokenizerLoader` +(`provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift`) +resolves an absent key to false in memory, as Python Transformers does, and keeps +an explicit Boolean. Input IDs, sampling and cache keys do not depend on it. + Bridge-side order (`EngineV2Bridge.submitTokenized`): request-id normalisation (`maxRequestIdLength = 256`; duplicates rejected) → first deadline check → translation (`maxTokens = request.max_tokens ?? diff --git a/docs/architecture/native-block-inference.md b/docs/architecture/native-block-inference.md index ba4721ab43..973d1ad6c7 100644 --- a/docs/architecture/native-block-inference.md +++ b/docs/architecture/native-block-inference.md @@ -1,6 +1,6 @@ # Native block-generation adapter -> Last updated: 2026-10-09 +> Last updated: 2026-10-31 This page explains the native block engine and its provider bridge boundary. DiffusionGemma uses explicit native-container ownership through ordinary slot @@ -247,12 +247,12 @@ content begins. A successfully parsed call does not guarantee that the model copied a requested argument correctly; semantic fidelity remains a separate gate. Both native empty-thought spellings, with and without the newline, are recognized. -`LocalTokenizerLoader` resolves the DiffusionGemma processor's absent -`clean_up_tokenization_spaces` to false through the SDK's -`DiffusionGemmaTokenizerConfiguration`. Explicit Boolean metadata is retained; -other processors keep the existing loader path. This avoids altering literal -punctuation and spaces inside quoted arguments after token generation. The -metadata files, input IDs and native sampling are unchanged. Exact decoding +`LocalTokenizerLoader` resolves an absent `clean_up_tokenization_spaces` to +false: for the DiffusionGemma processor through the SDK's +`DiffusionGemmaTokenizerConfiguration`, and for every other processor in the +loader itself. Explicit Boolean metadata is retained. This avoids altering +literal punctuation and spaces inside quoted arguments after token generation. +The metadata files, input IDs and native sampling are unchanged. Exact decoding does not repair an incorrect value already present in generated tokens. The released template defaults thinking off unless its binary `enable_thinking` diff --git a/docs/developer/test.md b/docs/developer/test.md index 51b2b1d9c4..35b42d4437 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-10-29 +> Last updated: 2026-10-31 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -524,9 +524,13 @@ provision test fixtures or opt into native qualification. ## Prompt Preparation And Admission ```bash -swift test --skip-build --filter 'PromptTokenCacheTests|ChatTemplateLoopRewritesTests|InboundChatRequestDecodeTests|ServeLoopColdLoadTests' +swift test --skip-build --filter 'LocalTokenizerDecodeSpacingTests|PromptTokenCacheTests|ChatTemplateLoopRewritesTests|InboundChatRequestDecodeTests|ServeLoopColdLoadTests' ``` +`LocalTokenizerDecodeSpacingTests` requires a tokenizer whose config omits +`clean_up_tokenization_spaces` (Gemma 4's published config does) to decode and +stream text exactly, with the same input IDs and an explicit Boolean kept. + `PromptTokenCacheTests` loads synthetic tokenizers through the production `LocalTokenizerLoader` for the Qwen split, GPT-2 byte-level and Gemma metaspace pre-tokenizer families, with no download, and requires piecewise, cached and diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift index 43d41bb0f4..b41577d9c4 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift @@ -5,8 +5,8 @@ /// macro expands to, but done by hand because we load tokenizers from a /// local on-disk cache rather than the Hugging Face Hub. Keeping the /// bridge in pure Swift lets us avoid pulling in MLXHuggingFace -/// (and its BoringSSL/NIO/Jinja transitive closure) just for the -/// `from(modelFolder:)` entrypoint we already have. +/// (and its BoringSSL/NIO/Jinja transitive closure) just for the steps of +/// `AutoTokenizer.from(modelFolder:)`, which `load(from:)` runs itself. /// /// Used by ProviderLoop and the engine/model factories. @@ -32,18 +32,19 @@ public struct LocalTokenizerLoader: TokenizerLoader, Sendable { upstream = try PreTrainedTokenizer( tokenizerConfig: .init(inputs.configurationDictionary()), tokenizerData: .init(inputs.dataDictionary())) - } else if PromptTokenCachePolicy.isEnabled(environment: environment) { - // The steps of `AutoTokenizer.from(modelFolder:)`, keeping the - // configurations for the prompt token cache. + } else { + // The steps of `AutoTokenizer.from(modelFolder:)`, with decode cleanup + // resolved and the configurations kept for the prompt token cache. let hub = LanguageModelConfigurationFromHub(modelFolder: directory) - guard let tokenizerConfig = try await hub.tokenizerConfig else { + guard let published = try await hub.tokenizerConfig else { throw Tokenizers.TokenizerError.missingConfig } + let tokenizerConfig = Self.resolvingDecodeCleanup(published) let tokenizerData = try await hub.tokenizerData upstream = try PreTrainedTokenizer(tokenizerConfig: tokenizerConfig, tokenizerData: tokenizerData) - configurations = .init(tokenizerConfig: tokenizerConfig, tokenizerData: tokenizerData) - } else { - upstream = try await AutoTokenizer.from(modelFolder: directory) + if PromptTokenCachePolicy.isEnabled(environment: environment) { + configurations = .init(tokenizerConfig: tokenizerConfig, tokenizerData: tokenizerData) + } } let modelType = ModelScanner.parseConfigJSON( at: directory.appendingPathComponent("config.json")).modelType @@ -58,6 +59,18 @@ public struct LocalTokenizerLoader: TokenizerLoader, Sendable { upstream, chatTemplate: chatTemplate, modelType: modelType, promptCacheConfigurations: configurations, environment: environment) } + + /// swift-transformers reads an absent `clean_up_tokenization_spaces` as true; Python + /// Transformers reads it as false. Cleanup rewrites decoded text: `git add .` comes back + /// as `git add.`, and a streamed `'start'` as `''start'`. Gemma 4's published config omits + /// the key. This resolves it in memory, so the verified files stay as they are; cleanup + /// runs only on decode, so input IDs do not change. An explicit Boolean is kept. + private static func resolvingDecodeCleanup(_ config: Config) -> Config { + let key: BinaryDistinctString = "clean_up_tokenization_spaces" + guard var fields = config.dictionary(), fields[key]?.boolean() == nil else { return config } + fields[key] = Config(false) + return Config(fields) + } } /// Adapter that satisfies `MLXLMCommon.Tokenizer` by forwarding to the diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerDecodeSpacingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerDecodeSpacingTests.swift new file mode 100644 index 0000000000..86654fc386 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerDecodeSpacingTests.swift @@ -0,0 +1,102 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon +import Testing +import Tokenizers + +@testable import ProviderCore + +/// Decoded text must spell what the tokens spell. Gemma 4's published tokenizer config has no +/// `clean_up_tokenization_spaces` key, and swift-transformers reads that as cleanup on, so a +/// served reply lost the space in `git add .` and repeated the quote in `'start'`. +@Suite("Local tokenizer decode spacing") +struct LocalTokenizerDecodeSpacingTests { + private static let exactTexts = [ + "git add .", "bash ./run.sh && cp .env.example .env", "rm -rf .git", "x != y ? a : b", + "name = 'start'", "s = ' ' + t", "a . b , c ? d !", "x ' value ' y", "we 're", "I 'm", "it 's", + "they 've", "do n't", ".foo .bar {", "function 'record_payload'", " exact spaces ", + ] + private static let promptCacheEnvironments: [[String: String]] = [[:], ["DARKBLOOM_TTFT_PROMPT_CACHE": "0"]] + + /// A character-level tokenizer the way Gemma 4's config declares it: no cleanup key unless asked. + private func tokenizerDirectory(cleanup: Any? = nil) throws -> URL { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("decode-spacing-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + var config: [String: Any] = [ + "tokenizer_class": "GemmaTokenizer", "processor_class": "Gemma4Processor", "unk_token": "", + ] + if let cleanup { config["clean_up_tokenization_spaces"] = cleanup } + var vocabulary: [String: Int] = ["": 0] + for value in 32...126 { vocabulary[String(UnicodeScalar(value)!)] = value - 31 } + let data: [String: Any] = [ + "model": ["type": "BPE", "vocab": vocabulary, "merges": [String](), "unk_token": ""], + "decoder": ["type": "Fuse"], + ] + try JSONSerialization.data(withJSONObject: config).write( + to: directory.appendingPathComponent("tokenizer_config.json")) + try JSONSerialization.data(withJSONObject: data).write(to: directory.appendingPathComponent("tokenizer.json")) + return directory + } + + @Test("an absent cleanup key keeps decoded text exact", arguments: promptCacheEnvironments) + func absentKeyKeepsTextExact(environment: [String: String]) async throws { + let directory = try tokenizerDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let tokenizer = try await LocalTokenizerLoader(environment: environment).load(from: directory) + for text in Self.exactTexts { + let tokens = tokenizer.encode(text: text, addSpecialTokens: false) + #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) == text) + #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: true) == text) + } + } + + @Test("a stream carries every byte once", arguments: promptCacheEnvironments) + func streamCarriesEveryByteOnce(environment: [String: String]) async throws { + let directory = try tokenizerDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let tokenizer = try await LocalTokenizerLoader(environment: environment).load(from: directory) + for text in Self.exactTexts { + let detokenizer = DetokenizerV2(tokenizer: tokenizer) + var streamed = "" + for token in tokenizer.encode(text: text, addSpecialTokens: false) { + streamed += detokenizer.append(token) + } + streamed += detokenizer.flush() + #expect(streamed == text) + } + } + + @Test("an explicit cleanup value is kept", arguments: [false, true]) + func explicitValueIsKept(cleanup: Bool) async throws { + let directory = try tokenizerDirectory(cleanup: cleanup) + defer { try? FileManager.default.removeItem(at: directory) } + let tokenizer = try await LocalTokenizerLoader().load(from: directory) + let tokens = tokenizer.encode(text: "a .", addSpecialTokens: false) + #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) == (cleanup ? "a." : "a .")) + } + + @Test("a null cleanup value reads as absent") + func nullValueReadsAsAbsent() async throws { + let directory = try tokenizerDirectory(cleanup: NSNull()) + defer { try? FileManager.default.removeItem(at: directory) } + let tokenizer = try await LocalTokenizerLoader().load(from: directory) + let tokens = tokenizer.encode(text: "a .", addSpecialTokens: false) + #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) == "a .") + } + + @Test("input IDs and the published config stay as they are") + func inputIDsAndConfigStay() async throws { + let directory = try tokenizerDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let original = try Data(contentsOf: directory.appendingPathComponent("tokenizer_config.json")) + let tokenizer = try await LocalTokenizerLoader().load(from: directory) + let untouched = try await AutoTokenizer.from(modelFolder: directory) + for text in Self.exactTexts { + #expect(tokenizer.encode(text: text, addSpecialTokens: false) + == untouched.encode(text: text, addSpecialTokens: false)) + } + #expect(try Data(contentsOf: directory.appendingPathComponent("tokenizer_config.json")) == original) + } +} From 0edf36fa14d66c02fc4746ef38e83ec1ec96b5cf Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 07:46:37 -0700 Subject: [PATCH 0018/1441] ci: run the provider suites again on this head No file changes. The previous run's shard 3 failed on cancelledSubmitStillWaitsForProducerAndNative, a Qwen media cancellation test this branch does not touch; it passed on #1668 with the same provider tree. A push is used because re-running trips Release Integrity. Co-Authored-By: Claude Opus 5.5 From 230e96b48f24f290092005634d153cab7a3a6f41 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 12:44:02 -0700 Subject: [PATCH 0019/1441] cluster: a running cluster service answers the new pairing after a re-pair The cluster service built its exchange and control listeners once, keyed to the pairing current at start, and rebuilt them only when the cable moved. After the Macs paired again, the other Mac's leases and setup exchange were refused (handshakeRejected) until the service restarted. Each listener check (every 5 s) now also compares the pairing identity the listener was built with (both pins, cluster label, link epoch and edge; never the secret) with the stored pairing. On a change both listeners are rebuilt with the new pairing; with no pairing they stop; an unreadable store changes nothing. The control node is dropped when this Mac's own member ID changes. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-service-follows-repair.md | 6 + docs/architecture/inference.md | 35 ++++ docs/developer/test.md | 21 ++ docs/provider/two-mac-cluster.md | 8 + .../Console/ClusterSetupLinkExchange.swift | 18 ++ .../Onboarding/ClusterService.swift | 95 ++++++--- .../Onboarding/ClusterServiceControl.swift | 18 +- .../ClusterConsoleCheck.swift | 1 + .../ConsolePairingChangeChecks.swift | 141 +++++++++++++ .../ClusterServicePairingChangeTests.swift | 188 ++++++++++++++++++ 10 files changed, 498 insertions(+), 33 deletions(-) create mode 100644 changelog.d/cluster-service-follows-repair.md create mode 100644 provider-swift/Tests/ClusterConsoleChecks/ConsolePairingChangeChecks.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServicePairingChangeTests.swift diff --git a/changelog.d/cluster-service-follows-repair.md b/changelog.d/cluster-service-follows-repair.md new file mode 100644 index 0000000000..b96c0deef1 --- /dev/null +++ b/changelog.d/cluster-service-follows-repair.md @@ -0,0 +1,6 @@ +### A running cluster service answers after the Macs pair again + +- When the two Macs pair again while their cluster services run (`darkbloom cluster` or `darkbloom cluster pair`), each service starts its setup and control-lease listeners again with the new pairing within about 5 seconds. They used to keep the earlier pairing's key until the service restarted, so the other Mac's leases and its "Reading both Macs over the cable" step were refused (`refused (handshakeRejected)`). The service log says `this Mac's pairing changed (): answering the paired Mac with the new one`. +- A Mac left with no pairing stops answering over the cable. A pairing store that cannot be read leaves the listeners as they are. +- A Mac that paired again under a new Secure Enclave key of its own drops its earlier control state, as it already did when the other Mac's key changed. +- A cluster service started by an earlier release keeps the earlier behavior until it restarts (log out and back in, or `darkbloom cluster stop` and then `darkbloom cluster`). diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..cfb2fad77c 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3538,6 +3538,41 @@ part the same key with a different file (`ClusterServiceAgent.partHealthPath`, service's heartbeat and still waits for its registration as a supervised member. An empty or absent key is passed on unchanged. +## Cluster service listeners follow the cable and the pairing + +Each Mac's cluster service answers the other Mac on two listeners: the setup +exchange's (`ClusterSetupLinkExchange.port`) and the control lease's +(`ClusterSetupLinkExchange.controlPort`). A listener binds the cable's port and +address as they are when it starts, and is keyed with the pairing that holds +then (`ClusterSetupLinkExchange.Responder.pairing`). It refuses every handshake +the other Mac keys with a later pairing (`handshakeRejected` there), so a +listener left on an earlier pairing refuses every lease and setup request. + +At most once per `ClusterService.listenerCheckSeconds` +(`static let listenerCheckSeconds: Double = 5`) seconds for each listener, +`ClusterService.listenerChange` compares the listener with what holds now: + +- a cable on another port or address restarts it there; +- another pairing restarts it with that pairing. `ClusterSetupLinkExchange.Pairing.Identity` + compares both pins, the cluster label, the link epoch and the edge, never the + edge secret; every ceremony derives a new link epoch, so pairing the same two + Macs again is another pairing; +- no pairing at all stops it; +- a pairing store that cannot be read changes nothing, as an unreadable setup + record leaves a running part alone. + +Each restart or stop of the exchange's listener names its reason in the service +log; the control lease's listener restarts and stops without a line. The +control node of an earlier pairing is dropped once the pairing names another +local or peer member (`ClusterService.ensureControl`). + +Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift` +(`ClusterService.listenerChange`, `ensureResponder`), +`provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterServiceControl.swift` +(`ensureControlResponder`, `ensureControl`) and +`provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupLinkExchange.swift` +(`ClusterSetupLinkExchange.Responder`). + ## GLM tool-stream completion GLM tool output uses the SDK GLM parser to validate the complete tool suffix at diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..215a1c6fa1 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -2462,6 +2462,27 @@ The planned-stop lifecycle suite also pauses the actual service immediately befo Planned-stop lifecycle checks exercise the actual peerLeaseState projection, accepted ClusterControlNode follower lease, ClusterControlIntent recording and follower part selection while the real owned child is retained after TERM, while start is paused, and after retirement. A held outbound lease custody flag must block final peer stop after local child exit. Optional-record compatibility and an already-idle peer are checked separately. No physical peer transport or installed native shutdown is claimed by these CPU cases. +### Cluster service listeners after pairing again + +`ClusterServicePairingChangeTests` runs the actual service's two listeners on +loopback ports of their own (`ClusterService.Listening`), keyed from real pairing +ceremonies stored in a private home. After the same two Macs pair again, the +earlier listeners refuse the new pairing (`handshakeRejected`) until the next +check starts them again; then the new pairing is answered and the earlier one +refused. A removed pairing stops both listeners, an unchanged or unreadable +pairing store keeps the same ones, and the control node of this Mac's earlier key +is dropped. The other Mac dials without the per-user request lock, which a +cluster service running on the same Mac shares; no production port or +Thunderbolt interface is used. `ClusterConsoleChecks` (`listenersFollowThePairing`) +checks the same refusal and restart on real ceremonies and listeners without the +service, and that a re-read pairing store gives the same identity, a new +ceremony another one and an unsafe store a read failure rather than no pairing. + +Focused check: `swift test --filter ClusterServicePairingChangeTests` from +`provider-swift`. Sources: +`provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServicePairingChangeTests.swift` +and `provider-swift/Tests/ClusterConsoleChecks/ConsolePairingChangeChecks.swift`. + ### Qwen27 capacity consistency checks Every Qwen TP row serves through these request-owned lanes. `QwenTensorParallelBatchSessionTests` diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index d8688b78b8..cc8e03f3b9 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -578,6 +578,14 @@ Automatic updates for a pair are a follow-up. Until then, update by hand: run `darkbloom cluster` and press `f` when offered; macOS asks for administrator approval to configure that port. Recovery RDMA enablement and Local Network privacy permission remain separate steps. +- **The Macs were paired again** while their cluster services ran + (`darkbloom cluster` or `darkbloom cluster pair`): each service answers with + the new pairing within seconds, and its log, + `~/.darkbloom/cluster-setup/service.log`, says `this Mac's pairing changed` + ([listeners](../architecture/inference.md#cluster-service-listeners-follow-the-cable-and-the-pairing)). + If the other Mac still refuses the connection (`refused (handshakeRejected)`), + restart its service, since one an earlier release started keeps the earlier + pairing: on that Mac, run `darkbloom cluster stop`, then `darkbloom cluster`. - **A part keeps ending the same way**: after three identical ends the screen says it and offers `d`; both Macs keep trying by themselves. - **The leader cannot reach the other Mac**: make sure the other Mac is on and diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupLinkExchange.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupLinkExchange.swift index 163e5128dc..9db7ef5151 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupLinkExchange.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupLinkExchange.swift @@ -109,6 +109,20 @@ public enum ClusterSetupLinkExchange { } public var localMemberID: String { ClusterSetupMemberFacts.memberID(pin: localPin) } public var peerMemberID: String { ClusterSetupMemberFacts.memberID(pin: peerPin) } + + /// What tells this pairing from another, from its public values only. Every ceremony derives a new link epoch + /// from its transcript, as it derives a new edge secret, so pairing the same two Macs again changes it too. + public struct Identity: Sendable, Equatable { + public let localPin: String + public let peerPin: String + public let clusterID: String + public let linkEpoch: String + public let edgeID: String + } + + public var identity: Identity { + Identity(localPin: localPin, peerPin: peerPin, clusterID: clusterID, linkEpoch: linkEpoch, edgeID: edgeID) + } } /// Nil when this Mac never paired over the link. With several pairings, the newest. @@ -153,6 +167,9 @@ public enum ClusterSetupLinkExchange { private let edgeID: UUID /// The cable port and address it listens on (it never follows the cable to another port by itself). public let selection: ClusterLinkInterfaceSelection + /// The pairing whose key it answers with. It never follows a later pairing by itself: the other Mac's every + /// connection keyed with that one is refused (`handshakeRejected` there). + public let pairing: Pairing.Identity public init(pairing: Pairing, selection: ClusterLinkInterfaceSelection, port: UInt16 = ClusterSetupLinkExchange.port, policy: ClusterLinkInterfacePolicy = .thunderboltOnly, @@ -164,6 +181,7 @@ public enum ClusterSetupLinkExchange { let edge = try ClusterSetupLinkExchange.edge(pairing, peerAddress: nil, label: epochLabel) edgeID = edge.edgeID self.selection = selection + self.pairing = pairing.identity let work = DispatchQueue(label: "darkbloom.cluster-setup.exchange") listener = try ClusterLinkControlListener(configuration: .init(interface: selection.interface, localAddress: selection.local.address, port: port, policy: policy, edges: [edge])) { event, peer in diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index 980bc6cf43..9b406f75ef 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -96,7 +96,7 @@ public final class ClusterService: @unchecked Sendable { /// The part whose end (or failed start) set `nextStart`: its restart backoff does not hold back another part. private var endedKey: String? private var backoff: Double = 3 - private var responder: ClusterSetupLinkExchange.Responder? + var responder: ClusterSetupLinkExchange.Responder? var stopping = false private var syncing = false private var nextSync = Date.distantPast @@ -141,9 +141,10 @@ public final class ClusterService: @unchecked Sendable { /// Seconds before the next ask: 10 while the other Mac answers, longer (to 120) while it does not, so the link's /// one-at-a-time request lock is not held for the other commands. private var relayAskInterval: Double = 10 - /// When each listener last looked for the cable on another port (`cableMove`). - private var responderCableCheck = Date.distantPast - var controlCableCheck = Date.distantPast + /// When each listener last checked its cable port and its pairing (`listenerChange`). + var responderCheck = Date.distantPast + var controlCheck = Date.distantPast + let listening: Listening var leaseInFlight = false var nextLease: Double = 0 var lastModeLine: String? @@ -160,17 +161,18 @@ public final class ClusterService: @unchecked Sendable { try self.init(settings: settings, paths: ClusterUserPaths()) } - /// Internal composition of the service's existing stores. Public callers keep - /// the canonical user namespace, the normal recovery deadline and the one-second supervision interval. + /// Internal composition of the service's existing stores. Public callers keep the canonical user namespace, + /// the normal recovery deadline, the one-second supervision interval and the cable's listeners. init(settings: Settings, paths: ClusterUserPaths, recoveryGraceSeconds: Double = 300, supervisionIntervalSeconds: Double = 1, beforePartStart: (@Sendable () -> Void)? = nil, - environment: [String: String]? = nil) { + environment: [String: String]? = nil, listening: Listening = .init()) { precondition(recoveryGraceSeconds.isFinite && recoveryGraceSeconds >= 0) precondition(supervisionIntervalSeconds.isFinite && supervisionIntervalSeconds > 0) self.recoveryGraceSeconds = recoveryGraceSeconds self.supervisionIntervalSeconds = supervisionIntervalSeconds self.beforePartStart = beforePartStart self.environment = environment + self.listening = listening pairingStore = .default(home: paths.homeDirectory) var wizard = settings.wizard wizard.derivedPlacement = true @@ -332,37 +334,75 @@ public final class ClusterService: @unchecked Sendable { } } - /// How often a listener looks for the cable on another port: a cable moved to another Thunderbolt port (or a port - /// whose address changed) leaves the listener on the old one, where the other Mac never reaches it. - static let cableCheckSeconds: Double = 5 + /// Where this service's two listeners answer: the cable's interface, on the exchange's and the control lease's own + /// ports. The checks put them on loopback, on ports of their own. + struct Listening: Sendable { + var exchangePort = ClusterSetupLinkExchange.port + var controlPort = ClusterSetupLinkExchange.controlPort + var policy = ClusterLinkInterfacePolicy.thunderboltOnly + /// Nil: the cable's interface on this Mac, read at each use (`LiveContext.linkSelection`). + var selection: ClusterLinkInterfaceSelection? + } + + func listenerSelection() throws -> ClusterLinkInterfaceSelection { + try listening.selection ?? context.linkSelection() + } - /// The cable's port now when it is not the one `listener` was started on (checked at most every - /// `cableCheckSeconds` per listener, `checked`); nil when it has not moved, or there is no listener or cable. - func cableMove(of listener: ClusterSetupLinkExchange.Responder?, - checked: ReferenceWritableKeyPath) -> ClusterLinkInterfaceSelection? { - guard let bound = listener?.selection else { return nil } + /// How often a listener checks that it still reaches the paired Mac: a cable moved to another Thunderbolt port (or a + /// port whose address changed) leaves it on the old one, where the other Mac never reaches it, and a pairing made + /// since it started leaves it keyed with the old one, so it refuses the other Mac's every connection (2026-10-31). + static let listenerCheckSeconds: Double = 5 + + /// What leaves a running listener unable to answer the paired Mac. + enum ListenerChange { + /// The cable is on another port, or its port has another address, now. + case cableMoved(ClusterLinkInterfaceSelection) + /// The pairing this Mac uses now is another one (`darkbloom cluster` or `darkbloom cluster pair` paired it + /// again). + case pairingChanged(ClusterSetupLinkExchange.Pairing.Identity) + /// This Mac holds no pairing now. + case unpaired + } + + /// What changed since `listener` started (checked at most every `listenerCheckSeconds` per listener, `checked`); nil + /// when nothing did, or there is no listener. A cable or pairing store that cannot be read now changes nothing. + func listenerChange(of listener: ClusterSetupLinkExchange.Responder?, + checked: ReferenceWritableKeyPath) -> ListenerChange? { + guard let listener else { return nil } let due = lock.withLock { () -> Bool in - guard Date().timeIntervalSince(self[keyPath: checked]) >= Self.cableCheckSeconds else { return false } + guard Date().timeIntervalSince(self[keyPath: checked]) >= Self.listenerCheckSeconds else { return false } self[keyPath: checked] = Date() return true } - guard due, let current = try? context.linkSelection(), - ClusterSetupLinkExchange.cableMoved(bound: bound, current: current) else { return nil } - return current + guard due else { return nil } + if let current = try? listenerSelection(), ClusterSetupLinkExchange.cableMoved(bound: listener.selection, current: current) { + return .cableMoved(current) + } + let pairing: ClusterSetupLinkExchange.Pairing? + do { pairing = try ClusterSetupLinkExchange.pairing(store: pairingStore) } catch { return nil } + guard let identity = pairing?.identity else { return .unpaired } + return identity == listener.pairing ? nil : .pairingChanged(identity) } - private func ensureResponder(say: @escaping @Sendable (String) -> Void) { - if let moved = cableMove(of: lock.withLock({ responder }), checked: \.responderCableCheck) { + func ensureResponder(say: @escaping @Sendable (String) -> Void) { + if let change = listenerChange(of: lock.withLock({ responder }), checked: \.responderCheck) { lock.withLock { responder }?.stop() lock.withLock { responder = nil } - say("the cable is on \(moved.interface) now: answering the paired Mac there") - // A port that was never set up has no fixed address: the other Mac cannot find this one there. - if let port = OnboardingLive.unsetCablePort(ClusterLinkReadinessProbe.inspectLocalLink()) { - say("\(port) is not set up for the cluster: run `darkbloom cluster` on this Mac and press f (macOS asks for your password once)") + switch change { + case .cableMoved(let moved): + say("the cable is on \(moved.interface) now: answering the paired Mac there") + // A port that was never set up has no fixed address: the other Mac cannot find this one there. + if let port = OnboardingLive.unsetCablePort(ClusterLinkReadinessProbe.inspectLocalLink()) { + say("\(port) is not set up for the cluster: run `darkbloom cluster` on this Mac and press f (macOS asks for your password once)") + } + case .pairingChanged(let current): + say("this Mac's pairing changed (\(current.clusterID)): answering the paired Mac with the new one") + case .unpaired: + say("this Mac is no longer paired: it stopped answering over the cable") } } guard lock.withLock({ responder == nil }), let pairing = try? ClusterSetupLinkExchange.pairing(store: pairingStore), - let selection = try? context.linkSelection() else { return } + let selection = try? listenerSelection() else { return } let context = self.context, store = self.store // A model the leader copies here over the cable lands in this Mac's model store, verified file by file. let provisioner = ClusterModelProvisionResponder(store: { @@ -376,7 +416,8 @@ public final class ClusterService: @unchecked Sendable { return ClusterModelWorkerCheck(executable: URL(fileURLWithPath: local.workerExecutable), runtimeBinarySHA256: local.runtimeBinarySHA256) }, say: say) do { - let created = try ClusterSetupLinkExchange.Responder(pairing: pairing, selection: selection, answer: { + let created = try ClusterSetupLinkExchange.Responder(pairing: pairing, selection: selection, + port: listening.exchangePort, policy: listening.policy, answer: { ClusterSetupLinkAnswer(report: context.report(input: context.pairInput(), saved: context.savedConfiguration(), inbox: ClusterSetupLocalReader.inbox(store)), facts: try context.localFacts(pairing: pairing, selection: selection)) }, receive: { [weak self] data in diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterServiceControl.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterServiceControl.swift index 1abbbb18d8..b9510b2354 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterServiceControl.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterServiceControl.swift @@ -106,16 +106,17 @@ extension ClusterService { // MARK: - The control listener func ensureControlResponder(say: @escaping @Sendable (String) -> Void) { - // The lease listener follows the cable to another port too (`cableMove`), or leases never reach this Mac there. - if cableMove(of: lock.withLock({ controlResponder }), checked: \.controlCableCheck) != nil { + // The lease listener follows the cable to another port and the pairing to a new one too (`listenerChange`), or + // leases never reach this Mac; the exchange's listener says so. + if listenerChange(of: lock.withLock({ controlResponder }), checked: \.controlCheck) != nil { lock.withLock { controlResponder }?.stop() lock.withLock { controlResponder = nil } } guard lock.withLock({ controlResponder == nil }), let pairing = try? ClusterSetupLinkExchange.pairing(store: pairingStore), - let selection = try? context.linkSelection() else { return } + let selection = try? listenerSelection() else { return } do { let created = try ClusterSetupLinkExchange.Responder(pairing: pairing, selection: selection, - port: ClusterSetupLinkExchange.controlPort, epochLabel: ClusterSetupLinkExchange.controlLabel, + port: listening.controlPort, policy: listening.policy, epochLabel: ClusterSetupLinkExchange.controlLabel, answer: { throw ClusterSetupFailure("the control listener reports nothing") }, receive: { _ in throw ClusterSetupFailure("the control listener takes no setup") }, command: { [weak self] data in @@ -172,8 +173,13 @@ extension ClusterService { // MARK: - Each tick func ensureControl(pairing: ClusterSetupLinkExchange.Pairing) { - // A node of an earlier pairing (this Mac was re-paired with another Mac while the service ran) is dropped. - lock.withLock { if let node = control, !node.claim.members.contains(pairing.peerMemberID) { control = nil } } + // A node of an earlier pairing (this Mac was re-paired with another Mac, or under a new key of its own, while the + // service ran) is dropped. + lock.withLock { + if let node = control, node.localID != pairing.localMemberID || !node.claim.members.contains(pairing.peerMemberID) { + control = nil + } + } guard lock.withLock({ control == nil }), let record = try? store.readRecord(), let leadership = record.leadership, leadership.peerPin == pairing.peerPin else { return } let local = localControlMember(pairing: pairing, record: record) diff --git a/provider-swift/Tests/ClusterConsoleChecks/ClusterConsoleCheck.swift b/provider-swift/Tests/ClusterConsoleChecks/ClusterConsoleCheck.swift index fa3462c886..eb51230243 100644 --- a/provider-swift/Tests/ClusterConsoleChecks/ClusterConsoleCheck.swift +++ b/provider-swift/Tests/ClusterConsoleChecks/ClusterConsoleCheck.swift @@ -61,6 +61,7 @@ import Darwin ("saved setup, trust and candidate", savedSetup), ("serving scope kept in the setup record", servingScopeInTheRecord), ("the cable moved to another port: listeners follow it", cableMovesToAnotherPort), + ("the Macs paired again: listeners follow the pairing", listenersFollowThePairing), ("the owner a setup names is the file, not the PATH link", ownerIsTheFileNotThePathLink), ("what each Mac holds", holdings), ("link fix results and the guided setup's reading", linkFixResults), diff --git a/provider-swift/Tests/ClusterConsoleChecks/ConsolePairingChangeChecks.swift b/provider-swift/Tests/ClusterConsoleChecks/ConsolePairingChangeChecks.swift new file mode 100644 index 0000000000..7120eb71a5 --- /dev/null +++ b/provider-swift/Tests/ClusterConsoleChecks/ConsolePairingChangeChecks.swift @@ -0,0 +1,141 @@ +import CryptoKit +import Darwin +import Foundation +import DarkbloomClusterRemote +import DarkbloomClusterSecurity +@testable import InstalledContract + +extension ClusterConsoleCheck { + /// A software P-256 key in place of a Mac's Secure Enclave key. + struct PairingKey: ClusterPairingIdentity { + let key = P256.Signing.PrivateKey() + var identityPublicKey: Data { key.publicKey.x963Representation } + func pairingSignature(for message: Data) throws -> Data { try key.signature(for: message).derRepresentation } + } + + /// One pairing ceremony in memory, each end stored in its own store with the edge both ends derive from their pins + /// and interfaces, as the pairing command stores it. + static func pairInMemory(_ listener: PairingKey, _ connector: PairingKey, stores: (ClusterPairingStore, ClusterPairingStore)) throws { + let posture = ClusterPairingPeerPosture(chipName: "Test chip", hardwareModel: "Test1,1", osVersion: "26.0.0", + sipEnabled: true, secureBootEnabled: true, authenticatedRootEnabled: true) + // The attestation is the identity key's signature over the ceremony's ephemeral key. + let hooks = ClusterPairingHooks(verifyAttestation: { attestation, identityKey, ephemeral in + guard let key = try? P256.Signing.PublicKey(x963Representation: identityKey), + let signature = try? P256.Signing.ECDSASignature(derRepresentation: attestation), + key.isValidSignature(signature, for: ephemeral) else { return nil } + return posture + }, rosterCanonical: { clusterID, generation, members in + Data(([clusterID, String(generation)] + members.map { $0.pin + $0.identityKey.base64EncodedString() }).joined(separator: "\n").utf8) + }) + func participant(_ key: PairingKey, _ store: ClusterPairingStore) -> ClusterPairingParticipant { + .storeBacked(identity: key, name: "Test Mac", interface: "lo0", attestation: { try key.pairingSignature(for: $0) }, store: store) + } + var sessions: [ClusterPairingRole: ClusterPairingSession] = [ + .listener: try ClusterPairingSession(role: .listener, participant: participant(listener, stores.0), hooks: hooks), + .connector: try ClusterPairingSession(role: .connector, participant: participant(connector, stores.1), hooks: hooks), + ] + var queue = [(ClusterPairingRole, ClusterPairingMessage)]() + var completed = 0 + func perform(_ steps: [ClusterPairingStep], _ role: ClusterPairingRole) { + for step in steps { + switch step { + case .send(let message): queue.append((role == .listener ? .connector : .listener, message)) + case .showCode: perform(sessions[role]!.decide(accept: true), role) + case .persist(let outcome): + let edge = ClusterLinkControlEdge.derivedEdgeID(firstMember: outcome.localPin, firstInterface: outcome.localInterface, + secondMember: outcome.peer.pin, secondInterface: outcome.peer.interface) + let stored = (try? (role == .listener ? stores.0 : stores.1).commit(outcome, edgeID: edge)) != nil + perform(sessions[role]!.localPersisted(stored), role) + case .completed: completed += 1 + case .peerDecided, .rollback, .failed: break + } + } + } + perform(sessions[.connector]!.start(), .connector) + while !queue.isEmpty { + let (to, message) = queue.removeFirst() + perform(sessions[to]!.receive(message), to) + } + guard completed == 2 else { throw ClusterSetupFailure("the pairing in memory did not complete") } + } + + /// A cluster service's listener answers with the key of the pairing it started with, and a pairing made since is + /// another pairing (2026-10-31: after the Macs paired again, the member's service refused every lease and the + /// wizard's reading with `handshakeRejected` until it restarted). The service starts a listener again when the + /// pairing read here is another one than the listener names, and stops it when there is none; an unreadable store + /// changes nothing. Real ceremonies in private stores, real listeners on loopback, the other Mac dialing with the + /// pairing it stored. + static func listenersFollowThePairing() throws { + typealias X = ClusterSetupLinkExchange + guard let selection = try? ClusterLinkInterfaceAdmission.select(interface: "lo0", localAddress: nil, peerAddress: nil, + policy: .loopbackForTests, inspector: ClusterLinkSystemInterfaceInspector()) else { + expect(false, "lo0 selection"); return + } + let port: UInt16 = 45_891 + let root = scratch.appendingPathComponent("pairing-again", isDirectory: true) + let here = ClusterPairingStore(directory: root.appendingPathComponent("this-mac/cluster-pairing", isDirectory: true)) + let there = ClusterPairingStore(directory: root.appendingPathComponent("other-mac/cluster-pairing", isDirectory: true)) + func listen(_ pairing: X.Pairing) throws -> X.Responder { + let listener = try X.Responder(pairing: pairing, selection: selection, port: port, policy: .loopbackForTests, + answer: { throw ClusterSetupFailure("not asked") }, receive: { _ in "" }, command: { _ in Data("answered".utf8) }) + try listener.start() + return listener + } + // What the other Mac's service and wizard get for a pairing ("answered", or why not), without the per-user request + // lock that `ClusterSetupLinkExchange.command` takes: a cluster service running on this Mac shares it. + func dial(_ pairing: X.Pairing) -> String { + do { + let session = try X.Session(pairing: pairing, selection: selection, peerAddress: .loopback, port: port, policy: .loopbackForTests) + defer { session.close() } + let reply = try session.request(tag: X.commandTag, Data("status".utf8), reply: X.commandReplyTag, seconds: 2) + return String(decoding: reply, as: UTF8.self) == "ok:answered" ? "answered" : "unexpected reply" + } catch let failure as ClusterSetupFailure { return failure.text } catch { return "\(error)" } + } + + let thisMac = PairingKey(), otherMac = PairingKey() + try pairInMemory(thisMac, otherMac, stores: (here, there)) + guard let first = try X.pairing(store: here), let firstThere = try X.pairing(store: there) else { + expect(false, "both Macs read the pairing back"); return + } + expectEqual(try X.pairing(store: here)?.identity, first.identity, "the same store reads as the same pairing: nothing restarts") + let listener = try listen(first) + defer { listener.stop() } + expectEqual(listener.pairing, first.identity, "a listener names the pairing whose key it answers with") + expectEqual(dial(firstThere), "answered", "the other Mac is answered with the pairing both Macs stored") + + // The same two keys pair again: the same pins and edge, a new link epoch and edge secret. + try pairInMemory(thisMac, otherMac, stores: (here, there)) + guard let second = try X.pairing(store: here), let secondThere = try X.pairing(store: there) else { + expect(false, "both Macs read the new pairing back"); return + } + expect(second.identity != first.identity && second.linkEpoch != first.linkEpoch, "pairing again is another pairing (a new link epoch)") + expect(second.localPin == first.localPin && second.peerPin == first.peerPin && second.edgeID == first.edgeID, + "with the same pins and edge") + let stale = dial(secondThere) + expect(stale.contains("refused (handshakeRejected)"), "a listener keyed with the earlier pairing refuses the new one: \(stale)") + listener.stop() + let restarted = try listen(second) + defer { restarted.stop() } + expectEqual(dial(secondThere), "answered", "started again with the pairing now, the listener answers the new pairing") + let earlier = dial(firstThere) + expect(earlier.contains("refused (handshakeRejected)"), "and refuses the earlier one: \(earlier)") + restarted.stop() + + // A new key on this Mac replaces its pairings: another local pin, edge and link epoch. + try pairInMemory(PairingKey(), otherMac, stores: (here, there)) + guard let rekeyed = try X.pairing(store: here) else { expect(false, "the pairing under the new key reads back"); return } + expect(rekeyed.localPin != second.localPin && rekeyed.peerPin == second.peerPin && rekeyed.edgeID != second.edgeID + && rekeyed.identity != second.identity, "a new Secure Enclave key is another pairing") + + // A store others may open is refused, never read as no pairing; after unpairing it reads as none, without a failure. + chmod(here.directory.path, 0o755) + var refused = false + do { _ = try X.pairing(store: here) } catch { refused = true } + chmod(here.directory.path, 0o700) + expect(refused, "an unsafe pairing store is a failure to read, not an unpairing") + _ = try here.forget(peerPin: rekeyed.peerPin) + do { expect(try X.pairing(store: here) == nil, "an unpaired Mac has no pairing to answer for") } catch { + expect(false, "an unpaired store reads without a failure: \(error)") + } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServicePairingChangeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServicePairingChangeTests.swift new file mode 100644 index 0000000000..927e80dded --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServicePairingChangeTests.swift @@ -0,0 +1,188 @@ +import Darwin +import Foundation +import Testing +import DarkbloomClusterRemote +import DarkbloomClusterSecurity +@testable import ProviderCore + +/// The cluster service's two listeners follow a pairing made while it runs (2026-10-31: after the two Macs paired +/// again, the member's service refused every lease and the wizard's reading with `handshakeRejected` until it was +/// restarted). The actual service keys real listeners on loopback, on ports of their own, from real pairing ceremonies +/// stored in a private home. The other Mac dials with its copy of the pairing's key, without the per-user request lock +/// that `ClusterSetupLinkExchange.command` takes and any cluster service running on this Mac shares. +@Suite(.serialized) +struct ClusterServicePairingChangeTests { + typealias Signer = ClusterPairingProviderTests.SoftwareSigner + typealias Exchange = ClusterSetupLinkExchange + + @Test func bothListenersAnswerAPairingMadeWhileTheServiceRuns() throws { + let fixture = try Fixture() + defer { fixture.remove() } + let thisMac = Signer(), otherMac = Signer() + let first = try fixture.pair(thisMac, otherMac) + #expect(fixture.tick() == ["answering the paired Mac over the cable"]) + for listener in fixture.listeners { #expect(fixture.refusal(first, on: listener) == nil) } + + let second = try fixture.pair(thisMac, otherMac) + #expect(second.identity != first.identity && second.linkEpoch != first.linkEpoch, + "pairing the same two Macs again is another pairing") + // What the other Mac met until the service was restarted: its new pairing refused at the handshake. + for listener in fixture.listeners { + #expect(fixture.refusal(second, on: listener)?.contains("refused (handshakeRejected)") == true) + } + #expect(fixture.tick() == ["this Mac's pairing changed (provider-pair): answering the paired Mac with the new one", + "answering the paired Mac over the cable"]) + for listener in fixture.listeners { + #expect(fixture.refusal(second, on: listener) == nil, "the new pairing is answered on port \(listener.port)") + #expect(fixture.refusal(first, on: listener)?.contains("refused (handshakeRejected)") == true, + "the earlier pairing is refused on port \(listener.port)") + } + } + + @Test func bothListenersStopWhenThisMacIsNoLongerPaired() throws { + let fixture = try Fixture() + defer { fixture.remove() } + let pairing = try fixture.pair(Signer(), Signer()) + _ = fixture.tick() + for listener in fixture.listeners { try #require(fixture.refusal(pairing, on: listener) == nil) } + + _ = try fixture.pairingStore.forget(peerPin: pairing.peerPin) + #expect(fixture.tick() == ["this Mac is no longer paired: it stopped answering over the cable"]) + let stopped = fixture.responders() + #expect(stopped.exchange == nil && stopped.control == nil) + for listener in fixture.listeners { + #expect(fixture.refusal(pairing, on: listener)?.contains("connectFailed") == true, "nothing listens on port \(listener.port)") + } + #expect(fixture.tick().isEmpty, "and nothing starts again while this Mac holds no pairing") + } + + @Test func anUnchangedOrUnreadablePairingKeepsBothListeners() throws { + let fixture = try Fixture() + defer { fixture.remove() } + let pairing = try fixture.pair(Signer(), Signer()) + _ = fixture.tick() + let started = fixture.responders() + for _ in 0..<3 { #expect(fixture.tick().isEmpty) } + // A pairing store that cannot be read is not taken for no pairing, as an unreadable setup record is not taken + // for a stop. + chmod(fixture.pairingStore.directory.path, 0o755) + #expect(fixture.tick().isEmpty) + chmod(fixture.pairingStore.directory.path, 0o700) + let kept = fixture.responders() + #expect(kept.exchange != nil && kept.exchange === started.exchange && kept.control != nil && kept.control === started.control, + "no listener was started again") + for listener in fixture.listeners { #expect(fixture.refusal(pairing, on: listener) == nil) } + } + + /// The claim of a node built before this Mac paired again under a new key of its own still names the other Mac: only + /// its local identity tells that it belongs to the earlier pairing. + @Test func aControlNodeOfThisMacsEarlierKeyIsDropped() throws { + let fixture = try Fixture() + defer { fixture.remove() } + let otherMac = Signer() + let earlier = try fixture.pair(Signer(), otherMac) + try fixture.lead(earlier) + fixture.service.lock.withLock { fixture.service.localHardware = ("fixture", 1 << 30, 1, .unknown) } + fixture.service.ensureControl(pairing: earlier) + #expect(fixture.service.lock.withLock { fixture.service.control?.localID } == earlier.localMemberID) + + let current = try fixture.pair(Signer(), otherMac) + #expect(current.localPin != earlier.localPin && current.peerPin == earlier.peerPin) + try fixture.lead(current) + fixture.service.ensureControl(pairing: current) + let node = fixture.service.lock.withLock { fixture.service.control } + #expect(node?.localID == current.localMemberID) + #expect(node?.claim.members.contains(earlier.localMemberID) == false) + } + + private final class Said: @unchecked Sendable { + private let lock = NSLock() + private var said: [String] = [] + func add(_ line: String) { lock.withLock { said.append(line) } } + var lines: [String] { lock.withLock { said } } + } + + private struct Fixture { + let home: URL + let service: ClusterService + let records: ClusterSetupStore + let listening: ClusterService.Listening + let loopback: ClusterLinkInterfaceSelection + /// The other Mac's own store: the ceremony stores its side there. + let peerStore: ClusterPairingStore + var pairingStore: ClusterPairingStore { .default(home: home) } + var listeners: [(port: UInt16, label: String)] { + [(listening.exchangePort, Exchange.exchangeLabel), (listening.controlPort, Exchange.controlLabel)] + } + + init() throws { + home = try NativePairMemberFixture.privateRoot() + let paths = try ClusterUserPaths(homeDirectory: home) + records = ClusterSetupStore(paths: .init(paths: paths)) + loopback = try ClusterLinkInterfaceAdmission.select(interface: "lo0", localAddress: nil, peerAddress: nil, + policy: .loopbackForTests, inspector: ClusterLinkSystemInterfaceInspector()) + // Loopback ports of their own, below the production listeners' (`ClusterSetupLinkExchange.port`, `.controlPort`). + let exchangePort = UInt16(46_100 + getpid() % 300 * 2) + listening = .init(exchangePort: exchangePort, controlPort: exchangePort + 1, policy: .loopbackForTests, + selection: loopback) + let wizard = ClusterSetupOperations.LiveSettings(providerConfiguration: home.appendingPathComponent("provider.toml"), + darkbloomExecutable: home.appendingPathComponent("not-executed"), sessionArguments: [], pair: nil, dryRun: true, + version: "fixture") + service = ClusterService(settings: .init(wizard: wizard, leaderArguments: [], followerArguments: []), paths: paths, + listening: listening) + peerStore = ClusterPairingStore(directory: home.appendingPathComponent("other-mac/cluster-pairing", isDirectory: true)) + } + + /// One ceremony with the provider's participants, stored in both Macs' stores; this Mac's pairing after it. + func pair(_ thisMac: Signer, _ otherMac: Signer) throws -> Exchange.Pairing { + _ = try ClusterPairingProviderTests.pair(thisMac, otherMac, stores: (pairingStore, peerStore)) + return try #require(try Exchange.pairing(store: pairingStore)) + } + + /// The onboarding's record for `pairing`, with this Mac driving it, as `darkbloom cluster` writes it. + func lead(_ pairing: Exchange.Pairing) throws { + _ = try records.updateRecord { + $0.leadership = .init(role: ClusterOnboardingRole.leader.rawValue, leaderPin: pairing.localPin, + peerPin: pairing.peerPin, peerName: "the other Mac", since: "fixture") + } + } + + /// One supervision tick of both listeners, with their checks due; the lines the service said. + func tick() -> [String] { + let said = Said() + service.lock.withLock { service.responderCheck = .distantPast; service.controlCheck = .distantPast } + service.ensureResponder { said.add($0) } + service.ensureControlResponder { said.add($0) } + return said.lines + } + + func responders() -> (exchange: Exchange.Responder?, control: Exchange.Responder?) { + service.lock.withLock { (service.responder, service.controlResponder) } + } + + /// Nil when the listener answers the other Mac's copy of `pairing` (any reply follows an accepted handshake), + /// else why it did not. The copy is the pairing's key with the pins the other way round. + func refusal(_ pairing: Exchange.Pairing, on listener: (port: UInt16, label: String)) -> String? { + let theirs = Exchange.Pairing(localPin: pairing.peerPin, peerPin: pairing.localPin, clusterID: pairing.clusterID, + linkEpoch: pairing.linkEpoch, edgeID: pairing.edgeID, secretFile: pairing.secretFile, secret: pairing.secret) + do { + let session = try Exchange.Session(pairing: theirs, selection: loopback, peerAddress: .loopback, port: listener.port, + policy: .loopbackForTests, label: listener.label) + defer { session.close() } + _ = try session.request(tag: Exchange.commandTag, Data("not a command".utf8), reply: Exchange.commandReplyTag, seconds: 2) + return nil + } catch let failure as ClusterSetupFailure { + return failure.text + } catch { + return "\(error)" + } + } + + func remove() { + let running = responders() + running.exchange?.stop() + running.control?.stop() + try? FileManager.default.removeItem(at: home) + } + } +} From 4fff08802d03fabd70172c63da12a83e77add39c Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:23:10 -0700 Subject: [PATCH 0020/1441] cluster: pairs set up with darkbloom cluster update themselves like a single Mac Nothing updated a Mac set up with `darkbloom cluster`: the cluster service's supervisor was built with no coordinator URL and autoUpdate off, the member part never starts the in-process updater, and the watchdog defers to the supervisor. The supervisor now runs the single-Mac update sequence (AutoUpdateController) at the pair's shared update slot, gated by auto_update and DARKBLOOM_NO_UPDATE_CHECK. Both Macs stage the verified release while serving; once both staged, rank 0 drains with the existing draining heartbeat (no accepted request is cancelled); once both drained, each installs and restarts from the new binary, and the leader re-plans once both run one build. A release one Mac cannot stage is installed on neither and both retry at the next slot. The candidate is promoted or rolled back by the watchdog's rules (ClusterCandidateRecovery). `darkbloom update` asks the supervisor for the same coordinated restart, so no log-out is needed. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-auto-update.md | 9 + docs/architecture/inference.md | 6 +- docs/developer/test.md | 36 ++ docs/provider/cli-reference.md | 9 +- docs/provider/cluster-always-on.md | 77 ++- docs/provider/two-mac-cluster.md | 73 ++- docs/reference/configuration.md | 2 +- .../Installed/ClusterPairUpdateProgress.swift | 76 +++ .../Installed/ClusterServiceWire.swift | 3 + .../Onboarding/ClusterOnboardingFlow.swift | 9 + .../Onboarding/ClusterService.swift | 17 +- .../ProviderLoop+ClusterUpdateDrain.swift | 81 +++ .../ProviderCore/ProviderLoop+Lifecycle.swift | 1 + .../Sources/ProviderCore/ProviderLoop.swift | 4 + .../ProviderCore/ProviderLoopConfig.swift | 6 + .../Service/ClusterServiceAgent.swift | 11 + .../ClusterMemberUpdateSlot.swift | 5 +- .../ClusterPairUpdate.swift | 120 +++++ .../Service/ClusterUpdateDrain.swift | 60 +++ .../Service/LifecycleMailbox.swift | 7 + .../Update/ClusterCandidateRecovery.swift | 102 ++++ .../Update/ClusterPairUpdateCycle.swift | 474 ++++++++++++++++++ .../darkbloom/ClusterMemberSupervisor.swift | 199 +++++++- .../darkbloom/ClusterServiceCommand.swift | 60 ++- .../StartCommand+ClusterMember.swift | 10 +- .../Sources/darkbloom/UpdateCommand.swift | 59 +++ .../OnboardingChecks.swift | 6 + .../Tests/ClusterSupervisionChecks/main.swift | 83 +++ .../Tests/ClusterSupervisionChecks/run.sh | 1 + .../ClusterServiceUpdateTests.swift | 311 ++++++++++++ .../Update/ClusterPairUpdateTests.swift | 382 ++++++++++++++ 31 files changed, 2234 insertions(+), 65 deletions(-) create mode 100644 changelog.d/cluster-auto-update.md create mode 100644 provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPairUpdateProgress.swift create mode 100644 provider-swift/Sources/ProviderCore/ProviderLoop+ClusterUpdateDrain.swift create mode 100644 provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift create mode 100644 provider-swift/Sources/ProviderCore/Service/ClusterUpdateDrain.swift create mode 100644 provider-swift/Sources/ProviderCore/Update/ClusterCandidateRecovery.swift create mode 100644 provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift diff --git a/changelog.d/cluster-auto-update.md b/changelog.d/cluster-auto-update.md new file mode 100644 index 0000000000..05d9c3a5d0 --- /dev/null +++ b/changelog.d/cluster-auto-update.md @@ -0,0 +1,9 @@ +### Pair Macs set up with `darkbloom cluster` update themselves + +- A Mac set up with `darkbloom cluster` now updates itself, as a single Mac does: with `auto_update` on (the default) and without `DARKBLOOM_NO_UPDATE_CHECK`, its cluster service checks the coordinator's latest release every 30 minutes, at the pair's update slot, which both Macs derive from their pairing's cluster ID. +- Each Mac downloads, verifies and stages the release while the pair serves. Only once both Macs have it does the pair stop taking new requests; the Mac that serves the pair finishes its accepted requests (at most 120 seconds, never cancelling one), then both Macs install the release and restart their cluster services, and the cluster sets itself up again for the new release with no command run. +- A pair under constant traffic updates too: once it takes no new requests, the accepted ones finish. A pair still running a request at the bound takes requests again and tries at the next slot. A release one Mac cannot download or verify is installed on neither Mac; both try again at the next slot. +- An installed release is promoted once its cluster service has stayed healthy for 10 minutes; three starts of its service that end on their own restore the previous release and quarantine the new one, as the watchdog does for a single Mac. +- `darkbloom update` on a cluster Mac installs the release and then restarts the cluster service into it together with the other Mac, after the pair drained; logging out and back in is no longer needed. Run it on both Macs (or let the other Mac update at the next slot); the first Mac waits up to 15 minutes for the second, also when automatic updates are off. A Mac whose partner has automatic updates off downloads nothing at the slot. +- A pair that serves on the leader's local API, or a Mac that serves alone, is not drained for an update yet: it does not update while it serves, and a cluster set to serve locally (`darkbloom cluster local`) or a Mac serving alone downloads nothing at the slot. +- A cluster service started by an earlier release does none of this: to reach this release, run `darkbloom update` on both Macs, then log out and back in on both (or restart them) once. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..34a6ce2905 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -2963,7 +2963,11 @@ transcript without a live line keeps only the reports `TransferProgressLine.takeLogLine` marks and the lines for the record. After a Darkbloom update changes a Mac's worker digest, the control leader's cluster service re-plans and re-adopts the same model by itself -(`ClusterService.checkForUpdate`, `ClusterOnboardingUpdate`). A model change of +(`ClusterService.checkForUpdate`, `ClusterOnboardingUpdate`), once both Macs +answer with the same worker build (`ClusterOnboardingUpdate.oneBuild`): the +[pair's coordinated update](../provider/cluster-always-on.md#the-pairs-coordinated-update) +restarts the two Macs seconds apart, and a plan made while one still runs the +other build would fail and wait 600 s. A model change of a serving cluster (`m`, or `darkbloom cluster local `) plans the same way: its list was priced while the running parts held their memory, where tensor parallel may not fit now, so once both parts stopped and both Macs gave the diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..37671c0c49 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1041,6 +1041,42 @@ timeout, one-time failure accounting and heartbeat promotion. It does not run native launchd, the controller cancellation interleaving or a signed release installation. +## Cluster Pair Coordinated Update + +`ClusterPairUpdateTests` +(`provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift`) +runs two Macs' `ClusterPairUpdateCycle` in one process: each with the real +updater on its own temporary install, a loopback `MockCoordinator` serving the +release, and a real member loop as its part (a scripted pair owner holds rank 0's +request). It checks that a busy pair stages while serving, closes admission only +once both Macs staged, finishes the accepted request uncancelled and then +installs on both; that a request past the drain bound reopens admission and +defers both Macs, and the next cycle updates; that one Mac's failed download +stops both and the next cycle updates both; that a Mac whose partner has +automatic updates off downloads nothing at the slot, while `darkbloom update` on +both Macs updates them; that a part that cannot drain downloads nothing; that a +Mac whose partner cannot be asked goes on alone only while no pair runs on it; +and the candidate's promotion (kept under another update's lease) and rollback. +`ClusterServiceUpdateTests` +(`provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift`) drives +the real supervisor with a shell standing in for the cluster service: the +single-Mac gate, a slot fired from a cluster ID whose slot is seconds away, no +slot cycle with automatic updates off (and `disabled` reported again once a +cycle's end is a minute old), `darkbloom update`'s request and the candidate's +rollback and promotion; the re-exec is observed, never performed. +`Tests/ClusterSupervisionChecks/run.sh` checks the progress rules +(`ClusterPairUpdate.partnerState`) with plain `swiftc`. + +```bash +CFFIXED_USER_HOME="$(mktemp -d)" swift test --skip-build --no-parallel \ + --filter 'ClusterPairUpdateTests|ClusterServiceUpdateTests' +``` + +Keep `CFFIXED_USER_HOME` (or an isolated user) on a Mac that serves: the member +loops and supervisors otherwise use the real `~/.darkbloom` for their cluster +files. These checks use loopback and temporary roots only; they do not run a +pair, launchd, a signed release or the coordinator's routing of a draining pair. + ## Public Fixtures And Private Qualification Public protocol JSON and prompt golden vectors contain fixed inputs and expected diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index abab9afda0..17aa65b5cb 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1801,6 +1801,13 @@ darkbloom update [--check-only] [--coordinator ] [--timeout ] [--f The update path verifies bundle, binary, and `mlx.metallib` hashes before replacing the running binary (`provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift`). +On a Mac whose `darkbloom cluster` service runs, the command then asks that +service's supervisor to restart into the installed release together with the +other Mac, after the pair drained, and prints its progress until the restart +(at most `--timeout` seconds); a deferral exits 1 +(`provider-swift/Sources/darkbloom/UpdateCommand.swift`, `ClusterServiceUpdateRequest`; +[updating Darkbloom on the pair](two-mac-cluster.md#updating-darkbloom-on-the-pair)). + ## `darkbloom autoupdate` Enable or disable automatic update checks at startup. @@ -2138,7 +2145,7 @@ override `provider.toml` for one process, are in | Key | Default | Effect | |---|---|---| | `[provider] memory_reserve_gb | 4 | GiB withheld from the selected OS-available/MLX load budget; the larger unified-cap reserve still applies. By default OS availability includes inactive pages or, when larger, the reclaimable file page cache, so this is not a free-page floor. Set process-start DARKBLOOM_MEMORY_AVAILABILITY=free-only for shared hosts; see [memory admission](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/docs/architecture/scheduling.md#shared-host-memory-admission). | -| `[provider] auto_update` | `true` | Startup + periodic self-update | +| `[provider] auto_update` | `true` | Startup + periodic self-update; on a `darkbloom cluster` Mac, the pair's coordinated update at its update slot ([cluster service](cluster-always-on.md#the-pairs-coordinated-update)) | | `[provider] auto_restart` | `true` | Arm the watchdog LaunchAgent | | `[provider] update_jitter_seconds` | `300` | Max random delay before an automatic install or a network provider drains a model for a prepared MTP replacement; serving continues during the delay. `0` disables jitter; capped at `3600`. Standalone MTP upgrades skip this delay. Random staggering provides no fleet availability guarantee (`provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift`, `updateJitterSeconds`; `provider-swift/Sources/ProviderCore/Update/UpdateJitter.swift`, `delay`; `provider-swift/Sources/ProviderCore/ProviderLoop+MTPDrain.swift`, `waitBeforeMTPUpgradeDrain`) | | `[backend] enabled_models` | `[]` | Advertise only these ids; empty = all serveable | diff --git a/docs/provider/cluster-always-on.md b/docs/provider/cluster-always-on.md index d4b21423f9..fc7105989a 100644 --- a/docs/provider/cluster-always-on.md +++ b/docs/provider/cluster-always-on.md @@ -27,18 +27,16 @@ the cluster comes back by itself, with no command run on either Mac (see [After a restart or a power cut](#after-a-restart-or-a-power-cut)). - launchd runs `darkbloom cluster service --supervise`: the same supervisor as - below, around `darkbloom cluster service`, without its update slot. A service + below, around `darkbloom cluster service`. A service that ends is restarted after 15 s, doubling to 300 s; three runs in a row each shorter than 120 s park it (nothing runs) until `darkbloom cluster` is run again, which restarts it and resets the budget. -- Nothing updates Darkbloom on these Macs: the supervisor runs with automatic - updates off (`provider-swift/Sources/darkbloom/ClusterServiceCommand.swift`, - `runSupervisor`), this Mac's part runs no updater - (`provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift`, which starts +- The supervisor updates Darkbloom on this Mac together with the other Mac + ([the pair's coordinated update](#the-pairs-coordinated-update)). This Mac's + part runs no updater of its own + (`provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift` starts `startAutoUpdateMonitor` only for a single-Mac provider), and the single-Mac - provider does not run beside the cluster. Run `darkbloom update` on both Macs - ([updating Darkbloom on the pair](two-mac-cluster.md#updating-darkbloom-on-the-pair)); - automatic updates for a pair are a follow-up. + provider does not run beside the cluster. - `RunAtLoad`, and `KeepAlive` only after an unsuccessful exit (throttled to the budget's first backoff): launchd brings back a supervisor that crashed, never one that was stopped. @@ -114,6 +112,66 @@ says which applies to each Mac, from its own settings: Darkbloom does not switch to a system daemon for this: with FileVault on, the disk stays locked until someone logs in, so a daemon would not help. +### The pair's coordinated update + +Each Mac's cluster service supervisor runs the single-Mac updater's sequence +(`AutoUpdateController`) for the pair, with the single-Mac gate: `auto_update`, +`DARKBLOOM_NO_UPDATE_CHECK` and the configured coordinator, read when the +supervisor starts (`Watchdog.settings`, +`provider-swift/Sources/darkbloom/ClusterServiceCommand.swift`, +`supervisorConfiguration`). One cycle +(`provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift`, +`ClusterPairUpdateCycle`) runs beside the serving cluster service: + +| Step | Single Mac | Pair (both Macs) | +|---|---|---| +| When | 5 min after start, then every 30 min | Every 30 min at the update slot of the pairing's cluster ID (`ClusterMemberUpdateSlot`), the same moment on both Macs; or at once for `darkbloom update` | +| Check, download, verify, stage | While serving (`SelfUpdater`) | The same, on each Mac, while the pair serves | +| Stop taking requests | Once staged | Once staged on both Macs (each reads the other's progress, `ClusterPairUpdateProgress`, from the other cluster service's status over the link) | +| Drain | Accepted requests finish, at most 120 s; never cancelled | The part that serves the pair (rank 0) finishes its accepted requests, at most 120 s (`ClusterUpdateDrainRequest`, through its lifecycle mailbox); the other part serves none. A request still running reopens the pair on both Macs and defers to the next slot | +| Install | Commit the staged bundle | Each Mac commits once both drained | +| Restart | launchd restarts the provider | The supervisor stops its cluster service (the drained part stops with it) and starts again from the installed binary | +| Recovery | The watchdog promotes the candidate after 600 s of fresh heartbeats, rolls back after 3 failed starts | The restarted supervisor does the same with its cluster service's heartbeat (`ClusterCandidateRecovery`). It runs the new binary, so a release whose supervisor cannot start at all is not rolled back | + +The rules each Mac applies to the other's progress are in +`provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift` +(`ClusterPairUpdate.partnerState`), and those for its own part in +`ClusterPairUpdateCycle`: + +1. Neither Mac stops taking requests before both have the release on disk, and + neither installs before both drained, so a release one Mac cannot download, + verify or stage is installed on neither; both retry at the next slot. +2. The drain never cancels an accepted request and sends no drain barrier: a + drain the pair gives up reopens admission on the same coordinator connection. + The stop that follows a completed drain acknowledges it as every stop does. +3. A Mac whose partner cannot be asked (no answer, a build without this + progress, or a progress not rewritten for + `ClusterPairUpdate.progressStaleSeconds`) goes on alone only when no cluster + worker runs on it, checked again before it installs, so it never breaks a + serving pair; with a pair loaded it waits, then defers. +4. Only the coordinator-paired part answers the drain + (`ProviderLoopConfig.clusterMemberAnswersUpdateDrain`). A part that serves + otherwise (the leader's local API server, a Mac serving alone) does not, so + the update defers while it serves. A service whose status says so + (`localOnly`, a solo part) gives the release up before downloading it. +5. A Mac whose partner has automatic updates off gives the slot's release up + before downloading it. A Mac with automatic updates off reports `disabled` + whenever no cycle runs on it, except for the minute after a cycle that + `darkbloom update` asked for ended. A cycle for `darkbloom update` instead + waits, while serving, for the other Mac's `darkbloom update`, at most + `ClusterPairUpdate.partnerStageWaitSeconds` (900 s) from its start. + +After both Macs restarted, the leader's cluster service plans the same model +again once both answer with the same worker build +(`ClusterOnboardingUpdate.oneBuild`), and the pair registers again under the +new release's cluster approval. Each step is one `cluster update:` line in +`~/.darkbloom/cluster-setup/service.log`, for example `cluster update: waiting +for the other Mac to have v`, `cluster update: this Mac's part finished +its accepted requests`, `cluster update: installed v`, `cluster update +deferred: ; no request was cancelled; the next update slot tries again`, +`cluster update: starting the cluster service on candidate v` and +`cluster update: this Mac's part serves again on v`. + ## Permissions asked once One administrator approval sets up the cluster link per Mac; macOS then decides @@ -184,6 +242,7 @@ system setting: | Follower never connects; log shows `Local network prohibited` | **Privacy & Security → Local Network** | Turn on Darkbloom; an ad-hoc build needs this per build | | A firewall alert after an update | `codesign -dv` on the listening binary | The binary is not Developer-ID signed; install the release build | | Install or provider log says `permissions: not asked once` | The listed reasons | Install the signed release (a locally built binary is ad-hoc signed and outside `Darkbloom.app`) | +| The pair does not update | `cluster update:` lines in `~/.darkbloom/cluster-setup/service.log` on both Macs | `automatic updates are off`: run `darkbloom update` on both Macs, or set `auto_update` on both (`darkbloom autoupdate enable`), which takes effect when the cluster service next starts (at login, or after its next update). `deferred`: a request ran past 120 s, or one Mac could not take the release; the next slot tries again. `does not drain for an update`: the pair serves on the local API or a Mac serves alone | ## Developer: a coordinator-paired member as a service @@ -254,7 +313,7 @@ it. It documents the developer route that runs `darkbloom start | The leader's pair engine stays wedged (its own watchdog's verdict) for 180 s | Same recycle | | An active request made no progress at all for `clamp(120, 120 + prompt tokens / 1000, 900)` s (when the member reports one) | Same recycle | | A pair forms | The leader runs one greedy 8-token warmup request before the pair accepts work; if it fails or takes over 300 s the pair is retired and formed again (`DARKBLOOM_CLUSTER_WARMUP=0` turns this off) | -| Cluster update slot (every 30 min, at an offset fixed by the cluster ID, the same on both Macs), on this route only, with `auto_update` on (the default) | If a release is available: drains the member, installs, restarts from the new binary; both Macs do this together. The cluster service of `darkbloom cluster` has no update slot ([updating Darkbloom on the pair](two-mac-cluster.md#updating-darkbloom-on-the-pair)) | +| Cluster update slot (every 30 min, at an offset fixed by the cluster ID, the same on both Macs), with `auto_update` on (the default) | On this route, if a release is available and the pair is idle: drains the member, installs, restarts from the new binary. The cluster service of `darkbloom cluster` runs [the pair's coordinated update](#the-pairs-coordinated-update) instead | | `darkbloom stop` | Drains, stops the member and keeps it stopped across reboots | | Before every run, and at the member's own start and end | Orphan sweep: a worker or owner whose parent is gone is given its own contract to end, then SIGTERM, SIGKILL only after the kill margin; a stranded device journal is cleared once nothing it names runs; bootstrap directories whose socket no process holds any more are removed (read from the descriptor tables; nothing connects). One log line when it found something (`darkbloom cluster reap --json` runs the same sweep by hand) | diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index d8688b78b8..2729cecb4a 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -533,33 +533,51 @@ happens by itself; `darkbloom cluster` says which applies to each Mac. ## Updating Darkbloom on the pair -The Macs of a pair do not update by themselves. The cluster service runs with -automatic updates off, its parts run no updater, and the single-Mac provider, -whose updater keeps one Mac current, does not run beside the cluster. -Automatic updates for a pair are a follow-up. Until then, update by hand: - -1. On each Mac, run: - - ```bash - darkbloom update - ``` +The Macs of a pair update themselves together, as a single Mac does, while +`auto_update` is on (the default) and `DARKBLOOM_NO_UPDATE_CHECK` is not set on +either Mac. Nothing needs to be run. Every 30 minutes, at the pair's update slot +(a time fixed by the pairing's cluster ID, the same on both Macs), each Mac's +cluster service asks the coordinator for its latest release: + +1. Each Mac downloads, verifies and stages the release while the pair serves. +2. Once both Macs have it, the pair stops taking new requests. The Mac that + serves the pair finishes the requests it accepted, within 120 seconds, and + never cancels one. +3. Both Macs install the release and restart their cluster services from it. +4. The leader plans the same model again for the new release once both Macs + answer with it, and the pair registers again under that release's cluster + approval. The log says `Darkbloom changed on both Macs: setting the cluster + up again for `. + +A pair still running a request after 120 seconds takes requests again and tries +at the next slot. A release that one Mac cannot download or verify is installed +on neither Mac; both try again at the next slot. Until a new +release's cluster service has stayed healthy for 10 minutes, three of its starts +that end by themselves bring back the previous release and quarantine the new +one, as the watchdog does for a single Mac. How the cluster service does this is +in [the pair's coordinated update](cluster-always-on.md#the-pairs-coordinated-update). + +To update at once, run on each Mac: + +```bash +darkbloom update +``` - It installs the release. Its last line, "Restart the provider for the new - version to take effect.", does not apply here: no single-Mac provider runs on - a pair Mac. -2. Wait. The leader compares each Mac's installed cluster worker with the saved - setup every minute while the cluster serves. When one changed, it stops both - parts, plans the same model again and serves it from the new release - ("Updating the cluster setup after a Darkbloom update."). Its log, - `~/.darkbloom/cluster-setup/service.log`, says - `Darkbloom changed on the other Mac: setting the cluster up again for ` - (or this Mac, or both Macs). An update of the second Mac sets it up once more. - While a Mac serves, these checks and any plan made then use the speed it - measured while idle and never run a GPU benchmark beside the model - ([device profile](../architecture/inference.md#automatic-local-cluster-batching)). -3. Log out and back in on each Mac, or restart it. The cluster service itself - keeps running the release it started with until it starts again, as it does - at login. +It installs the release, then asks this Mac's cluster service to restart into it +together with the other Mac, after the pair drained, and prints its progress +(`drained for v; waiting for the other Mac`). Both Macs restart once both +have the release. The Mac where it ran first waits up to 15 minutes, while it +serves, for the other Mac: for its `darkbloom update`, or for its next slot when +its automatic updates are on. +No log-out is needed. A cluster service started by an earlier release cannot do +this: log out and back in on both Macs once both have the release. + +While a Mac serves, the re-plan uses the speed it measured while idle and never +runs a GPU benchmark beside the model +([device profile](../architecture/inference.md#automatic-local-cluster-batching)). +A pair that serves on the leader's local API, or a Mac that serves alone, is not +drained for an update yet: its update waits while it serves (the log says +`this Mac's part does not drain for an update`). ## When something is in the way @@ -620,7 +638,8 @@ and they must match. ## Not yet in this build -- A pair does not update itself: run `darkbloom update` on both Macs +- A pair that serves on the leader's local API, or a Mac that serves alone, + does not update while it serves ([updating Darkbloom on the pair](#updating-darkbloom-on-the-pair)). - The login agent and macOS's one Local Network approval need the signed Darkbloom.app ([always on](cluster-always-on.md)). diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 0aa1e29379..23c6d0f4d7 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -407,7 +407,7 @@ provider or model command is running. Code: | Variable | Values / type | Default | Read in | Effect | |---|---|---|---|---| -| `DARKBLOOM_NO_UPDATE_CHECK` | any value | unset | `provider-swift/Sources/darkbloom/Darkbloom.swift`; `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift`; `provider-swift/Sources/darkbloom/WatchdogCommand.swift`; `provider-swift/Sources/ProviderCore/ProviderLoop+AutoUpdate.swift`; forwarded by `provider-swift/Sources/ProviderCore/Service/WatchdogAgent.swift` | Skips the startup version banner, the in-daemon auto-update loop, the start-mode check and the watchdog's update check; `scripts/install.sh` sets it for the runtime smoke test. | +| `DARKBLOOM_NO_UPDATE_CHECK` | any value | unset | `provider-swift/Sources/darkbloom/Darkbloom.swift`; `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift`; `provider-swift/Sources/darkbloom/WatchdogCommand.swift`; `provider-swift/Sources/ProviderCore/ProviderLoop+AutoUpdate.swift`; `provider-swift/Sources/darkbloom/ClusterServiceCommand.swift` (`supervisorConfiguration`); forwarded by `provider-swift/Sources/ProviderCore/Service/WatchdogAgent.swift` | Skips the startup version banner, the in-daemon auto-update loop, the start-mode check, the watchdog's update check and the `darkbloom cluster` pair's update at its slot; `scripts/install.sh` sets it for the runtime smoke test. | | `DARKBLOOM_AUTH_TOKEN_PATH` | file path | `~/.darkbloom/auth_token` | `provider-swift/Sources/ProviderCore/Auth/DeviceAuth.swift` | A nonempty explicit path replaces the token path. Without it, the token is read only from `~/.darkbloom/auth_token` (for `sudo darkbloom report`, the invoking user's, read-only through `AuthTokenStore.loadReadOnly`); there is no legacy-path fallback. | | `DARKBLOOM_LOCAL_DIR` | directory | `~/.darkbloom` | `provider-swift/Sources/ProviderCore/Server/LocalEndpoint.swift` | Directory for `local_token` and `local.json` (direct mode). | | `DARKBLOOM_STATE_FILE` | file path | `~/.darkbloom/daemon-state.json` | `provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift` | Daemon state snapshot read by `status`, `doctor` and the watchdog. | diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPairUpdateProgress.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPairUpdateProgress.swift new file mode 100644 index 0000000000..f16d19d48e --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPairUpdateProgress.swift @@ -0,0 +1,76 @@ +import Foundation + +/// One Mac's part in the pair's coordinated update (`ClusterPairUpdate`), as its cluster service supervisor writes it +/// and its cluster service reports it to the other Mac (`ClusterServiceStatus.pairUpdate`). Rewritten every +/// `ClusterPairUpdate.pollSeconds` while a cycle runs. +public struct ClusterPairUpdateProgress: Codable, Equatable, Sendable { + public enum Phase: String, Codable, Sendable { + /// No cycle runs; `detail` says how the last one ended. + case idle + /// Automatic updates are off on this Mac (`auto_update`, `DARKBLOOM_NO_UPDATE_CHECK`). + case disabled + /// The cycle asks the coordinator for its latest release and downloads it. + case checking + /// The release is verified and staged (or already installed) on this Mac; it still serves. + case staged + /// This Mac's part takes no new requests and finishes the accepted ones. + case draining + /// Nothing accepted is left on this Mac's part. + case drained + /// The release is installed; the cluster service restarts into it. + case restarting + /// This cycle was given up without installing; the next update slot tries again. + case deferred + /// The check, the download, the stage or the install failed; the next update slot tries again. + case failed + + /// A phase a later build adds reads as `checking`: still working, never ready, stale once no longer rewritten. + /// Failing on it would fail the other Mac's whole `ClusterServiceStatus`, which carries only plain values. + public init(from decoder: any Decoder) throws { + self = Phase(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .checking + } + } + + public var phase: Phase + /// The release this cycle installs; nil before the coordinator answered. + public var target: String? + /// The version this Mac runs. + public var running: String + /// Epoch seconds this Mac's cycle started; nil outside a cycle. + public var cycleStartedAt: Double? + /// The `darkbloom update` request this cycle answers, if any (`ClusterPairUpdate.Request`). + public var request: String? + public var writtenAt: Double + public var detail: String? + + public init(phase: Phase, target: String? = nil, running: String, cycleStartedAt: Double? = nil, + request: String? = nil, writtenAt: Double, detail: String? = nil) { + self.phase = phase + self.target = target + self.running = running + self.cycleStartedAt = cycleStartedAt + self.request = request + self.writtenAt = writtenAt + self.detail = detail + } + + public var isEnd: Bool { phase == .deferred || phase == .failed } + + /// One line for the log and `darkbloom update`. + public var line: String { + let release = target.map { "v\($0)" } ?? "the release" + let text: String + switch phase { + case .idle: text = "no update running" + case .disabled: text = "automatic updates are off" + case .checking: text = "checking for a release" + case .staged: text = "\(release) staged; waiting for the other Mac" + case .draining: text = "\(release) staged; finishing accepted requests" + case .drained: text = "drained for \(release); waiting for the other Mac" + case .restarting: text = "\(release) installed; restarting the cluster service" + case .deferred: text = "\(release) deferred to the next update slot" + case .failed: text = "\(release) failed; the next update slot tries again" + } + return detail.map { "\(text) (\($0))" } ?? text + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterServiceWire.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterServiceWire.swift index 65b86ff2f8..152bd16dbb 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterServiceWire.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterServiceWire.swift @@ -72,6 +72,9 @@ public struct ClusterServiceStatus: Codable, Sendable, Equatable { /// 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 + /// This Mac's part in the pair's coordinated update, as its cluster service supervisor writes it. Nil from an + /// older build, which cannot coordinate one. + public var pairUpdate: ClusterPairUpdateProgress? = nil public struct Control: Codable, Sendable, Equatable { public var leaderID: String public var leaderName: String diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift index 043da369a4..39a521c20b 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift @@ -446,6 +446,15 @@ public enum ClusterOnboardingUpdate { return now != pinned[member] } } + + /// Whether every pinned member answered and all run the same worker: only then can the model be planned again on + /// both Macs. The two Macs restart into an update seconds apart; a plan made while one still runs the other build + /// (or has not answered yet) fails and waits `retryAfterFailureSeconds`. + public static func oneBuild(pinned: [String: String], current: [String: String?]) -> Bool { + let digests = pinned.keys.map { current[$0] ?? nil } + guard !digests.isEmpty, !digests.contains(nil) else { return false } + return Set(digests).count == 1 + } } /// What the pairing reports while it runs. diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index 980bc6cf43..e3b85c3ce0 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -104,6 +104,8 @@ public final class ClusterService: @unchecked Sendable { private var updateInFlight = false private var nextUpdateCheck = Date.distantPast private var updatingLine: String? + /// Said once while the Macs run different builds after an update. + private var updateWaitLine: String? // The cluster approval is asked for once per run of this service on the control leader, and again every minute // while the pair is offered or serves locally with its approval set aside (`checkApproval`). private var approvalChecked = false @@ -938,6 +940,7 @@ public final class ClusterService: @unchecked Sendable { value.localOnly = record?.leadership.map { $0.scope.isLocalOnly } value.memberQuickEnds = memberQuickEnds value.approvalID = configuration?.nativeMember?.clusterApproval?.id ?? "" + value.pairUpdate = ClusterPairUpdate.readProgress(from: ClusterServiceAgent.updateProgressPath(serviceDirectory: store.paths.directory)) return value } } @@ -968,12 +971,22 @@ public final class ClusterService: @unchecked Sendable { if case .reached = context.reachPeer(), let facts = context.peerFacts { current[facts.memberID] = facts.runtimeBinarySHA256 } let changed = ClusterOnboardingUpdate.changed(pinned: pinned, current: current) guard !changed.isEmpty else { return } + let macs = changed.count == 1 && changed[0] == local.id ? "this Mac" : changed.count == 1 ? "the other Mac" : "both Macs" + // The two Macs restart into an update seconds apart, or one was updated alone: plan once both run one build. + guard ClusterOnboardingUpdate.oneBuild(pinned: pinned, current: current) else { + let line = "Darkbloom changed on \(macs): waiting until both Macs answer with the same build to set the cluster up again for \(model)" + if self.lock.withLock({ self.updateWaitLine != line }) { + self.lock.withLock { self.updateWaitLine = line } + say(line) + } + return + } + self.lock.withLock { self.updateWaitLine = nil } guard let held = ClusterControlCommandLock.acquire(seconds: 5) else { return } defer { held.release() } self.lock.withLock { self.updatingLine = ClusterOnboardingUpdate.statusLine } self.publish() - say("Darkbloom changed on \(changed.count == 1 && changed[0] == local.id ? "this Mac" : changed.count == 1 ? "the other Mac" : "both Macs"): " - + "setting the cluster up again for \(model)") + say("Darkbloom changed on \(macs): setting the cluster up again for \(model)") func failed(_ lines: [String]) { say("could not set the cluster up again after the update: " + lines.joined(separator: " ")) self.lock.withLock { self.nextUpdateCheck = Date().addingTimeInterval(ClusterOnboardingUpdate.retryAfterFailureSeconds) } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterUpdateDrain.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterUpdateDrain.swift new file mode 100644 index 0000000000..a828f35852 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterUpdateDrain.swift @@ -0,0 +1,81 @@ +import Foundation + +// The pair's coordinated update, on the coordinator-paired part (`ClusterPairUpdateCycle`). +// +// A member serves coordinator work only through its pair slot, so only the leader's part (rank 0) has accepted +// requests to finish. On its supervisor's request it closes admission exactly as the single-Mac updater does +// (`beginUpdateDraining`: refused requests are rerouted, the heartbeat says draining) and waits, bounded, for the +// accepted ones. It never cancels one and sends no drain barrier: a drain the pair gives up is undone on the same +// coordinator connection, and the stop that follows a completed drain sends the barrier as every stop does +// (`drainAndShutdown`). + +extension ProviderLoop { + internal func acceptPendingClusterUpdateDrain(from mailbox: LifecycleMailbox) async { + guard isClusterMember, loopConfig.clusterMemberAnswersUpdateDrain, + let request = mailbox.claimClusterUpdateDrainRequest(), request.isValid(for: mailbox.identity) else { return } + func report(_ outcome: ClusterUpdateDrainStatus.Outcome) { + try? mailbox.writeClusterUpdateDrainStatus(.init(requestID: request.id, outcome: outcome, remaining: lifecycleRemaining)) + } + switch request.action { + case .drain: + guard clusterUpdateDrainID == nil else { return report(.refused) } + clusterUpdateDrainID = request.id + clusterUpdateDrainTask = Task { await self.performClusterUpdateDrain(request, mailbox: mailbox) } + case .release: + let held = clusterUpdateDrainID != nil + clusterUpdateDrainID = nil + clusterUpdateDrainTask?.cancel() + clusterUpdateDrainTask = nil + if held, servingDrain.owner == .update, !isShuttingDown { + logger.info("Cluster update given up: taking requests again") + await resumeAfterClusterUpdateDrain() + } + report(.released) + } + } + + private func performClusterUpdateDrain(_ request: ClusterUpdateDrainRequest, mailbox: LifecycleMailbox) async { + func report(_ outcome: ClusterUpdateDrainStatus.Outcome) { + try? mailbox.writeClusterUpdateDrainStatus(.init(requestID: request.id, outcome: outcome, remaining: lifecycleRemaining)) + } + // Released, stopped or taken over by a stop meanwhile: the drain is no longer this request's. + func owned() -> Bool { clusterUpdateDrainID == request.id && servingDrain.owner == .update && !isShuttingDown } + defer { if clusterUpdateDrainID == nil || clusterUpdateDrainID == request.id { clusterUpdateDrainTask = nil } } + guard let slot = clusterPairSlot, clusterPairSlotServes(slot.modelID) else { + clusterUpdateDrainID = nil + return report(.notServing) + } + guard updatePhase == .idle, !servingDrain.refusing, !isShuttingDown, !memberControlRequiresStop else { + clusterUpdateDrainID = nil + return report(.refused) + } + logger.info("Cluster update: the pair takes no new requests; finishing the accepted ones (at most \(request.timeoutSeconds) s)") + beginUpdateDraining() + report(.draining) + let drained = await waitForInflightDrain(timeout: .seconds(request.timeoutSeconds), reason: "the cluster's update") + guard owned() else { return } + guard drained else { + logger.warning("Cluster update deferred: \(lifecycleRemaining) accepted request(s) still running after \(request.timeoutSeconds) s; none cancelled; taking requests again") + clusterUpdateDrainID = nil + await resumeAfterClusterUpdateDrain() + return report(.timedOut) + } + logger.info("Cluster update: no accepted request left; new requests stay refused until this part stops") + report(.drained) + try? await Task.sleep(nanoseconds: UInt64(ClusterPairUpdate.drainedHoldSeconds * 1_000_000_000)) + guard owned(), !Task.isCancelled else { return } + logger.warning("Cluster update: no stop arrived within \(Int(ClusterPairUpdate.drainedHoldSeconds)) s of the drain; taking requests again") + clusterUpdateDrainID = nil + await resumeAfterClusterUpdateDrain() + } + + /// The single-Mac resume (`resumeServingAfterUpdate`) for a member: its admission follows its pair slot. + private func resumeAfterClusterUpdateDrain() async { + updatePhase = .idle + resumeAfterUpdateDrain() + localResponseTracker.setAccepting(!servingDrain.refusing && !isShuttingDown) + if !servingDrain.refusing { lifecycleStatus = .init() } + refreshClusterMemberAdmission() + if let client = coordinatorClient { await client.sendEventHeartbeat() } + } +} diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Lifecycle.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Lifecycle.swift index d98d6e8b15..7ec03e4282 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+Lifecycle.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Lifecycle.swift @@ -152,6 +152,7 @@ extension ProviderLoop { } _ = await self?.acceptPendingModelSwitch(from: mailbox) _ = await self?.acceptPendingAddonControl(from: mailbox) + await self?.acceptPendingClusterUpdateDrain(from: mailbox) try? await Task.sleep(nanoseconds: 250_000_000) } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index 3d8265a633..f32fe89775 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -563,6 +563,10 @@ public actor ProviderLoop { /// processes; released on every non-restart exit and immediately after a /// durable commit. internal var updateSession: SelfUpdater.UpdateSession? + /// Cluster member only: the supervisor's drain for the pair's coordinated update that owns admission (its request + /// id), and the task that waits for the accepted requests and then holds the drain (`ProviderLoop+ClusterUpdateDrain`). + internal var clusterUpdateDrainID: String? + internal var clusterUpdateDrainTask: Task? /// Latest desired_models push received while admission is closed. A switch /// clears obsolete state before committing, then replays the fresh snapshot diff --git a/provider-swift/Sources/ProviderCore/ProviderLoopConfig.swift b/provider-swift/Sources/ProviderCore/ProviderLoopConfig.swift index d1e215afc9..0dd8c70c29 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoopConfig.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoopConfig.swift @@ -37,6 +37,10 @@ public struct ProviderLoopConfig: Sendable { /// Whether an accepted member connection that later drops ends the loop /// (true) or permits a reconnect (false). Read only in member mode. public let clusterMemberStopsOnDisconnect: Bool + /// Whether this member answers its cluster service supervisor's drain for the pair's coordinated update + /// (`ClusterUpdateDrainRequest`). Only a coordinator-paired part does: the control-only member inside a + /// local-API leader holds no pair slot, but its leader's HTTP server serves requests the member cannot see. + public let clusterMemberAnswersUpdateDrain: Bool /// Cluster member only: the models whose pair-serving grant this Mac's /// rank has passed (`ClusterMemberPreparation.prepare`). /// A member serves no solo inference, so for these models the single-Mac @@ -60,6 +64,7 @@ public struct ProviderLoopConfig: Sendable { autopilotPendingCandidates: AutopilotStartInventory.Pending? = nil, executionRole: ProviderExecutionRole = .solo, clusterMemberStopsOnDisconnect: Bool = true, + clusterMemberAnswersUpdateDrain: Bool = false, pairServingGrantedModelIDs: Set = [] ) { self.coordinatorURL = coordinatorURL @@ -77,6 +82,7 @@ public struct ProviderLoopConfig: Sendable { self.localEndpoint = localEndpoint self.executionRole = executionRole self.clusterMemberStopsOnDisconnect = clusterMemberStopsOnDisconnect + self.clusterMemberAnswersUpdateDrain = clusterMemberAnswersUpdateDrain self.pairServingGrantedModelIDs = pairServingGrantedModelIDs } diff --git a/provider-swift/Sources/ProviderCore/Service/ClusterServiceAgent.swift b/provider-swift/Sources/ProviderCore/Service/ClusterServiceAgent.swift index 5b5cfb39dd..7a4c2d6b9e 100644 --- a/provider-swift/Sources/ProviderCore/Service/ClusterServiceAgent.swift +++ b/provider-swift/Sources/ProviderCore/Service/ClusterServiceAgent.swift @@ -76,6 +76,17 @@ public enum ClusterServiceAgent { serviceDirectory.appendingPathComponent("part-health.json") } + /// The supervisor's progress in the pair's coordinated update, which the service reports to the other Mac + /// (`ClusterPairUpdateProgress`). + public static func updateProgressPath(serviceDirectory: URL) -> URL { + serviceDirectory.appendingPathComponent("service-update.json") + } + + /// `darkbloom update`'s request to restart into the release it installed (`ClusterPairUpdate.Request`). + public static func updateRequestPath(serviceDirectory: URL) -> URL { + serviceDirectory.appendingPathComponent("service-update-request.json") + } + // MARK: - Install public enum Outcome: String, Sendable, Equatable { diff --git a/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterMemberUpdateSlot.swift b/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterMemberUpdateSlot.swift index 5813a70f83..29a553ad6e 100644 --- a/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterMemberUpdateSlot.swift +++ b/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterMemberUpdateSlot.swift @@ -14,7 +14,10 @@ import Foundation /// install it, and start again; the coordinator re-forms the pair when both /// have registered and its approval covers the new runtime. If one Mac fails /// to update, the next slot retries, and until then the approval's pins keep a -/// mixed pair from forming. +/// mixed pair from forming. The cluster service of `darkbloom cluster` uses the +/// same slot for the pair's coordinated update (`ClusterPairUpdate`), which +/// stages while serving and drains a busy pair instead of skipping it (`decide` +/// serves the developer route). public enum ClusterMemberUpdateSlot { /// Same cadence as the solo provider's update check. public static let periodSeconds: Double = 1800 diff --git a/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift b/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift new file mode 100644 index 0000000000..e28a352959 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift @@ -0,0 +1,120 @@ +import Foundation + +/// The coordinated update of a `darkbloom cluster` pair as each Mac's cluster service supervisor runs it +/// (`ClusterPairUpdateCycle`): when the other Mac lets this one go on. +/// +/// Both Macs check for a release at the cluster's update slot (`ClusterMemberUpdateSlot`) and stage it while the pair +/// serves. Neither stops taking requests before the other has the same release on disk, and neither installs before +/// both have drained: the Mac whose part serves the pair finishes its accepted requests, and the other Mac's part +/// serves none of its own. A release one Mac cannot download, verify or stage is installed on neither, and a request +/// still running at the drain bound reopens the pair on both Macs; both retry at the next slot. Each Mac publishes its +/// progress (`ClusterPairUpdateProgress`) in its cluster service's status, which the other Mac reads over the link. +public enum ClusterPairUpdate { + /// How long a Mac waits, from the start of its cycle, for the other Mac to have the release on disk too. + public static let partnerStageWaitSeconds: Double = 900 + /// How long the part that serves the pair may take to finish its accepted requests once it stopped taking new + /// ones: the single-Mac updater's drain allowance (`ProviderLoop.updateDrainTimeout`). + public static let drainTimeoutSeconds: Double = 120 + /// From the start of its drain, how long a Mac waits for the other Mac to have drained too. + public static let partnerDrainWaitSeconds: Double = drainTimeoutSeconds + 60 + /// How long a part that drained keeps refusing requests while neither its stop nor a release arrives (its + /// supervisor went away): it then takes requests again. + public static let drainedHoldSeconds: Double = 900 + /// A progress in a working phase not rewritten for this long is from a supervisor that stopped. + public static let progressStaleSeconds: Double = 60 + /// How often a supervisor in a cycle rewrites its progress and reads the other Mac's. + public static let pollSeconds: Double = 5 + + /// The other Mac as this Mac reads it. + public enum Partner: Equatable, Sendable { + case reported(ClusterPairUpdateProgress) + /// It answered with a build that reports no update progress, so it cannot coordinate one. + case silent + /// No pairing, or its cluster service did not answer. + case unreachable + } + + /// What this Mac waits for: the release on the other Mac's disk, or the other Mac drained. + public enum Step: Sendable { + case staged + case drained + } + + public enum PartnerState: Equatable, Sendable { + /// The other Mac is at `step` for this release, or runs it already. + case ready + case waiting + /// The other Mac gave this release up (or will not take it); this Mac gives it up too. + case gaveUp(String) + /// The other Mac cannot be asked: this Mac goes on alone only when no pair runs on it. + case cannotCoordinate + } + + /// Whether `partner` lets this Mac's cycle for `target`, started at `cycleStartedAt`, go past `step`. `requested`: + /// the cycle answers `darkbloom update`, which is run on the other Mac too. + public static func partnerState(_ partner: Partner, target: String, step: Step, cycleStartedAt: Double, + now: Double, requested: Bool = false) -> PartnerState { + guard case .reported(let progress) = partner else { return .cannotCoordinate } + if progress.running == target { return .ready } + switch progress.phase { + case .disabled: + // Its slot never comes, but its own `darkbloom update` may: a requested cycle waits for it while serving. + if requested, step == .staged { return .waiting } + return .gaveUp("automatic updates are off on the other Mac") + case .idle: + // Its cycle may not have started yet: the two Macs reach the slot seconds apart. + return .waiting + case .deferred, .failed: + // An end written before this cycle started belongs to an earlier one. + guard progress.writtenAt >= cycleStartedAt, progress.target == nil || progress.target == target else { return .waiting } + return .gaveUp("the other Mac: " + progress.line) + case .checking, .staged, .draining, .drained, .restarting: + guard now - progress.writtenAt <= progressStaleSeconds else { return .cannotCoordinate } + guard let theirs = progress.target else { return .waiting } + guard theirs == target else { return .gaveUp("the other Mac installs v\(theirs), not v\(target)") } + switch step { + case .staged: return progress.phase == .checking ? .waiting : .ready + case .drained: return progress.phase == .drained || progress.phase == .restarting ? .ready : .waiting + } + } + } + + /// `darkbloom update` on a cluster Mac: restart into the release it installed, together with the other Mac. + public struct Request: Codable, Equatable, Sendable { + public var id: String + public var createdAt: Double + /// A request older than this is from a command that is long gone. + public static let maximumAgeSeconds: Double = 3600 + + public init(id: String = UUID().uuidString, createdAt: Double) { + self.id = id + self.createdAt = createdAt + } + + public func isCurrent(now: Double) -> Bool { + now - createdAt >= -5 && now - createdAt <= Self.maximumAgeSeconds + } + } + + public static func readProgress(from url: URL) -> ClusterPairUpdateProgress? { + ClusterSupervisionFiles.read(ClusterPairUpdateProgress.self, from: url) + } + + @discardableResult + public static func writeProgress(_ progress: ClusterPairUpdateProgress, to url: URL) -> Bool { + ClusterSupervisionFiles.write(progress, to: url) + } + + @discardableResult + public static func writeRequest(_ request: Request, to url: URL) -> Bool { + ClusterSupervisionFiles.write(request, to: url) + } + + /// The pending request, removed so it is answered once; nil when there is none or it is stale. + public static func takeRequest(from url: URL, now: Double) -> Request? { + guard FileManager.default.fileExists(atPath: url.path) else { return nil } + let request = ClusterSupervisionFiles.read(Request.self, from: url) + try? FileManager.default.removeItem(at: url) + return request.flatMap { $0.isCurrent(now: now) ? $0 : nil } + } +} diff --git a/provider-swift/Sources/ProviderCore/Service/ClusterUpdateDrain.swift b/provider-swift/Sources/ProviderCore/Service/ClusterUpdateDrain.swift new file mode 100644 index 0000000000..4204c2694f --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Service/ClusterUpdateDrain.swift @@ -0,0 +1,60 @@ +import Foundation + +/// The cluster service supervisor's request to this Mac's coordinator-paired part during the pair's coordinated +/// update (`ClusterPairUpdateCycle`), through the part's lifecycle mailbox. Unlike a stop, the drain is undone when +/// the update is given up: the part takes requests again on the same coordinator connection. +public struct ClusterUpdateDrainRequest: Codable, Sendable, Equatable { + public enum Action: String, Codable, Sendable { + /// Take no new requests and finish the accepted ones within `timeoutSeconds`; take requests again when they + /// do not finish. Nothing accepted is cancelled. + case drain + /// The update was given up after the part drained: take requests again. + case release + } + + public let id: String + public let action: Action + public let target: ProcessIdentity + public let timeoutSeconds: Int + public let createdAt: Double + + public init(action: Action, target: ProcessIdentity, timeoutSeconds: Int, createdAt: Double = Date().timeIntervalSince1970) { + id = UUID().uuidString + self.action = action + self.target = target + self.timeoutSeconds = timeoutSeconds + self.createdAt = createdAt + } + + public func isValid(for identity: ProcessIdentity, now: Double = Date().timeIntervalSince1970) -> Bool { + target == identity && UUID(uuidString: id) != nil && (0...3600).contains(timeoutSeconds) + && createdAt.isFinite && createdAt <= now + 5 && now - createdAt <= 3605 + } +} + +public struct ClusterUpdateDrainStatus: Codable, Sendable, Equatable { + public enum Outcome: String, Codable, Sendable { + /// New requests are refused; the accepted ones are finishing. + case draining + /// Nothing accepted is left. New requests stay refused until the part stops, is released, or its hold ends. + case drained + /// Accepted requests were still running at the bound: the part takes requests again; nothing was cancelled. + case timedOut + /// The part serves no requests of its own (it holds no pair slot): nothing to drain on this Mac. + case notServing + /// A stop, a model change or another drain owns admission: not drained. + case refused + /// The drain was undone on request: the part takes requests again. + case released + } + + public var requestID: String + public var outcome: Outcome + public var remaining: Int + + public init(requestID: String, outcome: Outcome, remaining: Int) { + self.requestID = requestID + self.outcome = outcome + self.remaining = remaining + } +} diff --git a/provider-swift/Sources/ProviderCore/Service/LifecycleMailbox.swift b/provider-swift/Sources/ProviderCore/Service/LifecycleMailbox.swift index dec33b0ce4..216a57f489 100644 --- a/provider-swift/Sources/ProviderCore/Service/LifecycleMailbox.swift +++ b/provider-swift/Sources/ProviderCore/Service/LifecycleMailbox.swift @@ -32,6 +32,13 @@ public struct LifecycleMailbox: Sendable { claim(AddonHoldControlRequest.self, suffix: "addon-request", claimPrefix: "addon-claim", afterClaim: {}) } + public func writeClusterUpdateDrainRequest(_ request: ClusterUpdateDrainRequest) throws { try write(request, suffix: "cluster-update-request") } + public func writeClusterUpdateDrainStatus(_ status: ClusterUpdateDrainStatus) throws { try write(status, suffix: "cluster-update-status") } + public func readClusterUpdateDrainStatus() -> ClusterUpdateDrainStatus? { read(ClusterUpdateDrainStatus.self, suffix: "cluster-update-status") } + public func claimClusterUpdateDrainRequest() -> ClusterUpdateDrainRequest? { + claim(ClusterUpdateDrainRequest.self, suffix: "cluster-update-request", claimPrefix: "cluster-update-claim", afterClaim: {}) + } + /// Rename is the acceptance boundary. Each loop/monitor can consume a /// publication once, and cleanup can never unlink a newer publication. public func claimSwitchRequest() -> ProviderModelSwitchRequest? { diff --git a/provider-swift/Sources/ProviderCore/Update/ClusterCandidateRecovery.swift b/provider-swift/Sources/ProviderCore/Update/ClusterCandidateRecovery.swift new file mode 100644 index 0000000000..a1278ae9e7 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Update/ClusterCandidateRecovery.swift @@ -0,0 +1,102 @@ +import Foundation + +/// Candidate promotion and rollback on a `darkbloom cluster` Mac: what the watchdog does for a single Mac's provider +/// (`WatchdogRecoveryService`), done by the cluster service supervisor for the cluster service it runs. A release the +/// pair installed (`ClusterPairUpdateCycle`, or `darkbloom update`) stays a candidate until its cluster service has +/// beaten with the new version, continuously, for the stabilization window; the third start that ends before that +/// restores the verified predecessor and quarantines the release (`UpdateRecoveryState.rollbackThreshold`). +/// Every transition holds the cross-process update lease, as the watchdog's do. +public struct ClusterCandidateRecovery: Sendable { + public enum Launch: Equatable, Sendable { + case notCandidate + /// The service about to start runs candidate `version`; `failedStarts` of its earlier starts failed. + case candidate(version: String, failedStarts: Int) + } + + public enum Health: Equatable, Sendable { + case noCandidate + case stabilizing + case promoted(version: String) + } + + public enum Failure: Equatable, Sendable { + /// No candidate attempt was pending: an ordinary end. + case notCandidate + case counted(version: String, failures: Int) + /// The verified predecessor is installed again; the supervisor starts again from it. + case rolledBack(from: String, to: String) + case rollbackRefused(version: String, reason: String) + } + + private let updater: SelfUpdater + private let stabilizationSeconds: Double + + public init(updater: SelfUpdater, stabilizationSeconds: Double = UpdateRecoveryState.defaultStabilizationSeconds) { + self.updater = updater + self.stabilizationSeconds = stabilizationSeconds + } + + /// Before the supervisor starts its cluster service: a pending candidate gets a launch attempt (the one the + /// restart prepared, or a new one after a failed start), so an end before promotion is counted exactly once. + public func noteLaunch(now: Double) -> Launch { + transition(operation: "cluster-candidate-launch") { state in + guard let candidate = state.candidate else { return Launch.notCandidate } + if candidate.pendingAttemptID == nil { + if candidate.launchIntent == nil { _ = state.prepareLaunchIntent(now: now, baseline: nil) } + _ = state.markLaunchIssued(now: now) + } + guard let current = state.candidate, current.pendingAttemptID != nil else { return Launch.notCandidate } + return Launch.candidate(version: current.release.version, failedStarts: current.failureCount) + } ?? .notCandidate + } + + /// While the service runs: `healthy` is a fresh heartbeat of the candidate version from the running service. A + /// lease another update holds (the pair's next cycle) leaves the candidate as it was. + public func observe(healthy: Bool, processStartedAt: Double?, now: Double) -> Health { + transition(operation: "cluster-candidate-health") { state in + guard let candidate = state.candidate else { return Health.noCandidate } + let promoted = state.observeCandidateHealth(healthySignal: healthy, processStartedAt: processStartedAt, + now: now, stabilizationSeconds: stabilizationSeconds) + return promoted ? Health.promoted(version: candidate.release.version) : Health.stabilizing + } ?? .stabilizing + } + + /// After the service ended without being asked to. + public func recordFailedStart(now: Double) -> Failure { + guard let session = try? updater.beginUpdateSession(operation: "cluster-candidate-failure", timeout: 1) else { return .notCandidate } + defer { session.release() } + do { + try session.recover(now: now) + var state = try session.readState() + guard let failures = state.recordPendingAttemptFailure(now: now), let candidate = state.candidate else { return .notCandidate } + try session.writeState(state) + let version = candidate.release.version + guard failures >= UpdateRecoveryState.rollbackThreshold else { return .counted(version: version, failures: failures) } + do { + let restored = try session.rollback(now: now, reason: "automatic rollback after \(failures) failed starts of the cluster service") + return .rolledBack(from: version, to: restored) + } catch { + state.deferRetryAfterRollbackFailure(now: now, reason: "\(error)") + try? session.writeState(state) + return .rollbackRefused(version: version, reason: "\(error)") + } + } catch { + return .notCandidate + } + } + + private func transition(operation: String, _ body: (inout UpdateRecoveryState) -> Value) -> Value? { + guard let session = try? updater.beginUpdateSession(operation: operation, timeout: 1) else { return nil } + defer { session.release() } + do { + try session.recover() + var state = try session.readState() + let before = state + let value = body(&state) + if state != before { try session.writeState(state) } + return value + } catch { + return nil + } + } +} diff --git a/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift b/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift new file mode 100644 index 0000000000..267b29212a --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift @@ -0,0 +1,474 @@ +import Foundation +import DarkbloomClusterProcess +import DarkbloomClusterRemote + +/// One coordinated update of this Mac in a `darkbloom cluster` pair, run by its cluster service supervisor at the +/// pair's update slot or for `darkbloom update` (`ClusterPairUpdate`). +/// +/// `AutoUpdateController` sequences it as it sequences a single Mac's background update: check and stage while +/// serving, stop taking requests only once the release is staged, drain to zero with a bound (deferring, never +/// cancelling, when accepted work does not finish), commit, restart. Two steps differ. The drain is the pair's: it +/// begins once the other Mac has the release too, and it is complete once both Macs drained. The restart is the +/// supervisor's: it stops the cluster service and starts again from the installed binary. +public final class ClusterPairUpdateCycle: @unchecked Sendable { + public struct Timing: Sendable { + public var partnerStageWait = ClusterPairUpdate.partnerStageWaitSeconds + public var drainTimeout = ClusterPairUpdate.drainTimeoutSeconds + public var partnerDrainWait = ClusterPairUpdate.partnerDrainWaitSeconds + public var poll = ClusterPairUpdate.pollSeconds + /// How long this Mac's part may take to answer the drain request at all. + public var partAnswer: Double = 15 + public static let production = Timing() + } + + /// This Mac's part as its cluster service publishes it. + public enum Part: Equatable, Sendable { + case notRunning + case running(ProcessIdentity) + /// It serves without answering the drain (`ProviderLoopConfig.clusterMemberAnswersUpdateDrain`): rank 0 on the + /// leader's local API, or a solo server. + case undrainable + /// The service runs but its status cannot be read: nothing is assumed. + case unknown + } + + public struct Environment: Sendable { + public var updater: SelfUpdater + /// Where this Mac's progress is written (`ClusterServiceAgent.updateProgressPath`). + public var progressPath: URL + public var partner: @Sendable () -> ClusterPairUpdate.Partner + public var part: @Sendable () -> Part + /// Whether a part that has not answered is still starting (it holds no request and no pair yet). + public var partStarting: @Sendable (ProcessIdentity) -> Bool + /// The parts' lifecycle mailboxes (`LifecycleMailbox`). + public var mailboxDirectory: URL + /// Whether a cluster worker runs on this Mac, so a pair is loaded here. + public var pairRunsHere: @Sendable () -> Bool + public var log: @Sendable (String) -> Void + public var timing: Timing = .production + + public init(updater: SelfUpdater, progressPath: URL, partner: @escaping @Sendable () -> ClusterPairUpdate.Partner, + part: @escaping @Sendable () -> Part, partStarting: @escaping @Sendable (ProcessIdentity) -> Bool, + mailboxDirectory: URL, pairRunsHere: @escaping @Sendable () -> Bool, + log: @escaping @Sendable (String) -> Void) { + self.updater = updater; self.progressPath = progressPath; self.partner = partner; self.part = part + self.partStarting = partStarting; self.mailboxDirectory = mailboxDirectory; self.pairRunsHere = pairRunsHere + self.log = log + } + } + + private struct PartDrain { + var identity: ProcessIdentity + var requestID: String + var outcome: ClusterUpdateDrainStatus.Outcome? + } + + private let environment: Environment + private let lock = NSLock() + private var startedAt: Double = 0 + private var request: String? + private var session: SelfUpdater.UpdateSession? + private var staged: SelfUpdater.StagedBundle? + private var installed: String? + private var target: String? + private var progress: ClusterPairUpdateProgress? + private var partDrain: PartDrain? + /// Why the pair cannot drain this cycle (said once, published with the deferral). + private var gaveUp: String? + + public init(environment: Environment) { + self.environment = environment + } + + /// `request`: the `darkbloom update` request this cycle answers. `restart` stops the cluster service and starts + /// again from the installed binary; it is called with the installed version, only after both Macs drained. + public func run(request: String? = nil, + restart: @escaping @Sendable (String) async throws -> Void) async -> AutoUpdateController.Outcome { + lock.withLock { startedAt = Self.now(); self.request = request } + let heartbeat = Task { [weak self, environment] in + while !Task.isCancelled { + await ClusterPairUpdateCycle.sleep(environment.timing.poll) + self?.rewriteProgress() + } + } + let updater = environment.updater, log = environment.log + let deps = AutoUpdateController.Dependencies( + claimStart: { self.claim() }, + resumeServing: { self.resume() }, + check: { await self.check() }, + downloadVerifyStage: { await self.stage($0) }, + beginDraining: { await self.beginPairDrain() }, + waitForDrain: { await self.waitForPairDrain($0) }, + commitInstall: { self.commit() }, + prepareInstalledRestart: { self.prepareRestart() }, + restart: { + guard let version = self.lock.withLock({ self.target }) else { throw CancellationError() } + try await restart(version) + }, + restartDidFail: { try? updater.cancelPendingCandidateAttempt(operation: "cluster-restart-failure") }, + log: { log("cluster update: \($0)") }) + let drainTimeout = Duration.milliseconds(Int64(environment.timing.drainTimeout * 1000)) + let outcome = await AutoUpdateController(deps: deps, drainTimeout: drainTimeout).run() + heartbeat.cancel() + await heartbeat.value + finish(outcome) + return outcome + } + + // MARK: - Steps + + private func claim() -> Bool { + do { + let session = try environment.updater.beginUpdateSession(operation: "cluster-auto-update", timeout: 0) + try session.recover() + lock.withLock { self.session = session } + } catch { + environment.log("cluster update: another update or recovery holds the update lease (\(error)); the next update slot tries again") + return false + } + let requested = lock.withLock { request } != nil + publish(.checking) + environment.log("cluster update: checking for a release" + (requested ? " (asked by `darkbloom update`)" : " at the update slot")) + return true + } + + private func check() async -> UpdateCheckResult { + guard let session = lock.withLock({ session }) else { return .checkFailed(reason: "the update lease was lost") } + let result = await environment.updater.checkForUpdate(session: session) + lock.withLock { + switch result { + case .updateAvailable(let current, let release): installed = current; target = release.version + case .restartRequired(let current, let version): installed = current; target = version + case .quarantined(let version, _): target = version + case .upToDate(let current): installed = current + case .checkFailed: break + } + } + return result + } + + private func stage(_ release: ReleaseInfo) async -> AutoUpdateController.StepOutcome { + // A release the pair cannot drain for, or the other Mac will not take (its automatic updates are off, or it gave + // this one up), is not downloaded. + if environment.part() == .undrainable { return .failed(Self.undrainable) } + if case .gaveUp(let reason) = partnerState(.staged, target: release.version) { return .failed(reason) } + switch await environment.updater.downloadAndVerify(release: release) { + case .failure(let error): + return .failed("\(error)") + case .success(let file): + defer { try? FileManager.default.removeItem(at: file) } + guard let session = lock.withLock({ session }) else { return .failed("the update lease was lost before staging") } + switch environment.updater.stageBundle(from: file, release: release, session: session) { + case .success(let bundle): + lock.withLock { staged = bundle } + publish(.staged) + return .completed + case .failure(let error): + return .failed("\(error)") + } + } + } + + /// The pair stops taking requests only once both Macs have the release: then this Mac's part is asked to drain. + private func beginPairDrain() async { + guard let target = lock.withLock({ target }) else { return giveUp("no release to install") } + let (started, timing) = (lock.withLock { startedAt }, environment.timing) + publish(.staged) + let deadline = started + timing.partnerStageWait + var said = false + wait: while true { + switch partnerState(.staged, target: target) { + case .ready: + environment.log("cluster update: the other Mac has v\(target) too") + break wait + case .gaveUp(let reason): + return giveUp(reason) + case .cannotCoordinate where !environment.pairRunsHere(): + environment.log("cluster update: the other Mac cannot coordinate an update and no pair runs on this Mac: updating this Mac alone") + break wait + case .cannotCoordinate, .waiting: + if !said { + said = true + environment.log("cluster update: waiting for the other Mac to have v\(target) (at most \(Int(max(0, deadline - Self.now()))) s)") + } + } + if Task.isCancelled { return giveUp("the cycle was stopped") } + guard Self.now() < deadline else { + return giveUp("the other Mac did not have v\(target) within \(Int(timing.partnerStageWait)) s") + } + await Self.sleep(timing.poll) + } + publish(.draining) + switch environment.part() { + case .notRunning: + environment.log("cluster update: this Mac runs no part: nothing to drain here") + case .undrainable: + giveUp(Self.undrainable) + case .unknown: + giveUp("this Mac's cluster service status cannot be read, so its part cannot be drained") + case .running(let identity): + let request = ClusterUpdateDrainRequest(action: .drain, target: identity, + timeoutSeconds: Int(timing.drainTimeout.rounded(.up)), createdAt: Self.now()) + do { + try LifecycleMailbox(identity: identity, directory: environment.mailboxDirectory).writeClusterUpdateDrainRequest(request) + lock.withLock { partDrain = PartDrain(identity: identity, requestID: request.id) } + environment.log("cluster update: asked this Mac's part (pid \(identity.pid)) to take no new requests and finish the accepted ones") + } catch { + giveUp("this Mac's part could not be asked to drain (\(error))") + } + } + } + + /// Both Macs drained: this Mac's part finished its accepted requests (or serves none), then the other Mac's did. + private func waitForPairDrain(_ timeout: Duration) async -> Bool { + guard lock.withLock({ gaveUp }) == nil, let target = lock.withLock({ target }) else { return false } + let timing = environment.timing + let started = Self.now() + let bound = Double(timeout.components.seconds) + Double(timeout.components.attoseconds) / 1e18 + if let drain = lock.withLock({ partDrain }) { + let mailbox = LifecycleMailbox(identity: drain.identity, directory: environment.mailboxDirectory) + var answered = false + own: while true { + if let status = mailbox.readClusterUpdateDrainStatus(), status.requestID == drain.requestID { + answered = true + lock.withLock { partDrain?.outcome = status.outcome } + switch status.outcome { + case .drained: + environment.log("cluster update: this Mac's part finished its accepted requests") + break own + case .notServing: + environment.log("cluster update: this Mac's part serves no requests of its own") + break own + case .timedOut: + giveUp("\(status.remaining) accepted request(s) were still running on this Mac's part after \(Int(bound)) s; none was cancelled"); return false + case .refused, .released: + giveUp("this Mac's part is stopping or changing its model"); return false + case .draining: + break + } + } + if !drain.identity.isCurrent() { + guard case .notRunning = environment.part() else { giveUp("this Mac's part restarted during the drain"); return false } + environment.log("cluster update: this Mac's part ended during the drain") + break own + } + if !answered, Self.now() - started > timing.partAnswer { + if environment.partStarting(drain.identity) { + environment.log("cluster update: this Mac's part is still starting: it holds no request yet") + break own + } + giveUp(Self.undrainable); return false + } + if Task.isCancelled { giveUp("the cycle was stopped"); return false } + guard Self.now() - started <= bound + timing.partAnswer else { + giveUp("this Mac's part did not finish draining within \(Int(bound)) s"); return false + } + await Self.sleep(timing.poll) + } + } + publish(.drained) + let deadline = started + timing.partnerDrainWait + while true { + switch partnerState(.drained, target: target) { + case .ready: + environment.log("cluster update: both Macs drained for v\(target)") + return true + case .gaveUp(let reason): + giveUp(reason); return false + // Asked again, not remembered from the stage wait: a pair that formed on this Mac since keeps it waiting. + case .cannotCoordinate where !environment.pairRunsHere(): + return true + case .cannotCoordinate, .waiting: + break + } + if Task.isCancelled { giveUp("the cycle was stopped"); return false } + guard Self.now() < deadline else { + giveUp("the other Mac did not drain for v\(target) within \(Int(timing.partnerDrainWait)) s"); return false + } + await Self.sleep(timing.poll) + } + } + + private func commit() -> AutoUpdateController.StepOutcome { + let (bundle, session, from) = lock.withLock { () -> (SelfUpdater.StagedBundle?, SelfUpdater.UpdateSession?, String?) in + defer { staged = nil } + return (staged, self.session, installed) + } + guard let bundle, let session else { return .failed("no staged release to install") } + switch environment.updater.commitStagedBundle(bundle, session: session) { + case .success: + environment.log("cluster update: installed v\(bundle.release.version)" + (from.map { " (was v\($0))" } ?? "")) + return .completed + case .failure(let error): + return .failed("\(error)") + } + } + + /// Records the launch the watchdog would record for a single Mac, so the restarted supervisor tracks the + /// candidate (`ClusterCandidateRecovery`), and frees the lease before the restart. + private func prepareRestart() -> AutoUpdateController.StepOutcome { + guard let session = lock.withLock({ session }) else { return .failed("the update lease was lost before the restart") } + do { + try environment.updater.prepareCandidateLaunch(session: session, baseline: nil, now: Self.now()) + } catch { + return .failed("\(error)") + } + session.release() + lock.withLock { self.session = nil } + publish(.restarting) + return .completed + } + + /// Every exit that does not restart: this Mac's part takes requests again, nothing staged is kept. + private func resume() { + let (drain, bundle, session) = lock.withLock { () -> (PartDrain?, SelfUpdater.StagedBundle?, SelfUpdater.UpdateSession?) in + defer { partDrain = nil; staged = nil; self.session = nil } + return (partDrain, staged, self.session) + } + if let drain, drain.outcome != .timedOut, drain.outcome != .notServing, drain.identity.isCurrent() { + let release = ClusterUpdateDrainRequest(action: .release, target: drain.identity, timeoutSeconds: 0, + createdAt: Self.now()) + try? LifecycleMailbox(identity: drain.identity, directory: environment.mailboxDirectory).writeClusterUpdateDrainRequest(release) + environment.log("cluster update: this Mac's part takes requests again") + } + bundle?.discard() + session?.release() + } + + private func finish(_ outcome: AutoUpdateController.Outcome) { + let reason = lock.withLock { gaveUp } + let retry = "; the next update slot tries again" + switch outcome { + case .alreadyRunning: + return + case .upToDate: + let current = lock.withLock { installed } + publish(.idle, detail: "up to date") + environment.log("cluster update: up to date" + (current.map { " (v\($0))" } ?? "")) + case .quarantined(let version): + publish(.failed, detail: "v\(version) is quarantined on this Mac after failed starts") + case .checkFailed(let failure): + publish(.failed, detail: failure) + environment.log("cluster update: the check failed (\(failure))" + retry) + case .stageFailed(let failure): + publish(.failed, detail: failure) + environment.log("cluster update: not staged; this Mac kept serving" + retry) + case .drainTimedOut, .cancelled: + let why = reason ?? (outcome == .cancelled ? "the cycle was stopped" : "the drain did not complete") + publish(.deferred, detail: why) + environment.log("cluster update deferred: \(why); no request was cancelled" + retry) + case .commitFailed(let failure): + publish(.failed, detail: failure) + environment.log("cluster update: installing failed; this Mac takes requests again" + retry) + case .restarted(let from, let to, _): + environment.log("cluster update: restarting the cluster service into v\(to) (was v\(from))") + case .restartFailed(let failure): + publish(.failed, detail: failure) + environment.log("cluster update: the restart failed (\(failure))" + retry) + } + } + + // MARK: - Helpers + + static let undrainable = "this Mac's part does not drain for an update (it serves on its local API or alone)" + + private static func now() -> Double { Date().timeIntervalSince1970 } + + private static func sleep(_ seconds: Double) async { + try? await Task.sleep(nanoseconds: UInt64(max(0, seconds) * 1_000_000_000)) + } + + private func partnerState(_ step: ClusterPairUpdate.Step, target: String) -> ClusterPairUpdate.PartnerState { + let (started, requested) = lock.withLock { (startedAt, request != nil) } + return ClusterPairUpdate.partnerState(environment.partner(), target: target, step: step, cycleStartedAt: started, + now: Self.now(), requested: requested) + } + + private func giveUp(_ reason: String) { + let first = lock.withLock { () -> Bool in + guard gaveUp == nil else { return false } + gaveUp = reason + return true + } + if first { environment.log("cluster update: \(reason)") } + } + + /// Written under the lock: a heartbeat's rewrite never lands after a later phase, and never after the cycle ended. + private func publish(_ phase: ClusterPairUpdateProgress.Phase, detail: String? = nil) { + lock.withLock { + let value = ClusterPairUpdateProgress(phase: phase, target: phase == .idle ? nil : target, + running: environment.updater.currentVersion, cycleStartedAt: phase == .idle ? nil : startedAt, + request: request, writtenAt: Self.now(), detail: detail) + progress = value + ClusterPairUpdate.writeProgress(value, to: environment.progressPath) + } + } + + /// Keeps the working phase fresh for the other Mac while a step waits (`ClusterPairUpdate.progressStaleSeconds`). + private func rewriteProgress() { + lock.withLock { + guard var value = progress, !value.isEnd, value.phase != .idle, value.phase != .restarting else { return } + value.writtenAt = Self.now() + progress = value + ClusterPairUpdate.writeProgress(value, to: environment.progressPath) + } + } +} + +extension ClusterPairUpdateCycle.Environment { + /// This Mac's cluster service: the installed release's updater (with the watchdog's bounded network session), the + /// part its status publishes, and the other Mac's progress over the link. + public static func live(serviceDirectory: URL, coordinatorURL: String, + log: @escaping @Sendable (String) -> Void) -> Self { + let partHealth = ClusterServiceAgent.partHealthPath(serviceDirectory: serviceDirectory) + let peer = ClusterPairUpdateCycle.PeerAddress() + return Self( + updater: SelfUpdater(coordinatorBaseURL: coordinatorURL, urlSession: SelfUpdater.watchdogURLSession()), + progressPath: ClusterServiceAgent.updateProgressPath(serviceDirectory: serviceDirectory), + partner: { ClusterPairUpdateCycle.livePartner(peer) }, + part: { ClusterPairUpdateCycle.livePart() }, + partStarting: { identity in + guard let health = ClusterSupervisionFiles.read(ClusterMemberHealth.self, from: partHealth) else { return false } + return health.pid == identity.pid && health.phase == .starting + && Date().timeIntervalSince1970 - health.writtenAt < 30 + }, + mailboxDirectory: DaemonStateFile.path().deletingLastPathComponent().appendingPathComponent("lifecycle"), + pairRunsHere: { ClusterOrphanWiredGuard.otherDarkbloomProcesses().contains(ClusterBundledHelpers.workerName) }, + log: log) + } +} + +extension ClusterPairUpdateCycle { + static func livePart() -> Part { + guard ClusterService.running() else { return .notRunning } + guard let status = ClusterService.publishedLive() else { return .unknown } + guard status.child.running else { return .notRunning } + if status.child.solo == true || status.localOnly == true { return .undrainable } + guard let pid = status.child.pid, let startedAt = status.child.startedAt else { return .unknown } + guard let identity = ProcessIdentity.read(pid: pid) else { return .notRunning } + return abs(Double(identity.startTimeMicros) / 1e6 - startedAt) < 0.001 ? .running(identity) : .notRunning + } + + /// The other Mac's address on the cable, kept between one cycle's polls so each skips the discovery. + final class PeerAddress: @unchecked Sendable { + private let lock = NSLock() + private var address: ClusterLinkIPv4Address? + var value: ClusterLinkIPv4Address? { + get { lock.withLock { address } } + set { lock.withLock { address = newValue } } + } + } + + static func livePartner(_ peer: PeerAddress) -> ClusterPairUpdate.Partner { + guard let pairing = try? ClusterSetupLinkExchange.pairing(), let selection = try? LiveContext.defaultLinkSelection(), + let body = try? JSONEncoder().encode(ClusterServiceCommand(op: .status)) else { return .unreachable } + guard let answer = try? ClusterSetupLinkExchange.command(pairing: pairing, selection: selection, peerAddress: peer.value, + body: body, seconds: 10), + let status = try? JSONDecoder().decode(ClusterServiceStatus.self, from: answer.reply) else { + peer.value = nil + return .unreachable + } + peer.value = answer.peerAddress + return status.pairUpdate.map { .reported($0) } ?? .silent + } +} diff --git a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift index 7d9b318956..716cbd8f02 100644 --- a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift +++ b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift @@ -14,11 +14,31 @@ import ProviderCore /// budget and backoff (`ClusterMemberRestartBudget`), and parks when the /// budget is spent instead of looping against JACCL and Metal memory; /// 4. at the cluster's update slot drains its member, installs a release and -/// starts again from the new binary (`ClusterMemberUpdateSlot`). +/// starts again from the new binary (`ClusterMemberUpdateSlot`). Around the +/// cluster service (`pairUpdate`), the pair's coordinated update runs while +/// the service serves (`ClusterPairUpdateCycle`), and a release it installed +/// is promoted or rolled back by its service's health (`ClusterCandidateRecovery`). /// /// It sends SIGKILL only as the guard's last resort for a member that /// ignored a SIGTERM for the whole grace; an operator stop always waits. final class ClusterMemberSupervisor: @unchecked Sendable { + /// The cluster service route's coordinated update and candidate recovery. + struct PairUpdate: Sendable { + /// The pairing's cluster ID, the same on both Macs: it fixes the update slot. Read at each slot. + var clusterID: @Sendable () -> String? + /// One coordinated update cycle (`ClusterPairUpdateCycle.run`) for `request` (a `darkbloom update`), logging + /// with `log`; `restart` stops the service so the supervisor starts again from the installed binary. + var run: @Sendable (_ request: String?, _ log: @escaping @Sendable (String) -> Void, + _ restart: @escaping @Sendable (String) async throws -> Void) async -> AutoUpdateController.Outcome + /// Where `darkbloom update` asks for a restart into the release it installed (`ClusterPairUpdate.Request`). + var requestPath: URL + /// Where this Mac's progress is written; idle (or disabled) outside a cycle. + var progressPath: URL + var recovery: ClusterCandidateRecovery? + /// Whether the service's published status says this Mac's part serves again (logged once after an update). + var partServes: @Sendable () -> Bool = { false } + } + struct Configuration { var executable: String var childArguments: [String] @@ -40,6 +60,12 @@ final class ClusterMemberSupervisor: @unchecked Sendable { var restartHint: String = "`darkbloom restart` (or `darkbloom stop` then start)" /// How often a running member is checked for its end and its next probe. var childPollSeconds: Double = 0.5 + /// The cluster service route's coordinated update; nil on the member route, which uses the slot above. + var pairUpdate: PairUpdate? = nil + /// Replaces this process with the installed binary (`execv`); a test observes the call instead. + var reexec: (@Sendable ([String]) -> Void)? = nil + /// The orphan sweep before every run signals this user's orphaned cluster processes; a test never does. + var sweepsOrphans = true } private let configuration: Configuration @@ -48,6 +74,15 @@ final class ClusterMemberSupervisor: @unchecked Sendable { private var child: Process? private var state: ClusterMemberSupervisorState private var budget: ClusterMemberRestartBudget + // The coordinated update of the cluster service route: the next slot (main loop only), whether a cycle runs and + // the version it asked to restart into (under `lock`, set from the cycle's task). + private var pairSlot: Double? + private var pairCycle: Task? + private var pairCycleRunning = false + private var requestedRestart: String? + // The candidate this run's service is (main loop only), until it is promoted. + private var candidate: String? + private var updatedServiceServes = false init(configuration: Configuration) { self.configuration = configuration @@ -96,6 +131,13 @@ final class ClusterMemberSupervisor: @unchecked Sendable { var updateSlot = configuration.setup.map { ClusterMemberUpdateSlot.nextSlot(after: Date().timeIntervalSince1970, clusterID: $0.clusterID) } + if let pair = configuration.pairUpdate { + // A cycle of an earlier supervisor run is over: the other Mac must not wait for it. + ClusterPairUpdate.writeProgress(restingProgress(now: Date().timeIntervalSince1970), to: pair.progressPath) + log(configuration.autoUpdate + ? "cluster update: automatic updates on; both Macs check at the pair's update slot every \(Int(ClusterMemberUpdateSlot.periodSeconds / 60)) min" + : "cluster update: automatic updates are off (auto_update, DARKBLOOM_NO_UPDATE_CHECK); `darkbloom update` still updates the pair") + } while !isStopping { guard await waitForLink() else { break } // Before every run (the first and each restart): nothing of the @@ -115,6 +157,11 @@ final class ClusterMemberSupervisor: @unchecked Sendable { case .updateDrainedWithoutInstall: continue case .ended(let end, let runSeconds, let detail): + if recordCandidateEnd(detail: detail) { + reexecAfterUpdate() + log("re-exec after the rollback failed; starting the member from this binary") + continue + } let decision = budget.record(end, runSeconds: runSeconds) state.budget = budget switch decision { @@ -147,6 +194,7 @@ final class ClusterMemberSupervisor: @unchecked Sendable { /// sweeps again at its start. Waits for a leftover's contract (bounded), /// so a member recycled a moment ago is given its own exit first. private func sweepOrphansBeforeRun() async { + guard configuration.sweepsOrphans else { return } let outcome = await Task.detached(priority: .utility) { () -> String? in do { return ClusterOrphanSweep.summary(try ClusterOrphanSweep.reap(waitForContract: true)) } catch { return "orphan sweep skipped: \(error)" } @@ -211,6 +259,7 @@ final class ClusterMemberSupervisor: @unchecked Sendable { process.standardInput = FileHandle.nullDevice try? FileManager.default.removeItem(at: configuration.healthPath) let started = Date().timeIntervalSince1970 + noteCandidateLaunch(now: started) do { try lock.withLock { guard !stopRequested else { throw CancellationError() } @@ -234,6 +283,7 @@ final class ClusterMemberSupervisor: @unchecked Sendable { var drainedForUpdate: UpdateIntent? var nextProbe = started + configuration.guardLimits.intervalSeconds var lastHealthPhase: ClusterMemberHealth.Phase? + var restarting = false while process.isRunning { // A plain sleep: during an operator stop the member may take long // to drain, and an interruptible sleep would spin. @@ -241,7 +291,11 @@ final class ClusterMemberSupervisor: @unchecked Sendable { let now = Date().timeIntervalSince1970 guard process.isRunning, now >= nextProbe else { continue } nextProbe = now + configuration.guardLimits.intervalSeconds - if isStopping || recycleReason != nil || drainedForUpdate != nil { continue } + if !restarting, let version = lock.withLock({ requestedRestart }) { + restarting = true + update(phase: .updating, detail: "restarting into v\(version)") + } + if isStopping || recycleReason != nil || drainedForUpdate != nil || restarting { continue } let health = ClusterSupervisionFiles.read(ClusterMemberHealth.self, from: configuration.healthPath) if let phase = health.flatMap({ $0.pid == pid ? $0.phase : nil }), phase != lastHealthPhase { log("member pid \(pid) is \(phase.rawValue)" + (health?.warmup.map { "; warmup \($0)" } ?? "")) @@ -276,6 +330,10 @@ final class ClusterMemberSupervisor: @unchecked Sendable { } } } + if recycleReason == nil, let pair = configuration.pairUpdate { + observeCandidate(pair, health: health, pid: pid, started: started, now: now) + startPairCycleIfDue(pair, pid: pid, now: now) + } } // The loop above already saw the member end (`isRunning` is false, so its status is final). No blocking // `waitUntilExit()` here: it parks this thread in its own run loop until a termination message arrives, and @@ -285,6 +343,14 @@ final class ClusterMemberSupervisor: @unchecked Sendable { let ended = Date().timeIntervalSince1970 let signal: Int32? = process.terminationReason == .uncaughtSignal ? process.terminationStatus : nil let exitCode: Int32? = process.terminationReason == .exit ? process.terminationStatus : nil + await endPairCycle() + if let version = lock.withLock({ () -> String? in defer { requestedRestart = nil }; return requestedRestart }), !isStopping { + state.lastRun = .init(pid: pid, startedAt: started, endedAt: ended, exitCode: exitCode, signal: signal, + end: "stopped to restart into v\(version)") + state.current = nil + candidate = nil + return .updateInstalled + } if let intent = drainedForUpdate, !isStopping { state.lastRun = .init(pid: pid, startedAt: started, endedAt: ended, exitCode: exitCode, signal: signal, end: "drained for update") @@ -368,16 +434,141 @@ final class ClusterMemberSupervisor: @unchecked Sendable { } private func reexecAfterUpdate() { - update(phase: .updating, detail: "starting the updated binary") + update(phase: .updating, detail: "starting the installed binary") let arguments = configuration.reexecArguments guard let program = arguments.first else { return } - log("re-executing \(program) after the coordinated update") + log("re-executing \(program) to start the installed release") + if let reexec = configuration.reexec { return reexec(arguments) } var cArguments = arguments.map { strdup($0) } cArguments.append(nil) execv(program, &cArguments) for pointer in cArguments { free(pointer) } } + // MARK: - The cluster service's coordinated update + + /// At the pair's update slot (with automatic updates on), or for a `darkbloom update` request, one cycle runs + /// beside the service it supervises, which keeps serving until the cycle asks for the restart. + private func startPairCycleIfDue(_ pair: PairUpdate, pid: Int32, now: Double) { + guard !lock.withLock({ pairCycleRunning }) else { return } + if pairSlot == nil, let clusterID = pair.clusterID() { + pairSlot = ClusterMemberUpdateSlot.nextSlot(after: now, clusterID: clusterID) + } + let request = ClusterPairUpdate.takeRequest(from: pair.requestPath, now: now) + let slotDue = pairSlot.map { now >= $0 } ?? false + if let request { + log("cluster update: `darkbloom update` asked for a restart into the installed release together with the other Mac (\(request.id.prefix(8)))") + } else if !configuration.autoUpdate { + return restAsDisabled(pair, now: now) + } else if !slotDue { + return + } + // A cycle at or after the slot is that slot's. + if slotDue { pairSlot = pair.clusterID().map { ClusterMemberUpdateSlot.nextSlot(after: now, clusterID: $0) } } + lock.withLock { pairCycleRunning = true } + let log: @Sendable (String) -> Void = { [weak self] in self?.log($0) } + let restart: @Sendable (String) async throws -> Void = { [weak self] version in + try self?.restartForUpdate(into: version, pid: pid) + } + pairCycle = Task.detached { [weak self] in + _ = await pair.run(request?.id, log, restart) + guard let self else { return } + self.lock.withLock { self.pairCycleRunning = false } + } + } + + /// This Mac outside a cycle: idle, or disabled while its automatic updates are off. + private func restingProgress(now: Double) -> ClusterPairUpdateProgress { + .init(phase: configuration.autoUpdate ? .idle : .disabled, running: ProviderCore.version, writtenAt: now) + } + + /// With automatic updates off, the end of a cycle `darkbloom update` asked for stays the other Mac's (and the + /// command's) answer for a minute; then this Mac says `disabled` again, or the other Mac's every slot would download + /// the release and wait for this one. + private func restAsDisabled(_ pair: PairUpdate, now: Double) { + let last = ClusterPairUpdate.readProgress(from: pair.progressPath) + guard last?.phase != .disabled, now - (last?.writtenAt ?? 0) > ClusterPairUpdate.progressStaleSeconds else { return } + ClusterPairUpdate.writeProgress(restingProgress(now: now), to: pair.progressPath) + } + + /// The cycle's restart, once both Macs drained and the release is installed: the service stops (its drained part + /// with it) and the supervisor starts again from the installed binary. + private func restartForUpdate(into version: String, pid: Int32) throws { + let running: Process? = lock.withLock { + guard !stopRequested, let current = child, current.processIdentifier == pid, current.isRunning else { return nil } + requestedRestart = version + return current + } + guard running != nil else { throw CancellationError() } + log("cluster update: v\(version) installed; stopping the cluster service (pid \(pid), SIGTERM) to start again from it") + kill(pid, SIGTERM) + } + + /// The run ended: a cycle still running belonged to the service that ended. Its cancellation undoes the part's + /// drain and keeps nothing staged. + private func endPairCycle() async { + guard let cycle = pairCycle else { return } + cycle.cancel() + await cycle.value + pairCycle = nil + } + + /// Before each start of the service: a release installed and not yet promoted is a candidate (`ClusterCandidateRecovery`). + private func noteCandidateLaunch(now: Double) { + candidate = nil + guard let recovery = configuration.pairUpdate?.recovery, + case .candidate(let version, let failed) = recovery.noteLaunch(now: now) else { return } + candidate = version + updatedServiceServes = false + log("cluster update: starting the cluster service on candidate v\(version)" + + (failed > 0 ? " (\(failed) failed start\(failed == 1 ? "" : "s") so far)" : "") + + "; it is promoted once its service stays healthy, rolled back after \(UpdateRecoveryState.rollbackThreshold) failed starts") + } + + /// The candidate's health is the service's own heartbeat: from this run's process, with the candidate version, + /// fresh. It promotes the candidate once continuous for the stabilization window, as the watchdog's daemon-state + /// heartbeat does for a single Mac. + private func observeCandidate(_ pair: PairUpdate, health: ClusterMemberHealth?, pid: Int32, started: Double, now: Double) { + guard let version = candidate, let recovery = pair.recovery else { return } + if !updatedServiceServes, pair.partServes() { + updatedServiceServes = true + log("cluster update: this Mac's part serves again on v\(version)") + } + let healthy = health.map { $0.pid == pid && $0.version == version && now - $0.writtenAt <= Self.candidateHeartbeatSeconds } ?? false + switch recovery.observe(healthy: healthy, processStartedAt: started, now: now) { + case .promoted(let promoted): + candidate = nil + log("cluster update: v\(promoted) promoted: its cluster service stayed healthy through the stabilization window") + case .noCandidate: + candidate = nil + case .stabilizing: + break + } + } + + /// A service heartbeat (every 2 s) older than this does not count toward promotion. + static let candidateHeartbeatSeconds: Double = 30 + + /// A candidate's service that ended without being asked to is a failed start; returns whether the third restored + /// the verified predecessor, which the supervisor then starts again from. + private func recordCandidateEnd(detail: String) -> Bool { + guard candidate != nil, let recovery = configuration.pairUpdate?.recovery else { return false } + candidate = nil + switch recovery.recordFailedStart(now: Date().timeIntervalSince1970) { + case .counted(let version, let failures): + log("cluster update: v\(version) failed start \(failures)/\(UpdateRecoveryState.rollbackThreshold) (\(detail))") + return false + case .rolledBack(let from, let to): + log("cluster update: v\(from) failed \(UpdateRecoveryState.rollbackThreshold) starts; restored v\(to) and quarantined v\(from)") + return true + case .rollbackRefused(let version, let reason): + log("cluster update: rolling v\(version) back was refused (\(reason)); the installed release is kept and tried again later") + return false + case .notCandidate: + return false + } + } + // MARK: - Helpers private func acquireLock() -> Int32? { diff --git a/provider-swift/Sources/darkbloom/ClusterServiceCommand.swift b/provider-swift/Sources/darkbloom/ClusterServiceCommand.swift index f978b0ae8e..c99142bf94 100644 --- a/provider-swift/Sources/darkbloom/ClusterServiceCommand.swift +++ b/provider-swift/Sources/darkbloom/ClusterServiceCommand.swift @@ -9,7 +9,8 @@ extension Cluster { /// part while the leader has the cluster serving. Runs until SIGTERM or SIGINT. /// /// launchd runs it as `--supervise`: the S18 supervisor, which runs the - /// service as its child and restarts it with the restart budget and backoff. + /// service as its child and restarts it with the restart budget and backoff, + /// and updates the pair together with the other Mac's supervisor. struct Service: AsyncParsableCommand { static let configuration = CommandConfiguration(commandName: "service", abstract: "Run this Mac's cluster service (started by `darkbloom cluster`).", shouldDisplay: false) @@ -64,28 +65,55 @@ extension Cluster { /// `cluster service --supervise`: the S18 supervisor around `cluster service`. private func runSupervisor() async throws { - let environment = ProcessInfo.processInfo.environment - let directory = try ClusterService.paths().lock.deletingLastPathComponent() let executable = Start.currentExecutablePath() - let supervisor = ClusterMemberSupervisor(configuration: .init( + let supervisor = ClusterMemberSupervisor(configuration: Self.supervisorConfiguration( + executable: executable, serviceOptions: serviceOptions, configPath: configOptions.config, + environment: ProcessInfo.processInfo.environment, + serviceDirectory: try ClusterService.paths().lock.deletingLastPathComponent(), + reexecArguments: [executable] + Array(CommandLine.arguments.dropFirst()))) + let signals = try DistributedStartSignals() + defer { signals.close() } + signals.attach { supervisor.requestStop() } + // Exit 0 also when another supervisor already keeps the service, so launchd does not relaunch this one. + _ = await supervisor.run() + } + + /// The supervisor updates the pair as the single-Mac updater updates one Mac: the same `auto_update` and + /// `DARKBLOOM_NO_UPDATE_CHECK` gate and the same coordinator (`Watchdog.settings`), at the update slot of the + /// pairing's cluster ID, which both Macs share (`ClusterPairUpdateCycle`). + static func supervisorConfiguration( + executable: String, serviceOptions: [String], configPath: String?, environment: [String: String], + serviceDirectory: URL, reexecArguments: [String], + clusterID: @escaping @Sendable () -> String? = { try? ClusterSetupLinkExchange.pairing()?.clusterID } + ) -> ClusterMemberSupervisor.Configuration { + let settings = Watchdog.settings(configPath: configPath, environment: environment) + let coordinatorURL = settings.coordinatorURL + return .init( executable: executable, childArguments: ClusterServiceAgentPlan.childArguments(serviceOptions: serviceOptions), environment: environment, - statePath: ClusterServiceAgent.supervisorStatePath(serviceDirectory: directory), - healthPath: ClusterServiceAgent.healthPath(serviceDirectory: directory), - // The service waits for the cable itself (it answers once the link is up) and is - // updated with the app, not at the member's update slot. - setup: nil, coordinatorURL: "", autoUpdate: false, + statePath: ClusterServiceAgent.supervisorStatePath(serviceDirectory: serviceDirectory), + healthPath: ClusterServiceAgent.healthPath(serviceDirectory: serviceDirectory), + // The service waits for the cable itself (it answers once the link is up). + setup: nil, coordinatorURL: coordinatorURL, autoUpdate: settings.autoUpdate, budgetLimits: .resolve(environment), guardLimits: .resolve(environment), recycleGraceSeconds: Double(ClusterServiceAgentPlan.partStopGraceSeconds), - reexecArguments: [executable] + Array(CommandLine.arguments.dropFirst()), + reexecArguments: reexecArguments, logName: "cluster service supervisor", - restartHint: "`darkbloom cluster` is run again (or `darkbloom cluster stop`)")) - let signals = try DistributedStartSignals() - defer { signals.close() } - signals.attach { supervisor.requestStop() } - // Exit 0 also when another supervisor already keeps the service, so launchd does not relaunch this one. - _ = await supervisor.run() + restartHint: "`darkbloom cluster` is run again (or `darkbloom cluster stop`)", + pairUpdate: .init( + clusterID: clusterID, + run: { request, log, restart in + let environment = ClusterPairUpdateCycle.Environment.live( + serviceDirectory: serviceDirectory, coordinatorURL: coordinatorURL, log: log) + return await ClusterPairUpdateCycle(environment: environment).run(request: request, restart: restart) + }, + requestPath: ClusterServiceAgent.updateRequestPath(serviceDirectory: serviceDirectory), + progressPath: ClusterServiceAgent.updateProgressPath(serviceDirectory: serviceDirectory), + recovery: ClusterCandidateRecovery(updater: SelfUpdater(coordinatorBaseURL: coordinatorURL)), + partServes: { + ClusterService.publishedLive().map { $0.serving && $0.child.running && $0.session?.ready != false } ?? false + })) } } diff --git a/provider-swift/Sources/darkbloom/StartCommand+ClusterMember.swift b/provider-swift/Sources/darkbloom/StartCommand+ClusterMember.swift index 80f6ea4686..d3e1ed8faf 100644 --- a/provider-swift/Sources/darkbloom/StartCommand+ClusterMember.swift +++ b/provider-swift/Sources/darkbloom/StartCommand+ClusterMember.swift @@ -10,8 +10,10 @@ extension Start { } /// `offered`: the saved setup carries an approval this Mac installed, so its member registers a membership and - /// the coordinator may form a pair with it. - func makeClusterMemberLoopAndPreparation(reference: ClusterConfigurationReference, stopOnDisconnect: Bool = false) + /// the coordinator may form a pair with it. `answersUpdateDrain`: the coordinator-paired part, which drains for + /// the pair's coordinated update (`ProviderLoopConfig.clusterMemberAnswersUpdateDrain`). + func makeClusterMemberLoopAndPreparation(reference: ClusterConfigurationReference, stopOnDisconnect: Bool = false, + answersUpdateDrain: Bool = false) async throws -> (loop: ProviderLoop, prepared: ClusterMemberPreparation, offered: Bool) { // The model's pair-serving grant for the rank this Mac runs, with this // Mac's own chip class (any Apple silicon; owner 2026-10-14), is decided inside the @@ -57,6 +59,7 @@ extension Start { runtimeCapabilities: capabilities, modelHashes: prepared.model.weightHash.map { [prepared.model.id: $0] } ?? [:], executionRole: .clusterMember, clusterMemberStopsOnDisconnect: stopOnDisconnect, + clusterMemberAnswersUpdateDrain: answersUpdateDrain, pairServingGrantedModelIDs: [prepared.model.id]) let loop = try ProviderLoop(config: loopConfig) if let installation { @@ -89,7 +92,8 @@ extension Start { // bootstrap directories), reported in this member's log. Self.sweepOrphans(phase: "start", waitForContract: true) defer { Self.sweepOrphans(phase: "end", waitForContract: true) } - let (loop, prepared, offered) = try await makeClusterMemberLoopAndPreparation(reference: factory.reference) + let (loop, prepared, offered) = try await makeClusterMemberLoopAndPreparation(reference: factory.reference, + answersUpdateDrain: true) heartbeat.attach(loop: loop) // A setup saved for coordinator pairing over the link serves the // pair's committed starts (S10): the leader hosts the link listener diff --git a/provider-swift/Sources/darkbloom/UpdateCommand.swift b/provider-swift/Sources/darkbloom/UpdateCommand.swift index 0e331f813a..2225fe9d5c 100644 --- a/provider-swift/Sources/darkbloom/UpdateCommand.swift +++ b/provider-swift/Sources/darkbloom/UpdateCommand.swift @@ -104,6 +104,8 @@ struct Update: AsyncParsableCommand { print("Updated: v\(from) -> v\(to)") if LaunchAgent.isLoaded() { try await restartInstalledProvider(updater, operation: "manual-update-restart") + } else if ClusterService.running() { + try await restartClusterService(into: to) } else { print("Restart the provider for the new version to take effect.") } @@ -112,6 +114,8 @@ struct Update: AsyncParsableCommand { print("v\(to) is already installed (current process: v\(from)).") if LaunchAgent.isLoaded() { try await restartInstalledProvider(updater, operation: "manual-candidate-restart") + } else if ClusterService.running() { + try await restartClusterService(into: to) } else { print("Restart the provider for v\(to) to take effect.") } @@ -172,4 +176,59 @@ struct Update: AsyncParsableCommand { try await ServiceDrain.waitForRestart(previous: previous, timeout: 180) } + /// A `darkbloom cluster` Mac: its cluster service supervisor restarts into the installed release together with + /// the other Mac, after the pair drained, as at the pair's update slot (`ClusterPairUpdateCycle`). + private func restartClusterService(into version: String) async throws { + let directory = try ClusterService.paths().lock.deletingLastPathComponent() + let request = ClusterPairUpdate.Request(createdAt: Date().timeIntervalSince1970) + let outcome = try await ClusterServiceUpdateRequest.restart(into: version, request: request, serviceDirectory: directory, + timeoutSeconds: drain.timeout, say: { print($0) }) + guard outcome != .failed else { throw ExitCode.failure } + } + +} + +/// `darkbloom update` asks the cluster service supervisor for the pair's restart into the installed release +/// (`ClusterPairUpdate.Request`) and follows its progress. +enum ClusterServiceUpdateRequest { + enum Outcome: Equatable { case restarting, waiting, failed } + + static func restart(into version: String, request: ClusterPairUpdate.Request, serviceDirectory: URL, timeoutSeconds: Int, + pollSeconds: Double = 1, say: (String) -> Void) async throws -> Outcome { + let progressPath = ClusterServiceAgent.updateProgressPath(serviceDirectory: serviceDirectory) + // A supervisor of an earlier build neither publishes progress nor reads the request. + guard ClusterPairUpdate.readProgress(from: progressPath) != nil else { + say("This Mac's cluster service runs a build that does not restart for an update. Log out and back in on both Macs " + + "(or restart them) once both have v\(version).") + return .waiting + } + guard ClusterPairUpdate.writeRequest(request, to: ClusterServiceAgent.updateRequestPath(serviceDirectory: serviceDirectory)) else { + throw ValidationError("Could not ask this Mac's cluster service to restart (\(serviceDirectory.path) is not writable).") + } + say("Asked this Mac's cluster service to restart into v\(version) together with the other Mac; the pair finishes its accepted requests first.") + say("Run `darkbloom update` on the other Mac too (or wait for the pair's next update slot): both restart once both have v\(version).") + let deadline = Date().addingTimeInterval(Double(timeoutSeconds)) + var said: String? + while Date() < deadline { + if let progress = ClusterPairUpdate.readProgress(from: progressPath), progress.request == request.id { + if progress.line != said { + said = progress.line + say(" \(progress.line)") + } + switch progress.phase { + case .restarting: + say("The cluster service restarts into v\(version); the cluster sets itself up again once both Macs run it.") + return .restarting + case .deferred, .failed: + say("Not restarted now. The pair tries again at its next update slot, or run `darkbloom update` again.") + return .failed + default: + break + } + } + try await Task.sleep(nanoseconds: UInt64(pollSeconds * 1_000_000_000)) + } + say("Still waiting after \(timeoutSeconds) s; the cluster service goes on by itself. Its log: ~/.darkbloom/cluster-setup/service.log") + return .waiting + } } diff --git a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift index dbb5cc080c..aca40f6a19 100644 --- a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift +++ b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift @@ -1254,6 +1254,12 @@ import Darwin expect(U.changed(pinned: pinned, current: ["mac-a": "a2a2", "mac-b": "b2b2"]) == ["mac-a", "mac-b"], "update: both updated") expect(U.changed(pinned: pinned, current: ["mac-a": "aaaa", "mac-b": nil]).isEmpty, "update: a Mac that did not answer is no reason") expect(U.changed(pinned: pinned, current: [:]).isEmpty, "update: nothing known, nothing re-planned") + // The pair's coordinated update restarts both Macs seconds apart: plan again once both answer with one build. + expect(U.oneBuild(pinned: pinned, current: ["mac-a": "a2a2", "mac-b": "a2a2"]), "update: both run the new build: plan again") + expect(!U.oneBuild(pinned: pinned, current: ["mac-a": "a2a2", "mac-b": "bbbb"]), "update: the other Mac still runs the old build: wait") + expect(!U.oneBuild(pinned: pinned, current: ["mac-a": "a2a2", "mac-b": nil]), "update: the other Mac has not answered yet: wait") + expect(!U.oneBuild(pinned: pinned, current: ["mac-a": "a2a2"]), "update: the other Mac not asked: wait") + expect(!U.oneBuild(pinned: [:], current: [:]), "update: no setup, nothing to plan") expect(U.statusLine == "Updating the cluster setup after a Darkbloom update.", "update: the status line") expect(U.checkEverySeconds <= 60 && U.retryAfterFailureSeconds >= 300, "update: noticed within a minute, a failure not retried in a loop") // The re-plan waits for both Macs' memory: every Mac's summary, and both of them. diff --git a/provider-swift/Tests/ClusterSupervisionChecks/main.swift b/provider-swift/Tests/ClusterSupervisionChecks/main.swift index ab35a3113d..a90c4e507b 100644 --- a/provider-swift/Tests/ClusterSupervisionChecks/main.swift +++ b/provider-swift/Tests/ClusterSupervisionChecks/main.swift @@ -245,6 +245,89 @@ do { check(ClusterMemberUpdateSlot.decide(now: slot, slot: slot, busy: false) == .check, "idle at the slot checks") check(ClusterMemberUpdateSlot.decide(now: slot + 5, slot: slot, busy: true) == .deferBusy(retryAt: slot + 20), "busy defers") check(ClusterMemberUpdateSlot.decide(now: slot + 601, slot: slot, busy: true) == .skip, "busy past 10 min skips the slot") + // The cluster service route keys the slot on the pairing's cluster ID, which both Macs read from their pairing. + let pairing = "pair-7f3a" + let first = ClusterMemberUpdateSlot.nextSlot(after: now + 11, clusterID: pairing) + check(first == ClusterMemberUpdateSlot.nextSlot(after: now + 11.6, clusterID: pairing), "both Macs of a pairing share its slot") + check(ClusterMemberUpdateSlot.nextSlot(after: first, clusterID: pairing) == first + 1800, "and every slot after it") +} + +// MARK: - The pair's coordinated update (cluster service route) + +do { + typealias U = ClusterPairUpdate + let start = 50_000.0 + func progress(_ phase: ClusterPairUpdateProgress.Phase, target: String? = "2.0.0", running: String = "1.0.0", + written: Double = start + 1, detail: String? = nil) -> U.Partner { + .reported(.init(phase: phase, target: target, running: running, cycleStartedAt: start, writtenAt: written, detail: detail)) + } + func state(_ partner: U.Partner, _ step: U.Step, now: Double = start + 2, requested: Bool = false) -> U.PartnerState { + U.partnerState(partner, target: "2.0.0", step: step, cycleStartedAt: start, now: now, requested: requested) + } + // Neither Mac stops taking requests before both have the release on disk. + check(state(progress(.checking), .staged) == .waiting, "the other Mac still downloads: wait") + check(state(progress(.checking, target: nil), .staged) == .waiting, "the other Mac has not heard from the coordinator yet: wait") + for phase in [ClusterPairUpdateProgress.Phase.staged, .draining, .drained, .restarting] { + check(state(progress(phase), .staged) == .ready, "the other Mac has the release (\(phase.rawValue)): drain") + } + // Neither installs before both drained. + check(state(progress(.staged), .drained) == .waiting && state(progress(.draining), .drained) == .waiting, + "the other Mac still finishes its accepted requests: wait") + check(state(progress(.drained), .drained) == .ready && state(progress(.restarting), .drained) == .ready, "both drained: install") + // A Mac that already runs the release (it updated alone, or by hand) lets the other one go on. + check(state(progress(.idle, target: nil, running: "2.0.0"), .drained) == .ready, "the other Mac runs the release") + // One Mac that cannot take the release stops both: neither installs, both retry at the next slot. + if case .gaveUp(let reason) = state(progress(.failed, detail: "hashMismatch"), .staged) { + check(reason.contains("hashMismatch") && reason.contains("v2.0.0"), "the other Mac's failure is named: \(reason)") + } else { check(false, "a failed download on the other Mac stops this one") } + if case .gaveUp = state(progress(.deferred, detail: "1 accepted request(s) were still running"), .drained) {} else { + check(false, "a drain the other Mac gave up stops this one") + } + // An end of an earlier cycle (the two slots reach both Macs seconds apart) is no answer to this one. + check(state(progress(.deferred, written: start - 30), .staged) == .waiting, "an earlier cycle's deferral is not this cycle's") + check(state(progress(.failed, target: "1.9.0"), .staged) == .waiting, "a failure for another release is not this one's") + if case .gaveUp(let reason) = state(progress(.staged, target: "2.1.0"), .staged) { + check(reason.contains("v2.1.0"), "another release on the other Mac: \(reason)") + } else { check(false, "the two Macs never install different releases") } + let disabled = U.Partner.reported(.init(phase: .disabled, running: "1.0.0", writtenAt: 1)) + if case .gaveUp(let reason) = state(disabled, .staged) { + check(reason.contains("off on the other Mac"), "auto_update off on the other Mac: \(reason)") + } else { check(false, "the other Mac's automatic updates are off") } + // `darkbloom update` waits, while serving, for the one run on the other Mac; a drained Mac does not wait for it. + check(state(disabled, .staged, requested: true) == .waiting, "a requested update waits for the other Mac's") + if case .gaveUp = state(disabled, .drained, requested: true) {} else { check(false, "a drained Mac does not wait for a Mac with updates off") } + check(state(progress(.idle, target: nil), .staged) == .waiting, "an idle Mac may start its cycle a little later") + // A supervisor that stopped writing, an older build and a Mac that does not answer cannot coordinate. + check(state(progress(.staged, written: start - 120), .staged, now: start + 1) == .cannotCoordinate, "a stale progress") + check(state(.silent, .staged) == .cannotCoordinate && state(.unreachable, .drained) == .cannotCoordinate, + "silent or unreachable: this Mac goes on alone only when no pair runs on it") + check(U.drainTimeoutSeconds == 120, "the single-Mac updater's drain bound") + check(U.partnerDrainWaitSeconds > U.drainTimeoutSeconds && U.drainedHoldSeconds > U.partnerDrainWaitSeconds, + "a drained part waits longer than the pair can take to install") + check(U.partnerStageWaitSeconds < ClusterMemberUpdateSlot.periodSeconds, "a cycle ends before the next slot") + check(ClusterPairUpdateProgress(phase: .deferred, target: "2.0.0", running: "1.0.0", writtenAt: 0, detail: "busy").line + == "v2.0.0 deferred to the next update slot (busy)", "the progress line") + // A phase a later build adds neither fails the other Mac's status nor reads as ready. + let later = #"{"phase":"verifying","target":"2.0.0","running":"1.0.0","writtenAt":50001}"# + let unknown = try? JSONDecoder().decode(ClusterPairUpdateProgress.self, from: Data(later.utf8)) + check(unknown?.phase == .checking, "an unknown phase decodes as still working") + check(unknown.map { state(.reported($0), .staged) == .waiting && state(.reported($0), .drained) == .waiting } == true, + "an unknown phase is waited for, never taken for ready") + + // `darkbloom update`'s request is answered once, and a stale one not at all. + let directory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("pair-update-checks-\(getpid())") + defer { try? FileManager.default.removeItem(at: directory) } + let path = directory.appendingPathComponent("service-update-request.json") + check(U.writeRequest(.init(id: "r1", createdAt: start), to: path), "request written") + check(U.takeRequest(from: path, now: start + 3)?.id == "r1", "the request is taken") + check(U.takeRequest(from: path, now: start + 4) == nil, "and only once") + check(U.writeRequest(.init(id: "r2", createdAt: start), to: path), "request written") + check(U.takeRequest(from: path, now: start + U.Request.maximumAgeSeconds + 1) == nil, "a request older than an hour is dropped") + check(!FileManager.default.fileExists(atPath: path.path), "and removed") + let written = ClusterPairUpdateProgress(phase: .staged, target: "2.0.0", running: "1.0.0", cycleStartedAt: start, + request: "r1", writtenAt: start + 1) + let progressPath = directory.appendingPathComponent("service-update.json") + check(U.writeProgress(written, to: progressPath) && U.readProgress(from: progressPath) == written, "progress round trip") } // MARK: - Files and state summary diff --git a/provider-swift/Tests/ClusterSupervisionChecks/run.sh b/provider-swift/Tests/ClusterSupervisionChecks/run.sh index d62ac911f0..925461ae64 100755 --- a/provider-swift/Tests/ClusterSupervisionChecks/run.sh +++ b/provider-swift/Tests/ClusterSupervisionChecks/run.sh @@ -17,5 +17,6 @@ xcrun swiftc -swift-version 6 -warnings-as-errors -target "$(uname -m)-apple-mac -module-name ClusterSupervisionChecks \ "$sources"/Service/ClusterSupervision/*.swift \ "$sources/Inference/Distributed/Diagnostics/Link/ClusterLinkReadinessState.swift" \ + "$sources/Inference/Distributed/Installed/ClusterPairUpdateProgress.swift" \ "$here/main.swift" -o "$build/checks" EXPECTED_FNV_OFFSET="$expected_offset" "$build/checks" diff --git a/provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift b/provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift new file mode 100644 index 0000000000..f3bc9abbf7 --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift @@ -0,0 +1,311 @@ +import CryptoKit +import Foundation +import ProviderCore +import Testing +@testable import darkbloom +@testable import ProviderCore + +/// The cluster service supervisor's update (`darkbloom cluster`): its wiring to the single-Mac gate, the pair's update +/// slot and `darkbloom update`'s request, around a real supervisor with a shell standing in for the cluster service +/// (no model, network, launchd or re-exec: the re-exec is observed). The cycle itself is covered with real installs in +/// `ClusterPairUpdateTests`. +@Suite("Cluster service update", .serialized) +struct ClusterServiceUpdateTests { + private final class Recorder: @unchecked Sendable { + private let lock = NSLock() + private var values: [String] = [] + func add(_ value: String) { lock.withLock { values.append(value) } } + var all: [String] { lock.withLock { values } } + } + + private func temporaryDirectory(_ name: String) throws -> URL { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("\(name)-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + return directory + } + + private func state(_ directory: URL) -> ClusterMemberSupervisorState? { + ClusterSupervisionFiles.read(ClusterMemberSupervisorState.self, from: ClusterServiceAgent.supervisorStatePath(serviceDirectory: directory)) + } + + private func waitUntil(seconds: Double, _ condition: () -> Bool) async -> Bool { + let deadline = Date().addingTimeInterval(seconds) + while Date() < deadline { + if condition() { return true } + try? await Task.sleep(nanoseconds: 50_000_000) + } + return condition() + } + + /// A cluster ID whose update slot falls `2...4` s from now, so the real slot schedule fires during the test. + private func imminentClusterID() -> String { + let now = Date().timeIntervalSince1970 + for index in 0..<100_000 { + let id = "slot-check-\(index)" + let wait = ClusterMemberUpdateSlot.nextSlot(after: now, clusterID: id) - now + if (2...4).contains(wait) { return id } + } + return "slot-check-none" + } + + private func configuration(directory: URL, script: String, autoUpdate: Bool, clusterID: String, + recovery: ClusterCandidateRecovery? = nil, reexecs: Recorder, + run: @escaping @Sendable (String?, @escaping @Sendable (String) -> Void, + @escaping @Sendable (String) async throws -> Void) async -> AutoUpdateController.Outcome) + -> ClusterMemberSupervisor.Configuration { + var limits = ClusterMemberLivenessGuard.Limits() + limits.intervalSeconds = 0.2 + limits.startGraceSeconds = 600 + limits.downSeconds = 600 + return .init(executable: "/bin/sh", childArguments: ["-c", script], environment: ["PATH": "/usr/bin:/bin"], + statePath: ClusterServiceAgent.supervisorStatePath(serviceDirectory: directory), + healthPath: ClusterServiceAgent.healthPath(serviceDirectory: directory), + setup: nil, coordinatorURL: "http://127.0.0.1:9", autoUpdate: autoUpdate, + budgetLimits: .init(maxQuickFailures: 5, quickFailureWindowSeconds: 30, initialBackoffSeconds: 1, maxBackoffSeconds: 1), + guardLimits: limits, recycleGraceSeconds: 5, reexecArguments: ["/installed/darkbloom", "cluster", "service", "--supervise"], + logName: "cluster service supervisor", childPollSeconds: 0.05, + pairUpdate: .init(clusterID: { clusterID }, run: run, + requestPath: ClusterServiceAgent.updateRequestPath(serviceDirectory: directory), + progressPath: ClusterServiceAgent.updateProgressPath(serviceDirectory: directory), + recovery: recovery), + reexec: { reexecs.add($0.joined(separator: " ")) }, sweepsOrphans: false) + } + + // MARK: - Wiring + + /// `darkbloom cluster`'s supervisor takes the single-Mac gate: `auto_update`, `DARKBLOOM_NO_UPDATE_CHECK` and the + /// configured coordinator, and keys the slot on the pairing's cluster ID. + @Test(arguments: [(true, false, true), (false, false, false), (true, true, false)]) + func supervisorTakesTheSingleMacGate(autoUpdate: Bool, noUpdateCheck: Bool, expected: Bool) throws { + let directory = try temporaryDirectory("cluster-update-gate") + defer { try? FileManager.default.removeItem(at: directory) } + let path = directory.appendingPathComponent("provider.toml") + var config = ProviderConfig(provider: ProviderSettings(name: "pair")) + config.provider.autoUpdate = autoUpdate + config.coordinator.url = "wss://coordinator.example.invalid/ws/provider" + try ConfigManager.save(config, to: path) + let environment = noUpdateCheck ? ["DARKBLOOM_NO_UPDATE_CHECK": "1"] : [:] + let configured = Cluster.Service.supervisorConfiguration(executable: "/A/darkbloom", serviceOptions: ["--config", path.path], + configPath: path.path, environment: environment, serviceDirectory: directory, + reexecArguments: ["/A/darkbloom", "cluster", "service", "--supervise"], clusterID: { "pair-7f3a" }) + #expect(configured.autoUpdate == expected) + #expect(configured.coordinatorURL == "wss://coordinator.example.invalid/ws/provider") + #expect(configured.setup == nil, "the service waits for the cable itself") + let pair = try #require(configured.pairUpdate) + #expect(pair.clusterID() == "pair-7f3a") + #expect(pair.requestPath == directory.appendingPathComponent("service-update-request.json")) + #expect(pair.progressPath == directory.appendingPathComponent("service-update.json")) + #expect(pair.recovery != nil, "a release the pair installs is promoted or rolled back by its service's health") + #expect(configured.childArguments == ["cluster", "service", "--config", path.path]) + } + + // MARK: - The slot + + /// At the pair's slot the cycle runs beside the serving service; its restart stops the service and the supervisor + /// starts again from the installed binary (re-exec), with the progress idle beforehand for the other Mac. + @Test func slotRunsTheCycleBesideTheServiceAndRestartsIntoTheRelease() async throws { + let directory = try temporaryDirectory("cluster-update-slot") + defer { try? FileManager.default.removeItem(at: directory) } + let calls = Recorder(), reexecs = Recorder() + let supervisor = ClusterMemberSupervisor(configuration: configuration(directory: directory, script: "exec sleep 60", + autoUpdate: true, clusterID: imminentClusterID(), reexecs: reexecs) { request, log, restart in + calls.add(request ?? "slot") + log("cluster update: test cycle") + try? await restart("2.0.0") + return .restarted(from: "1.0.0", to: "2.0.0", drained: true) + }) + let run = Task { await supervisor.run() } + #expect(await waitUntil(seconds: 2) { + ClusterPairUpdate.readProgress(from: ClusterServiceAgent.updateProgressPath(serviceDirectory: directory))?.phase == .idle + }, "the other Mac never waits for a cycle of an earlier run") + #expect(await waitUntil(seconds: 15) { !reexecs.all.isEmpty }, "the slot fired, the service stopped and the supervisor re-executed") + #expect(calls.all == ["slot"]) + #expect(reexecs.all == ["/installed/darkbloom cluster service --supervise"]) + #expect(state(directory)?.lastRun?.end == "stopped to restart into v2.0.0") + // In a test the re-exec returns: the supervisor keeps going and starts the service again. + #expect(await waitUntil(seconds: 10) { state(directory)?.runs == 2 && state(directory)?.phase == .running }) + supervisor.requestStop() + #expect(await run.value == 0) + #expect(calls.all == ["slot"], "the next slot is a period later") + } + + /// With automatic updates off the slot never runs a cycle, and the other Mac reads `disabled`: from the start, and + /// again a minute after a cycle `darkbloom update` asked for ended, so the other Mac's slot downloads nothing. + @Test func autoUpdateOffRunsNoSlotCycle() async throws { + let directory = try temporaryDirectory("cluster-update-off") + defer { try? FileManager.default.removeItem(at: directory) } + let calls = Recorder(), reexecs = Recorder() + let progressPath = ClusterServiceAgent.updateProgressPath(serviceDirectory: directory) + let supervisor = ClusterMemberSupervisor(configuration: configuration(directory: directory, script: "exec sleep 60", + autoUpdate: false, clusterID: imminentClusterID(), reexecs: reexecs) { request, _, _ in + calls.add(request ?? "slot") + return .upToDate + }) + let run = Task { await supervisor.run() } + #expect(await waitUntil(seconds: 2) { ClusterPairUpdate.readProgress(from: progressPath)?.phase == .disabled }) + try await Task.sleep(nanoseconds: 6_000_000_000) + #expect(calls.all.isEmpty && reexecs.all.isEmpty, "the slot passed without a cycle") + + let now = Date().timeIntervalSince1970 + ClusterPairUpdate.writeProgress(.init(phase: .failed, target: "2.0.0", running: "1.0.0", request: "update-1", + writtenAt: now, detail: "hashMismatch"), to: progressPath) + try await Task.sleep(nanoseconds: 1_000_000_000) + #expect(ClusterPairUpdate.readProgress(from: progressPath)?.phase == .failed, "a fresh end is still the other Mac's answer") + ClusterPairUpdate.writeProgress(.init(phase: .idle, running: "1.0.0", request: "update-1", + writtenAt: now - ClusterPairUpdate.progressStaleSeconds - 1, detail: "up to date"), to: progressPath) + #expect(await waitUntil(seconds: 5) { ClusterPairUpdate.readProgress(from: progressPath)?.phase == .disabled }, + "an end older than a minute gives way to disabled again") + #expect(calls.all.isEmpty) + supervisor.requestStop() + #expect(await run.value == 0) + } + + // MARK: - `darkbloom update` + + /// `darkbloom update` on a cluster Mac asks the supervisor for the pair's restart now (automatic updates off or on) + /// and follows its progress: the cluster service restarts without a log-out. + @Test func darkbloomUpdateRestartsTheClusterService() async throws { + let directory = try temporaryDirectory("cluster-update-manual") + defer { try? FileManager.default.removeItem(at: directory) } + let calls = Recorder(), reexecs = Recorder() + let progressPath = ClusterServiceAgent.updateProgressPath(serviceDirectory: directory) + let supervisor = ClusterMemberSupervisor(configuration: configuration(directory: directory, script: "exec sleep 60", + autoUpdate: false, clusterID: "pair-far-from-its-slot", reexecs: reexecs) { request, _, restart in + calls.add(request ?? "slot") + for phase in [ClusterPairUpdateProgress.Phase.staged, .drained, .restarting] { + ClusterPairUpdate.writeProgress(.init(phase: phase, target: "2.0.0", running: "1.0.0", cycleStartedAt: 1, + request: request, writtenAt: Date().timeIntervalSince1970), to: progressPath) + try? await Task.sleep(nanoseconds: 300_000_000) + } + try? await restart("2.0.0") + return .restarted(from: "1.0.0", to: "2.0.0", drained: true) + }) + let run = Task { await supervisor.run() } + #expect(await waitUntil(seconds: 5) { state(directory)?.phase == .running }) + let request = ClusterPairUpdate.Request(createdAt: Date().timeIntervalSince1970) + let said = Recorder() + let outcome = try await ClusterServiceUpdateRequest.restart(into: "2.0.0", request: request, serviceDirectory: directory, + timeoutSeconds: 20, pollSeconds: 0.1, say: { said.add($0) }) + #expect(outcome == .restarting, "\(said.all)") + #expect(said.all.contains { $0.contains("drained for v2.0.0") }, "\(said.all)") + #expect(calls.all == [request.id], "the request ran one cycle now, not at the slot") + #expect(await waitUntil(seconds: 10) { reexecs.all.count == 1 }) + #expect(!FileManager.default.fileExists(atPath: ClusterServiceAgent.updateRequestPath(serviceDirectory: directory).path), + "the request is answered once") + supervisor.requestStop() + #expect(await run.value == 0) + } + + /// A supervisor of an earlier build publishes no progress: the command says how to restart instead of waiting. + @Test func darkbloomUpdateWithAnEarlierServiceSaysToLogOutAndIn() async throws { + let directory = try temporaryDirectory("cluster-update-earlier") + defer { try? FileManager.default.removeItem(at: directory) } + let said = Recorder() + let outcome = try await ClusterServiceUpdateRequest.restart(into: "2.0.0", request: .init(createdAt: Date().timeIntervalSince1970), + serviceDirectory: directory, timeoutSeconds: 1, say: { said.add($0) }) + #expect(outcome == .waiting) + #expect(said.all.first?.contains("Log out and back in on both Macs") == true, "\(said.all)") + } + + // MARK: - Candidate promotion and rollback + + /// The release a cycle installed is a candidate: three starts of its service that end on their own restore the + /// verified predecessor, quarantine the release and start again from the restored binary. + @Test func failingCandidateIsRolledBackAndTheSupervisorRestartsFromThePredecessor() async throws { + let install = try CandidateInstall() + defer { install.cleanUp() } + let directory = try temporaryDirectory("cluster-update-rollback") + defer { try? FileManager.default.removeItem(at: directory) } + let reexecs = Recorder() + let supervisor = ClusterMemberSupervisor(configuration: configuration(directory: directory, script: "exit 1", + autoUpdate: false, clusterID: "pair-far-from-its-slot", recovery: ClusterCandidateRecovery(updater: install.updater), + reexecs: reexecs) { _, _, _ in .upToDate }) + let run = Task { await supervisor.run() } + #expect(await waitUntil(seconds: 20) { !reexecs.all.isEmpty }, "three failed starts roll the candidate back") + #expect(try install.liveBinary() == "1.0.0-darkbloom") + let recovery = try UpdateRecoveryStore(installRoot: install.installRoot, verifyCodeSignatures: false).loadState() + #expect(recovery.quarantine?.version == "2.0.0" && recovery.candidate == nil) + #expect((state(directory)?.runs ?? 0) >= 3, "rolled back at the third failed start") + supervisor.requestStop() + #expect(await run.value == 0) + } + + /// A candidate whose service keeps beating with the new version through the stabilization window is promoted. + @Test func healthyCandidateIsPromoted() async throws { + let install = try CandidateInstall() + defer { install.cleanUp() } + let directory = try temporaryDirectory("cluster-update-promote") + defer { try? FileManager.default.removeItem(at: directory) } + let reexecs = Recorder() + let beating = #"while :; do printf '{"pid":%d,"version":"2.0.0","phase":"serving","writtenAt":%s}' $$ "$(date +%s)" "# + + #"> "$DARKBLOOM_CLUSTER_MEMBER_HEALTH_FILE"; sleep 0.2; done"# + let supervisor = ClusterMemberSupervisor(configuration: configuration(directory: directory, script: beating, + autoUpdate: false, clusterID: "pair-far-from-its-slot", + recovery: ClusterCandidateRecovery(updater: install.updater, stabilizationSeconds: 1), reexecs: reexecs) { _, _, _ in .upToDate }) + let run = Task { await supervisor.run() } + #expect(await waitUntil(seconds: 15) { + (try? UpdateRecoveryStore(installRoot: install.installRoot, verifyCodeSignatures: false).loadState().current?.version) == "2.0.0" + }, "promoted after the window") + let recovery = try UpdateRecoveryStore(installRoot: install.installRoot, verifyCodeSignatures: false).loadState() + #expect(recovery.candidate == nil && recovery.quarantine == nil) + #expect(try install.liveBinary() == "2.0.0-darkbloom" && reexecs.all.isEmpty) + supervisor.requestStop() + #expect(await run.value == 0) + } +} + +/// A temporary install with release 2.0.0 installed over 1.0.0 and not yet promoted (no network, unsigned fixtures). +private struct CandidateInstall { + let root: URL + let installRoot: URL + let updater: SelfUpdater + + init() throws { + let fm = FileManager.default + root = fm.temporaryDirectory.appendingPathComponent("cluster-candidate-\(UUID().uuidString)", isDirectory: true) + installRoot = root.appendingPathComponent("install", isDirectory: true) + try Self.writeApp(version: "1.0.0", root: installRoot) + let bin = installRoot.appendingPathComponent("bin") + try fm.createDirectory(at: bin, withIntermediateDirectories: true) + for name in ["darkbloom", "darkbloom-enclave", "mlx.metallib"] { + try fm.createSymbolicLink(atPath: bin.appendingPathComponent(name).path, + withDestinationPath: "../Darkbloom.app/Contents/MacOS/\(name)") + } + let source = root.appendingPathComponent("release", isDirectory: true) + try Self.writeApp(version: "2.0.0", root: source) + let flat = source.appendingPathComponent("bin", isDirectory: true) + try fm.createDirectory(at: flat, withIntermediateDirectories: true) + for name in ["darkbloom", "darkbloom-enclave", "mlx.metallib"] { + try fm.copyItem(at: source.appendingPathComponent("Darkbloom.app/Contents/MacOS/\(name)"), to: flat.appendingPathComponent(name)) + } + let tarball = root.appendingPathComponent("release.tar.gz") + let tar = Process() + tar.executableURL = URL(fileURLWithPath: "/usr/bin/tar") + tar.arguments = ["czf", tarball.path, "-C", source.path, "."] + try tar.run() + tar.waitUntilExit() + let digest = SHA256.hash(data: try Data(contentsOf: tarball)).map { String(format: "%02x", $0) }.joined() + updater = SelfUpdater(coordinatorBaseURL: "http://127.0.0.1:9", installRoot: installRoot, verifyCodeSignatures: false, + currentVersion: "1.0.0") + let release = ReleaseInfo(version: "2.0.0", platform: "macos-arm64", url: "file:///unused", bundleHash: digest) + guard case .success = updater.installBundleForTesting(from: tarball, release: release, installDir: installRoot) else { + throw CocoaError(.fileWriteUnknown) + } + } + + func liveBinary() throws -> String { + try String(contentsOf: installRoot.appendingPathComponent("Darkbloom.app/Contents/MacOS/darkbloom"), encoding: .utf8) + } + + func cleanUp() { try? FileManager.default.removeItem(at: root) } + + private static func writeApp(version: String, root: URL) throws { + let contents = root.appendingPathComponent("Darkbloom.app/Contents") + let macOS = contents.appendingPathComponent("MacOS") + try FileManager.default.createDirectory(at: macOS, withIntermediateDirectories: true) + try Data("".utf8).write(to: contents.appendingPathComponent("Info.plist")) + try Data("\(version)-darkbloom".utf8).write(to: macOS.appendingPathComponent("darkbloom")) + try Data("\(version)-enclave".utf8).write(to: macOS.appendingPathComponent("darkbloom-enclave")) + try Data("\(version)-metallib".utf8).write(to: macOS.appendingPathComponent("mlx.metallib")) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift new file mode 100644 index 0000000000..1738f01888 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift @@ -0,0 +1,382 @@ +/// The coordinated update of a `darkbloom cluster` pair (`ClusterPairUpdateCycle`), with real components: each Mac's +/// cycle runs the real updater against its own temporary install root (`UpdateRecoveryFixture`) and a loopback +/// release server (`MockCoordinator`), and each Mac's part is a real member loop on that coordinator, whose pair slot +/// is served by a scripted owner and which answers the drain through its lifecycle mailbox. No binary is replaced +/// outside the temporary roots, no model or GPU runs, and nothing leaves loopback. + +import Foundation +import Testing +@testable import ProviderCore + +private let pairTiming: ClusterPairUpdateCycle.Timing = { + var timing = ClusterPairUpdateCycle.Timing() + timing.partnerStageWait = 30 + timing.drainTimeout = 15 + timing.partnerDrainWait = 30 + timing.poll = 0.05 + timing.partAnswer = 10 + return timing +}() + +private final class Lines: @unchecked Sendable { + private let lock = NSLock() + private var values: [String] = [] + func append(_ line: String) { lock.withLock { values.append(line) } } + var all: [String] { lock.withLock { values } } +} + +private func poll(seconds: Double, _ condition: () async -> Bool) async -> Bool { + let deadline = Date().addingTimeInterval(seconds) + while Date() < deadline { + if await condition() { return true } + try? await Task.sleep(nanoseconds: 50_000_000) + } + return await condition() +} + +private func stagingDirectories(_ fixture: UpdateRecoveryFixture) -> [String] { + ((try? FileManager.default.contentsOfDirectory(atPath: fixture.installRoot.path)) ?? []).filter { $0.hasPrefix(".update-staging-") } +} + +/// One Mac of the pair: its install, its loopback coordinator (which also serves the release) and its part. +private struct PairMac { + let fixture: UpdateRecoveryFixture + let mock: MockCoordinator + let baseURL: URL + let directory: URL + let loop: ProviderLoop? + let task: Task? + let publicKey: String? + + var progressPath: URL { directory.appendingPathComponent("service-update.json") } + var mailboxDirectory: URL { directory.appendingPathComponent("lifecycle") } + var mailbox: LifecycleMailbox { LifecycleMailbox(identity: ProcessIdentity.current()!, directory: mailboxDirectory) } + + /// `part`: run a member loop as this Mac's part (registered with its coordinator, no pair slot yet). + static func make(release: MockReleaseFixture? = nil, part: Bool = true) async throws -> PairMac { + let fixture = try UpdateRecoveryFixture() + let mock = MockCoordinator(release: release ?? fixture.mockReleaseFixture(), releaseArtifact: fixture.artifact) + let baseURL = try await mock.start() + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("pair-update-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + guard part else { + return PairMac(fixture: fixture, mock: mock, baseURL: baseURL, directory: directory, loop: nil, task: nil, publicKey: nil) + } + let url = baseURL.mockProviderWebSocketURL() + let hardware = HardwareInfo(machineModel: "Mac16,5", chipName: "Apple M4 Max", chipFamily: .m4, chipTier: .max, + memoryGb: 64, memoryAvailableGb: 64, cpuCores: .init(total: 16, performance: 12, efficiency: 4), + gpuCores: 40, memoryBandwidthGbs: 546) + let loop = try ProviderLoop( + config: .init(coordinatorURL: url, hardware: hardware, + models: [.init(id: clusterPairFixtureModel, modelType: "qwen3_5", sizeBytes: 1, estimatedMemoryGb: 1)], + config: .init(provider: .init(name: "cluster-pair-update", autoUpdate: false), backend: .init(), + coordinator: .init(url: url, heartbeatIntervalSecs: 1)), + executionRole: .clusterMember, clusterMemberStopsOnDisconnect: false, clusterMemberAnswersUpdateDrain: true), + attestationSigner: ServeLoopTestSigner()) + await loop.setEngineV2RuntimeForTesting(EngineV2Runtime()) + await loop.setServeUsesHostServicesForTesting(false) + await loop.setDaemonStateFileForTesting(directory.appendingPathComponent("state.json")) + await loop.setClusterPairWarmupForTesting(timeoutSeconds: nil) + let task = Task { try await loop.run() } + let registration = try #require(try await mock.awaitFirstRegister(timeout: .seconds(15))) + try await mock.pushClusterMemberAcceptance(nonce: try #require(registration.memberRegistrationNonce)) + try await loop.waitForClusterMemberRegistration(until: .now.advanced(by: .seconds(5))) + return PairMac(fixture: fixture, mock: mock, baseURL: baseURL, directory: directory, loop: loop, task: task, + publicKey: registration.publicKey) + } + + /// Makes this Mac rank 0: its part serves the pair slot; every request waits for `owner.hold` before its first token. + func servePair() async throws -> ScriptedPairOwner { + let owner = ScriptedPairOwner() + owner.hold = DispatchSemaphore(value: 0) + let loop = try #require(self.loop) + try await loop.publishClusterPairSlot(clusterPairSpecification(owner), owner: owner) + #expect(try await mock.waitForSnapshot(timeout: .seconds(10)) { $0.heartbeats.last?.status == .idle } != nil) + return owner + } + + func push(_ id: String) async throws { + let body = try JSONSerialization.data(withJSONObject: [ + "model": clusterPairFixtureModel, "messages": [["role": "user", "content": "pair"]], + "max_tokens": 3, "stream": true, "temperature": 0, "reasoning_parser": "none"]) + try await mock.pushInferenceRequest(requestId: id, providerPublicKeyBase64: try #require(publicKey), + chatRequestJSON: body, consumerKeyPair: .generate()) + } + + func cycle(partner: PairMac, updater: SelfUpdater? = nil, log: Lines, timing: ClusterPairUpdateCycle.Timing = pairTiming, + part published: ClusterPairUpdateCycle.Part? = nil) -> ClusterPairUpdateCycle { + let partnerPath = partner.progressPath + let part = published ?? (loop == nil ? .notRunning : .running(ProcessIdentity.current()!)) + var environment = ClusterPairUpdateCycle.Environment( + updater: updater ?? fixture.updater(baseURL: baseURL), progressPath: progressPath, + partner: { ClusterPairUpdate.readProgress(from: partnerPath).map { .reported($0) } ?? .unreachable }, + part: { part }, partStarting: { _ in false }, mailboxDirectory: mailboxDirectory, + // A pair is loaded on both Macs: neither may go on alone. + pairRunsHere: { true }, log: { log.append($0) }) + environment.timing = timing + return ClusterPairUpdateCycle(environment: environment) + } + + func cleanUp() async { + if let task { + task.cancel() + _ = await ServeLoopFixture.finishes(task, within: .seconds(30)) + } + await mock.shutdown() + fixture.cleanup() + try? FileManager.default.removeItem(at: directory) + } +} + +private final class Restarts: @unchecked Sendable { + private let lock = NSLock() + private var values: [String] = [] + func record(_ mac: String, _ version: String) { lock.withLock { values.append("\(mac):\(version)") } } + var all: [String] { lock.withLock { values.sorted() } } +} + +@Suite("Cluster pair coordinated update", .serialized, .timeLimit(.minutes(3))) +struct ClusterPairUpdateTests { + /// Rank 0 serves a request that outlives the stage: the pair stages while it serves, stops taking requests only + /// then, lets the request finish (never cancelled), and only then both Macs install and restart. + @Test func busyPairStagesThenDrainsWithoutCuttingThenUpdates() async throws { + let rank0 = try await PairMac.make(), rank1 = try await PairMac.make() + defer { Task { await rank0.cleanUp(); await rank1.cleanUp() } } + let owner = try await rank0.servePair() + try await rank0.push("in-flight") + #expect(try await rank0.mock.waitForSnapshot(timeout: .seconds(10)) { $0.inferenceAccepted.contains { $0.requestId == "in-flight" } } != nil) + + let log0 = Lines(), log1 = Lines(), restarts = Restarts() + let cycle0 = rank0.cycle(partner: rank1, log: log0), cycle1 = rank1.cycle(partner: rank0, log: log1) + async let outcome0 = cycle0.run { restarts.record("rank0", $0) } + async let outcome1 = cycle1.run { restarts.record("rank1", $0) } + + // Both Macs staged while the pair served; rank 0's part closed admission only after that. + #expect(await poll(seconds: 30) { rank0.mailbox.readClusterUpdateDrainStatus()?.outcome == .draining }) + #expect(!stagingDirectories(rank0.fixture).isEmpty && !stagingDirectories(rank1.fixture).isEmpty) + #expect(try rank0.fixture.liveBinaryContents() == "1.0.0-darkbloom" && rank1.fixture.liveBinaryContents() == "1.0.0-darkbloom") + #expect(await poll(seconds: 10) { rank1.mailbox.readClusterUpdateDrainStatus()?.outcome == .notServing }, + "rank 1's part serves no request of its own") + // The coordinator is told (heartbeat `draining`) and a request routed anyway is refused, not accepted. + #expect(try await rank0.mock.waitForSnapshot(timeout: .seconds(10)) { $0.heartbeats.last?.status == .draining } != nil) + try await rank0.push("after-drain-began") + let refused = try await rank0.mock.waitForSnapshot(timeout: .seconds(10)) { $0.inferenceErrors.contains { $0.requestId == "after-drain-began" } } + #expect(refused?.inferenceErrors.first { $0.requestId == "after-drain-began" }?.statusCode == 503) + #expect(refused?.inferenceAccepted.contains { $0.requestId == "after-drain-began" } == false) + // Nothing is installed while the accepted request runs. + try await Task.sleep(nanoseconds: 500_000_000) + #expect(try rank0.fixture.liveBinaryContents() == "1.0.0-darkbloom" && restarts.all.isEmpty) + + owner.hold?.signal() + let finished = try await rank0.mock.waitForSnapshot(timeout: .seconds(10)) { $0.inferenceComplete.contains { $0.requestId == "in-flight" } } + #expect(finished?.inferenceErrors.contains { $0.requestId == "in-flight" } == false) + #expect(owner.lastLease?.cancelCount == 0, "the accepted request was never cancelled") + + let (result0, result1) = await (outcome0, outcome1) + #expect(result0 == .restarted(from: "1.0.0", to: "2.0.0", drained: true), "\(log0.all)") + #expect(result1 == .restarted(from: "1.0.0", to: "2.0.0", drained: true), "\(log1.all)") + #expect(restarts.all == ["rank0:2.0.0", "rank1:2.0.0"]) + #expect(try rank0.fixture.liveBinaryContents() == "2.0.0-darkbloom" && rank1.fixture.liveBinaryContents() == "2.0.0-darkbloom") + for mac in [rank0, rank1] { + let state = try UpdateRecoveryStore(installRoot: mac.fixture.installRoot, verifyCodeSignatures: false).loadState() + #expect(state.candidate?.release.version == "2.0.0" && state.candidate?.launchIntent != nil, "the restart is a tracked candidate") + #expect(ClusterPairUpdate.readProgress(from: mac.progressPath)?.phase == .restarting) + } + #expect(log0.all.contains { $0.contains("staged") } && log0.all.contains { $0.contains("installed v2.0.0") }) + } + + /// A request that outlives the drain bound: rank 0 takes requests again (nothing cancelled), both Macs keep their + /// release, and the next slot updates the pair once the request is done. + @Test func pairBusyPastTheDrainBoundDefersThenUpdatesAtTheNextSlot() async throws { + let rank0 = try await PairMac.make(), rank1 = try await PairMac.make() + defer { Task { await rank0.cleanUp(); await rank1.cleanUp() } } + let owner = try await rank0.servePair() + try await rank0.push("long") + #expect(try await rank0.mock.waitForSnapshot(timeout: .seconds(10)) { $0.inferenceAccepted.contains { $0.requestId == "long" } } != nil) + + var short = pairTiming + short.drainTimeout = 1 + let log0 = Lines(), log1 = Lines(), restarts = Restarts() + async let first0 = rank0.cycle(partner: rank1, log: log0, timing: short).run { restarts.record("rank0", $0) } + async let first1 = rank1.cycle(partner: rank0, log: log1, timing: short).run { restarts.record("rank1", $0) } + let (deferred0, deferred1) = await (first0, first1) + #expect(deferred0 == .drainTimedOut && deferred1 == .drainTimedOut, "\(log0.all) \(log1.all)") + #expect(rank0.mailbox.readClusterUpdateDrainStatus()?.outcome == .timedOut) + #expect(restarts.all.isEmpty) + #expect(try rank0.fixture.liveBinaryContents() == "1.0.0-darkbloom" && rank1.fixture.liveBinaryContents() == "1.0.0-darkbloom") + #expect(stagingDirectories(rank0.fixture).isEmpty && stagingDirectories(rank1.fixture).isEmpty, "nothing staged is kept") + #expect(ClusterPairUpdate.readProgress(from: rank0.progressPath)?.phase == .deferred) + #expect(ClusterPairUpdate.readProgress(from: rank1.progressPath)?.phase == .deferred) + // Rank 0 takes requests again on the same connection; the long request was never cancelled. + #expect(try await rank0.mock.waitForSnapshot(timeout: .seconds(10)) { $0.heartbeats.last?.status != .draining } != nil) + #expect(owner.lastLease?.cancelCount == 0) + owner.hold?.signal() + #expect(try await rank0.mock.waitForSnapshot(timeout: .seconds(10)) { $0.inferenceComplete.contains { $0.requestId == "long" } } != nil) + + // The next slot: the same pair, idle now, updates. + async let next0 = rank0.cycle(partner: rank1, log: log0).run { restarts.record("rank0", $0) } + async let next1 = rank1.cycle(partner: rank0, log: log1).run { restarts.record("rank1", $0) } + let (updated0, updated1) = await (next0, next1) + #expect(updated0 == .restarted(from: "1.0.0", to: "2.0.0", drained: true), "\(log0.all)") + #expect(updated1 == .restarted(from: "1.0.0", to: "2.0.0", drained: true), "\(log1.all)") + #expect(try rank0.fixture.liveBinaryContents() == "2.0.0-darkbloom" && rank1.fixture.liveBinaryContents() == "2.0.0-darkbloom") + } + + /// One Mac cannot verify the release: neither Mac stops taking requests or installs, and both retry at the next slot. + @Test func oneMacFailingKeepsBothOnTheirReleaseAndTheNextSlotRetries() async throws { + let healthy = try await PairMac.make(part: false) + var broken = MockReleaseFixture() + let failing = try await PairMac.make(part: false) + broken = failing.fixture.mockReleaseFixture() + broken.bundleHash = String(repeating: "0", count: 64) + let badMock = MockCoordinator(release: broken, releaseArtifact: failing.fixture.artifact) + let badURL = try await badMock.start() + defer { Task { await healthy.cleanUp(); await failing.cleanUp(); await badMock.shutdown() } } + + let logA = Lines(), logB = Lines(), restarts = Restarts() + async let a = healthy.cycle(partner: failing, log: logA).run { restarts.record("healthy", $0) } + async let b = failing.cycle(partner: healthy, updater: failing.fixture.updater(baseURL: badURL), log: logB) + .run { restarts.record("failing", $0) } + let (outcomeA, outcomeB) = await (a, b) + guard case .stageFailed(let reason) = outcomeB else { Issue.record("expected stageFailed, got \(outcomeB)"); return } + #expect(reason.contains("hashMismatch")) + #expect(outcomeA == .drainTimedOut, "the healthy Mac gives the release up too: \(logA.all)") + #expect(logA.all.contains { $0.contains("the other Mac:") && $0.contains("failed") }, "\(logA.all)") + #expect(restarts.all.isEmpty) + #expect(try healthy.fixture.liveBinaryContents() == "1.0.0-darkbloom" && failing.fixture.liveBinaryContents() == "1.0.0-darkbloom") + #expect(stagingDirectories(healthy.fixture).isEmpty && stagingDirectories(failing.fixture).isEmpty) + #expect(ClusterPairUpdate.readProgress(from: failing.progressPath)?.phase == .failed) + + // The next slot, with the release verifiable again on both Macs. + async let retryA = healthy.cycle(partner: failing, log: logA).run { restarts.record("healthy", $0) } + async let retryB = failing.cycle(partner: healthy, log: logB).run { restarts.record("failing", $0) } + let (doneA, doneB) = await (retryA, retryB) + #expect(doneA == .restarted(from: "1.0.0", to: "2.0.0", drained: true), "\(logA.all)") + #expect(doneB == .restarted(from: "1.0.0", to: "2.0.0", drained: true), "\(logB.all)") + #expect(restarts.all == ["failing:2.0.0", "healthy:2.0.0"]) + #expect(try healthy.fixture.liveBinaryContents() == "2.0.0-darkbloom" && failing.fixture.liveBinaryContents() == "2.0.0-darkbloom") + } + + /// The other Mac has automatic updates off: the slot downloads nothing. `darkbloom update` run on both Macs updates + /// the pair: the Mac asked first waits, while serving, for the other Mac's. + @Test func partnerWithAutomaticUpdatesOffUpdatesWhenAskedOnBothMacs() async throws { + let first = try await PairMac.make(part: false), second = try await PairMac.make(part: false) + defer { Task { await first.cleanUp(); await second.cleanUp() } } + ClusterPairUpdate.writeProgress(.init(phase: .disabled, running: "1.0.0", writtenAt: Date().timeIntervalSince1970), + to: second.progressPath) + let log1 = Lines(), log2 = Lines(), restarts = Restarts() + let slot = await first.cycle(partner: second, log: log1).run { restarts.record("first", $0) } + #expect(slot == .stageFailed("automatic updates are off on the other Mac"), "given up before the download: \(log1.all)") + #expect(stagingDirectories(first.fixture).isEmpty && restarts.all.isEmpty) + + async let asked1 = first.cycle(partner: second, log: log1).run(request: "update-1") { restarts.record("first", $0) } + #expect(await poll(seconds: 10) { ClusterPairUpdate.readProgress(from: first.progressPath)?.phase == .staged }) + try await Task.sleep(nanoseconds: 500_000_000) + #expect(ClusterPairUpdate.readProgress(from: first.progressPath)?.phase == .staged, "still waiting for the other Mac") + async let asked2 = second.cycle(partner: first, log: log2).run(request: "update-2") { restarts.record("second", $0) } + let (done1, done2) = await (asked1, asked2) + #expect(done1 == .restarted(from: "1.0.0", to: "2.0.0", drained: true), "\(log1.all)") + #expect(done2 == .restarted(from: "1.0.0", to: "2.0.0", drained: true), "\(log2.all)") + #expect(restarts.all == ["first:2.0.0", "second:2.0.0"]) + #expect(try first.fixture.liveBinaryContents() == "2.0.0-darkbloom" && second.fixture.liveBinaryContents() == "2.0.0-darkbloom") + } + + /// A part that serves without answering the drain (the leader's local API, a solo server): the slot downloads + /// nothing and the part keeps serving; the next slot tries again. + @Test func partThatCannotDrainDownloadsNothing() async throws { + let mac = try await PairMac.make(part: false), other = try await PairMac.make(part: false) + defer { Task { await mac.cleanUp(); await other.cleanUp() } } + let log = Lines(), restarts = Restarts() + let outcome = await mac.cycle(partner: other, log: log, part: .undrainable).run { restarts.record("mac", $0) } + #expect(outcome == .stageFailed(ClusterPairUpdateCycle.undrainable), "given up before the download: \(log.all)") + #expect(stagingDirectories(mac.fixture).isEmpty && restarts.all.isEmpty) + #expect(try mac.fixture.liveBinaryContents() == "1.0.0-darkbloom") + #expect(ClusterPairUpdate.readProgress(from: mac.progressPath)?.phase == .failed, "the other Mac gives the release up too") + } + + /// The other Mac cannot be asked: this Mac goes on alone only while no pair runs on it, and it asks again before it + /// installs, so a pair that formed on it meanwhile keeps it waiting and the cycle defers. + @Test func macWhosePartnerCannotBeAskedGoesOnAloneOnlyWithoutAPair() async throws { + let mac = try await PairMac.make(part: false) + defer { Task { await mac.cleanUp() } } + var timing = pairTiming + timing.partnerDrainWait = 2 + func cycle(pairRunsHere: @escaping @Sendable () -> Bool, log: Lines) -> ClusterPairUpdateCycle { + var environment = ClusterPairUpdateCycle.Environment(updater: mac.fixture.updater(baseURL: mac.baseURL), + progressPath: mac.progressPath, partner: { .unreachable }, part: { .notRunning }, partStarting: { _ in false }, + mailboxDirectory: mac.mailboxDirectory, pairRunsHere: pairRunsHere, log: { log.append($0) }) + environment.timing = timing + return ClusterPairUpdateCycle(environment: environment) + } + let asked = Lines(), log = Lines(), restarts = Restarts() + let formed = await cycle(pairRunsHere: { asked.append("asked"); return asked.all.count > 1 }, log: log) + .run { restarts.record("mac", $0) } + #expect(formed == .drainTimedOut, "a pair formed after the stage wait: \(log.all)") + #expect(restarts.all.isEmpty) + #expect(try mac.fixture.liveBinaryContents() == "1.0.0-darkbloom") + + let alone = await cycle(pairRunsHere: { false }, log: log).run { restarts.record("mac", $0) } + #expect(alone == .restarted(from: "1.0.0", to: "2.0.0", drained: true), "no pair here: \(log.all)") + #expect(restarts.all == ["mac:2.0.0"]) + } + + /// The part's side of the drain: release after a drain reopens admission on the same connection, and only the + /// coordinator-paired part answers at all. + @Test func drainedPartTakesRequestsAgainWhenReleased() async throws { + let rank0 = try await PairMac.make() + defer { Task { await rank0.cleanUp() } } + _ = try await rank0.servePair() + let identity = try #require(ProcessIdentity.current()) + let drain = ClusterUpdateDrainRequest(action: .drain, target: identity, timeoutSeconds: 10) + try rank0.mailbox.writeClusterUpdateDrainRequest(drain) + #expect(await poll(seconds: 10) { rank0.mailbox.readClusterUpdateDrainStatus() == .init(requestID: drain.id, outcome: .drained, remaining: 0) }) + #expect(try await rank0.mock.waitForSnapshot(timeout: .seconds(10)) { $0.heartbeats.last?.status == .draining } != nil) + #expect(await rank0.loop?.state.refusingNewWork == true) + let release = ClusterUpdateDrainRequest(action: .release, target: identity, timeoutSeconds: 0) + try rank0.mailbox.writeClusterUpdateDrainRequest(release) + #expect(await poll(seconds: 10) { rank0.mailbox.readClusterUpdateDrainStatus()?.outcome == .released }) + #expect(try await rank0.mock.waitForSnapshot(timeout: .seconds(10)) { $0.heartbeats.last?.status == .idle } != nil) + #expect(await rank0.loop?.state.refusingNewWork == false) + #expect(await rank0.loop?.updatePhase == .idle) + #expect(rank0.mock.snapshot().drainBarriers.isEmpty, "an undone drain never fences the connection") + } + + /// A release the pair installed is a candidate: promoted once its service stays healthy, rolled back to the + /// verified predecessor (and quarantined) after three failed starts, as the watchdog does for a single Mac. + @Test func candidateIsPromotedOrRolledBackLikeTheWatchdogs() async throws { + let mac = try await PairMac.make(part: false) + defer { Task { await mac.cleanUp() } } + let updater = mac.fixture.updater(baseURL: mac.baseURL) + guard case .updated(_, let installed) = await updater.update() else { Issue.record("install failed"); return } + #expect(installed == "2.0.0") + let recovery = ClusterCandidateRecovery(updater: updater, stabilizationSeconds: 10) + #expect(recovery.noteLaunch(now: 1_000) == .candidate(version: "2.0.0", failedStarts: 0)) + #expect(recovery.observe(healthy: true, processStartedAt: 999, now: 1_001) == .stabilizing) + let held = try updater.beginUpdateSession(operation: "pair-cycle") + #expect(recovery.observe(healthy: true, processStartedAt: 999, now: 1_002) == .stabilizing, "another update's lease keeps the candidate") + held.release() + #expect(recovery.observe(healthy: false, processStartedAt: 999, now: 1_005) == .stabilizing, "a missed heartbeat restarts the window") + #expect(recovery.observe(healthy: true, processStartedAt: 999, now: 1_006) == .stabilizing) + #expect(recovery.observe(healthy: true, processStartedAt: 999, now: 1_016) == .promoted(version: "2.0.0")) + #expect(recovery.noteLaunch(now: 1_020) == .notCandidate, "a promoted release is no candidate") + #expect(try UpdateRecoveryStore(installRoot: mac.fixture.installRoot, verifyCodeSignatures: false).loadState().current?.version == "2.0.0") + + let other = try await PairMac.make(part: false) + defer { Task { await other.cleanUp() } } + let otherUpdater = other.fixture.updater(baseURL: other.baseURL) + guard case .updated = await otherUpdater.update() else { Issue.record("install failed"); return } + let failing = ClusterCandidateRecovery(updater: otherUpdater) + for start in 1...2 { + #expect(failing.noteLaunch(now: Double(start * 100)) == .candidate(version: "2.0.0", failedStarts: start - 1)) + #expect(failing.recordFailedStart(now: Double(start * 100 + 5)) == .counted(version: "2.0.0", failures: start)) + } + #expect(failing.noteLaunch(now: 300) == .candidate(version: "2.0.0", failedStarts: 2)) + #expect(failing.recordFailedStart(now: 305) == .rolledBack(from: "2.0.0", to: "1.0.0")) + #expect(try other.fixture.liveBinaryContents() == "1.0.0-darkbloom") + let state = try UpdateRecoveryStore(installRoot: other.fixture.installRoot, verifyCodeSignatures: false).loadState() + #expect(state.quarantine?.version == "2.0.0" && state.candidate == nil) + guard case .quarantined(let version, _) = await otherUpdater.checkForUpdate() else { Issue.record("not quarantined"); return } + #expect(version == "2.0.0", "the next slot does not install the failed release again") + #expect(failing.recordFailedStart(now: 400) == .notCandidate, "an ordinary end after the rollback counts nothing") + } +} From 16d59d9ce686d918d4feec704090c28fd57788f2 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:46:33 -0700 Subject: [PATCH 0021/1441] Gemma 4 replies keep characters written as byte tokens swift-transformers' ByteFallbackDecoder releases <0xHH> tokens only when a later token arrives, so a decode ending in them drops them and shows nothing pending. Gemma 4 writes characters outside its vocabulary that way: a reply ending in one lost it, and DetokenizerV2 could restart its segment inside a run and corrupt the character. LocalTokenizerBridge.decode now releases a trailing run itself. Token IDs, sampling, model state and cache keys do not change; only the text decoded from the same tokens does. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-byte-fallback-flush.md | 5 + docs/architecture/inference.md | 9 ++ docs/developer/test.md | 11 ++ .../Prompting/LocalTokenizerLoader.swift | 38 ++++- .../LocalTokenizerByteFallbackTests.swift | 151 ++++++++++++++++++ 5 files changed, 213 insertions(+), 1 deletion(-) create mode 100644 changelog.d/gemma-byte-fallback-flush.md create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift diff --git a/changelog.d/gemma-byte-fallback-flush.md b/changelog.d/gemma-byte-fallback-flush.md new file mode 100644 index 0000000000..d0e5cc655e --- /dev/null +++ b/changelog.d/gemma-byte-fallback-flush.md @@ -0,0 +1,5 @@ +### Gemma 4 replies keep characters outside its vocabulary + +- A Gemma 4 reply that ended in a character its vocabulary writes as byte tokens, such as many newer emoji, rare CJK and most Hangul syllables, lost that character: `all zipped up 🗜` came back as `all zipped up `. A long reply could also corrupt such a character when streaming restarted its decode inside its bytes. +- The Swift tokenizer library releases byte tokens only when a later token arrives. The provider's tokenizer bridge now releases a trailing run itself. +- Token IDs, sampling, model state and cache keys do not change. Only the text decoded from the same tokens does. A reply cut inside a character by `max_tokens` now ends in U+FFFD instead of dropping it, and a byte token's `logprobs` text is U+FFFD or its ASCII character instead of empty. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..00fa10685d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1558,6 +1558,15 @@ submits the frame. `SendHandle` and `ChunkSender` persist across reconnects, so an old request's frame processed after a replacement sink binds still passes this check; it does not enforce request-to-session identity. +Decoded text keeps a character the tokenizer writes as `<0xHH>` tokens wherever it +falls. swift-transformers' `ByteFallbackDecoder` releases those tokens only when a +later token arrives, so a decode ending in them drops them and shows nothing pending. +Gemma 4 writes characters outside its vocabulary this way, so `LocalTokenizerBridge.decode` +(`provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift`) +releases a trailing run itself. A partial run reads as U+FFFD, which `DetokenizerV2` +holds back, so its segment restart cannot land inside a character. A decoder that +spells or releases these tokens turns this off. + The chat template is rendered on every request. When caching is enabled for the request, `LocalTokenizerBridge` encodes the rendered prompt through `PromptTokenCache` (`provider-swift/Sources/ProviderCore/Inference/Prompting/PromptTokenCache.swift`): diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..ef91bc75fe 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -549,6 +549,17 @@ first, and a request for the loading model when a second copy would not fit. and the body decode on the CPU with only the tokenizer loaded and the background comparisons off; it exits 2 if any token ID or decoded field differs. +```bash +swift test --skip-build --filter 'LocalTokenizerByteFallbackTests' +``` + +`LocalTokenizerByteFallbackTests` loads a synthetic tokenizer with Gemma 4's decoder +sequence through the production `LocalTokenizerLoader` and requires characters +written as `<0xHH>` tokens to survive a whole decode, a stream, a segment restart +inside the run and a trailing special token, a run cut inside a character to end in +one U+FFFD, and the unknown token not to read as a byte. A literal `<0x41>` token on +another decoder keeps its spelling. + ## Desktop Control And Frontend `make desktop-test` exercises the frontend journeys and bridge validation. diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift index 43d41bb0f4..234b3ee2c1 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift @@ -70,12 +70,15 @@ private struct LocalTokenizerBridge: @unchecked Sendable, MLXLMCommon.Tokenizer, private let chatTemplate: String? private let modelType: String? let promptTokenCache: PromptTokenCache? + /// Byte values by token ID, when the decoder holds `<0xHH>` tokens back. + private let heldBackBytes: [Int: UInt8] init( _ upstream: any Tokenizers.Tokenizer, chatTemplate: String?, modelType: String?, promptCacheConfigurations: PromptTokenCache.Configurations?, environment: [String: String] ) { self.upstream = upstream + heldBackBytes = Self.byteTokens(heldBackBy: upstream) self.chatTemplate = chatTemplate.map { NemotronTemplateFilters.bindingFilters( in: normalizeSwiftJinjaTemplate($0), modelType: modelType) @@ -98,8 +101,41 @@ private struct LocalTokenizerBridge: @unchecked Sendable, MLXLMCommon.Tokenizer, upstream.encode(text: text, addSpecialTokens: addSpecialTokens) } + /// swift-transformers' `ByteFallbackDecoder` releases `<0xHH>` tokens only when a later + /// token arrives, so a decode ending in them drops them and shows nothing pending: Gemma 4 + /// lost a reply's last character outside its vocabulary, and `DetokenizerV2` could restart + /// its segment inside one. A partial run reads as U+FFFD, which `DetokenizerV2` holds back. func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { - upstream.decode(tokens: tokenIds, skipSpecialTokens: skipSpecialTokens) + let text = upstream.decode(tokens: tokenIds, skipSpecialTokens: skipSpecialTokens) + guard !heldBackBytes.isEmpty else { return text } + var bytes: [UInt8] = [] + // With `skipSpecialTokens` upstream drops special tokens before its decoder runs, so one + // inside or after the run does not end it. + for id in tokenIds.reversed() { + if let byte = heldBackBytes[id] { + bytes.append(byte) + } else if !skipSpecialTokens || !upstream.decode(tokens: [id], skipSpecialTokens: true).isEmpty { + break + } + } + return bytes.isEmpty ? text : text + String(decoding: bytes.reversed(), as: UTF8.self) + } + + /// The `<0xHH>` tokens of a decoder that holds them back: a lone one decodes to nothing. + /// Empty for a decoder that spells or releases them, so a fixed upstream turns this off. + private static func byteTokens(heldBackBy upstream: any Tokenizers.Tokenizer) -> [Int: UInt8] { + var bytes: [Int: UInt8] = [:] + for value in UInt8.min...UInt8.max { + let token = String(format: "<0x%02X>", value) + // A token outside the vocabulary converts to the unknown ID. + if let id = upstream.convertTokenToId(token), upstream.convertIdToToken(id) == token { + bytes[id] = value + } + } + guard let probe = bytes.keys.first, + upstream.decode(tokens: [probe], skipSpecialTokens: false).isEmpty + else { return [:] } + return bytes } func convertTokenToId(_ token: String) -> Int? { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift new file mode 100644 index 0000000000..51104f39d3 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift @@ -0,0 +1,151 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon +import Testing + +@testable import ProviderCore + +/// A character outside the vocabulary is written as `<0xHH>` tokens. Client text must carry it +/// wherever it falls: swift-transformers' `ByteFallbackDecoder` drops a trailing run, so Gemma 4 +/// lost a reply's last emoji, and a restart inside a run corrupted a long reply. +@Suite("Local tokenizer byte fallback") +struct LocalTokenizerByteFallbackTests { + private static let texts = [ + "all zipped up 🗜", "🗜", "ends 갂", "a🗜b🗜", "🗜🗜", "mixed 丌 and ∛ then 🩵", "plain ascii", + ] + private static let promptCacheEnvironments: [[String: String]] = [[:], ["DARKBLOOM_TTFT_PROMPT_CACHE": "0"]] + + /// A character-level tokenizer with Gemma 4's decoder sequence: ASCII has its own tokens and + /// everything else is byte tokens. + private func tokenizerDirectory( + decoder: [String: Any]? = nil, byteTokens: ClosedRange? = 0...255, literal: [String] = [] + ) throws -> URL { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("byte-fallback-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + var vocabulary: [String: Int] = ["": 0, "": 1] + for value in 32...126 { vocabulary[String(UnicodeScalar(value)!)] = vocabulary.count } + if let byteTokens { + for value in byteTokens { vocabulary[String(format: "<0x%02X>", value)] = vocabulary.count } + } + for token in literal { vocabulary[token] = vocabulary.count } + let sequence: [String: Any] = [ + "type": "Sequence", + "decoders": [ + ["type": "Replace", "pattern": ["String": "▁"], "content": " "] as [String: Any], + ["type": "ByteFallback"], ["type": "Fuse"], + ], + ] + let config: [String: Any] = [ + "tokenizer_class": "GemmaTokenizer", "processor_class": "Gemma4Processor", "unk_token": "", + "clean_up_tokenization_spaces": false, + ] + let data: [String: Any] = [ + "model": ["type": "BPE", "vocab": vocabulary, "merges": [String](), "unk_token": ""], + "added_tokens": [["id": 1, "content": "", "special": true] as [String: Any]], + "decoder": decoder ?? sequence, + ] + try JSONSerialization.data(withJSONObject: config).write( + to: directory.appendingPathComponent("tokenizer_config.json")) + try JSONSerialization.data(withJSONObject: data).write(to: directory.appendingPathComponent("tokenizer.json")) + return directory + } + + /// The IDs the model generates for `text`, without going through the encoder. + private func ids(_ text: String, _ tokenizer: any MLXLMCommon.Tokenizer) throws -> [Int] { + var ids: [Int] = [] + for scalar in text.unicodeScalars { + if scalar.isASCII { + ids.append(try #require(tokenizer.convertTokenToId(String(scalar)))) + } else { + for byte in String(scalar).utf8 { + ids.append(try #require(tokenizer.convertTokenToId(String(format: "<0x%02X>", byte)))) + } + } + } + return ids + } + + private func streamed(_ ids: [Int], _ tokenizer: any MLXLMCommon.Tokenizer) -> String { + let detokenizer = DetokenizerV2(tokenizer: tokenizer) + var text = "" + for id in ids { text += detokenizer.append(id) } + return text + detokenizer.flush() + } + + @Test("a decode keeps a trailing run", arguments: promptCacheEnvironments) + func decodeKeepsTrailingRun(environment: [String: String]) async throws { + let directory = try tokenizerDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let tokenizer = try await LocalTokenizerLoader(environment: environment).load(from: directory) + for text in Self.texts { + let tokens = try ids(text, tokenizer) + #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) == text) + #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: true) == text) + } + } + + @Test("a stream carries every character once", arguments: promptCacheEnvironments) + func streamCarriesEveryCharacter(environment: [String: String]) async throws { + let directory = try tokenizerDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let tokenizer = try await LocalTokenizerLoader(environment: environment).load(from: directory) + for text in Self.texts { + #expect(streamed(try ids(text, tokenizer), tokenizer) == text) + } + } + + @Test("a segment restart does not land inside a run") + func restartInsideARun() async throws { + let directory = try tokenizerDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let tokenizer = try await LocalTokenizerLoader().load(from: directory) + // The segment's soft cap is 256 tokens: put the four bytes on every side of it, twice. + for padding in 248...258 { + let text = String(repeating: "a", count: padding) + "🗜" + String(repeating: "b", count: padding) + "🗜 end" + #expect(streamed(try ids(text, tokenizer), tokenizer) == text) + } + } + + @Test("a trailing special token does not hide a run") + func trailingSpecialToken() async throws { + let directory = try tokenizerDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let tokenizer = try await LocalTokenizerLoader().load(from: directory) + let eos = try #require(tokenizer.convertTokenToId("")) + let tokens = try ids("zipped 🗜", tokenizer) + [eos] + #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: true) == "zipped 🗜") + #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) == "zipped 🗜") + } + + @Test("a run cut mid-character ends in one replacement character") + func cutMidCharacter() async throws { + let directory = try tokenizerDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let tokenizer = try await LocalTokenizerLoader().load(from: directory) + let tokens = Array(try ids("ab🗜", tokenizer).dropLast(2)) + #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) == "ab\u{FFFD}") + #expect(streamed(tokens, tokenizer) == "ab\u{FFFD}") + } + + @Test("another decoder keeps its spelling of a literal byte token") + func otherDecoderKeepsSpelling() async throws { + let directory = try tokenizerDirectory(decoder: ["type": "Fuse"], byteTokens: nil, literal: ["<0x41>"]) + defer { try? FileManager.default.removeItem(at: directory) } + let tokenizer = try await LocalTokenizerLoader().load(from: directory) + let literal = try #require(tokenizer.convertTokenToId("<0x41>")) + #expect(tokenizer.decode(tokenIds: [literal], skipSpecialTokens: false) == "<0x41>") + #expect(tokenizer.decode(tokenIds: try ids("a", tokenizer) + [literal], skipSpecialTokens: false) == "a<0x41>") + } + + @Test("the unknown token is not read as a byte") + func unknownTokenIsNotAByte() async throws { + // Only some byte tokens exist, so the others convert to the unknown ID. + let directory = try tokenizerDirectory(byteTokens: 0xF0...0xFF) + defer { try? FileManager.default.removeItem(at: directory) } + let tokenizer = try await LocalTokenizerLoader().load(from: directory) + let unknown = try #require(tokenizer.convertTokenToId("")) + #expect(tokenizer.decode(tokenIds: try ids("a", tokenizer) + [unknown], skipSpecialTokens: false) == "a") + } +} From c24c287a18b544a20e7ae3156e98eb23648962f3 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:08:45 -0700 Subject: [PATCH 0022/1441] cluster: check a release starts before the supervisor restarts into it The cluster service's supervisor restarts into an installed release by replacing itself (execv). A release whose binary could not start at all left no supervisor to count its failed starts, so nothing rolled it back, unlike a single Mac, whose watchdog survives the update. Before that restart, the supervisor now runs the binary once with --version (30 s bound) and requires the release's exact version. A failure rolls the release back and quarantines it at once through ClusterCandidateRecovery; the supervisor never restarts into it and starts the cluster service again itself. The rollback's own restart into the restored predecessor gets the same check. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-auto-update.md | 1 + docs/developer/test.md | 11 +- docs/provider/cluster-always-on.md | 27 ++- docs/provider/two-mac-cluster.md | 7 +- .../Update/ClusterCandidateRecovery.swift | 89 ++++++-- .../darkbloom/ClusterMemberSupervisor.swift | 72 +++++-- provider-swift/Sources/darkbloom/main.swift | 4 +- .../ClusterServiceUpdateTests.swift | 198 ++++++++++++++++-- .../Update/ClusterPairUpdateTests.swift | 51 +++++ 9 files changed, 402 insertions(+), 58 deletions(-) diff --git a/changelog.d/cluster-auto-update.md b/changelog.d/cluster-auto-update.md index 05d9c3a5d0..96cfbf1c21 100644 --- a/changelog.d/cluster-auto-update.md +++ b/changelog.d/cluster-auto-update.md @@ -4,6 +4,7 @@ - Each Mac downloads, verifies and stages the release while the pair serves. Only once both Macs have it does the pair stop taking new requests; the Mac that serves the pair finishes its accepted requests (at most 120 seconds, never cancelling one), then both Macs install the release and restart their cluster services, and the cluster sets itself up again for the new release with no command run. - A pair under constant traffic updates too: once it takes no new requests, the accepted ones finish. A pair still running a request at the bound takes requests again and tries at the next slot. A release one Mac cannot download or verify is installed on neither Mac; both try again at the next slot. - An installed release is promoted once its cluster service has stayed healthy for 10 minutes; three starts of its service that end on their own restore the previous release and quarantine the new one, as the watchdog does for a single Mac. +- Before a Mac restarts into an installed release, its cluster service runs the new `darkbloom --version` once (at most 30 seconds). A release that does not answer with its version is never restarted into: the Mac restores the previous release at once, quarantines the new one and starts its cluster service again, so a release that cannot start no longer leaves the Mac with nothing to roll it back. - `darkbloom update` on a cluster Mac installs the release and then restarts the cluster service into it together with the other Mac, after the pair drained; logging out and back in is no longer needed. Run it on both Macs (or let the other Mac update at the next slot); the first Mac waits up to 15 minutes for the second, also when automatic updates are off. A Mac whose partner has automatic updates off downloads nothing at the slot. - A pair that serves on the leader's local API, or a Mac that serves alone, is not drained for an update yet: it does not update while it serves, and a cluster set to serve locally (`darkbloom cluster local`) or a Mac serving alone downloads nothing at the slot. - A cluster service started by an earlier release does none of this: to reach this release, run `darkbloom update` on both Macs, then log out and back in on both (or restart them) once. diff --git a/docs/developer/test.md b/docs/developer/test.md index 37671c0c49..59a7815c07 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1056,14 +1056,21 @@ stops both and the next cycle updates both; that a Mac whose partner has automatic updates off downloads nothing at the slot, while `darkbloom update` on both Macs updates them; that a part that cannot drain downloads nothing; that a Mac whose partner cannot be asked goes on alone only while no pair runs on it; -and the candidate's promotion (kept under another update's lease) and rollback. +the candidate's promotion (kept under another update's lease) and rollback; +the start check's verdicts on script binaries; and the rollback at once of a +candidate that failed its start check. `ClusterServiceUpdateTests` (`provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift`) drives the real supervisor with a shell standing in for the cluster service: the single-Mac gate, a slot fired from a cluster ID whose slot is seconds away, no slot cycle with automatic updates off (and `disabled` reported again once a cycle's end is a minute old), `darkbloom update`'s request and the candidate's -rollback and promotion; the re-exec is observed, never performed. +rollback and promotion. The start check runs the temporary install's +`darkbloom`, a script: a release whose `--version` exits non-zero, outlasts a +1 s bound or reports another version is rolled back and quarantined without the +re-exec, and the supervisor serves again from the restored binary; a release +that answers is re-executed into as before; a restored predecessor that cannot +start is not re-executed into. The re-exec is observed, never performed. `Tests/ClusterSupervisionChecks/run.sh` checks the progress rules (`ClusterPairUpdate.partnerState`) with plain `swiftc`. diff --git a/docs/provider/cluster-always-on.md b/docs/provider/cluster-always-on.md index fc7105989a..8feb15d2fb 100644 --- a/docs/provider/cluster-always-on.md +++ b/docs/provider/cluster-always-on.md @@ -130,8 +130,8 @@ supervisor starts (`Watchdog.settings`, | Stop taking requests | Once staged | Once staged on both Macs (each reads the other's progress, `ClusterPairUpdateProgress`, from the other cluster service's status over the link) | | Drain | Accepted requests finish, at most 120 s; never cancelled | The part that serves the pair (rank 0) finishes its accepted requests, at most 120 s (`ClusterUpdateDrainRequest`, through its lifecycle mailbox); the other part serves none. A request still running reopens the pair on both Macs and defers to the next slot | | Install | Commit the staged bundle | Each Mac commits once both drained | -| Restart | launchd restarts the provider | The supervisor stops its cluster service (the drained part stops with it) and starts again from the installed binary | -| Recovery | The watchdog promotes the candidate after 600 s of fresh heartbeats, rolls back after 3 failed starts | The restarted supervisor does the same with its cluster service's heartbeat (`ClusterCandidateRecovery`). It runs the new binary, so a release whose supervisor cannot start at all is not rolled back | +| Restart | launchd restarts the provider | The supervisor stops its cluster service (the drained part stops with it), checks that the installed binary starts, and starts again from it | +| Recovery | The watchdog promotes the candidate after 600 s of fresh heartbeats, rolls back after 3 failed starts | A binary that fails the start check is never restarted into: the supervisor restores the previous release and quarantines the new one at once, and starts its cluster service again. Otherwise the restarted supervisor does what the watchdog does, with its cluster service's heartbeat (`ClusterCandidateRecovery`) | The rules each Mac applies to the other's progress are in `provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift` @@ -161,6 +161,25 @@ The rules each Mac applies to the other's progress are in waits, while serving, for the other Mac's `darkbloom update`, at most `ClusterPairUpdate.partnerStageWaitSeconds` (900 s) from its start. +The supervisor restarts by replacing itself with the installed binary +(`execv`). Unlike a single Mac's watchdog, no other process outlives that +restart to roll a release back, so the supervisor first runs the binary once as +its child (the start check, `ClusterCandidateRecovery.startCheckFailure`): +`darkbloom --version` must exit 0 within +`ClusterCandidateRecovery.startCheckTimeoutSeconds` (30 s) and print the +release's version. This loads the binary as the restart would: the dynamic +loader and the frameworks it links, its code signature and the argument parser. +A binary that fails is not restarted into. The supervisor counts one failed +start, restores the verified predecessor and quarantines the release at once +(`ClusterCandidateRecovery.recordFailedStartCheck`), and starts the cluster +service again from the restored binary. The other Mac is not rolled back with +it: if the release started there, the two Macs run different releases, and the +pair serves again once a newer release updates both. A rollback after three +failed starts checks the restored predecessor the same way; if that check fails +too, the supervisor starts the cluster service itself instead of restarting +into it. A binary that passes the check but whose supervisor fails before it +starts the cluster service is still not rolled back. + After both Macs restarted, the leader's cluster service plans the same model again once both answer with the same worker build (`ClusterOnboardingUpdate.oneBuild`), and the pair registers again under the @@ -169,6 +188,8 @@ new release's cluster approval. Each step is one `cluster update:` line in for the other Mac to have v`, `cluster update: this Mac's part finished its accepted requests`, `cluster update: installed v`, `cluster update deferred: ; no request was cancelled; the next update slot tries again`, +`cluster update: v failed its start check (), so the supervisor +does not restart into it; restored v and quarantined v`, `cluster update: starting the cluster service on candidate v` and `cluster update: this Mac's part serves again on v`. @@ -242,7 +263,7 @@ system setting: | Follower never connects; log shows `Local network prohibited` | **Privacy & Security → Local Network** | Turn on Darkbloom; an ad-hoc build needs this per build | | A firewall alert after an update | `codesign -dv` on the listening binary | The binary is not Developer-ID signed; install the release build | | Install or provider log says `permissions: not asked once` | The listed reasons | Install the signed release (a locally built binary is ad-hoc signed and outside `Darkbloom.app`) | -| The pair does not update | `cluster update:` lines in `~/.darkbloom/cluster-setup/service.log` on both Macs | `automatic updates are off`: run `darkbloom update` on both Macs, or set `auto_update` on both (`darkbloom autoupdate enable`), which takes effect when the cluster service next starts (at login, or after its next update). `deferred`: a request ran past 120 s, or one Mac could not take the release; the next slot tries again. `does not drain for an update`: the pair serves on the local API or a Mac serves alone | +| The pair does not update | `cluster update:` lines in `~/.darkbloom/cluster-setup/service.log` on both Macs | `automatic updates are off`: run `darkbloom update` on both Macs, or set `auto_update` on both (`darkbloom autoupdate enable`), which takes effect when the cluster service next starts (at login, or after its next update). `deferred`: a request ran past 120 s, or one Mac could not take the release; the next slot tries again. `does not drain for an update`: the pair serves on the local API or a Mac serves alone. `failed its start check`: the release did not start on this Mac, which keeps its previous release and does not install that release again; a newer release updates it | ## Developer: a coordinator-paired member as a service diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 2729cecb4a..2567020000 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -554,8 +554,11 @@ at the next slot. A release that one Mac cannot download or verify is installed on neither Mac; both try again at the next slot. Until a new release's cluster service has stayed healthy for 10 minutes, three of its starts that end by themselves bring back the previous release and quarantine the new -one, as the watchdog does for a single Mac. How the cluster service does this is -in [the pair's coordinated update](cluster-always-on.md#the-pairs-coordinated-update). +one, as the watchdog does for a single Mac. A Mac never restarts into a new +release that does not start at all (it checks before the restart): it brings +back the previous release at once and quarantines the new one. How the cluster +service does this is in +[the pair's coordinated update](cluster-always-on.md#the-pairs-coordinated-update). To update at once, run on each Mac: diff --git a/provider-swift/Sources/ProviderCore/Update/ClusterCandidateRecovery.swift b/provider-swift/Sources/ProviderCore/Update/ClusterCandidateRecovery.swift index a1278ae9e7..8bd40e8279 100644 --- a/provider-swift/Sources/ProviderCore/Update/ClusterCandidateRecovery.swift +++ b/provider-swift/Sources/ProviderCore/Update/ClusterCandidateRecovery.swift @@ -6,6 +6,10 @@ import Foundation /// beaten with the new version, continuously, for the stabilization window; the third start that ends before that /// restores the verified predecessor and quarantines the release (`UpdateRecoveryState.rollbackThreshold`). /// Every transition holds the cross-process update lease, as the watchdog's do. +/// +/// The supervisor restarts into a release by replacing itself (`execv`), so a release whose binary cannot start +/// at all would leave no supervisor to count its failed starts. The start check (`startCheckFailure`) runs that +/// binary first; one that fails it is rolled back at once (`recordFailedStartCheck`) and never restarted into. public struct ClusterCandidateRecovery: Sendable { public enum Launch: Equatable, Sendable { case notCandidate @@ -40,11 +44,7 @@ public struct ClusterCandidateRecovery: Sendable { /// restart prepared, or a new one after a failed start), so an end before promotion is counted exactly once. public func noteLaunch(now: Double) -> Launch { transition(operation: "cluster-candidate-launch") { state in - guard let candidate = state.candidate else { return Launch.notCandidate } - if candidate.pendingAttemptID == nil { - if candidate.launchIntent == nil { _ = state.prepareLaunchIntent(now: now, baseline: nil) } - _ = state.markLaunchIssued(now: now) - } + Self.issueLaunch(&state, now: now) guard let current = state.candidate, current.pendingAttemptID != nil else { return Launch.notCandidate } return Launch.candidate(version: current.release.version, failedStarts: current.failureCount) } ?? .notCandidate @@ -72,19 +72,82 @@ public struct ClusterCandidateRecovery: Sendable { try session.writeState(state) let version = candidate.release.version guard failures >= UpdateRecoveryState.rollbackThreshold else { return .counted(version: version, failures: failures) } - do { - let restored = try session.rollback(now: now, reason: "automatic rollback after \(failures) failed starts of the cluster service") - return .rolledBack(from: version, to: restored) - } catch { - state.deferRetryAfterRollbackFailure(now: now, reason: "\(error)") - try? session.writeState(state) - return .rollbackRefused(version: version, reason: "\(error)") - } + return rollBack(session, state: state, version: version, + reason: "automatic rollback after \(failures) failed starts of the cluster service", now: now) } catch { return .notCandidate } } + /// How long the binary the supervisor restarts into may take to answer its start check. + public static let startCheckTimeoutSeconds: Double = 30 + + /// Before the supervisor replaces itself with the installed binary at `executable`, that binary runs once as the + /// supervisor's child with `--version`: it is loaded as the restart would load it (the dynamic loader and the + /// frameworks it links, its code signature, the argument parser) while the supervisor, which alone can still roll + /// the release back, keeps running. It passes when it exits 0 within `timeout` and prints exactly `version`. + /// Returns why it did not; nil when it passed. + public static func startCheckFailure(executable: String, version: String, + timeout: Double = startCheckTimeoutSeconds) -> String? { + let output: Data + do { + output = try BoundedProcess.runCapturingStandardOutput(URL(fileURLWithPath: executable), + arguments: ["--version"], timeout: timeout) + } catch BoundedProcess.Failure.exited(let status, _) { + return "`--version` exited \(status)" + } catch BoundedProcess.Failure.signalled(let signal) { + return "`--version` ended on signal \(signal)" + } catch BoundedProcess.Failure.timedOut, BoundedProcess.Failure.wouldNotTerminate { + return "`--version` did not finish within \(Int(timeout)) s" + } catch { + return "it could not be run: \(error.localizedDescription)" + } + let reported = String(decoding: output, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) + guard reported != version else { return nil } + // Only a version is repeated: whatever else a wrong binary prints stays out of the log. + return SemanticVersion(reported) == nil ? "it printed no version" : "it reports v\(reported)" + } + + /// Before the supervisor restarts into candidate `version`, its binary failed the start check (`reason`). After + /// that restart no supervisor would be left to count its failed starts, so this one is conclusive: it counts as a + /// failed start, and the verified predecessor is restored and the release quarantined at once. + public func recordFailedStartCheck(version: String, reason: String, now: Double) -> Failure { + guard let session = try? updater.beginUpdateSession(operation: "cluster-candidate-start-check", timeout: 1) else { return .notCandidate } + defer { session.release() } + do { + try session.recover(now: now) + var state = try session.readState() + guard state.candidate?.release.version == version else { return .notCandidate } + Self.issueLaunch(&state, now: now) + state.recordPendingAttemptFailure(now: now) + try session.writeState(state) + return rollBack(session, state: state, version: version, + reason: "automatic rollback: v\(version) failed its start check before the restart (\(reason))", now: now) + } catch { + return .notCandidate + } + } + + /// A pending candidate's launch attempt: the one the restart prepared, or a new one after a failed start. + private static func issueLaunch(_ state: inout UpdateRecoveryState, now: Double) { + guard let candidate = state.candidate, candidate.pendingAttemptID == nil else { return } + if candidate.launchIntent == nil { _ = state.prepareLaunchIntent(now: now, baseline: nil) } + _ = state.markLaunchIssued(now: now) + } + + /// Restores the verified predecessor of candidate `version`; a refused rollback keeps it and backs its retry off. + private func rollBack(_ session: SelfUpdater.UpdateSession, state: UpdateRecoveryState, version: String, + reason: String, now: Double) -> Failure { + do { + return .rolledBack(from: version, to: try session.rollback(now: now, reason: reason)) + } catch { + var state = state + state.deferRetryAfterRollbackFailure(now: now, reason: "\(error)") + try? session.writeState(state) + return .rollbackRefused(version: version, reason: "\(error)") + } + } + private func transition(operation: String, _ body: (inout UpdateRecoveryState) -> Value) -> Value? { guard let session = try? updater.beginUpdateSession(operation: operation, timeout: 1) else { return nil } defer { session.release() } diff --git a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift index 716cbd8f02..50bc99a18a 100644 --- a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift +++ b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift @@ -17,7 +17,8 @@ import ProviderCore /// starts again from the new binary (`ClusterMemberUpdateSlot`). Around the /// cluster service (`pairUpdate`), the pair's coordinated update runs while /// the service serves (`ClusterPairUpdateCycle`), and a release it installed -/// is promoted or rolled back by its service's health (`ClusterCandidateRecovery`). +/// is promoted or rolled back by its service's health (`ClusterCandidateRecovery`), +/// or rolled back at once when its binary fails the start check before the restart. /// /// It sends SIGKILL only as the guard's last resort for a member that /// ignored a SIGTERM for the whole grace; an operator stop always waits. @@ -64,6 +65,8 @@ final class ClusterMemberSupervisor: @unchecked Sendable { var pairUpdate: PairUpdate? = nil /// Replaces this process with the installed binary (`execv`); a test observes the call instead. var reexec: (@Sendable ([String]) -> Void)? = nil + /// How long that binary may take to pass its start check first (`ClusterCandidateRecovery.startCheckFailure`). + var startCheckTimeoutSeconds = ClusterCandidateRecovery.startCheckTimeoutSeconds /// The orphan sweep before every run signals this user's orphaned cluster processes; a test never does. var sweepsOrphans = true } @@ -149,7 +152,11 @@ final class ClusterMemberSupervisor: @unchecked Sendable { switch outcome { case .stopped: break - case .updateInstalled: + case .updateInstalled(let version): + if let version, let failure = await startCheckFailure(version) { + stayAfterFailedStartCheck(of: version, failure: failure) + continue + } reexecAfterUpdate() // execv returned: the new binary could not be started; keep the old one running. log("re-exec after the update failed; starting the member from this binary") @@ -157,7 +164,12 @@ final class ClusterMemberSupervisor: @unchecked Sendable { case .updateDrainedWithoutInstall: continue case .ended(let end, let runSeconds, let detail): - if recordCandidateEnd(detail: detail) { + if let restored = recordCandidateEnd(detail: detail) { + if let failure = await startCheckFailure(restored) { + log("cluster update: the restored v\(restored) failed its start check (\(failure)), so the supervisor " + + "does not restart into it; starting the cluster service again from this supervisor") + continue + } reexecAfterUpdate() log("re-exec after the rollback failed; starting the member from this binary") continue @@ -245,7 +257,9 @@ final class ClusterMemberSupervisor: @unchecked Sendable { private enum RunOutcome { case stopped case ended(ClusterMemberRunEnd, runSeconds: Double, detail: String) - case updateInstalled + /// A release is installed: the supervisor restarts into it. `version`: the release the pair's cycle installed, + /// which passes the start check first; nil on the member route, whose job the watchdog recovers. + case updateInstalled(version: String?) case updateDrainedWithoutInstall } @@ -349,13 +363,13 @@ final class ClusterMemberSupervisor: @unchecked Sendable { end: "stopped to restart into v\(version)") state.current = nil candidate = nil - return .updateInstalled + return .updateInstalled(version: version) } if let intent = drainedForUpdate, !isStopping { state.lastRun = .init(pid: pid, startedAt: started, endedAt: ended, exitCode: exitCode, signal: signal, end: "drained for update") state.current = nil - return await applyUpdate(intent) ? .updateInstalled : .updateDrainedWithoutInstall + return await applyUpdate(intent) ? .updateInstalled(version: nil) : .updateDrainedWithoutInstall } let end = ClusterMemberRunEnd.classify(stopRequested: isStopping, exitCode: exitCode, signal: signal) let detail: String @@ -549,26 +563,56 @@ final class ClusterMemberSupervisor: @unchecked Sendable { /// A service heartbeat (every 2 s) older than this does not count toward promotion. static let candidateHeartbeatSeconds: Double = 30 - /// A candidate's service that ended without being asked to is a failed start; returns whether the third restored - /// the verified predecessor, which the supervisor then starts again from. - private func recordCandidateEnd(detail: String) -> Bool { - guard candidate != nil, let recovery = configuration.pairUpdate?.recovery else { return false } + /// A candidate's service that ended without being asked to is a failed start; returns the verified predecessor the + /// third restored, which the supervisor then starts again from. + private func recordCandidateEnd(detail: String) -> String? { + guard candidate != nil, let recovery = configuration.pairUpdate?.recovery else { return nil } candidate = nil switch recovery.recordFailedStart(now: Date().timeIntervalSince1970) { case .counted(let version, let failures): log("cluster update: v\(version) failed start \(failures)/\(UpdateRecoveryState.rollbackThreshold) (\(detail))") - return false + return nil case .rolledBack(let from, let to): log("cluster update: v\(from) failed \(UpdateRecoveryState.rollbackThreshold) starts; restored v\(to) and quarantined v\(from)") - return true + return to case .rollbackRefused(let version, let reason): log("cluster update: rolling v\(version) back was refused (\(reason)); the installed release is kept and tried again later") - return false + return nil case .notCandidate: - return false + return nil } } + /// Before this process replaces itself (`execv`) with the installed `version`, on the route that rolls releases + /// back (`PairUpdate.recovery`), that binary runs once as its child (`ClusterCandidateRecovery.startCheckFailure`). + /// Nil when it passed, or when there is no check to run. + private func startCheckFailure(_ version: String) async -> String? { + guard configuration.pairUpdate?.recovery != nil, let program = configuration.reexecArguments.first else { return nil } + let timeout = configuration.startCheckTimeoutSeconds + return await Task.detached { + ClusterCandidateRecovery.startCheckFailure(executable: program, version: version, timeout: timeout) + }.value + } + + /// A release that failed its start check would fail every start, and after an `execv` no supervisor would be left + /// to count them: this supervisor stays, restores the verified predecessor and quarantines the release at once, + /// then starts the cluster service again from what is installed. The cycle that asked for the restart is over. + private func stayAfterFailedStartCheck(of version: String, failure: String) { + guard let pair = configuration.pairUpdate, let recovery = pair.recovery else { return } + let now = Date().timeIntervalSince1970 + let outcome: String + switch recovery.recordFailedStartCheck(version: version, reason: failure, now: now) { + case .rolledBack(_, let restored): + outcome = "restored v\(restored) and quarantined v\(version)" + case .rollbackRefused(_, let reason): + outcome = "rolling it back was refused (\(reason)); the installed release is kept" + case .counted, .notCandidate: + outcome = "it was not rolled back (another update holds the lease, or it is no longer the pending release)" + } + log("cluster update: v\(version) failed its start check (\(failure)), so the supervisor does not restart into it; \(outcome)") + ClusterPairUpdate.writeProgress(restingProgress(now: now), to: pair.progressPath) + } + // MARK: - Helpers private func acquireLock() -> Int32? { diff --git a/provider-swift/Sources/darkbloom/main.swift b/provider-swift/Sources/darkbloom/main.swift index 02e41c8b00..960b885a2e 100644 --- a/provider-swift/Sources/darkbloom/main.swift +++ b/provider-swift/Sources/darkbloom/main.swift @@ -29,7 +29,9 @@ if rawArgs.first == AppAttestQualificationCommand.argument { // Before parsing (including help/version/errors) and before the AppKit serve // branch, so no subcommand has to remember to print this notice. Keep stdout -// available for JSON, completion scripts and runtime-smoke markers. +// available for JSON, completion scripts and runtime-smoke markers, and for +// `--version`, which an updating cluster supervisor compares exactly +// (`ClusterCandidateRecovery.startCheckFailure`). MacOSUpgradeNotice.emit() #if os(macOS) diff --git a/provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift b/provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift index f3bc9abbf7..e90bd86ce9 100644 --- a/provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift @@ -7,8 +7,8 @@ import Testing /// The cluster service supervisor's update (`darkbloom cluster`): its wiring to the single-Mac gate, the pair's update /// slot and `darkbloom update`'s request, around a real supervisor with a shell standing in for the cluster service -/// (no model, network, launchd or re-exec: the re-exec is observed). The cycle itself is covered with real installs in -/// `ClusterPairUpdateTests`. +/// (no model, network, launchd or re-exec: the re-exec is observed). The start check before a restart runs the +/// temporary install's `darkbloom`, a script. The cycle itself is covered with real installs in `ClusterPairUpdateTests`. @Suite("Cluster service update", .serialized) struct ClusterServiceUpdateTests { private final class Recorder: @unchecked Sendable { @@ -48,7 +48,11 @@ struct ClusterServiceUpdateTests { return "slot-check-none" } - private func configuration(directory: URL, script: String, autoUpdate: Bool, clusterID: String, + /// `service` stands in for the cluster service (a shell running `script` unless a test install's binary serves); + /// `installed` is the binary the supervisor restarts into, start-checked within `startCheckSeconds`. + private func configuration(directory: URL, script: String = "", service: String = "/bin/sh", + installed: String = "/installed/darkbloom", startCheckSeconds: Double = 5, + autoUpdate: Bool, clusterID: String, recovery: ClusterCandidateRecovery? = nil, reexecs: Recorder, run: @escaping @Sendable (String?, @escaping @Sendable (String) -> Void, @escaping @Sendable (String) async throws -> Void) async -> AutoUpdateController.Outcome) @@ -57,18 +61,19 @@ struct ClusterServiceUpdateTests { limits.intervalSeconds = 0.2 limits.startGraceSeconds = 600 limits.downSeconds = 600 - return .init(executable: "/bin/sh", childArguments: ["-c", script], environment: ["PATH": "/usr/bin:/bin"], + return .init(executable: service, childArguments: ["-c", script], environment: ["PATH": "/usr/bin:/bin"], statePath: ClusterServiceAgent.supervisorStatePath(serviceDirectory: directory), healthPath: ClusterServiceAgent.healthPath(serviceDirectory: directory), setup: nil, coordinatorURL: "http://127.0.0.1:9", autoUpdate: autoUpdate, budgetLimits: .init(maxQuickFailures: 5, quickFailureWindowSeconds: 30, initialBackoffSeconds: 1, maxBackoffSeconds: 1), - guardLimits: limits, recycleGraceSeconds: 5, reexecArguments: ["/installed/darkbloom", "cluster", "service", "--supervise"], + guardLimits: limits, recycleGraceSeconds: 5, reexecArguments: [installed, "cluster", "service", "--supervise"], logName: "cluster service supervisor", childPollSeconds: 0.05, pairUpdate: .init(clusterID: { clusterID }, run: run, requestPath: ClusterServiceAgent.updateRequestPath(serviceDirectory: directory), progressPath: ClusterServiceAgent.updateProgressPath(serviceDirectory: directory), recovery: recovery), - reexec: { reexecs.add($0.joined(separator: " ")) }, sweepsOrphans: false) + reexec: { reexecs.add($0.joined(separator: " ")) }, startCheckTimeoutSeconds: startCheckSeconds, + sweepsOrphans: false) } // MARK: - Wiring @@ -210,7 +215,8 @@ struct ClusterServiceUpdateTests { // MARK: - Candidate promotion and rollback /// The release a cycle installed is a candidate: three starts of its service that end on their own restore the - /// verified predecessor, quarantine the release and start again from the restored binary. + /// verified predecessor, quarantine the release and start again from the restored binary, once it passes its + /// start check. @Test func failingCandidateIsRolledBackAndTheSupervisorRestartsFromThePredecessor() async throws { let install = try CandidateInstall() defer { install.cleanUp() } @@ -218,11 +224,12 @@ struct ClusterServiceUpdateTests { defer { try? FileManager.default.removeItem(at: directory) } let reexecs = Recorder() let supervisor = ClusterMemberSupervisor(configuration: configuration(directory: directory, script: "exit 1", - autoUpdate: false, clusterID: "pair-far-from-its-slot", recovery: ClusterCandidateRecovery(updater: install.updater), - reexecs: reexecs) { _, _, _ in .upToDate }) + installed: install.binary, autoUpdate: false, clusterID: "pair-far-from-its-slot", + recovery: ClusterCandidateRecovery(updater: install.updater), reexecs: reexecs) { _, _, _ in .upToDate }) let run = Task { await supervisor.run() } #expect(await waitUntil(seconds: 20) { !reexecs.all.isEmpty }, "three failed starts roll the candidate back") - #expect(try install.liveBinary() == "1.0.0-darkbloom") + #expect(reexecs.all == ["\(install.binary) cluster service --supervise"]) + #expect(try install.liveRelease() == "1.0.0") let recovery = try UpdateRecoveryStore(installRoot: install.installRoot, verifyCodeSignatures: false).loadState() #expect(recovery.quarantine?.version == "2.0.0" && recovery.candidate == nil) #expect((state(directory)?.runs ?? 0) >= 3, "rolled back at the third failed start") @@ -230,6 +237,108 @@ struct ClusterServiceUpdateTests { #expect(await run.value == 0) } + /// The predecessor a rollback restored is start-checked too: one that cannot start is not restarted into, and the + /// supervisor starts the cluster service again itself. + @Test func restoredPredecessorThatCannotStartIsNotRestartedInto() async throws { + let install = try CandidateInstall(predecessor: .exitsNonZero) + defer { install.cleanUp() } + let directory = try temporaryDirectory("cluster-update-rollback-check") + defer { try? FileManager.default.removeItem(at: directory) } + let reexecs = Recorder() + let supervisor = ClusterMemberSupervisor(configuration: configuration(directory: directory, script: "exit 1", + installed: install.binary, autoUpdate: false, clusterID: "pair-far-from-its-slot", + recovery: ClusterCandidateRecovery(updater: install.updater), reexecs: reexecs) { _, _, _ in .upToDate }) + let run = Task { await supervisor.run() } + let store = UpdateRecoveryStore(installRoot: install.installRoot, verifyCodeSignatures: false) + #expect(await waitUntil(seconds: 20) { (try? store.loadState())?.quarantine?.version == "2.0.0" }, + "three failed starts roll the candidate back") + #expect(await waitUntil(seconds: 10) { (state(directory)?.runs ?? 0) >= 4 }, "the service starts again under this supervisor") + #expect(reexecs.all.isEmpty, "a restored binary that cannot start is not restarted into") + #expect(try install.liveRelease() == "1.0.0") + supervisor.requestStop() + #expect(await run.value == 0) + } + + // MARK: - The start check before a restart + + /// The pair's cycle as the supervisor sees it: 2.0.0 is installed and its launch prepared, the progress says the + /// service restarts, and the cycle asks for the restart. + private func cycleInstalling(_ install: CandidateInstall, directory: URL) + -> @Sendable (String?, @escaping @Sendable (String) -> Void, @escaping @Sendable (String) async throws -> Void) async + -> AutoUpdateController.Outcome { + { request, _, restart in + do { try install.install() } catch { return .commitFailed("\(error)") } + ClusterPairUpdate.writeProgress(.init(phase: .restarting, target: "2.0.0", running: "1.0.0", cycleStartedAt: 1, + request: request, writtenAt: Date().timeIntervalSince1970), to: ClusterServiceAgent.updateProgressPath(serviceDirectory: directory)) + try? await restart("2.0.0") + return .restarted(from: "1.0.0", to: "2.0.0", drained: true) + } + } + + /// A supervisor whose cluster service is the test install's `darkbloom`, and the `darkbloom update` request that + /// runs the cycle installing 2.0.0 at once. + private func superviseUpdate(_ install: CandidateInstall, directory: URL, reexecs: Recorder) + async -> (ClusterMemberSupervisor, Task) { + let supervisor = ClusterMemberSupervisor(configuration: configuration(directory: directory, service: install.binary, + installed: install.binary, startCheckSeconds: 1, autoUpdate: false, clusterID: "pair-far-from-its-slot", + recovery: ClusterCandidateRecovery(updater: install.updater), reexecs: reexecs, + run: cycleInstalling(install, directory: directory))) + let run = Task { await supervisor.run() } + #expect(await waitUntil(seconds: 5) { state(directory)?.phase == .running }) + #expect(ClusterPairUpdate.writeRequest(.init(createdAt: Date().timeIntervalSince1970), + to: ClusterServiceAgent.updateRequestPath(serviceDirectory: directory))) + return (supervisor, run) + } + + /// Before the supervisor restarts into the release its cycle installed, the release's `darkbloom` runs once with + /// `--version`. One that exits non-zero, outlasts the bound or reports another version is never restarted into: + /// the supervisor stays, restores the predecessor and quarantines the release at once, and starts the cluster + /// service again from the restored binary. + @Test(arguments: [StartAnswer.exitsNonZero, .hangs, .reportsAnotherVersion]) + func releaseThatCannotStartIsRolledBackInsteadOfRestartedInto(_ answer: StartAnswer) async throws { + let install = try CandidateInstall(candidate: answer, installed: false) + defer { install.cleanUp() } + let directory = try temporaryDirectory("cluster-update-start-check") + defer { try? FileManager.default.removeItem(at: directory) } + let reexecs = Recorder() + let (supervisor, run) = await superviseUpdate(install, directory: directory, reexecs: reexecs) + let store = UpdateRecoveryStore(installRoot: install.installRoot, verifyCodeSignatures: false) + #expect(await waitUntil(seconds: 20) { (try? store.loadState())?.quarantine?.version == "2.0.0" }, + "rolled back at its first failed start check") + #expect(await waitUntil(seconds: 10) { + guard let current = state(directory)?.current, state(directory)?.runs == 2 else { return false } + let health = ClusterSupervisionFiles.read(ClusterMemberHealth.self, from: ClusterServiceAgent.healthPath(serviceDirectory: directory)) + return health?.pid == current.pid && health?.version == "1.0.0" + }, "this supervisor runs the cluster service again, from the restored binary") + #expect(reexecs.all.isEmpty, "never restarted into a release that cannot start") + #expect(try install.liveRelease() == "1.0.0") + let recovery = try store.loadState() + #expect(recovery.candidate == nil && recovery.current?.version == "1.0.0") + #expect(recovery.quarantine?.failureCount == 1 && recovery.quarantine?.reason.contains("start check") == true) + #expect(ClusterPairUpdate.readProgress(from: ClusterServiceAgent.updateProgressPath(serviceDirectory: directory))?.phase == .disabled, + "the cycle is over: this Mac rests on its release") + supervisor.requestStop() + #expect(await run.value == 0) + } + + /// A release whose `darkbloom` starts and reports its version is restarted into as before, and stays the candidate. + @Test func releaseThatStartsIsRestartedInto() async throws { + let install = try CandidateInstall(installed: false) + defer { install.cleanUp() } + let directory = try temporaryDirectory("cluster-update-start-check-passes") + defer { try? FileManager.default.removeItem(at: directory) } + let reexecs = Recorder() + let (supervisor, run) = await superviseUpdate(install, directory: directory, reexecs: reexecs) + #expect(await waitUntil(seconds: 20) { !reexecs.all.isEmpty }, "restarted into the release") + #expect(reexecs.all == ["\(install.binary) cluster service --supervise"]) + #expect(state(directory)?.lastRun?.end == "stopped to restart into v2.0.0") + #expect(try install.liveRelease() == "2.0.0") + let recovery = try UpdateRecoveryStore(installRoot: install.installRoot, verifyCodeSignatures: false).loadState() + #expect(recovery.candidate?.release.version == "2.0.0" && recovery.quarantine == nil) + supervisor.requestStop() + #expect(await run.value == 0) + } + /// A candidate whose service keeps beating with the new version through the stabilization window is promoted. @Test func healthyCandidateIsPromoted() async throws { let install = try CandidateInstall() @@ -248,23 +357,42 @@ struct ClusterServiceUpdateTests { }, "promoted after the window") let recovery = try UpdateRecoveryStore(installRoot: install.installRoot, verifyCodeSignatures: false).loadState() #expect(recovery.candidate == nil && recovery.quarantine == nil) - #expect(try install.liveBinary() == "2.0.0-darkbloom" && reexecs.all.isEmpty) + #expect(try install.liveRelease() == "2.0.0" && reexecs.all.isEmpty) supervisor.requestStop() #expect(await run.value == 0) } } +/// How a test release's `darkbloom --version` answers. +enum StartAnswer: String, Sendable { + case reportsItsVersion, exitsNonZero, hangs, reportsAnotherVersion + + func command(version: String) -> String { + switch self { + case .reportsItsVersion: return "echo \(version)" + case .exitsNonZero: return "exit 1" + case .hangs: return "exec sleep 30" + case .reportsAnotherVersion: return "echo 1.9.9" + } + } +} + /// A temporary install with release 2.0.0 installed over 1.0.0 and not yet promoted (no network, unsigned fixtures). +/// Each release's `darkbloom` is a script: `--version` answers as the test says, and otherwise it beats as that +/// release's cluster service would. private struct CandidateInstall { let root: URL let installRoot: URL let updater: SelfUpdater + private let tarball: URL + private let release: ReleaseInfo - init() throws { + /// `installed`: 2.0.0 is installed already; otherwise `install()` installs it, as the test's cycle does. + init(predecessor: StartAnswer = .reportsItsVersion, candidate: StartAnswer = .reportsItsVersion, installed: Bool = true) throws { let fm = FileManager.default root = fm.temporaryDirectory.appendingPathComponent("cluster-candidate-\(UUID().uuidString)", isDirectory: true) installRoot = root.appendingPathComponent("install", isDirectory: true) - try Self.writeApp(version: "1.0.0", root: installRoot) + try Self.writeApp(version: "1.0.0", answer: predecessor, root: installRoot) let bin = installRoot.appendingPathComponent("bin") try fm.createDirectory(at: bin, withIntermediateDirectories: true) for name in ["darkbloom", "darkbloom-enclave", "mlx.metallib"] { @@ -272,13 +400,13 @@ private struct CandidateInstall { withDestinationPath: "../Darkbloom.app/Contents/MacOS/\(name)") } let source = root.appendingPathComponent("release", isDirectory: true) - try Self.writeApp(version: "2.0.0", root: source) + try Self.writeApp(version: "2.0.0", answer: candidate, root: source) let flat = source.appendingPathComponent("bin", isDirectory: true) try fm.createDirectory(at: flat, withIntermediateDirectories: true) for name in ["darkbloom", "darkbloom-enclave", "mlx.metallib"] { try fm.copyItem(at: source.appendingPathComponent("Darkbloom.app/Contents/MacOS/\(name)"), to: flat.appendingPathComponent(name)) } - let tarball = root.appendingPathComponent("release.tar.gz") + tarball = root.appendingPathComponent("release.tar.gz") let tar = Process() tar.executableURL = URL(fileURLWithPath: "/usr/bin/tar") tar.arguments = ["czf", tarball.path, "-C", source.path, "."] @@ -287,24 +415,48 @@ private struct CandidateInstall { let digest = SHA256.hash(data: try Data(contentsOf: tarball)).map { String(format: "%02x", $0) }.joined() updater = SelfUpdater(coordinatorBaseURL: "http://127.0.0.1:9", installRoot: installRoot, verifyCodeSignatures: false, currentVersion: "1.0.0") - let release = ReleaseInfo(version: "2.0.0", platform: "macos-arm64", url: "file:///unused", bundleHash: digest) - guard case .success = updater.installBundleForTesting(from: tarball, release: release, installDir: installRoot) else { - throw CocoaError(.fileWriteUnknown) - } + release = ReleaseInfo(version: "2.0.0", platform: "macos-arm64", url: "file:///unused", bundleHash: digest) + if installed { try commit() } + } + + /// The installed `darkbloom`, which the supervisor restarts into. + var binary: String { installRoot.appendingPathComponent("Darkbloom.app/Contents/MacOS/darkbloom").path } + + /// Installs 2.0.0 and prepares its launch, as the pair's cycle does before it asks for the restart. + func install() throws { + try commit() + try updater.prepareCandidateLaunch(operation: "test-cluster-restart", baseline: nil) } - func liveBinary() throws -> String { - try String(contentsOf: installRoot.appendingPathComponent("Darkbloom.app/Contents/MacOS/darkbloom"), encoding: .utf8) + /// The release whose `darkbloom` is installed. + func liveRelease() throws -> String? { + try String(contentsOfFile: binary, encoding: .utf8).split(separator: "\n") + .first { $0.hasPrefix("# release ") }.map { String($0.dropFirst("# release ".count)) } } func cleanUp() { try? FileManager.default.removeItem(at: root) } - private static func writeApp(version: String, root: URL) throws { + private func commit() throws { + guard case .success = updater.installBundleForTesting(from: tarball, release: release, installDir: installRoot) else { + throw CocoaError(.fileWriteUnknown) + } + } + + private static func writeApp(version: String, answer: StartAnswer, root: URL) throws { let contents = root.appendingPathComponent("Darkbloom.app/Contents") let macOS = contents.appendingPathComponent("MacOS") try FileManager.default.createDirectory(at: macOS, withIntermediateDirectories: true) try Data("".utf8).write(to: contents.appendingPathComponent("Info.plist")) - try Data("\(version)-darkbloom".utf8).write(to: macOS.appendingPathComponent("darkbloom")) + let darkbloom = macOS.appendingPathComponent("darkbloom") + try Data(""" + #!/bin/sh + # release \(version) + if [ "$1" = --version ]; then \(answer.command(version: version)); exit; fi + while :; do printf '{"pid":%d,"version":"\(version)","phase":"serving","writtenAt":%s}' $$ "$(date +%s)" \ + > "$DARKBLOOM_CLUSTER_MEMBER_HEALTH_FILE"; sleep 0.2; done + + """.utf8).write(to: darkbloom) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: darkbloom.path) try Data("\(version)-enclave".utf8).write(to: macOS.appendingPathComponent("darkbloom-enclave")) try Data("\(version)-metallib".utf8).write(to: macOS.appendingPathComponent("mlx.metallib")) } diff --git a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift index 1738f01888..4d97d8ee77 100644 --- a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift @@ -379,4 +379,55 @@ struct ClusterPairUpdateTests { #expect(version == "2.0.0", "the next slot does not install the failed release again") #expect(failing.recordFailedStart(now: 400) == .notCandidate, "an ordinary end after the rollback counts nothing") } + + /// Before the supervisor restarts into an installed binary, it runs it once with `--version`: the check passes only + /// on exit 0 within the bound with exactly the expected version, and repeats nothing but a version from its output. + @Test func startCheckPassesOnlyABinaryThatReportsItsVersionInTime() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("start-check-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + func check(_ body: String) throws -> String? { + let binary = directory.appendingPathComponent(UUID().uuidString) + try Data("#!/bin/sh\n\(body)\n".utf8).write(to: binary) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: binary.path) + return ClusterCandidateRecovery.startCheckFailure(executable: binary.path, version: "2.0.0", timeout: 1) + } + #expect(try check(#"[ "$1" = --version ] && echo 2.0.0"#) == nil) + #expect(try check("exit 1") == "`--version` exited 1") + #expect(try check("kill -KILL $$") == "`--version` ended on signal 9") + #expect(try check("exec sleep 30") == "`--version` did not finish within 1 s") + #expect(try check("echo 1.9.9") == "it reports v1.9.9") + #expect(try check("echo 'token=not-a-version'") == "it printed no version", "nothing else the binary prints is repeated") + let missing = directory.appendingPathComponent("missing").path + #expect(ClusterCandidateRecovery.startCheckFailure(executable: missing, version: "2.0.0", timeout: 1)? + .hasPrefix("it could not be run") == true) + } + + /// A candidate whose binary failed its start check before the restart: after that restart no supervisor would count + /// its failed starts, so the predecessor is restored and the release quarantined at once. Only the pending release + /// is, and only under the update lease. + @Test func candidateThatFailsItsStartCheckIsRolledBackAtOnce() async throws { + let mac = try await PairMac.make(part: false) + defer { Task { await mac.cleanUp() } } + let updater = mac.fixture.updater(baseURL: mac.baseURL) + guard case .updated = await updater.update() else { Issue.record("install failed"); return } + try updater.prepareCandidateLaunch(operation: "cluster-restart", baseline: nil) + let recovery = ClusterCandidateRecovery(updater: updater) + #expect(recovery.recordFailedStartCheck(version: "1.9.9", reason: "it reports v1.9.9", now: 200) == .notCandidate, + "not the pending release") + let held = try updater.beginUpdateSession(operation: "pair-cycle") + #expect(recovery.recordFailedStartCheck(version: "2.0.0", reason: "`--version` exited 1", now: 201) == .notCandidate, + "another update holds the lease") + held.release() + #expect(try mac.fixture.liveBinaryContents() == "2.0.0-darkbloom") + #expect(recovery.recordFailedStartCheck(version: "2.0.0", reason: "`--version` exited 1", now: 202) + == .rolledBack(from: "2.0.0", to: "1.0.0")) + #expect(try mac.fixture.liveBinaryContents() == "1.0.0-darkbloom") + let state = try UpdateRecoveryStore(installRoot: mac.fixture.installRoot, verifyCodeSignatures: false).loadState() + #expect(state.candidate == nil && state.current?.version == "1.0.0") + #expect(state.quarantine?.version == "2.0.0" && state.quarantine?.failureCount == 1, "one failed start") + #expect(state.quarantine?.reason.contains("failed its start check before the restart (`--version` exited 1)") == true) + guard case .quarantined(let version, _) = await updater.checkForUpdate() else { Issue.record("not quarantined"); return } + #expect(version == "2.0.0", "the next slot does not install it again") + } } From b1c3d66843e466759583f3c276196294ced97840 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:53:24 -0700 Subject: [PATCH 0023/1441] Byte-fallback tests and changelog after independent verification Tests only and the changelog, no source change: a reply of byte tokens alone longer than any walk bound, a control character written as a byte, and the unknown-token test loads the tokenizer repeatedly because the probe reads whichever byte token a dictionary lists first. The changelog now states the stop-string exception, the streamed logprobs entries, logprobs bytes and /detokenize. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-byte-fallback-flush.md | 7 +++--- .../LocalTokenizerByteFallbackTests.swift | 25 ++++++++++++++++--- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/changelog.d/gemma-byte-fallback-flush.md b/changelog.d/gemma-byte-fallback-flush.md index d0e5cc655e..3f22c7588c 100644 --- a/changelog.d/gemma-byte-fallback-flush.md +++ b/changelog.d/gemma-byte-fallback-flush.md @@ -1,5 +1,6 @@ ### Gemma 4 replies keep characters outside its vocabulary -- A Gemma 4 reply that ended in a character its vocabulary writes as byte tokens, such as many newer emoji, rare CJK and most Hangul syllables, lost that character: `all zipped up 🗜` came back as `all zipped up `. A long reply could also corrupt such a character when streaming restarted its decode inside its bytes. -- The Swift tokenizer library releases byte tokens only when a later token arrives. The provider's tokenizer bridge now releases a trailing run itself. -- Token IDs, sampling, model state and cache keys do not change. Only the text decoded from the same tokens does. A reply cut inside a character by `max_tokens` now ends in U+FFFD instead of dropping it, and a byte token's `logprobs` text is U+FFFD or its ASCII character instead of empty. +- A Gemma 4 reply that ended in characters its vocabulary writes as byte tokens, such as many newer emoji, rare CJK and most Hangul syllables, lost all of them: `all zipped up 🗜` came back as `all zipped up `, and a reply made only of such characters came back empty. A long reply could also corrupt such a character when streaming restarted its decode inside its bytes. +- The Swift tokenizer library releases byte tokens only when a later token arrives. The provider's tokenizer bridge now releases a trailing run itself. `/detokenize` keeps it too. +- Token IDs, numeric logprobs, sampling and cache keys do not change, with one exception: a stop string that a trailing run completes now matches when the run completes, one token sooner, so `completion_tokens` can fall by one. +- A streamed reply's `logprobs` gains the entries of those tokens, which it used to drop. A byte token's `logprobs` text and `bytes` are U+FFFD or its ASCII character instead of empty, not the real byte. A reply cut inside a character by `max_tokens` now ends in U+FFFD instead of dropping it. diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift index 51104f39d3..e420784478 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift @@ -96,6 +96,22 @@ struct LocalTokenizerByteFallbackTests { } } + @Test("a reply of byte tokens alone keeps all of them") + func allByteReply() async throws { + let directory = try tokenizerDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let tokenizer = try await LocalTokenizerLoader().load(from: directory) + // Longer than any bound a walk might take, and a control character written as a byte. + let text = String(repeating: "갂🗜丌", count: 100) + "\r" + let tokens = try text.unicodeScalars.flatMap { scalar in + try String(scalar).utf8.map { byte in + try #require(tokenizer.convertTokenToId(String(format: "<0x%02X>", byte))) + } + } + #expect(tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) == text) + #expect(streamed(tokens, tokenizer) == text) + } + @Test("a segment restart does not land inside a run") func restartInsideARun() async throws { let directory = try tokenizerDirectory() @@ -144,8 +160,11 @@ struct LocalTokenizerByteFallbackTests { // Only some byte tokens exist, so the others convert to the unknown ID. let directory = try tokenizerDirectory(byteTokens: 0xF0...0xFF) defer { try? FileManager.default.removeItem(at: directory) } - let tokenizer = try await LocalTokenizerLoader().load(from: directory) - let unknown = try #require(tokenizer.convertTokenToId("")) - #expect(tokenizer.decode(tokenIds: try ids("a", tokenizer) + [unknown], skipSpecialTokens: false) == "a") + // The probe reads whichever byte token a dictionary lists first, so load it more than once. + for _ in 0..<40 { + let tokenizer = try await LocalTokenizerLoader().load(from: directory) + let unknown = try #require(tokenizer.convertTokenToId("")) + #expect(tokenizer.decode(tokenIds: try ids("a", tokenizer) + [unknown], skipSpecialTokens: false) == "a") + } } } From 94d7a0b06fbbb68598734842e761ec9ef57d3c22 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:37:00 -0700 Subject: [PATCH 0024/1441] Share one expert dispatch across Gemma prompt tokens and decode rows Bumps libs/mlx-swift-lm to ef43498b9 (branch feat/gemma4-batched-prompt-experts on 7933a0fa). Registered Gemma stages now compute a prompt frame's expert blocks in one unsorted dispatch per operation, instead of one subgraph per prompt token (about six launches per token per layer since the 2026-10-23 token expert policy). Batch-decode rows share the same call. Every (token, expert) pair is still an M=1 gather_qmv product, and the top-8 reduction keeps its one-row col_reduce_small layout. Each token therefore keeps its bytes, and the exact Gemma arithmetic receipt (gemma4-bf16-token-expert-reduction-v1) and the cache identities it separates are unchanged. Evidence (docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md): - Gemma4PrefillExpertTests on CPU: bytes equal at 7-512 tokens and decode rows 2/3/8, at 4 and 8 bits. - M5 Ultra GPU: bytes equal for 1-2048 rows at the production kernel classes, and at hidden 2816 / width 704 / 128 experts. - Synthetic expert layer: 2,048 tokens 349.9 -> 36.8 ms. - Gemma4BatchDecodeTests, Gemma4BatchArithmeticAgreementTests, GemmaPrefillArithmeticTests, GemmaPrefixChunkTests and ResidentAdmissionGemma4Tests pass. Not validated: pair throughput, full-model numerics, other GPU generations. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-pipeline-speed.md | 3 + docs/architecture/hardware-support.md | 4 +- docs/architecture/inference.md | 31 +++++-- docs/developer/test.md | 19 ++-- ...026-11-01-gemma-pipeline-prompt-experts.md | 89 +++++++++++++++++++ docs/reports/README.md | 3 +- libs/mlx-swift-lm | 2 +- 7 files changed, 134 insertions(+), 17 deletions(-) create mode 100644 changelog.d/gemma-pipeline-speed.md create mode 100644 docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md diff --git a/changelog.d/gemma-pipeline-speed.md b/changelog.d/gemma-pipeline-speed.md new file mode 100644 index 0000000000..ab2c331010 --- /dev/null +++ b/changelog.d/gemma-pipeline-speed.md @@ -0,0 +1,3 @@ +### Faster Gemma 4 pipeline pairs + +- Gemma 4 pipeline stages compute a prompt chunk's expert blocks in one shared dispatch per operation instead of one subgraph per prompt token, with the same bytes for every token (unchanged arithmetic receipt). Batch-decode rows share the same dispatch. On one synthetic expert layer this cut a 2,048-token chunk from about 350 ms to about 37 ms; pair throughput is not yet measured. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index c91f96c2e6..4340fa6664 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1,6 +1,6 @@ # Hardware support and the provider memory model -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 What hardware the provider runs on and how it decides, in bytes, whether a model may load and how much KV cache each resident model may use. Read this to @@ -1117,6 +1117,8 @@ Registered Gemma prompt projections use an explicit singleton-token reduction policy for supported BF16 affine packing, as described in [inference](inference.md#gemma-prompt-projection-reductions). The exact arithmetic receipt separates older rectangular-projection results and cache identities. +The prompt's expert blocks share one unsorted dispatch per operation and keep +each token's bytes, so the receipt is unchanged. Component tests do not qualify a complete model, both rank orders, or prompt throughput. Keep existing cross-chip failures and require fresh full-artifact numerical and timing evidence for both scoped prompt policies. Attention and diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..89a983bc4c 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -4475,7 +4475,9 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Meta one-token requests. Ordinary affine 4/8-bit group-64 projections retain native matmul `M=1` through leading weight views; custom and floating modules retain their original per-request forward method. The unscaled value RMS reduction -and each routed expert operation retain singleton request shapes as well. +retains singleton request shapes. The rows' routed experts share one unsorted +call that keeps each row's singleton bytes +([Gemma prompt projection reductions](#gemma-prompt-projection-reductions)). The scope owns no cache, changes no shared MLX dispatcher, and is disabled for singletons, prefill and speculative rectangles. @@ -4857,17 +4859,30 @@ packed weights; it adds no persistent weight copy. Query/key/value, output, shared MLP and router projections use their existing model call sites. Norms, the vocabulary head, independent decode lanes and singleton frames retain their existing operations. -The same explicit prompt scope invokes each BF16 token's complete expert block -with its unchanged selected indices and weights. This preserves singleton -GeGLU and weighted reduction rather than entering a wide sorted expert graph; -ordinary SDK prompts and speculative verification keep their existing paths. Custom modules, other dtypes/packing, and ordinary -SDK callers retain the original forward method. +The same explicit prompt scope keeps each BF16 token's complete expert block +at one token: its unchanged selected indices and weights, an M=1 gathered +product per selected expert, singleton GeGLU and its own top-K weighted +reduction, rather than a wide sorted expert graph. All tokens of a frame share +one call (`SwitchGLU.callAndWeightedReduceRows`) that keeps their assignments +unsorted. MLX selects `gather_qmv` from the bits, dtype and the N and K widths +alone, and the top-8 reduction's `col_reduce_small` thread layout depends only +on the hidden width, so each token's bytes equal those of its own one-token +call. The tokens share one dispatch per operation instead of about six per +token per layer. Independent decode rows use the same call +([Gemma ordinary batch decode arithmetic](#gemma-ordinary-batch-decode-arithmetic)). +Ordinary SDK prompts and speculative verification keep their existing paths. +Custom modules, other dtypes/packing, and ordinary SDK callers retain the +original forward method. The exact Gemma arithmetic receipt binds both prompt projection and expert reduction policies before LOAD, separating prior rectangular-projection cache and plan identities. The stable family policy identifier and required environment flags remain the same. +The shared expert dispatch changes no byte, so the receipt and the cache +identities it separates are unchanged. Component byte equality is separate from full-model two-chip numerical -qualification, and the M=1 prompt graph requires its own throughput measurement. +qualification. The M=1 prompt graph still needs a pair throughput measurement; +the synthetic component timings are in +[Gemma pipeline prompt experts](../reports/2026-11-01-gemma-pipeline-prompt-experts.md). The SDK helper is `libs/mlx-swift-lm/Libraries/MLXLLM/Models/Gemma4PrefillProjection.swift`; stage activation and receipt binding are in diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..ea56b6a9a2 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -2217,13 +2217,20 @@ prompt projections with actual singleton calls at chunk boundaries, checks explicit scope restoration and unsupported/custom fallbacks, and verifies the unchanged tied head. `Gemma4PrefillExpertTests` executes the actual Gemma decoder, router, shared MLP and sparse expert block with the attention output isolated to zero; -it assembles an independent projection/expert oracle while preserving the -original rectangular normalization and elementwise operations, and compares -selected routes across prompt boundaries. A separate expert-only composition +it assembles an independent projection/expert oracle from one-token expert +calls while preserving the original rectangular normalization and elementwise +operations. It requires one unsorted expert call carrying every token's routes +in order, with the oracle's bytes, at 7 to 512 tokens. A separate expert-only composition check compares complete singleton calls with the shared branch isolated to -zero. Ordinary and verification paths remain covered. These checks do not +zero, and a decode check requires 2, 3 and 8 independent rows to share one +unsorted call with each row's one-row bytes. Ordinary and verification paths +remain covered, and the original rectangular call still sorts. These checks do not claim whole-layer singleton equivalence: existing normalization can depend on -rectangle shape on CPU. +rectangle shape on CPU. With `GEMMA4_EXPERT_ROWS_GPU=1` the suite also +compares the shared call with one-row calls on the GPU for 1 to 2,048 rows, at +a geometry with the production kernel classes; `=production` adds hidden 2,816, +expert width 704 and 128 experts. Run the GPU case alone, in an exclusive +hardware window. `GemmaPrefillArithmeticTests` in the runtime target verifies that both exact policies change the receipt while the family environment and chunk policy remain bound. These CPU checks do not establish full-model cross-chip qualification diff --git a/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md b/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md new file mode 100644 index 0000000000..f40da4abcb --- /dev/null +++ b/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md @@ -0,0 +1,89 @@ +# Gemma pipeline prompt experts: one shared dispatch, the same bytes + +> Last updated: 2026-11-01 + +This record covers the change to the registered Gemma 4 stages' prompt expert +blocks: they now share one unsorted dispatch per operation instead of building +one subgraph per prompt token. It gives the equality evidence and synthetic +component timings measured on one Mac. It is not a pair, full-model or +qualification result, and it contains no prompt, endpoint or machine identifier. + +## Context + +Since 2026-10-23 (`gemma4-bf16-token-expert-reduction-v1` in the exact Gemma +arithmetic receipt) a registered Gemma stage computes every prompt token's +expert block at one token, so that prompt arithmetic is the same on every Apple +GPU generation. The receipt was added because rectangular expert products +select chip-specific kernels. The implementation built that per-token +arithmetic as one subgraph per token: about six launches per token per layer, +or about 180,000 launches for a 2,048-token frame on a 15-layer stage. No +prompt throughput had been measured for it. + +## Change + +`SwitchGLU.callAndWeightedReduceRows` (mlx-swift-lm) projects all rows of a +frame in one call with their expert assignments kept in row order: + +- every (row, expert) pair is still an M=1 gathered product. MLX selects + `gather_qmv` from the bits, dtype and the N and K widths alone, and its grid + gives each row its own threadgroups; +- the top-8 weighted reduction keeps its one-row `col_reduce_small` thread + layout, which depends only on the hidden width. + +Each row therefore keeps the bytes of its own one-row call, and the receipt is +unchanged. Gemma's batch-decode rows (`Gemma4BatchDecodeScope`) use the same +call. + +## Equality evidence + +| Check | Device | Result | +|---|---|---| +| `Gemma4PrefillExpertTests`: whole-layer composition against a one-token expert oracle, 7 to 512 tokens, 4 and 8 bits | CPU | bytes equal; one unsorted expert call | +| Same suite: expert branch against per-token layer calls; decode rows 2, 3 and 8 | CPU | bytes equal | +| `GEMMA4_EXPERT_ROWS_GPU=1`: hidden 768, width 192, 16 experts (the production kernel classes), 1 to 2,048 rows, 4 and 8 bits | M5 Ultra GPU | bytes equal; values finite and nonzero | +| `GEMMA4_EXPERT_ROWS_GPU=production`: hidden 2,816, width 704, 128 experts, 1 to 513 rows | M5 Ultra GPU | bytes equal | +| Sensitivity: the shared call against the earlier sorted rectangular call at 512 and 2,048 rows | M5 Ultra GPU | bytes differ, as expected | + +The suites ran in a debug build of `libs/darkbloom-cluster` with the SDK test +file linked in and a source-matched `mlx.metallib` (SHA-256 +`5b97893cc20e6e9651edf3284d970488af9a9bdd64820231e95fee760eec70ac`, MLX +`72dffa2d`). Other GPU generations were not run. [INFERENCE] The selection +above should hold on them too: on this route `gather_qmv` takes no architecture +input, and the reduction's threadgroup is 32 by 8 on any GPU whose kernels +hold 256 threads per threadgroup. + +## Synthetic timings + +One layer with random packed weights at the registered geometry: experts at +4 bits, dense MLP and router at 8 bits. Median of five warm runs, debug Swift +build, on an M5 Ultra that was also serving other GPU work, so the figures +carry contention noise. + +| Expert block, 4-bit | 512 tokens | 2,048 tokens | +|---|---:|---:| +| Per-token subgraphs (before) | 74.6 ms | 349.9 ms | +| Shared unsorted dispatch (after) | 9.8 ms | 36.8 ms | +| Sorted rectangle (the prompt path before 2026-10-23) | 1.6 ms | 3.6 ms | + +| Dense projections of one sliding layer (q, k, v, o, MLP, router) | 512 tokens | 2,048 tokens | +|---|---:|---:| +| M=1 rows (the registered prompt policy, unchanged) | 12.8 ms | 27.7 ms | +| Rectangle | 3.7 ms | 3.7 ms | + +[INFERENCE] For a 15-layer stage and a 2,048-token frame, the projections took +about 5.7 s before and take about 1.0 s after, ignoring attention and norms. +That would lift the stage's projection-bound prompt rate from about 360 to +about 2,000 tokens per second. The M=1 policy still costs about 9x the +rectangle. Closing that gap needs a multi-row `qmv` kernel that keeps qmv's +per-row reduction order. + +## Not established + +- Pair prompt or decode throughput, both schedules, both rank orders. +- Full-artifact numerical agreement on any chip pair. +- Other GPU generations (M1 to M4) and the release build. + +Code: `libs/mlx-swift-lm/Libraries/MLXLMCommon/SwitchLayers.swift` +(`SwitchGLU.callAndWeightedReduceRows`) and +`libs/mlx-swift-lm/Libraries/MLXLLM/Models/Gemma4Text.swift` (`Gemma4Experts`). +Mechanism: [Gemma prompt projection reductions](../architecture/inference.md#gemma-prompt-projection-reductions). diff --git a/docs/reports/README.md b/docs/reports/README.md index 96e0b79cef..28707b07fe 100644 --- a/docs/reports/README.md +++ b/docs/reports/README.md @@ -1,9 +1,10 @@ # Provider And Native Evidence -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Dated records and raw native evidence retain their original content, revisions and limitations. A record is not a fresh test result or proof of private platform compatibility. +- [Gemma pipeline prompt experts](2026-11-01-gemma-pipeline-prompt-experts.md) - the registered Gemma stages' prompt expert blocks in one shared unsorted dispatch with the same bytes: CPU and M5 Ultra GPU equality evidence and synthetic one-layer timings; no pair or qualification result. - [Public cluster models](2026-10-31-public-cluster-models.md) - the owner's declaration of GLM-5.3-Flash and Qwen3.8-27B for public cluster traffic in pipeline and tensor parallel, the checks it rests on and why releases carry pair-serving grants; the evidence document of `ClusterPublicModels`. - [Mixed-step prefill geometry](2026-10-21-mixed-step-prefill-geometry.md) - load, engine, inter-token latency and KV-subtracted activation measurements behind Gemma 4's 2,048 / 4,096 prompt geometry, its media ceiling and the GPT-OSS and dense Qwen opt-in. - [GLM-5.3-Flash single-Mac qualification record](2026-10-21-glm53-flash-single-mac-qualification.md) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 7933a0faad..ef43498b90 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 7933a0faad62559a010a1126241c61a1822315d9 +Subproject commit ef43498b90ec6b395ac4d41b7149ac383ad22c5a From 5a4c94f6487b29694c087f9dbbe2b487d47d3b50 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:37:34 -0700 Subject: [PATCH 0025/1441] State Gemma 4's expert routing for the placement prior Gemma4PlacementFamily now states expertRouting (8 of 128 experts per layer, from Gemma4StageGeometry) and names the experts.switch_glu banks as routed experts. Gemma layouts carry routedExperts: 12,846,366,720 bytes (QAT 4-bit) and 24,265,359,360 bytes (8-bit). ClusterHardwarePrior then reads 2,424,219,708 weight bytes per QAT 4-bit token instead of every layer byte. That matches the exact-header audit of 2026-09-20, and the old figure was about 6x too high. The three Gemma golden layouts gain the block. The 12 golden plan digests change only by the layout the plan echoes; cut 15 pipeline and both recorded pairs' ranks are unchanged. GemmaRoutedExpertChecks builds the QAT 4-bit layout from the retained real headers and requires it to equal the golden layout. PlacementChecks: 1422 checks pass. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-pipeline-speed.md | 1 + docs/architecture/inference.md | 13 +++++ docs/developer/test.md | 6 ++- .../Metadata/Gemma4PlacementFamily.swift | 10 ++++ .../Gemma4/Metadata/Gemma4StageGeometry.swift | 5 +- .../GemmaRoutedExpertChecks.swift | 49 +++++++++++++++++++ .../PlacementChecks/Golden/expected.json | 12 ++--- .../Golden/layouts/gemma-4-26b-8bit.json | 2 +- .../Golden/layouts/gemma-4-26b-qat-4bit.json | 2 +- .../Golden/layouts/gemma-4-26b.json | 2 +- .../pairs/m3ultra-m5ultra/expected.json | 12 ++--- .../Tests/PlacementChecks/Main.swift | 1 + 12 files changed, 98 insertions(+), 17 deletions(-) create mode 100644 libs/darkbloom-cluster/Tests/PlacementChecks/GemmaRoutedExpertChecks.swift diff --git a/changelog.d/gemma-pipeline-speed.md b/changelog.d/gemma-pipeline-speed.md index ab2c331010..91c723ecb1 100644 --- a/changelog.d/gemma-pipeline-speed.md +++ b/changelog.d/gemma-pipeline-speed.md @@ -1,3 +1,4 @@ ### Faster Gemma 4 pipeline pairs - Gemma 4 pipeline stages compute a prompt chunk's expert blocks in one shared dispatch per operation instead of one subgraph per prompt token, with the same bytes for every token (unchanged arithmetic receipt). Batch-decode rows share the same dispatch. On one synthetic expert layer this cut a 2,048-token chunk from about 350 ms to about 37 ms; pair throughput is not yet measured. +- The planner's hardware prior counts 8 of Gemma 4's 128 experts per token instead of every expert byte. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 89a983bc4c..511a20992f 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4498,6 +4498,19 @@ and leaving/rejoining rows. Their CPU checks require identical native logits and all live KV values. This is not full-artifact GPU, pair or throughput qualification; those checks remain required. +### Gemma routed-expert prior + +`Gemma4PlacementFamily` states that every layer routes a token to 8 of its 128 +experts (`expertRouting`, from `Gemma4StageGeometry`) and names the +`experts.switch_glu` banks as routed experts (`isRoutedExpert`). Gemma layouts +therefore carry `routedExperts`: 12,846,366,720 bytes for the QAT 4-bit +artifact and 24,265,359,360 bytes for the 8-bit one. The hardware prior +(`ClusterHardwarePrior.decodeBytesPerToken`) counts 2,424,219,708 weight bytes +per QAT 4-bit token instead of every layer byte. The golden pipeline plans +keep their cuts and modes; the prior feeds the device-index and +tensor-parallel share estimates (`ClusterHardwarePrior.absolute`, +`ClusterDecodeSplit`). + ### Qualification records for identical catalog files The plain `gemma-4-26b` and `gemma-4-26b-8bit` catalog entries have identical diff --git a/docs/developer/test.md b/docs/developer/test.md index ea56b6a9a2..9c6a070660 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -25,7 +25,11 @@ not native model capabilities, numerical parity or hardware qualification. The placement checks also cover exact family request scopes, completion-heavy and long-prompt helper plans, overflow refusal, conservative memory refusal and -unchanged GLM adapter bounds. Run `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh` +unchanged GLM adapter bounds. `GemmaRoutedExpertChecks.swift` builds the Gemma +QAT 4-bit layout from the retained real headers in +`libs/darkbloom-cluster/Tests/StageMetadataChecks/Inputs`, requires it to equal +its golden layout with `routedExperts` included, and requires the prior to read +2,424,219,708 weight bytes per token. Run `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh` and `provider-swift/Tests/ClusterPlacementChecks/run.sh`; then run `provider-swift/Tests/ClusterPlacementChecks/run-flow.sh` for the real child-process provider path with a fake installed helper. These checks use recorded metadata diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4PlacementFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4PlacementFamily.swift index ac6b0d5249..0f4c189cfb 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4PlacementFamily.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4PlacementFamily.swift @@ -85,6 +85,16 @@ struct Gemma4PlacementFamily: ClusterPlacementFamily { func layerKind(_ layer: Int) -> String { Gemma4StageGeometry.kind(globalLayerIndex: layer) } + /// A decode step reads 8 of every layer's 128 expert banks; the router and + /// the dense MLP beside them are read whole. + var expertRouting: ClusterExpertRouting? { + ClusterExpertRouting(selected: Gemma4StageGeometry.expertsPerToken, experts: Gemma4StageGeometry.routedExperts) + } + + func isRoutedExpert(storedTensor name: String) -> Bool { + layer(ofStoredTensor: name) != nil && name.contains(".experts.switch_glu.") + } + /// Keys and values in bfloat16: per token on a full-attention layer; on a /// sliding layer a ring of the window, allocated whole, and the view one /// frame attends over (`Gemma4StateBudget`). diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4StageGeometry.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4StageGeometry.swift index 5b395130b3..e448671c42 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4StageGeometry.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4StageGeometry.swift @@ -10,6 +10,8 @@ enum Gemma4StageGeometry { static let slidingWindow = 1024 static let slidingKVHeads = 8, slidingHeadDimension = 256 static let fullKVHeads = 2, fullHeadDimension = 512 + /// Every layer routes each token to 8 of its 128 experts. + static let routedExperts = 128, expertsPerToken = 8 /// Five sliding-window layers, then one full-attention layer, five times. static let fullAttentionInterval = 6 static let slidingKind = "sliding_attention", fullKind = "full_attention" @@ -44,7 +46,8 @@ enum Gemma4StageGeometry { throw ProbeError("Gemma stage metadata requires the original text wrapper") } let integers = ["num_hidden_layers": layerCount, "hidden_size": hiddenSize, "vocab_size": vocabularySize, - "intermediate_size": 2112, "moe_intermediate_size": 704, "num_experts": 128, "top_k_experts": 8, + "intermediate_size": 2112, "moe_intermediate_size": 704, "num_experts": routedExperts, + "top_k_experts": expertsPerToken, "sliding_window": slidingWindow, "num_attention_heads": queryHeads, "num_key_value_heads": slidingKVHeads, "num_global_key_value_heads": fullKVHeads, "head_dim": slidingHeadDimension, "global_head_dim": fullHeadDimension, diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaRoutedExpertChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaRoutedExpertChecks.swift new file mode 100644 index 0000000000..1322a06a42 --- /dev/null +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaRoutedExpertChecks.swift @@ -0,0 +1,49 @@ +import DarkbloomClusterPlacement +import DarkbloomClusterProtocol +import Foundation + +/// Gemma 4 26B routes each token to 8 of a layer's 128 experts. The QAT +/// 4-bit layout built here from the artifact's retained real tensor headers +/// (`StageMetadataChecks/Inputs`) must equal its golden layout, routed experts +/// included, and the hardware prior must read 8/128 of those banks per token: +/// 2,424,219,708 bytes, the figure the exact-header audit of 2026-09-20 +/// recorded, instead of every layer byte. +func checkGemmaRoutedExperts(golden: URL, _ checks: PlacementChecks) throws { + let inputs = golden.deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("StageMetadataChecks/Inputs", isDirectory: true) + var tensors: [ClusterPlacementStoredTensor] = [] + let headers = try FileManager.default.contentsOfDirectory(atPath: inputs.path) + .filter { $0.hasSuffix(".safetensors.header.json") }.sorted() + for file in headers { + let header = try JSONSerialization.jsonObject(with: Data(contentsOf: inputs.appendingPathComponent(file))) + as? [String: Any] ?? [:] + for (name, value) in header where name != "__metadata__" { + guard let entry = value as? [String: Any], let dtype = entry["dtype"] as? String, + let shape = entry["shape"] as? [Int], let offsets = entry["data_offsets"] as? [Int], + offsets.count == 2, offsets[1] > offsets[0] else { + throw ProbeError("Malformed retained Gemma header entry: \(name)") + } + tensors.append(.init(name: name, byteCount: offsets[1] - offsets[0], dtype: dtype, shape: shape)) + } + } + let layout = try ClusterPlacementLayouts.layout( + configuration: Data(contentsOf: inputs.appendingPathComponent("config.json")), tensors: tensors, + manifest: Data(contentsOf: inputs.appendingPathComponent("manifest.json"))) + let expected = try ClusterModelLayout.decode( + Data(contentsOf: golden.appendingPathComponent("layouts/gemma-4-26b-qat-4bit.json"))) + checks.require("Gemma QAT 4-bit: the layout from the retained real headers equals its golden layout, routed experts included", + headers.count == 3 && layout == expected) + let experts = layout.routedExperts + checks.require("Gemma QAT 4-bit routes 8 of 128 experts; its expert banks hold 12,846,366,720 bytes, no tensor-parallel share", + experts?.routing == ClusterExpertRouting(selected: 8, experts: 128) && experts?.loadedBytes == 12_846_366_720 + && experts?.tensorParallelDividedBytes == nil) + checks.require("Gemma QAT 4-bit decode reads 2,424,219,708 weight bytes per token (8/128 of the expert banks)", + ClusterHardwarePrior.decodeBytesPerToken(layout) == 2_424_219_708) + // The 8-bit artifact's golden layout carries the same routing over its 8-bit banks. + for name in ["gemma-4-26b-8bit", "gemma-4-26b"] { + let eight = try ClusterModelLayout.decode(Data(contentsOf: golden.appendingPathComponent("layouts/\(name).json"))) + checks.require("\(name): 8 of 128 routed experts over 24,265,359,360 bytes of 8-bit banks", + eight.routedExperts?.routing == ClusterExpertRouting(selected: 8, experts: 128) + && eight.routedExperts?.loadedBytes == 24_265_359_360) + } +} diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/expected.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/expected.json index 8bd6c48808..9e71e90567 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/expected.json +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/expected.json @@ -43,9 +43,9 @@ }, "gemma-4-26b": { "cut": 15, - "handOffPlanSHA256": "d18c86e08d609efff04dba63a250d8a26580ff9bc0fe3854b2399961cc8711a9", + "handOffPlanSHA256": "660cb1537bea8a3af6709fa7e82fe8f59a197c54200be814083be361c8410aa7", "mode": "pipeline_v1", - "planSHA256": "4a7acb8341eb99036e819e651b6eb0a91f7d17256192b06c1864c1fdb938eeb4", + "planSHA256": "4773f5dda0b6eab7234e2345227ce08f7f1e5e75e1be6872a6709dea650e7da6", "ranks": [ { "device": "mac-a", @@ -64,9 +64,9 @@ }, "gemma-4-26b-8bit": { "cut": 15, - "handOffPlanSHA256": "4c7e27371b3173548670079e804af65e7229ab812146d9a9d3b5a532ea96d511", + "handOffPlanSHA256": "92f2a8f617a28b13fc68ba89a34a7870e953e17ccdb004d9a0087e2030e63dd6", "mode": "pipeline_v1", - "planSHA256": "8c0e0dc6c7781fe37db90ea37f423fa8b9c370bfea8010a3e2531d00cc41ca8b", + "planSHA256": "98018701fbd5f5049ab44f105fe0ab2f0edb1b7dc63443cedd08597bbbdf63c2", "ranks": [ { "device": "mac-a", @@ -85,9 +85,9 @@ }, "gemma-4-26b-qat-4bit": { "cut": 15, - "handOffPlanSHA256": "2b8dc675c45902362c5c01aa93149de0472c2afec72f00232f240278d6ede4df", + "handOffPlanSHA256": "d134439b21431a48404e2af363824fccf6e02053d771a5b7a67ae7599a6af3a5", "mode": "pipeline_v1", - "planSHA256": "d6bc775b447fc25abc13db52b72b7d0c17b47a0b87f356f0cd57f86d5aa7e21c", + "planSHA256": "ef31103798080a01f959ba00f07a56b5d80cbacf4f16634b9313007d776c31fa", "ranks": [ { "device": "mac-a", diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-8bit.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-8bit.json index b1778ac039..b13a8ab341 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-8bit.json +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-8bit.json @@ -1 +1 @@ -{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6","boundaryBytesPerToken":5632,"configurationSHA256":"1b318c90eed55cc01711dbcae4ab7604dc6f785de59b20458f9b49017c7c9cae","egress":{"largestTensorBytes":738197504,"loadedBytes":784340480,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1142547552,"requestWorkBytes":0,"storedBytes":1142547552,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":738197504,"loadedBytes":784334848,"requestWorkBytes":0,"storedBytes":784334848,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"runtimeModelID":"registered_gemma4_26b_8bit","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]} +{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6","boundaryBytesPerToken":5632,"configurationSHA256":"1b318c90eed55cc01711dbcae4ab7604dc6f785de59b20458f9b49017c7c9cae","egress":{"largestTensorBytes":738197504,"loadedBytes":784340480,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1142547552,"requestWorkBytes":0,"storedBytes":1142547552,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":738197504,"loadedBytes":784334848,"requestWorkBytes":0,"storedBytes":784334848,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"routedExperts":{"loadedBytes":24265359360,"routing":{"experts":128,"selected":8}},"runtimeModelID":"registered_gemma4_26b_8bit","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]} diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json index 1668d30971..2eb3687281 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json @@ -1 +1 @@ -{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"2468a0cb3049a871f42052f4d9f9380bf12a0792f64c7a29f768559fc7d28785","boundaryBytesPerToken":5632,"configurationSHA256":"29910322dd085f45c8f95c6c0f1611b20f722d6f6c8394321b34817e98a972fa","egress":{"largestTensorBytes":369098752,"loadedBytes":415241728,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1140925536,"requestWorkBytes":0,"storedBytes":1140925536,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":369098752,"loadedBytes":415236096,"requestWorkBytes":0,"storedBytes":415236096,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"runtimeModelID":"registered_gemma4_26b_qat_4bit","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]} +{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"2468a0cb3049a871f42052f4d9f9380bf12a0792f64c7a29f768559fc7d28785","boundaryBytesPerToken":5632,"configurationSHA256":"29910322dd085f45c8f95c6c0f1611b20f722d6f6c8394321b34817e98a972fa","egress":{"largestTensorBytes":369098752,"loadedBytes":415241728,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1140925536,"requestWorkBytes":0,"storedBytes":1140925536,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":369098752,"loadedBytes":415236096,"requestWorkBytes":0,"storedBytes":415236096,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":126877696,"loadedBytes":467063042,"requestWorkBytes":0,"storedBytes":467063042,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":126877696,"loadedBytes":475174146,"requestWorkBytes":0,"storedBytes":475174146,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"routedExperts":{"loadedBytes":12846366720,"routing":{"experts":128,"selected":8}},"runtimeModelID":"registered_gemma4_26b_qat_4bit","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]} diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b.json index 0f7b245b87..7007a83d71 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b.json +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b.json @@ -1 +1 @@ -{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6","boundaryBytesPerToken":5632,"configurationSHA256":"1b318c90eed55cc01711dbcae4ab7604dc6f785de59b20458f9b49017c7c9cae","egress":{"largestTensorBytes":738197504,"loadedBytes":784340480,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1142547552,"requestWorkBytes":0,"storedBytes":1142547552,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":738197504,"loadedBytes":784334848,"requestWorkBytes":0,"storedBytes":784334848,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"runtimeModelID":"registered_gemma4_26b","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]} +{"admittedCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29],"artifactSHA256":"a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6","boundaryBytesPerToken":5632,"configurationSHA256":"1b318c90eed55cc01711dbcae4ab7604dc6f785de59b20458f9b49017c7c9cae","egress":{"largestTensorBytes":738197504,"loadedBytes":784340480,"requestWorkBytes":0,"storedBytes":5632,"tensorCount":4},"excluded":{"largestTensorBytes":47185920,"loadedBytes":1142547552,"requestWorkBytes":0,"storedBytes":1142547552,"tensorCount":358},"generationModes":["pipeline_v1"],"ingress":{"largestTensorBytes":738197504,"loadedBytes":784334848,"requestWorkBytes":0,"storedBytes":784334848,"tensorCount":3},"layers":[{"cost":1,"index":0,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":1,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":2,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":3,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":4,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":5,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":6,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":7,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":8,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":9,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":10,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":11,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":12,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":13,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":14,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":15,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":16,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":17,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":18,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":19,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":20,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":21,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":22,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":23,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}},{"cost":1,"index":24,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":25,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":26,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":27,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":28,"kind":"sliding_attention","stateBytesPerToken":0,"stateFixedBytes":20963332,"transientBytesPerQuery":16384,"transientBytesPerQueryKey":64,"transientKeyWindow":1535,"weights":{"largestTensorBytes":253755392,"loadedBytes":864997634,"requestWorkBytes":0,"storedBytes":864997634,"tensorCount":45}},{"cost":1,"index":29,"kind":"full_attention","stateBytesPerToken":4096,"stateFixedBytes":4,"transientBytesPerQuery":32768,"transientBytesPerQueryKey":64,"weights":{"largestTensorBytes":253755392,"loadedBytes":880317698,"requestWorkBytes":0,"storedBytes":880317698,"tensorCount":42}}],"maximumChunkTokens":512,"maximumOutputTokens":128,"maximumPromptTokens":8192,"prefillSchedules":["serial_v1","one_chunk_lookahead_v1"],"requestChargeEveryRankBytes":719380600,"requestChargeEveryRankBytesPerToken":22528,"routedExperts":{"loadedBytes":24265359360,"routing":{"experts":128,"selected":8}},"runtimeModelID":"registered_gemma4_26b","schema":"darkbloom_cluster_model_layout_v1","structuralCuts":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]} diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/pairs/m3ultra-m5ultra/expected.json b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/pairs/m3ultra-m5ultra/expected.json index e275189a6c..bdcb4a2f53 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/pairs/m3ultra-m5ultra/expected.json +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Golden/pairs/m3ultra-m5ultra/expected.json @@ -43,9 +43,9 @@ }, "gemma-4-26b": { "cut": 15, - "handOffPlanSHA256": "2420b14ee7687f033f5a58b7fa9c325ae6121af03b4cd4be0f5f41a016e2c436", + "handOffPlanSHA256": "6dbd01083d074d1aa44f08f1d25603e93145492395501e6f9a1f6c1766247a00", "mode": "pipeline_v1", - "planSHA256": "ad764d50791a75f5c9c1a9f407276e1c717fb6f5e6847e8ea82380f5b0cdbf79", + "planSHA256": "dbc808e3abc53b12d32170bdbb964cbc478e129050f06b0d843a8880a164d5d5", "ranks": [ { "device": "mac-a", @@ -64,9 +64,9 @@ }, "gemma-4-26b-8bit": { "cut": 15, - "handOffPlanSHA256": "cbaef9455f5c272fe17a847a206a173ce94c84f9c5ebadde7a9b0f43f1ebc6e5", + "handOffPlanSHA256": "9608c7ee6e2b22cb943a557b68cf734c22c6ecc4f93a07f8a0b26104cc191cb3", "mode": "pipeline_v1", - "planSHA256": "042a04d32603765619f97b7044c24c9d846a4bde9e741830d39648504c73ad27", + "planSHA256": "4edd4f8c73fb0e0eadb07f432ffc2644c42212b7c53aa29a041482e6fad7a625", "ranks": [ { "device": "mac-a", @@ -85,9 +85,9 @@ }, "gemma-4-26b-qat-4bit": { "cut": 15, - "handOffPlanSHA256": "ea678c6cf760925bd0ac3ec68359692b856dee2e6f67a0ee51d25fb3fe52abdb", + "handOffPlanSHA256": "db53aeb719616838b61b304b734aaaa284fac2ba3b18ccbc6b9063604f2cf1b4", "mode": "pipeline_v1", - "planSHA256": "b4c956fee4903ca1e6c6a81b54d0409d531ec446b12dd644ff0690734455ff6c", + "planSHA256": "c5b174e249c69c9f7eacef02029a1c80125dc7fa9e7832e60fa96c2d44571ccb", "ranks": [ { "device": "mac-a", diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/Main.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/Main.swift index 1c51a219b2..71af6d3349 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/Main.swift +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/Main.swift @@ -63,6 +63,7 @@ import Foundation try checkForcedMode(inputs, checks) try checkAutoChoice(inputs, golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks) try checkGLMTensorParallel(golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks) + try checkGemmaRoutedExperts(golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks) try checkServedModes(golden: URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks) try checkPipelineSpeculativeHolding(URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks) try checkQwenPipelineSpeculative(URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true), checks) From a3d7407608c94f987b592e78b23376eeaf015b57 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:39:13 -0700 Subject: [PATCH 0026/1441] Serve four lanes by default on serial-prefill Gemma 4 pipelines Coordinator-registered Gemma pipeline pairs served one request at a time: nothing on the native-member path sets a width, and every pipeline lane adapter defaulted to one. DistributedInstalledPlan.defaultBatchLanes now gives a text-only Gemma 4 pipeline whose saved setup prefills serially gemma4PipelineBatchLanes (4), following GLM tensor parallel's installed default: - decode rows keep their one-request arithmetic (Gemma4BatchDecodeScope, bound by Gemma4BatchArithmeticAgreement), and each prompt frame runs alone on its request's chunk grid; - each lane is charged its whole request state on every rank and admitted against live memory (reserveLane); a lane that does not fit is refused alone, retryably; - paged KV reserves pages per request, so the width allocates nothing at load, and the activation floor is unchanged (one prompt frame per step). Lanes prefill serially, so a setup saved with one_chunk_lookahead_v1 keeps its schedule and one lane. A planned batch width already requires serial prefill. Every other adapter, a saved width and the owner's DARKBLOOM_CLUSTER_BATCH_LANES behave as before. Tests: DistributedInstalledLanesTests (all adapters and schedules), DistributedInstalledCancellationTests, ClusterPairSlotOwnerLanesTests and DistributedAutomaticBatchPlannerTests (34 tests). ClusterInstalledSessionChecks check a Gemma fixture's default reaching the rank and a lookahead fixture keeping one lane. Not validated: multi-lane joining, cancellation and output agreement on the real pair. Raising the default is an owner decision after those runs. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-pipeline-speed.md | 1 + docs/architecture/hardware-support.md | 6 +++ docs/architecture/inference.md | 33 ++++++++++++++-- docs/developer/test.md | 7 +++- docs/provider/two-mac-cluster.md | 5 ++- .../Installed/DistributedInstalledPlan.swift | 38 ++++++++++++++----- .../InstalledBatchLanesCheck.swift | 17 +++++++++ .../InstalledFixture.swift | 4 +- .../InstalledSessionCheck.swift | 4 +- .../DistributedInstalledLanesTests.swift | 26 +++++++++++++ 10 files changed, 124 insertions(+), 17 deletions(-) diff --git a/changelog.d/gemma-pipeline-speed.md b/changelog.d/gemma-pipeline-speed.md index 91c723ecb1..156ce1d906 100644 --- a/changelog.d/gemma-pipeline-speed.md +++ b/changelog.d/gemma-pipeline-speed.md @@ -1,4 +1,5 @@ ### Faster Gemma 4 pipeline pairs - Gemma 4 pipeline stages compute a prompt chunk's expert blocks in one shared dispatch per operation instead of one subgraph per prompt token, with the same bytes for every token (unchanged arithmetic receipt). Batch-decode rows share the same dispatch. On one synthetic expert layer this cut a 2,048-token chunk from about 350 ms to about 37 ms; pair throughput is not yet measured. +- A Gemma 4 pipeline pair whose setup prefills serially, coordinator-registered pairs included, now serves four requests at once. Each lane is admitted against live memory on both Macs. A pair planned with the one-chunk lookahead keeps serving one request at a time. - The planner's hardware prior counts 8 of Gemma 4's 128 experts per token instead of every expert byte. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 4340fa6664..0dcd9d98ce 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1124,6 +1124,12 @@ throughput. Keep existing cross-chip failures and require fresh full-artifact numerical and timing evidence for both scoped prompt policies. Attention and full-model composition retain their independent qualification requirements. +A serial-prefill Gemma 4 pipeline serves four lanes by default +([Gemma pipeline lanes](inference.md#gemma-pipeline-lanes)). Each lane is +charged its whole request state on every rank and admitted against live +memory. The measured activation floor still applies: prompt frames run one at +a time and decode rows add only M=1 work. + ### Additional TP resident allocations TP layouts may carry allocator-bounded resident allocations outside their text diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 511a20992f..6bf40eb455 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -123,7 +123,9 @@ never negative), `rankN_weights_bytes`, `rankN_fit` and `rankN_device`. Existing per-request admission and LOAD safeguards remain authoritative. GLM, private-image and coordinator-installed native-member sessions do not use this -automatic policy. Explicit diagnostic mode or lane settings retain their choice. +automatic policy; a serial-prefill Gemma 4 pipeline serves its installed +default lanes instead ([Gemma pipeline lanes](#gemma-pipeline-lanes)). +Explicit diagnostic mode or lane settings retain their choice. Automatic replacement reads the installed plan helper's device profile and the current pair's recorded keyed-link costs and served-request history. It uses @@ -3042,7 +3044,8 @@ step boundaries; a lane without its answer cannot run another forward. The leader still exchanges headers and replies when no lane can advance, with `role.none` and no model work. This lets the follower admit a joining request while the provider's synchronous reservation is holding the queue needed to -answer an older token. The installed lane default stays one; multi-lane +answer an older token. The installed lane default stays one (a serial-prefill +Gemma 4 pipeline serves [four](#gemma-pipeline-lanes)); multi-lane sampling, joining and native output equivalence require separate qualification (`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Batch/QwenBatchDecisionProgress.swift`, `QwenResidentRuntime.leadBatch`). @@ -3093,7 +3096,8 @@ the worker's pending acknowledgment Native, installed-owner and qualification gates enable independent retirement only for the existing Qwen-family lane adapters in plain pipeline with 2...8 -lanes (installed image candidates are excluded). The default stays one. Other +lanes (installed image candidates are excluded). The default stays one, except +for a serial-prefill Gemma 4 pipeline ([Gemma pipeline lanes](#gemma-pipeline-lanes)). Other modes retain their existing failure policy, and GLM tensor-parallel retirement and its eight-lane default are unchanged. A cancellation racing an already finishing lane retains the existing clean-finish linearization: native state @@ -4498,6 +4502,29 @@ and leaving/rejoining rows. Their CPU checks require identical native logits and all live KV values. This is not full-artifact GPU, pair or throughput qualification; those checks remain required. +### Gemma pipeline lanes + +A Gemma 4 pipeline whose saved setup prefills serially serves +`DistributedInstalledPlan.gemma4PipelineBatchLanes` (4) requests at once, +coordinator-registered pairs included. Every other pipeline lane adapter keeps +the default of one (`DistributedInstalledPlan.defaultBatchLanes`). A saved +width or the owner's `DARKBLOOM_CLUSTER_BATCH_LANES` still overrides the +default. + +| Property | Basis | +|---|---| +| A lane costs no request its own tokens | Decode rows keep their one-request arithmetic ([batch decode](#gemma-ordinary-batch-decode-arithmetic)); each prompt frame runs alone on its request's own chunk grid (`QwenBatchSettings`) | +| Memory | Each lane is charged its whole request state on every rank and admitted against live memory (`QwenResidentRuntime.reserveLane`); a lane the host cannot hold is refused alone, retryably | +| No load-time allocation | The paged pool reserves pages per request, not per lane (`CBv2StageKVHost`) | +| Activation floor | Unchanged: one prompt frame runs per step, and decode rows add only M=1 work | +| Cancellation | A cancelled lane retires alone (`DistributedInstalledPlan.lanesRetireAlone`) | +| One-chunk lookahead | Lanes prefill serially, so a setup that saved `one_chunk_lookahead_v1` keeps its schedule and one lane, as a planned batch width requires serial prefill (`ClusterConfiguration`) | + +Both owners derive the width from the same saved setup and bind it into the +load agreement (`Gemma4BatchArithmeticAgreement`). The width is not qualified +on hardware: multi-lane joining, cancellation and output agreement on the +real pair remain separate checks, as for every pipeline lane adapter. + ### Gemma routed-expert prior `Gemma4PlacementFamily` states that every layer routes a token to 8 of its 128 diff --git a/docs/developer/test.md b/docs/developer/test.md index 9c6a070660..f65e53f735 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1874,8 +1874,11 @@ with the fixed owner arguments and checks its exact environment, supported lane widths, out-of-range rejection, malformed-override parity even with an eight-lane family default, admission/owner/native parity, unsupported mode and image gates, and both member ranks. No model, GPU or real service is -started. The checks preserve the singleton and GLM tensor-parallel defaults; -actual multi-lane output, encrypted transport and retirement still require +started. The checks preserve the singleton and GLM tensor-parallel defaults +and the serial-prefill Gemma 4 pipeline's four default lanes, which reach the +rank, while a Gemma setup saved with the one-chunk lookahead keeps one lane; +`DistributedInstalledLanesTests` covers the same rules for every adapter and +schedule. Actual multi-lane output, encrypted transport and retirement still require qualification on both Macs. The same real-child checks pass canonical local `MLX_METAL_FAST_SYNCH=0|1` choices through the owner and final native launch, reject free-text spellings from forwarding, preserve unrelated native guards, diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index d8688b78b8..7bbcbd1c84 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-31 +> Last updated: 2026-11-01 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 @@ -156,6 +156,9 @@ pair's model and split; a release's cluster runtime facts carry them for GLM-5.3-Flash and Qwen3.8-27B ([serving a pair](../reference/cluster-control-protocol.md#serving-a-pair)). A tensor-parallel pair registers like a pipeline one; its plan names no cut. +A Gemma 4 pipeline pair whose plan prefills serially takes four requests at +once; one planned with the one-chunk lookahead takes one at a time +([Gemma pipeline lanes](../architecture/inference.md#gemma-pipeline-lanes)). 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 diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift index 6369d1c732..a417011024 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift @@ -264,8 +264,9 @@ struct DistributedInstalledPlan: Sendable { "DARKBLOOM_CLUSTER_LOAD_DIGESTS": ["1", "tensors"], ] - /// The pair's batch lanes: the adapter's default in the selected mode - /// (`defaultBatchLanes(adapter:mode:hasPrivateImages:)`), unless the owner's + /// The pair's batch lanes: the adapter's default in the selected mode and + /// prefill schedule (`defaultBatchLanes(adapter:mode:hasPrivateImages:runtimeModelID:prefillSchedule:)`), + /// unless the setup saved a priced width or the owner's /// environment names 1...8 (1 serves one request at a time). A malformed /// override explicitly keeps one lane, so a sanitized child cannot restore /// a wider family default. Nil where the @@ -277,7 +278,8 @@ struct DistributedInstalledPlan: Sendable { func batchLanes(_ environment: [String: String] = ProcessInfo.processInfo.environment) -> Int? { guard let adapter = ClusterRuntimeAdapter(rawValue: capability.adapterID), let lanes = Self.defaultBatchLanes(adapter: adapter, mode: configuration.selectedGenerationMode, - hasPrivateImages: capability.hasPrivateImages, runtimeModelID: capability.runtimeModelID) else { + hasPrivateImages: capability.hasPrivateImages, runtimeModelID: capability.runtimeModelID, + prefillSchedule: configuration.selectedPrefillSchedule) else { return nil } // The assistant quote admits exactly this capacity. A diagnostic @@ -313,7 +315,10 @@ struct DistributedInstalledPlan: Sendable { /// The lanes a pair of `adapter` serves by default in `mode`, or nil when /// its workers serve one request at a time there. /// - Pipeline: the lane adapters (`laneAdapters`), text only, at - /// `defaultBatchLanes`. + /// `defaultBatchLanes`; Gemma 4 with serial prefill at + /// `gemma4PipelineBatchLanes`. Lanes prefill serially, so a setup that + /// saved the one-chunk lookahead keeps it and one lane. A nil schedule + /// names no setup and takes the family-neutral default. /// - Qwen tensor parallel (every registered TP row, dense or routed /// experts): one by default; a priced saved width or explicit local /// diagnostic may select its native 2...8 lane owner. @@ -324,8 +329,11 @@ struct DistributedInstalledPlan: Sendable { /// path as a request alone (`GLM5NextTensorParallelMedia`), so the /// capability's image candidate does not change the lanes. static func defaultBatchLanes(adapter: ClusterRuntimeAdapter, mode: ClusterGenerationMode, - hasPrivateImages: Bool, runtimeModelID: String? = nil) -> Int? { + hasPrivateImages: Bool, runtimeModelID: String? = nil, + prefillSchedule: ClusterPrefillSchedule? = nil) -> Int? { switch mode { + case .pipeline where !hasPrivateImages && adapter == .gemma4LayerStage && prefillSchedule == .serial: + gemma4PipelineBatchLanes case .pipeline where !hasPrivateImages && laneAdapters.contains(adapter): defaultBatchLanes case .tensorParallel where tensorParallelLaneAdapters.contains(adapter): tensorParallelBatchLanes case .tensorParallel where servesQwenTensorLanes(adapter: adapter, runtimeModelID: runtimeModelID) && !hasPrivateImages: @@ -343,11 +351,23 @@ struct DistributedInstalledPlan: Sendable { /// Concurrent requests a lane-serving pair batches by default. Both /// owners serve them (`ClusterOwnerLeaseState.lanes`), and the leader's /// session, bridge and local API admit as many; more requests wait in the - /// API's queue. The default stays one while the repaired joining and - /// cancellation paths undergo model-specific multi-lane qualification. - /// Earlier pair measurements (Qwen 3.5 35B A3B, 2026-10-19) preceded - /// those repairs and do not qualify the current loop. + /// API's queue. The default stays one (Gemma 4's serial pipeline aside) + /// while the repaired joining and cancellation paths undergo + /// model-specific multi-lane qualification. Earlier pair measurements + /// (Qwen 3.5 35B A3B, 2026-10-19) preceded those repairs and do not + /// qualify the current loop. static let defaultBatchLanes = 1 + /// Concurrent requests a serial-prefill Gemma 4 pipeline serves by + /// default, coordinator-registered pairs included. Each decode row keeps + /// its one-request arithmetic (`Gemma4BatchDecodeScope`, bound by + /// `Gemma4BatchArithmeticAgreement`) and each prompt frame runs alone on + /// its request's own chunk grid, so a lane costs no request its own + /// tokens. Each lane is charged its whole request state on every rank + /// and admitted against live memory; a lane the host cannot hold is + /// refused alone, retryably. Paged KV reserves pages per request, not per + /// lane, so the width adds no load-time allocation. Four of the priced + /// pipeline widths (2, 4, 8) until the pair measures more. + static let gemma4PipelineBatchLanes = 4 /// Concurrent requests GLM tensor parallel serves by default: the /// protocol's lane cap (`ClusterWorkerLaneSession`, `ClusterWorkerPair`). /// Its lanes run one request's unit after another (each bitwise alone), so diff --git a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledBatchLanesCheck.swift b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledBatchLanesCheck.swift index 41956de4b2..ce784144a1 100644 --- a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledBatchLanesCheck.swift +++ b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledBatchLanesCheck.swift @@ -201,6 +201,23 @@ extension InstalledSessionCheck { registered: ("registered_gemma4_26b_qat_4bit", "registered_gemma4_26b_qat_4bit_greedy_generation_v1", "fixture/gemma"), adapter: .gemma4LayerStage) let gemmaPrepared = try gemma.prepare() + // A serial-prefill Gemma pipeline, coordinator-registered or not, serves its four default lanes. + try require(gemmaPrepared.plan.configuration.selectedPrefillSchedule == .serial + && gemmaPrepared.plan.batchLanes([:]) == DistributedInstalledPlan.gemma4PipelineBatchLanes + && gemmaPrepared.plan.lanesRetireAlone([:]), "Gemma serial pipeline default lanes differ") + let gemmaDefault = gemmaPrepared.plan.nativeEnvironment(matrix: gemmaPrepared.matrixURL, + ownerEnvironment: try observed(gemmaPrepared.plan.localOwnerConfiguration(ownerEnvironment: [:]))) + try require(gemmaDefault[key] == String(DistributedInstalledPlan.gemma4PipelineBatchLanes), + "Gemma default lanes did not reach the rank") + // A saved one-chunk lookahead keeps its schedule: lanes prefill serially, so it keeps one lane. + let lookahead = try InstalledFixture.make(root: f.root.appendingPathComponent("lane-gemma-lookahead"), + probe: f.probe, owner: probe, worker: f.worker, + registered: ("registered_gemma4_26b_qat_4bit", "registered_gemma4_26b_qat_4bit_greedy_generation_v1", "fixture/gemma"), + adapter: .gemma4LayerStage, prefillSchedule: .oneChunkLookahead) + let lookaheadPlan = try lookahead.prepare().plan + try require(lookaheadPlan.configuration.selectedPrefillSchedule == .oneChunkLookahead + && lookaheadPlan.batchLanes([:]) == 1 && !lookaheadPlan.lanesRetireAlone([:]), + "Gemma lookahead pipeline gained default lanes") for lanes in [1, 2, 4, 8] { let child = try observed(gemmaPrepared.plan.localOwnerConfiguration(ownerEnvironment: [key: String(lanes)])) let native = gemmaPrepared.plan.nativeEnvironment(matrix: gemmaPrepared.matrixURL, ownerEnvironment: child) diff --git a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift index 37e14e873a..af24383ab6 100644 --- a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift +++ b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift @@ -22,7 +22,7 @@ struct InstalledFixture: Sendable { registered: (model: String, profile: String, publicID: String) = ("registered_qwen35_9b", "registered_qwen35_9b_greedy_generation_v1", "fixture/public-model"), adapter: ClusterRuntimeAdapter = .qwen35Dense, standsForRegisteredArtifact: Bool = true, - batchLanes: Int? = nil) throws -> Self { + batchLanes: Int? = nil, prefillSchedule: ClusterPrefillSchedule? = nil) throws -> Self { try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) let model = root.appendingPathComponent("model", isDirectory: true) try FileManager.default.createDirectory(at: model, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) @@ -58,6 +58,7 @@ struct InstalledFixture: Sendable { .init(rank:0,sourceLayerStart:0,sourceLayerEnd:4,stagePlanSHA256:pin("1"),constructionConfigurationSHA256:pin("2")), .init(rank:1,sourceLayerStart:4,sourceLayerEnd:32,stagePlanSHA256:pin("3"),constructionConfigurationSHA256:pin("4"))])], arithmeticPolicyID:adapter.arithmeticPolicyID,arithmeticPolicySHA256:pin("5"), + supportedPrefillSchedules:prefillSchedule == nil ? [.serial] : ClusterPrefillSchedule.allCases, supportedGenerationModes:advertisedModes) let capBytes = try ClusterRuntimeCapabilityCodec.encode(cap), capHash = hash(capBytes) try capBytes.write(to: model.appendingPathComponent("fixture-capability.json")) @@ -76,6 +77,7 @@ struct InstalledFixture: Sendable { "tokenizerFiles":named.filter{$0.1 != "config"}.map{["path":$0.0,"sha256":hash($0.2),"purpose":$0.1 == "template" ? "chatTemplate":"tokenizer"]}] if let generationMode { object["generationMode"]=generationMode } if let batchLanes { object["batchLanes"] = batchLanes } + if let prefillSchedule { object["prefillSchedule"] = prefillSchedule.rawValue } if pairing { let approval:[String:Any]=["id":"installed-fixture-approval","model":"fixture/public-model","generation":1, "plan_sha256":pin("f"),"artifact_sha256":artifact,"native_runtime_sha256":binary,"metallib_sha256":pin("6"), diff --git a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift index 5c90dfd238..60a9c05081 100644 --- a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift +++ b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift @@ -981,7 +981,9 @@ final class EndpointBox: @unchecked Sendable { /// values every rank is given (the pair driver's own values), under budgets /// derived from the setup; GPT-OSS and Gemma 4 included. static func adaptersOnTheInstalledPath(_ f:InstalledFixture) throws { - let gemma=["MLX_GATHER_QMM_EXPERT_SLICES":"trust","MLX_GEMMA4_FUSED_WEIGHTED_UNSORT":"1"] + // A serial-prefill Gemma pipeline also names its default lanes. + let gemma=["MLX_GATHER_QMM_EXPERT_SLICES":"trust","MLX_GEMMA4_FUSED_WEIGHTED_UNSORT":"1", + DistributedInstalledPlan.batchLanesSwitch:String(DistributedInstalledPlan.gemma4PipelineBatchLanes)] let cases:[(String,ClusterRuntimeAdapter,String,[String:String],String?)]=[ ("a35",.qwen35RoutedExperts,"registered_qwen35_35b_a3b",["MLX_GATHER_QMM_EXPERT_SLICES":"trust"],"phase_split_v1"), ("a36",.qwen35RoutedExperts,"registered_qwen36_35b_a3b",["MLX_GATHER_QMM_EXPERT_SLICES":"trust"],"phase_split_v1"), diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedInstalledLanesTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedInstalledLanesTests.swift index db85eb8163..1ae33e2183 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedInstalledLanesTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedInstalledLanesTests.swift @@ -33,6 +33,32 @@ struct DistributedInstalledLanesTests { } } + @Test func gemmaSerialPipelineServesFourLanesAndLookaheadKeepsOne() { + #expect(Plan.gemma4PipelineBatchLanes == 4) + #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: false, + prefillSchedule: .serial) == 4) + // Lanes prefill serially: a saved lookahead keeps its schedule and one lane. + #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: false, + prefillSchedule: .oneChunkLookahead) == Plan.defaultBatchLanes) + #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: false) == Plan.defaultBatchLanes) + #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: true, + prefillSchedule: .serial) == nil) + for mode in ClusterGenerationMode.allCases where mode != .pipeline { + #expect(Plan.defaultBatchLanes(adapter: .gemma4LayerStage, mode: mode, hasPrivateImages: false, + prefillSchedule: .serial) == nil) + } + // Every other lane adapter keeps its singleton default under either schedule. + for adapter in Plan.laneAdapters where adapter != .gemma4LayerStage { + for schedule in ClusterPrefillSchedule.allCases { + #expect(Plan.defaultBatchLanes(adapter: adapter, mode: .pipeline, hasPrivateImages: false, + prefillSchedule: schedule) == Plan.defaultBatchLanes) + } + } + // A cancelled Gemma lane retires alone, as every pipeline lane adapter's does. + #expect(Plan.lanesRetireAlone(adapter: .gemma4LayerStage, mode: .pipeline, hasPrivateImages: false, + lanes: Plan.gemma4PipelineBatchLanes)) + } + @Test func otherModesAndFamiliesKeepTheirLanes() { // GLM's pipeline still serves one request at a time. #expect(Plan.defaultBatchLanes(adapter: .glm5NextLayerStage, mode: .pipeline, hasPrivateImages: false) == nil) From 562eaf89aa3c578995818af3f18e49f2ea8eb02f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:52:05 -0700 Subject: [PATCH 0027/1441] Group Gemma's shared expert rows by expert for weight locality Bumps libs/mlx-swift-lm to 211512fd (feat/gemma4-batched-prompt-experts). The shared expert call now groups a frame's assignments by expert, so consecutive threadgroups read the same weights. It still does not give the gathers the sorted hint, so every pair stays an M=1 gather_qmv product, and the rows return to token order before the unchanged reduction. Each token's bytes and the receipt are unchanged. Evidence: GPU equality at the production kernel classes and at production geometry; Gemma4PrefillExpertTests, Gemma4BatchDecodeTests, Gemma4BatchArithmeticAgreementTests and GemmaPrefillArithmeticTests (CPU, 9 tests); and Gemma4StagePagedSyntheticTests (GPU, lanes join and leave). On a synthetic production-geometry expert layer (4-bit, 2,048 tokens) the shared call went 37.2 -> 30.8 ms; the per-token graph took 414.3 ms in the same run. The report and docs say so. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-pipeline-speed.md | 2 +- docs/architecture/hardware-support.md | 4 +- docs/architecture/inference.md | 14 ++++--- docs/developer/test.md | 7 ++-- ...026-11-01-gemma-pipeline-prompt-experts.md | 41 ++++++++++++------- docs/reports/README.md | 2 +- libs/mlx-swift-lm | 2 +- 7 files changed, 43 insertions(+), 29 deletions(-) diff --git a/changelog.d/gemma-pipeline-speed.md b/changelog.d/gemma-pipeline-speed.md index 156ce1d906..171b5279d8 100644 --- a/changelog.d/gemma-pipeline-speed.md +++ b/changelog.d/gemma-pipeline-speed.md @@ -1,5 +1,5 @@ ### Faster Gemma 4 pipeline pairs -- Gemma 4 pipeline stages compute a prompt chunk's expert blocks in one shared dispatch per operation instead of one subgraph per prompt token, with the same bytes for every token (unchanged arithmetic receipt). Batch-decode rows share the same dispatch. On one synthetic expert layer this cut a 2,048-token chunk from about 350 ms to about 37 ms; pair throughput is not yet measured. +- Gemma 4 pipeline stages compute a prompt chunk's expert blocks in one shared dispatch per operation instead of one subgraph per prompt token, with the same bytes for every token (unchanged arithmetic receipt). Batch-decode rows share the same dispatch. On one synthetic expert layer this cut a 2,048-token chunk from about 370 ms to about 31 ms; pair throughput is not yet measured. - A Gemma 4 pipeline pair whose setup prefills serially, coordinator-registered pairs included, now serves four requests at once. Each lane is admitted against live memory on both Macs. A pair planned with the one-chunk lookahead keeps serving one request at a time. - The planner's hardware prior counts 8 of Gemma 4's 128 experts per token instead of every expert byte. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 0dcd9d98ce..7a599859d6 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1117,8 +1117,8 @@ Registered Gemma prompt projections use an explicit singleton-token reduction policy for supported BF16 affine packing, as described in [inference](inference.md#gemma-prompt-projection-reductions). The exact arithmetic receipt separates older rectangular-projection results and cache identities. -The prompt's expert blocks share one unsorted dispatch per operation and keep -each token's bytes, so the receipt is unchanged. +The prompt's expert blocks share one dispatch per operation and keep each +token's bytes, so the receipt is unchanged. Component tests do not qualify a complete model, both rank orders, or prompt throughput. Keep existing cross-chip failures and require fresh full-artifact numerical and timing evidence for both scoped prompt policies. Attention and diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 6bf40eb455..2f6f79b02d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4479,8 +4479,8 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Meta one-token requests. Ordinary affine 4/8-bit group-64 projections retain native matmul `M=1` through leading weight views; custom and floating modules retain their original per-request forward method. The unscaled value RMS reduction -retains singleton request shapes. The rows' routed experts share one unsorted -call that keeps each row's singleton bytes +retains singleton request shapes. The rows' routed experts share one call +that keeps each row's singleton bytes ([Gemma prompt projection reductions](#gemma-prompt-projection-reductions)). The scope owns no cache, changes no shared MLX dispatcher, and is disabled for singletons, prefill and speculative rectangles. @@ -4903,10 +4903,12 @@ The same explicit prompt scope keeps each BF16 token's complete expert block at one token: its unchanged selected indices and weights, an M=1 gathered product per selected expert, singleton GeGLU and its own top-K weighted reduction, rather than a wide sorted expert graph. All tokens of a frame share -one call (`SwitchGLU.callAndWeightedReduceRows`) that keeps their assignments -unsorted. MLX selects `gather_qmv` from the bits, dtype and the N and K widths -alone, and the top-8 reduction's `col_reduce_small` thread layout depends only -on the hidden width, so each token's bytes equal those of its own one-token +one call (`SwitchGLU.callAndWeightedReduceRows`). It groups their assignments +by expert for weight locality but does not give the gathers the sorted hint, so +every pair keeps the unsorted M=1 route. MLX selects `gather_qmv` from the +bits, dtype and the N and K widths alone. The rows return to token order before +the top-8 reduction, whose `col_reduce_small` thread layout depends only on the +hidden width. Each token's bytes therefore equal those of its own one-token call. The tokens share one dispatch per operation instead of about six per token per layer. Independent decode rows use the same call ([Gemma ordinary batch decode arithmetic](#gemma-ordinary-batch-decode-arithmetic)). diff --git a/docs/developer/test.md b/docs/developer/test.md index f65e53f735..2865718615 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -2226,11 +2226,12 @@ unchanged tied head. `Gemma4PrefillExpertTests` executes the actual Gemma decode shared MLP and sparse expert block with the attention output isolated to zero; it assembles an independent projection/expert oracle from one-token expert calls while preserving the original rectangular normalization and elementwise -operations. It requires one unsorted expert call carrying every token's routes -in order, with the oracle's bytes, at 7 to 512 tokens. A separate expert-only composition +operations. It requires one expert call, never hinted as sorted, carrying every +token's routes (grouped by expert from 64 assignments), with the oracle's +bytes, at 7 to 512 tokens. A separate expert-only composition check compares complete singleton calls with the shared branch isolated to zero, and a decode check requires 2, 3 and 8 independent rows to share one -unsorted call with each row's one-row bytes. Ordinary and verification paths +call with each row's one-row bytes. Ordinary and verification paths remain covered, and the original rectangular call still sorts. These checks do not claim whole-layer singleton equivalence: existing normalization can depend on rectangle shape on CPU. With `GEMMA4_EXPERT_ROWS_GPU=1` the suite also diff --git a/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md b/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md index f40da4abcb..98e55973dd 100644 --- a/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md +++ b/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md @@ -3,7 +3,7 @@ > Last updated: 2026-11-01 This record covers the change to the registered Gemma 4 stages' prompt expert -blocks: they now share one unsorted dispatch per operation instead of building +blocks: they now share one dispatch per operation instead of building one subgraph per prompt token. It gives the equality evidence and synthetic component timings measured on one Mac. It is not a pair, full-model or qualification result, and it contains no prompt, endpoint or machine identifier. @@ -22,13 +22,16 @@ prompt throughput had been measured for it. ## Change `SwitchGLU.callAndWeightedReduceRows` (mlx-swift-lm) projects all rows of a -frame in one call with their expert assignments kept in row order: +frame in one call: -- every (row, expert) pair is still an M=1 gathered product. MLX selects - `gather_qmv` from the bits, dtype and the N and K widths alone, and its grid - gives each row its own threadgroups; -- the top-8 weighted reduction keeps its one-row `col_reduce_small` thread - layout, which depends only on the hidden width. +- it groups 64 or more assignments by expert for weight locality, but does + not give the gathers the sorted hint; +- every (row, expert) pair is therefore still an M=1 gathered product. MLX + selects `gather_qmv` from the bits, dtype and the N and K widths alone, + and its grid gives each pair its own threadgroups; +- the rows return to their order before the top-8 weighted reduction, which + keeps its one-row `col_reduce_small` thread layout. That layout depends + only on the hidden width. Each row therefore keeps the bytes of its own one-row call, and the receipt is unchanged. Gemma's batch-decode rows (`Gemma4BatchDecodeScope`) use the same @@ -38,11 +41,12 @@ call. | Check | Device | Result | |---|---|---| -| `Gemma4PrefillExpertTests`: whole-layer composition against a one-token expert oracle, 7 to 512 tokens, 4 and 8 bits | CPU | bytes equal; one unsorted expert call | +| `Gemma4PrefillExpertTests`: whole-layer composition against a one-token expert oracle, 7 to 512 tokens, 4 and 8 bits | CPU | bytes equal; one expert call, never hinted as sorted | | Same suite: expert branch against per-token layer calls; decode rows 2, 3 and 8 | CPU | bytes equal | | `GEMMA4_EXPERT_ROWS_GPU=1`: hidden 768, width 192, 16 experts (the production kernel classes), 1 to 2,048 rows, 4 and 8 bits | M5 Ultra GPU | bytes equal; values finite and nonzero | | `GEMMA4_EXPERT_ROWS_GPU=production`: hidden 2,816, width 704, 128 experts, 1 to 513 rows | M5 Ultra GPU | bytes equal | | Sensitivity: the shared call against the earlier sorted rectangular call at 512 and 2,048 rows | M5 Ultra GPU | bytes differ, as expected | +| `Gemma4StagePagedSyntheticTests`: two synthetic stages, lanes joining and leaving | M5 Ultra GPU | each request decodes its tokens alone | The suites ran in a debug build of `libs/darkbloom-cluster` with the SDK test file linked in and a source-matched `mlx.metallib` (SHA-256 @@ -59,11 +63,18 @@ One layer with random packed weights at the registered geometry: experts at build, on an M5 Ultra that was also serving other GPU work, so the figures carry contention noise. +One run timed every expert-block variant at the production geometry: + | Expert block, 4-bit | 512 tokens | 2,048 tokens | |---|---:|---:| -| Per-token subgraphs (before) | 74.6 ms | 349.9 ms | -| Shared unsorted dispatch (after) | 9.8 ms | 36.8 ms | -| Sorted rectangle (the prompt path before 2026-10-23) | 1.6 ms | 3.6 ms | +| Per-token subgraphs (before) | 89.5 ms | 414.3 ms | +| Shared dispatch, token order | 9.8 ms | 37.2 ms | +| Shared dispatch, grouped by expert (after) | 8.2 ms | 30.8 ms | +| Sorted rectangle (the prompt path before 2026-10-23) | 1.9 ms | 3.8 ms | + +A rerun of the final code measured 8.2 and 30.6 ms against 79.5 and 369.5 ms +for the per-token graph. Every shared-dispatch variant equalled the per-token +bytes. | Dense projections of one sliding layer (q, k, v, o, MLP, router) | 512 tokens | 2,048 tokens | |---|---:|---:| @@ -71,10 +82,10 @@ carry contention noise. | Rectangle | 3.7 ms | 3.7 ms | [INFERENCE] For a 15-layer stage and a 2,048-token frame, the projections took -about 5.7 s before and take about 1.0 s after, ignoring attention and norms. -That would lift the stage's projection-bound prompt rate from about 360 to -about 2,000 tokens per second. The M=1 policy still costs about 9x the -rectangle. Closing that gap needs a multi-row `qmv` kernel that keeps qmv's +about 5.7 to 6.6 s before and take about 0.9 s after, ignoring attention and +norms. That would lift the stage's projection-bound prompt rate from about 310 +to 360 tokens per second to about 2,300. The M=1 policy still costs about 8x +the rectangle. Closing that gap needs a multi-row `qmv` kernel that keeps qmv's per-row reduction order. ## Not established diff --git a/docs/reports/README.md b/docs/reports/README.md index 28707b07fe..5200bb7ed9 100644 --- a/docs/reports/README.md +++ b/docs/reports/README.md @@ -4,7 +4,7 @@ Dated records and raw native evidence retain their original content, revisions and limitations. A record is not a fresh test result or proof of private platform compatibility. -- [Gemma pipeline prompt experts](2026-11-01-gemma-pipeline-prompt-experts.md) - the registered Gemma stages' prompt expert blocks in one shared unsorted dispatch with the same bytes: CPU and M5 Ultra GPU equality evidence and synthetic one-layer timings; no pair or qualification result. +- [Gemma pipeline prompt experts](2026-11-01-gemma-pipeline-prompt-experts.md) - the registered Gemma stages' prompt expert blocks in one shared dispatch with the same bytes: CPU and M5 Ultra GPU equality evidence and synthetic one-layer timings; no pair or qualification result. - [Public cluster models](2026-10-31-public-cluster-models.md) - the owner's declaration of GLM-5.3-Flash and Qwen3.8-27B for public cluster traffic in pipeline and tensor parallel, the checks it rests on and why releases carry pair-serving grants; the evidence document of `ClusterPublicModels`. - [Mixed-step prefill geometry](2026-10-21-mixed-step-prefill-geometry.md) - load, engine, inter-token latency and KV-subtracted activation measurements behind Gemma 4's 2,048 / 4,096 prompt geometry, its media ceiling and the GPT-OSS and dense Qwen opt-in. - [GLM-5.3-Flash single-Mac qualification record](2026-10-21-glm53-flash-single-mac-qualification.md) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index ef43498b90..211512fdc9 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit ef43498b90ec6b395ac4d41b7149ac383ad22c5a +Subproject commit 211512fdc98bce9c41177866b9151c741473c23e From ad496c28791e0b5f01b66e27932408ba12f7fad8 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:57:22 -0700 Subject: [PATCH 0028/1441] cluster: Gemma 4 tensor-parallel plan, shards and oracles The foundation of two-rank tensor parallel for gemma-4-26b-qat-4bit and gemma-4-26b-8bit. Nothing serves it yet: the Gemma adapter still advertises only the pipeline, and no placement family states its facts. - Gemma4TensorParallelPlan (gemma4_heads_and_expert_channels_v1, Foundation only) cuts every stored text tensor of both registered artifacts. Attention splits by query heads with their KV heads (8 query heads, and 4 sliding or 1 full KV head, per rank). The dense MLP and every expert split by channels with equal shares: an odd group count stores the middle group on both ranks, with zero gate/up rows for the other rank's half. Router, norms and embedding are replicated, and the tied head splits by vocabulary halves. Unknown, misaligned, untied-head and vision tensors are refused. - Gemma4TensorParallelModel loads the whole model, the split-sum oracle or one rank's shard, through the SDK hooks of the mlx-swift-lm bump. It generates greedily with per-step top-k logits and log probabilities. - Gemma4TensorParallelSelection: vocabulary-split greedy, keyed Gumbel-max sampling, a top-k log-probability gather and an exact whole-row gather. - Gemma4TensorParallelLocalPair runs both shards in one process. It is the bitwise `simulated` oracle. - darkbloom-cluster-tp-check gemma synthesize|run|compare|allsum compares runs through QualificationComparator. Tests/GemmaTensorParallelOracles/run.sh runs the oracle matrix over the sealed local ring. - Unit tests, and a model-free plan check against the registered QAT 4-bit safetensors headers. - Bumps libs/mlx-swift-lm to feat/gemma4-tensor-parallel (6544d45a5). Validated on one M5 Ultra over loopback, with synthetic weights only: two tp ranks over the sealed ring equal the in-process oracle bit for bit in every variant. Not validated: real weights, JACCL, the real pair and speed. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 58 +- docs/developer/test.md | 41 ++ libs/darkbloom-cluster-worker/Package.swift | 6 +- .../TensorParallelCheck/GemmaCheck.swift | 333 +++++++++++ .../TensorParallelCheck.swift | 6 + .../Tests/GemmaTensorParallelOracles/run.sh | 62 ++ .../Gemma4TensorParallelLocalPair.swift | 90 +++ .../Gemma4TensorParallelModel.swift | 417 +++++++++++++ .../Gemma4TensorParallelPlan.swift | 443 ++++++++++++++ .../Gemma4TensorParallelSelection.swift | 133 +++++ .../Gemma4TensorParallelSplitSum.swift | 172 ++++++ .../Gemma4TensorParallelTests.swift | 565 ++++++++++++++++++ .../GemmaTensorParallelPlanCheck.swift | 94 +++ .../TensorParallelPlanChecks/gemma-run.sh | 14 + libs/mlx-swift-lm | 2 +- 15 files changed, 2432 insertions(+), 4 deletions(-) create mode 100644 libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift create mode 100755 libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLocalPair.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelModel.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPlan.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSelection.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSplitSum.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelTests.swift create mode 100644 libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/GemmaTensorParallelPlanCheck.swift create mode 100755 libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/gemma-run.sh diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..5c71e84546 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4027,10 +4027,66 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Reside `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPlan.swift`, `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift`, `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift`, -`libs/mlx-swift-lm/Libraries/MLXLMCommon/Qwen35TensorParallelSwitchLinear.swift`, +`libs/mlx-swift-lm/Libraries/MLXLMCommon/TensorParallelSwitchLinear.swift` +(`TensorParallelSwitchLinear`, still also named `Qwen35TensorParallelSwitchLinear`), `libs/mlx-swift-lm/Libraries/MLXLLM/Models/Qwen35.swift` (`Qwen35SparseMoeBlock`). See [focused cluster tests](../developer/test.md#focused-qwen35-moe-tensor-parallel-checks). +## Gemma 4 tensor-parallel foundation + +Gemma 4 26B A4B (`gemma-4-26b-qat-4bit`, `gemma-4-26b-8bit`) has a two-rank +tensor-parallel plan, SDK hooks and one-Mac oracles. Nothing serves it yet: +`Gemma4ResidentAdapterDefinition` still advertises only the pipeline, and no +placement family states tensor-parallel facts. + +`Gemma4TensorParallelPlan` (`gemma4_heads_and_expert_channels_v1`) gives every +stored text tensor of both registered artifacts one cut and refuses unknown, +misaligned, untied-head and vision tensors: + +| Part | Cut per rank | Collective | +|---|---|---| +| `q_proj`, `k_proj`, sliding `v_proj` | Rows of 8 query heads and their KV heads (4 sliding, 1 full); full layers keep K=V | — | +| `o_proj` | Input columns of those heads | FP32 partial summed before `post_attention_layernorm` | +| Dense MLP (2,112 = 33 groups) and every expert (704 = 11 groups) | Gate/up rows of half the channels; down input columns widened to whole groups | One packed collective per layer: every selected expert's FP32 row and the dense row, each summed before rounding, router weighting and its branch's post-norm | +| Router, norms, `layer_scalar`, embedding | Replicated | — | +| Tied head | This rank's half of the vocabulary rows (views of the embedding) | One per selection | + +An odd group count cannot split evenly, so both ranks store the middle group. +Each rank's gate and up projections carry zero rows (zero words, scales and +offsets) for the other rank's half of that group. Those channels are exactly +zero, the shared down columns add nothing on the rank that does not own them, +and both ranks hold 1,088 dense and 384 expert channels: equal shares. +A layer issues two collectives and a decode step 61. + +`Gemma4TensorShard` builds each rank from the SDK's own modules with half the +heads and the local widths. `Gemma4TextModel.installTensorParallel` then sets +three things: the `o_proj` sum, the packed feed-forward +(`TensorParallelSwitchLinear.carrying`, generalized from Qwen's), and the +vocabulary-split head. A model without it runs the unchanged single-Mac path. +`Gemma4TensorParallelSelection` chooses across ranks: + +- greedy: a two-value argmax collective; +- keyed sampling: the whole row's Gumbel-max token under a shared key, through the same collective; +- top-k logits and log probabilities: one gather of each rank's top-k and log-sum-exp; +- the whole row: `-0` padding, every bit kept, so the product's sampler draws the single-Mac token on every rank. + +Oracles run on synthetic checkpoints with the 26B's structure scaled down: + +- `simulated`: both real shards in one process, summing FP32 partials. Two + ranks over the sealed loopback ring equal it bit for bit. +- `split-sum`: the whole model with each row-parallel projection replaced by + two FP32 partials. It is the decomposition's oracle, bitwise equal to the + ranks on the CPU. On an M5 Ultra GPU, a 1,024-row full-attention `k_proj` at + prefill width rounds some rows unlike its 512-row half. + +Code map: + +- `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/` +- `libs/mlx-swift-lm/Libraries/MLXLLM/Models/Gemma4TensorParallel.swift` +- `libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift` + +See [focused Gemma 4 tensor-parallel checks](../developer/test.md#focused-gemma-4-tensor-parallel-checks). + ## Exact-quote placement `ClusterPlacementPlanner.rankQuoted` is the model-independent decision seam for adapters that provide exact simultaneous native/host peaks and current bounds. It filters infeasible shapes and unsupported modes, then uses the same hardware-only ordering as `plan`: candidates whose every range fits its Mac's hardware (`ClusterDeviceProfile.hardwareFits`: buffer and allocator limits, need within the GPU working set and the at-rest admissible memory `atRestAdmissibleBytes`), then predicted request time, ties and the tensor-parallel margin. Live free memory and file cache never order candidates; each rank's live fit is reported and the load gate still decides each load. A supported TP adapter must supply TP layout facts and keyed reduction measurements. Neither resource balance nor chip-name rules replace request-time scoring; balance only breaks ties. Candidates whose predicted times differ only by rounding (relative 1e-9, as every serial pipeline cut does on identical Macs) are ordered by `capacityBalance`, the smallest share of a rank's hardware capacity (`min(residentCapacityBytes, atRestAdmissibleBytes)`) left beyond its need, before the lower cut, so identical Macs split evenly and live free memory cannot pick the cut. Every structural boundary, including one layer on a slower member, remains available when its adapter quotes fit. diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..bdd59d30e5 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1227,6 +1227,47 @@ not load a model or qualify its output. Sources: The [routed-expert TP architecture](../architecture/inference.md#qwen35-routed-expert-tensor-parallel) states the arithmetic descriptor and supported scope. +## Focused Gemma 4 tensor-parallel checks + +These checks use synthetic weights on one Mac, over loopback only. They prove +neither real-weight numerics, a pair qualification nor speed. + +1. Run the model-free plan check (no MLX; it compiles in seconds) and the CPU + unit tests: + + ```bash + bash libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/gemma-run.sh + swift test --package-path libs/darkbloom-cluster --filter Gemma4TensorParallelTests + ``` + + The plan check covers both registered artifacts' text tensors once per rank + and matches their registered text bytes. The unit tests cover: + + - the plan against the registered QAT 4-bit artifact's 1,697 header shapes + (`Tests/StageMetadataChecks/Inputs`), and the 8-bit artifact's derived shapes + and registered text bytes; + - refusals of unknown, misaligned and vision tensors; + - shard parameters against independent slices; + - two in-process ranks against the split-sum oracle, bit for bit; + - the packed feed-forward collective against separate collectives; + - the vocabulary-split head against the whole head. + +2. Build `darkbloom-cluster-tp-check` and put a source-matched `mlx.metallib` + beside it ([build](build.md)). Then run the GPU oracles: + + ```bash + bash libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh \ + /path/to/darkbloom-cluster-tp-check /new/scratch/dir 58123 + ``` + + The script synthesizes five variants: 4- and 8-bit, routed and all-expert, + and FP32. For each, it runs `full`, `split-sum`, `simulated` and two `tp` + ranks over the sealed local ring on ports 58123–58124. + +3. Verify. Each `tp` rank must equal `simulated` bit for bit (exit status 0). + The script also prints QualificationComparator's verdict for each rank + against `full`. + ## Focused Tooling Checks For the PR reviewer, run the seven offline suites listed in diff --git a/libs/darkbloom-cluster-worker/Package.swift b/libs/darkbloom-cluster-worker/Package.swift index 6563915e5e..1911f1c19a 100644 --- a/libs/darkbloom-cluster-worker/Package.swift +++ b/libs/darkbloom-cluster-worker/Package.swift @@ -76,9 +76,11 @@ let package = Package( "DarkbloomClusterQualification", "PairCheckFakeWorker", .product(name: "DarkbloomClusterProtocol", package: "darkbloom-cluster"), ]), - // Tensor parallel for the dense Qwen models: the unsharded reference, the - // single-process oracle and one rank of a two-rank run, plus the comparator. + // Tensor parallel for the Qwen, GLM and Gemma 4 models: the unsharded + // reference, the single-process oracle and one rank of a two-rank run, + // plus the comparators (Gemma's through QualificationComparator). .executableTarget(name: "TensorParallelCheck", dependencies: [ + "DarkbloomClusterQualification", .product(name: "DarkbloomClusterRuntime", package: "darkbloom-cluster"), .product(name: "MLX", package: "mlx-swift"), ]), diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift new file mode 100644 index 0000000000..b6b4830f74 --- /dev/null +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift @@ -0,0 +1,333 @@ +import DarkbloomClusterQualification +import DarkbloomClusterRuntime +import Darwin +import Foundation +import MLX + +// Gemma 4 MoE tensor-parallel oracles (Gemma4TensorParallelModel), greedy: +// +// darkbloom-cluster-tp-check gemma synthesize --output /NEW/DIR [--bits 4|8] [--seed N] [--dtype bfloat16|float32] +// [--experts N --top-k K] +// a tiny random Gemma 4 MoE checkpoint with the 26B's structure and request.json (never a model pass) +// darkbloom-cluster-tp-check gemma run --mode full|split-sum|simulated|shard|tp --model-dir DIR --request FILE --report FILE +// [--record-top K] [--backend ring|socket|jaccl] [--reduction native|sealed-bench] [--shard-rank R] +// [--pack yes|no] [--deadline-seconds S] +// darkbloom-cluster-tp-check gemma compare --reference FILE --candidate FILE [--bitwise yes|no] [--near-tie-ulps U] +// darkbloom-cluster-tp-check gemma allsum [--backend ring|socket|jaccl] [--count N] +// +// `full` is the unsharded model; `simulated` the one-process oracle: both +// ranks' shards in one process, each on its own thread and stream, every +// collective the FP32 sum of both ranks' partials (`tp` must equal it bit for +// bit); `split-sum` the decomposition's oracle: the unsharded model whose +// row-parallel projections add both ranks' FP32 partials (bitwise to `tp` on +// the CPU; on an M5 Ultra GPU a 1,024-row prefill k_proj rounds some rows +// unlike its 512-row half); `shard` one rank's shard with no peer +// (diagnostic: wrong tokens by construction, one chip's share of the +// compute); `tp` one rank of a two-rank run over JACCL (two Macs) or the +// local ring or socket (two processes on one Mac over 127.0.0.1, correctness +// only). `--reduction sealed-bench` seals every floating collective with the +// fork's sealed all-sum (BENCH keys from an unauthenticated ephemeral +// exchange: the sealed path's arithmetic and cost, never a product trust). +// `compare` holds a candidate to a reference with QualificationComparator; +// `--bitwise yes` also requires every token, recorded top logit and log +// probability and the final row to be bit-identical (tp against simulated). +// A report names roles and chips only, never a host, an address or a path. +enum GemmaCheck { + struct Report: Codable { + var schema = "darkbloom_cluster_tp_check_gemma_report_v1" + var mode: String + var role: String + var rank: Int + var size: Int + var backend: String? + var reduction: String? + var correctnessOnly: Bool + var chip: String + var plan: String + var modelConfigurationSHA256: String + var modelID: String + var requestID: String + var promptTokens: Int + var promptTokenIDsSHA256: String + var outputCount: Int + var chunkSize: Int + var packedFeedForward: Bool + var loadSeconds: Double + var loadedParameterBytes: Int + var reductionsPerForward: Int? + var floatingReductions: Int? + var tokenIDs: [Int] + var tokenIDsSHA256: String + var topTokenIDs: [[Int]]? + var topLogits: [[Float]]? + var topLogprobs: [[Float]]? + var finalLogits: [Float]? + var firstTokenSeconds: Double + var decodeSeconds: Double + var ranksAgree: Bool? + var passed: Bool + } + + static func run(_ arguments: [String]) throws { + guard let command = arguments.first else { throw Failure("gemma: synthesize, run, compare or allsum") } + var fields: [String: String] = [:] + var index = 1 + while index < arguments.count { + guard arguments[index].hasPrefix("--"), index + 1 < arguments.count else { + throw Failure("gemma: arguments are --name value pairs") + } + fields[arguments[index]] = arguments[index + 1] + index += 2 + } + switch command { + case "synthesize": try synthesize(fields) + case "run": try runRank(fields) + case "compare": try compare(fields) + case "allsum": try allSum(fields) + default: throw Failure("gemma: synthesize, run, compare or allsum") + } + } + + private static func synthesize(_ fields: [String: String]) throws { + guard let output = fields["--output"], output.hasPrefix("/"), !FileManager.default.fileExists(atPath: output), + let bits = Int(fields["--bits"] ?? "4"), [4, 8].contains(bits), + let seed = UInt64(fields["--seed"] ?? "7"), + let dtypeName = Optional(fields["--dtype"] ?? "bfloat16"), ["bfloat16", "float32"].contains(dtypeName), + let experts = Int(fields["--experts"] ?? "16"), let topK = Int(fields["--top-k"] ?? "4") else { + throw Failure("gemma synthesize needs --output /NEW/DIR [--bits 4|8] [--seed N] [--dtype bfloat16|float32] [--experts N --top-k K]") + } + let directory = URL(fileURLWithPath: output, isDirectory: true) + try Gemma4TensorParallelModel.writeSyntheticCheckpoint(directory: directory, seed: seed, bits: bits, + dtype: dtypeName == "float32" ? .float32 : .bfloat16, experts: experts, topK: topK) + let prompt = (0 ..< 40).map { ($0 * 37 + 11) % 512 } + let request: [String: Any] = ["requestID": "synthetic-gemma4", "modelID": "synthetic-gemma4-moe-tiny-\(bits)bit-\(dtypeName)-e\(experts)k\(topK)", + "promptTokenIDs": prompt, "promptTokenIDsSHA256": tokenDigest(prompt), "outputCount": 24, "chunkSize": 16] + try JSONSerialization.data(withJSONObject: request, options: [.sortedKeys]) + .write(to: directory.appendingPathComponent("request.json")) + note("synthetic Gemma 4 checkpoint (\(bits)-bit) and request written") + } + + private static func runRank(_ fields: [String: String]) throws { + guard let mode = fields["--mode"], ["full", "split-sum", "simulated", "shard", "tp"].contains(mode), + let directory = fields["--model-dir"], let requestPath = fields["--request"], + let reportPath = fields["--report"], !FileManager.default.fileExists(atPath: reportPath), + let recordTop = Int(fields["--record-top"] ?? "8"), (0 ... 64).contains(recordTop), + let shardRank = Int(fields["--shard-rank"] ?? "0"), (0 ... 1).contains(shardRank), + let deadline = Int(fields["--deadline-seconds"] ?? "900"), (30 ... 7200).contains(deadline), + ["native", "sealed-bench"].contains(fields["--reduction"] ?? "native"), + ["yes", "no"].contains(fields["--pack"] ?? "yes") else { + throw Failure("gemma run needs --mode full|split-sum|simulated|shard|tp, --model-dir, --request, a new --report and bounded options") + } + let sealed = (fields["--reduction"] ?? "native") == "sealed-bench" + guard !sealed || mode == "tp" else { throw Failure("--reduction sealed-bench applies to a tp rank only") } + let pack = (fields["--pack"] ?? "yes") == "yes" + try ProcessForcedExit.routeTerminationSignals() + ProcessNativeMemoryRelease.installForForcedExit() + try ProcessDeadline.arm(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + UInt64(deadline) * 1_000_000_000, + status: 124) + let requestData = try Data(contentsOf: URL(fileURLWithPath: requestPath)) + guard requestData.count < 1 << 20 else { throw Failure("request file too large") } + let request = try JSONDecoder().decode(Request.self, from: requestData) + guard tokenDigest(request.promptTokenIDs) == request.promptTokenIDsSHA256, + (1 ... 4096).contains(request.outputCount), (1 ... 4096).contains(request.chunkSize) else { + throw Failure("the request's digest or bounds are wrong") + } + let modelDirectory = URL(fileURLWithPath: directory) + let configurationSHA = sha256Hex(try Data(contentsOf: modelDirectory.appendingPathComponent("config.json"))) + + var group: QwenTensorParallelGroup? + let role: Gemma4TensorParallelModel.Role + let reduction: QwenTensorParallelReduction? + var pair: Gemma4TensorParallelLocalPair? + switch mode { + case "full": role = .full; reduction = nil + case "split-sum": role = .splitSum; reduction = nil + case "simulated": + role = .shard(rank: 0) + pair = Gemma4TensorParallelLocalPair() + reduction = pair!.reduction(rank: 0) + case "shard": + role = .shard(rank: shardRank) + reduction = QwenTensorParallelLocalReduction(rank: shardRank, size: 2) + note("DIAGNOSTIC shard: rank \(shardRank)'s shard with no peer; tokens are not meaningful") + default: + guard let backend = QwenTensorParallelGroup.Backend(rawValue: fields["--backend"] ?? "ring") else { + throw Failure("unknown backend") + } + let g = try QwenTensorParallelGroup(backend: backend) + group = g + role = .shard(rank: g.rank) + reduction = g + note("rank \(g.rank) of \(g.size) over \(backend.rawValue)\(backend.correctnessOnly ? " (correctness only, not a pair timing)" : "")") + // Everything that changes the collectives is agreed before loading. + let workload = "\(configurationSHA)|\(request.promptTokenIDsSHA256)|\(request.outputCount)|\(request.chunkSize)|top=\(recordTop)|pack=\(pack)|sealed=\(sealed)|\(Gemma4TensorParallelPlan.arithmeticAgreementFields.joined(separator: ","))" + guard try g.digestsEqual(fnv(workload)) else { + throw Failure("the ranks disagree on the workload, the model configuration or the arithmetic contract") + } + if sealed { + var scope = Data("darkbloom-tp-sealed-scope-v1|gemma4|".utf8) + scope.append(Data(configurationSHA.utf8)) + let codec = try QwenTensorParallelSealCodec.bench(group: g, scope: scope) + try codec.install() + g.sealed = codec + note("sealed all-sum installed (BENCH keys: unauthenticated ephemeral exchange; cost measurement only)") + } + } + note("loading \(mode == "simulated" ? "both ranks in one process" : role.label)") + let model = try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory, role: role, reduction: reduction, + packFeedForward: pack) + note("loaded in \(String(format: "%.2f", model.loadSeconds)) s, \(model.loadedParameterBytes) parameter bytes") + if let group { guard try group.agree([7]) else { throw Failure("load barrier failed") } } + let generation: Gemma4TensorParallelModel.Generation + var pairAgrees: Bool? + if let pair { + final class Ranks: @unchecked Sendable { let models: [Gemma4TensorParallelModel]; init(_ m: [Gemma4TensorParallelModel]) { models = m } } + let ranks = Ranks([model, try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory, + role: .shard(rank: 1), reduction: pair.reduction(rank: 1), packFeedForward: pack)]) + let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize + let both = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in + try ranks.models[rank].generate(prompt: prompt, outputCount: count, chunk: chunk, recordTop: recordTop) + } + func bits(_ rows: [[Float]]) -> [[UInt32]] { rows.map { $0.map(\.bitPattern) } } + pairAgrees = both[0].tokenIDs == both[1].tokenIDs && bits(both[0].topLogits) == bits(both[1].topLogits) + && bits(both[0].topLogprobs) == bits(both[1].topLogprobs) + && both[0].finalLogits.map { $0.map(\.bitPattern) } == both[1].finalLogits.map { $0.map(\.bitPattern) } + generation = both[0] + } else { + generation = try model.generate(prompt: request.promptTokenIDs, outputCount: request.outputCount, + chunk: request.chunkSize, recordTop: recordTop) + } + var report = Report(mode: mode, role: mode == "simulated" ? "simulated-tp2" : role.label, + rank: group?.rank ?? (mode == "shard" ? shardRank : 0), + size: group?.size ?? (pair == nil ? 1 : 2), backend: group?.backend.rawValue, reduction: sealed ? "sealed-bench" : nil, + correctnessOnly: group.map { $0.backend.correctnessOnly } ?? false, chip: chipName(), + plan: Gemma4TensorParallelPlan.name, modelConfigurationSHA256: configurationSHA, modelID: request.modelID, + requestID: request.requestID, promptTokens: request.promptTokenIDs.count, + promptTokenIDsSHA256: request.promptTokenIDsSHA256, outputCount: request.outputCount, + chunkSize: request.chunkSize, packedFeedForward: pack, loadSeconds: model.loadSeconds, + loadedParameterBytes: model.loadedParameterBytes, + reductionsPerForward: ["full", "split-sum"].contains(mode) ? nil : model.plan.reductionsPerForward, + floatingReductions: group?.floatingReductions, + tokenIDs: generation.tokenIDs, tokenIDsSHA256: tokenDigest(generation.tokenIDs), + topTokenIDs: recordTop > 0 ? generation.topTokenIDs : nil, topLogits: recordTop > 0 ? generation.topLogits : nil, + topLogprobs: recordTop > 0 ? generation.topLogprobs : nil, finalLogits: generation.finalLogits, + firstTokenSeconds: generation.firstTokenSeconds, decodeSeconds: generation.decodeSeconds, + ranksAgree: pairAgrees, passed: pairAgrees ?? true) + if let group { + let evidence = report.tokenIDsSHA256 + "|" + sha256Hex(Data((generation.finalLogits ?? []).flatMap { + withUnsafeBytes(of: $0.bitPattern.littleEndian) { Array($0) } })) + report.ranksAgree = try group.digestsEqual(fnv(evidence)) + report.passed = try group.agree([report.ranksAgree == true ? 1 : 0]) + } + note("tokens \(String(report.tokenIDsSHA256.prefix(16))): \(generation.tokenIDs.prefix(12).map(String.init).joined(separator: " "))…" + + (report.ranksAgree.map { " ranks agree: \($0)" } ?? "")) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .prettyPrinted] + guard FileManager.default.createFile(atPath: reportPath, contents: try encoder.encode(report)) else { + throw Failure("could not write the report") + } + note("report written; passed \(report.passed)") + ProcessForcedExit.finish(status: report.passed ? 0 : 2, reason: "tp-check-gemma-complete") + } + + /// QualificationComparator's verdict for two runs of one request, and + /// with `--bitwise yes` the exact equality of everything recorded. + private static func compare(_ fields: [String: String]) throws { + guard let referencePath = fields["--reference"], let candidatePath = fields["--candidate"], + let nearTie = Float(fields["--near-tie-ulps"] ?? "4"), nearTie >= 0, + ["yes", "no"].contains(fields["--bitwise"] ?? "no") else { + throw Failure("gemma compare needs --reference and --candidate [--bitwise yes|no] [--near-tie-ulps U]") + } + let decoder = JSONDecoder() + let reference = try decoder.decode(Report.self, from: Data(contentsOf: URL(fileURLWithPath: referencePath))) + let candidate = try decoder.decode(Report.self, from: Data(contentsOf: URL(fileURLWithPath: candidatePath))) + let comparison = try QualificationComparator(nearTieULPs: nearTie) + .compare(reference: try subject(reference), candidate: try subject(candidate)) + var lines = [QualificationComparator.render(comparison)] + var passed = [.exact, .tokensEqualLogitsDiffer, .divergedAtNearTie].contains(comparison.verdict) + if fields["--bitwise"] == "yes" { + func bits(_ rows: [[Float]]?) -> [[UInt32]]? { rows.map { $0.map { $0.map(\.bitPattern) } } } + let equal = reference.tokenIDs == candidate.tokenIDs + && bits(reference.topLogits) == bits(candidate.topLogits) + && bits(reference.topLogprobs) == bits(candidate.topLogprobs) + && reference.topTokenIDs == candidate.topTokenIDs + && reference.finalLogits.map { $0.map(\.bitPattern) } == candidate.finalLogits.map { $0.map(\.bitPattern) } + && reference.finalLogits != nil + lines.append("bitwise (tokens, top logits and log probabilities, final row): " + (equal ? "IDENTICAL" : "DIFFER")) + passed = passed && equal + } + lines.append("verdict \(comparison.verdict.rawValue); passed \(passed)") + print(lines.joined(separator: "\n")) + Darwin.exit(passed ? 0 : 3) + } + + /// One report as the comparator reads it: the request's identity (the + /// generation mode recorded, not compared) and its evidence. Each step's + /// near-tie unit is a bfloat16 place: the softcap's input is the head's + /// BF16 projection. + private static func subject(_ report: Report) throws -> QualificationSubject { + let identity: [String: Any] = [ + "modelID": report.modelID, "profileID": "tp-check-gemma", "requestID": report.requestID, + "promptTokenCount": report.promptTokens, "promptTokenIDsSHA256": report.promptTokenIDsSHA256, + "chunkSize": report.chunkSize, "outputCount": report.outputCount, "stopTokenIDs": [Int](), + "stageCut": 0, "prefillSchedule": "serial_v1", "artifactSHA256": report.modelConfigurationSHA256, + "configurationSHA256": report.modelConfigurationSHA256, "planSHA256": sha256Hex(Data(report.plan.utf8)), + "generationMode": report.mode, + ] + let decoded = try JSONDecoder().decode(QualificationIdentity.self, + from: JSONSerialization.data(withJSONObject: identity, options: [.sortedKeys])) + var steps: [QualificationStep]? + if let ids = report.topTokenIDs, let logits = report.topLogits, ids.count == report.tokenIDs.count { + steps = report.tokenIDs.indices.map { index in + QualificationStep(ordinal: index, frameSequence: index, committedTokens: report.promptTokens + index, + tokenID: report.tokenIDs[index], topTokenIDs: ids[index], topLogits: logits[index], + maximumTieCount: 1, rowSHA256: sha256Hex(Data(logits[index].flatMap { + withUnsafeBytes(of: $0.bitPattern.littleEndian) { Array($0) } })), rowDType: "bfloat16") + } + } + var evidence = QualificationEvidence(selectedTokenIDs: report.tokenIDs, finishReason: "length", + completedFrames: nil, committedTokens: report.promptTokens + report.tokenIDs.count, steps: steps) + if let row = report.finalLogits { + let bytes = Data(row.flatMap { withUnsafeBytes(of: $0.bitPattern.littleEndian) { Array($0) } }) + evidence.finalLogits = QualificationFinalLogits(shape: [row.count], dtype: "float32", byteCount: bytes.count, + logicalBytesSHA256: sha256Hex(bytes), values: row) + } + return QualificationSubject(label: "\(report.role) on \(report.chip)", identity: decoded, evidence: evidence) + } + + /// Cross-rank sums at Gemma 4 26B decode and prefill widths (2,816): the + /// attention row, the packed feed-forward rows (top-8 + 1) and a 2,048-token + /// chunk's attention rows, each `count` times, native and sealed. + private static func allSum(_ fields: [String: String]) throws { + guard let backend = QwenTensorParallelGroup.Backend(rawValue: fields["--backend"] ?? "ring"), + let count = Int(fields["--count"] ?? "61"), (1 ... 10_000).contains(count) else { + throw Failure("gemma allsum takes [--backend ring|socket|jaccl] [--count N]") + } + let group = try QwenTensorParallelGroup(backend: backend) + note("rank \(group.rank) of \(group.size) over \(backend.rawValue)\(backend.correctnessOnly ? " (correctness only, not a pair timing)" : "")") + let shapes = [[1, 1, 2816], [1, 9, 2816], [1, 2048, 2816]] + func pass(sealed: Bool) throws { + for shape in shapes { + let value = MLXArray.ones(shape, dtype: .float32) * Float(group.rank + 1) + eval(value) + _ = try group.exchangeIntegers([1]) + let start = DispatchTime.now().uptimeNanoseconds + var chained = value + for _ in 0 ..< count { chained = group.allSum(chained) * 0.5 } + eval(chained) + let each = Double(DispatchTime.now().uptimeNanoseconds - start) / 1e6 / Double(count) + // (1 + 2) / 2 from the first sum on: any other value is a stale or torn read. + let error = abs(chained - 1.5).max().item(Float.self) + note(String(format: "gemma allsum sealed=%d shape=%@ bytes=%d per_sum=%.3f ms max_error=%g", sealed ? 1 : 0, + shape.map(String.init).joined(separator: "x"), shape.reduce(4, *), each, error)) + guard error == 0 else { throw Failure("a cross-rank sum returned a wrong value") } + } + } + try pass(sealed: false) + let codec = try QwenTensorParallelSealCodec.bench(group: group, scope: Data("gemma-tp-allsum".utf8)) + try codec.install() + group.sealed = codec + try pass(sealed: true) + note("gemma allsum passed") + } +} diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift index 23c7fad6aa..ab83c73b1e 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift @@ -22,6 +22,8 @@ import MLX // tensor parallel against one rank without a registered model; never a model pass) // darkbloom-cluster-tp-check record --rank0 FILE --rank1 FILE --reference FILE [--reference FILE] --model-dir DIR // --output FILE [--partials float32|bfloat16] [--near-tie-ulps U] (appends one qualification record line) +// darkbloom-cluster-tp-check glm ... (GLM-5.3-Flash, GLMBench.swift) +// darkbloom-cluster-tp-check gemma ... (Gemma 4 MoE oracles, GemmaCheck.swift) // // `full` is the unsharded model on one Mac (this code path's single-Mac // reference); `simulated` is the single-process tensor-parallel oracle (the @@ -521,6 +523,10 @@ enum CompareCommand { try QwenPrefillBench.run(Array(CommandLine.arguments.dropFirst(2))) return } + if CommandLine.arguments.count > 1, CommandLine.arguments[1] == "gemma" { + try GemmaCheck.run(Array(CommandLine.arguments.dropFirst(2))) + return + } let options = try Options(Array(CommandLine.arguments.dropFirst())) let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys, .prettyPrinted] diff --git a/libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh b/libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh new file mode 100755 index 0000000000..5fd5b4549c --- /dev/null +++ b/libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh @@ -0,0 +1,62 @@ +#!/bin/bash +# Gemma 4 tensor-parallel oracles on synthetic checkpoints, one Mac, loopback +# only (correctness, never a timing or a pair qualification): +# bash libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh TP_CHECK SCRATCH_DIR [PORT] +# TP_CHECK is a built darkbloom-cluster-tp-check with a source-matched +# mlx.metallib beside it; SCRATCH_DIR a new directory; PORT the first of two +# free 127.0.0.1 ports for the local ring (default 58123). +# +# For each synthetic variant: `full`, `split-sum`, `simulated` (both ranks in +# one process), then two `tp` ranks over the sealed local ring. Required: +# each tp rank bitwise equal to `simulated`. Reported: the comparator's +# verdict of each rank against `full`, and `split-sum` against tp. +set -euo pipefail +tp_check="$1" +scratch="$2" +port="${3:-58123}" +if [[ ! -x "$tp_check" || -e "$scratch" ]]; then + echo 'usage: run.sh TP_CHECK NEW_SCRATCH_DIR [PORT]' >&2 + exit 2 +fi +mkdir -p "$scratch" +printf '[["127.0.0.1:%d"],["127.0.0.1:%d"]]' "$port" "$((port + 1))" > "$scratch/hosts.json" +failures=0 +run_variant() { + local name="$1"; shift + local environment="$1"; shift + local dir="$scratch/$name" + nice -n 19 "$tp_check" gemma synthesize --output "$dir" "$@" >/dev/null 2>&1 + for mode in full split-sum simulated; do + env $environment nice -n 19 "$tp_check" gemma run --mode "$mode" --model-dir "$dir" \ + --request "$dir/request.json" --report "$dir/$mode.json" >"$dir/$mode.log" 2>&1 + done + env $environment MLX_RANK=0 MLX_HOSTFILE="$scratch/hosts.json" nice -n 19 "$tp_check" gemma run --mode tp \ + --backend ring --reduction sealed-bench --model-dir "$dir" --request "$dir/request.json" \ + --report "$dir/tp-rank0.json" --deadline-seconds 300 >"$dir/tp-rank0.log" 2>&1 & + local rank0=$! + env $environment MLX_RANK=1 MLX_HOSTFILE="$scratch/hosts.json" nice -n 19 "$tp_check" gemma run --mode tp \ + --backend ring --reduction sealed-bench --model-dir "$dir" --request "$dir/request.json" \ + --report "$dir/tp-rank1.json" --deadline-seconds 300 >"$dir/tp-rank1.log" 2>&1 + wait "$rank0" + for rank in 0 1; do + if "$tp_check" gemma compare --reference "$dir/simulated.json" --candidate "$dir/tp-rank$rank.json" \ + --bitwise yes >"$dir/tp-rank$rank-vs-simulated.txt" 2>&1; then + echo "$name: tp rank $rank == simulated, bitwise" + else + echo "$name: tp rank $rank DIFFERS from simulated"; failures=$((failures + 1)) + fi + "$tp_check" gemma compare --reference "$dir/full.json" --candidate "$dir/tp-rank$rank.json" \ + >"$dir/tp-rank$rank-vs-full.txt" 2>&1 || true + echo "$name: tp rank $rank against full: $(grep '^verdict ' "$dir/tp-rank$rank-vs-full.txt")" + done + "$tp_check" gemma compare --reference "$dir/split-sum.json" --candidate "$dir/tp-rank0.json" --bitwise yes \ + >"$dir/split-sum-vs-tp.txt" 2>&1 || true + echo "$name: split-sum against tp: $(grep -E '^bitwise' "$dir/split-sum-vs-tp.txt")" +} +run_variant w4-routed "" --bits 4 +run_variant w8-routed "" --bits 8 +run_variant w4-all-experts "" --bits 4 --experts 4 --top-k 4 +run_variant w8-all-experts "" --bits 8 --experts 4 --top-k 4 +run_variant w4-routed-fp32 "MLX_ENABLE_TF32=0" --bits 4 --dtype float32 +echo "required tp == simulated failures: $failures" +exit $(( failures == 0 ? 0 : 1 )) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLocalPair.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLocalPair.swift new file mode 100644 index 0000000000..267ce1aed5 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLocalPair.swift @@ -0,0 +1,90 @@ +import Foundation +import MLX + +/// Both ranks of a Gemma 4 tensor-parallel pair in one process: each rank's +/// shard runs on its own thread and MLX stream, and every collective is the +/// elementwise FP32 sum of both ranks' partials, added in rank order (the +/// add of two values is commutative, so it is the sum a two-rank all-sum +/// returns). Every rank-local operation keeps the rank's own shapes and +/// kernels, so a two-process run over a real collective must equal it bit +/// for bit: the oracle for the transport, its sealing and the collective +/// schedule. Each collective evaluates its inputs, so this is an oracle, not +/// a timing. +public final class Gemma4TensorParallelLocalPair: @unchecked Sendable { + private let condition = NSCondition() + private var leaving = 0, step = 0 + private var values: [Int: [Float]] = [:], shapes: [Int: [Int]] = [:] + private var output: [Float] = [] + /// Every collective's payload shape, in order. + public private(set) var payloads: [[Int]] = [] + + public init() {} + + /// Rank `rank`'s reduction. + public func reduction(rank: Int) -> QwenTensorParallelReduction { Rank(rank: rank, pair: self) } + + private final class Rank: QwenTensorParallelReduction, @unchecked Sendable { + let rank: Int, size = 2 + let pair: Gemma4TensorParallelLocalPair + init(rank: Int, pair: Gemma4TensorParallelLocalPair) { self.rank = rank; self.pair = pair } + func allSum(_ value: MLXArray) -> MLXArray { pair.sum(value, rank: rank) } + } + + func sum(_ value: MLXArray, rank: Int) -> MLXArray { + precondition(value.dtype == .float32, "Gemma tensor-parallel collectives carry FP32") + let mine = value.asArray(Float.self) + condition.lock() + defer { condition.unlock() } + while leaving > 0 { condition.wait() } + let generation = step + precondition(values[rank] == nil, "rank \(rank) entered a collective twice") + values[rank] = mine + shapes[rank] = value.shape + if values.count == 2 { + precondition(shapes[0] == shapes[1], "the ranks' collectives differ in shape") + output = zip(values[0]!, values[1]!).map(+) + payloads.append(shapes[0]!) + leaving = 2 + condition.broadcast() + } else { + let deadline = Date().addingTimeInterval(600) + while leaving == 0 && step == generation { + precondition(condition.wait(until: deadline), "the other rank never reached the collective") + } + } + let result = output + leaving -= 1 + if leaving == 0 { + values = [:]; shapes = [:]; output = []; step += 1 + condition.broadcast() + } + return MLXArray(result, value.shape) + } + + /// Runs `body(rank)` for both ranks at once, each on a thread of its own + /// with its own default stream on `device` (MLX's default stream is + /// process-wide and not thread-safe); returns both results in rank order. + public static func run(device: Device, _ body: @escaping @Sendable (Int) throws -> T) throws -> [T] { + let results = PairResults() + let done = DispatchGroup() + for rank in 0 ..< 2 { + done.enter() + let thread = Thread { + let result = Device.withDefaultDevice(device) { + Stream.withNewDefaultStream(device: device) { Result { try body(rank) } } + } + results.lock.lock(); results.values[rank] = result; results.lock.unlock() + done.leave() + } + thread.stackSize = 8 << 20 + thread.start() + } + done.wait() + return try results.values.map { try $0!.get() } + } +} + +private final class PairResults: @unchecked Sendable { + var values: [Result?] = [nil, nil] + let lock = NSLock() +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelModel.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelModel.swift new file mode 100644 index 0000000000..949124fe5d --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelModel.swift @@ -0,0 +1,417 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +/// A Gemma 4 MoE text model loaded whole, as the single-process +/// tensor-parallel oracle, or as one rank's shard, and generation over it. +/// +/// - `full`: the unsharded model (the single-Mac reference on this code path). +/// - `splitSum`: the unsharded model whose row-parallel projections compute +/// both ranks' FP32 partials over their stored columns (zero outside each +/// rank's own channels) and add them in FP32, and whose head normalizes +/// log probabilities over the two vocabulary halves: the decomposition's +/// oracle. Two ranks equal it bit for bit wherever each column-parallel +/// kernel's rows do not depend on the row count (the CPU; on an M5 Ultra +/// GPU a prefill-width full-attention `k_proj` of 1,024 rows rounds some +/// rows differently from its 512-row half). `Gemma4TensorParallelLocalPair` +/// runs both real shards in one process: the bitwise oracle everywhere. +/// - `shard(rank)`: this rank's heads and channels only, built by the SDK's +/// own Gemma 4 modules from the rank's local configuration; every layer +/// sums its attention partial and one packed feed-forward collective +/// through `reduction`, and the head projects this rank's vocabulary rows +/// (`Gemma4TensorParallelSelection` chooses across ranks). +public final class Gemma4TensorParallelModel { + public enum Role: Equatable, Sendable { + case full + case splitSum + case shard(rank: Int) + + public var label: String { + switch self { + case .full: return "full" + case .splitSum: return "split-sum-tp2" + case .shard(let rank): return "tp2-rank\(rank)" + } + } + } + + public let role: Role + public let plan: Gemma4TensorParallelPlan + public let vocabularyRange: Range + public let configurationSHA256: String + public let loadSeconds: Double + public let loadedParameterBytes: Int + let model: Gemma4Model + let reduction: QwenTensorParallelReduction? + + var textModel: Gemma4TextModel { model.textModel } + + /// Reads a checkpoint directory (`config.json`, `model.safetensors.index.json` + /// and the files it names) directly: tools and oracles. Vision tensors are + /// skipped; every other tensor must be a text tensor the plan covers. + public static func load(modelDirectory: URL, role: Role, reduction: QwenTensorParallelReduction?, + packFeedForward: Bool = true) throws -> Gemma4TensorParallelModel { + let configurationData = try Data(contentsOf: modelDirectory.appendingPathComponent("config.json")) + return try assemble(configurationData: configurationData, role: role, reduction: reduction, + packFeedForward: packFeedForward) { keep in + let indexData = try Data(contentsOf: modelDirectory.appendingPathComponent("model.safetensors.index.json")) + guard let index = (try JSONSerialization.jsonObject(with: indexData) as? [String: Any])?["weight_map"] + as? [String: String] else { + throw ProbeError("Gemma tensor parallel load: the checkpoint index has no weight map") + } + var byFile: [String: [String]] = [:] + for (key, file) in index { + guard !file.contains("/"), file.hasSuffix(".safetensors") else { + throw ProbeError("Gemma tensor parallel load: the checkpoint index names an unexpected file") + } + byFile[file, default: []].append(key) + } + for file in byFile.keys.sorted() { + let arrays = try loadArrays(url: modelDirectory.appendingPathComponent(file)) + for key in byFile[file]!.sorted() { + guard let value = arrays[key] else { throw ProbeError("Gemma tensor parallel load: \(file) lacks \(key)") } + try keep(key, value) + } + } + } + } + + /// The model of `role` from a configuration and its stored tensors: + /// `tensors` hands every stored tensor (by checkpoint key) to `keep`, + /// which cuts this rank's part and materializes it at once. + static func assemble(configurationData: Data, role: Role, reduction: QwenTensorParallelReduction?, + packFeedForward: Bool = true, + tensors: (_ keep: (String, MLXArray) throws -> Void) throws -> Void) throws + -> Gemma4TensorParallelModel { + let started = DispatchTime.now().uptimeNanoseconds + guard var root = try JSONSerialization.jsonObject(with: configurationData) as? [String: Any], + let text = root["text_config"] as? [String: Any] else { + throw ProbeError("Gemma tensor parallel load: expected a gemma4 configuration with a text configuration") + } + let plan = try Gemma4TensorParallelPlan(configuration: root) + // The wrapper takes the vocabulary from its root (262,144 when absent). + root["vocab_size"] = plan.vocabularySize + let full = try JSONDecoder().decode(Gemma4Configuration.self, + from: JSONSerialization.data(withJSONObject: root, options: [.sortedKeys])) + let rank: Int + switch role { + case .full, .splitSum: + rank = 0 + guard reduction == nil else { throw ProbeError("Gemma tensor parallel load: only a shard takes a reduction") } + case .shard(let r): + rank = r + guard let reduction, reduction.size == plan.size, reduction.rank == r else { + throw ProbeError("Gemma tensor parallel load: a shard needs the reduction of its own rank and group size") + } + } + var constructed = root + if case .shard = role { constructed["text_config"] = try plan.shardTextConfiguration(text, rank: rank) } + let configuration = try JSONDecoder().decode(Gemma4Configuration.self, + from: JSONSerialization.data(withJSONObject: constructed, options: [.sortedKeys])) + let model = Gemma4Model(configuration) + + var weights: [String: MLXArray] = [:] + try tensors { key, value in + if !key.hasPrefix("language_model.") { + guard Gemma4TensorParallelPlan.isVisionTensor(key) else { + throw ProbeError("Gemma tensor parallel load: unknown checkpoint key \(key)") + } + return + } + guard weights[key] == nil else { throw ProbeError("Gemma tensor parallel load: \(key) was given twice") } + guard try plan.expectedShape(key: key) == value.shape else { + throw ProbeError("Gemma tensor parallel load: \(key) has shape \(value.shape), not the plan's") + } + let cut = try plan.cut(key: key, rank: rank) + let part: MLXArray + if case .shard = role { part = try Gemma4TensorParallelSlicer.cut(value, cut, key: key, plan: plan) } + else { part = value } + // Materialize each part now: the stored tensor it came from is + // released before the next one is read. + eval(part) + weights[key] = part + } + quantize(model: model) { path, _ in + weights[path + ".scales"] != nil ? (plan.groupSize, plan.bits(forModule: path), .affine) : nil + } + try model.update(parameters: ModuleParameters.unflattened(weights), verify: [.all]) + + var extra: [MLXArray] = [] + switch role { + case .full: + break + case .shard(let r): + try model.textModel.installTensorParallel(shard: Gemma4TensorShard(rank: r), full: full.textConfiguration, + packFeedForward: packFeedForward) { reduction!.allSum($0) } + case .splitSum: + extra = try Gemma4TensorParallelSplitSum.install(in: model, plan: plan) + } + let parameters = model.parameters().flattened().map(\.1) + eval(parameters + extra) + Memory.clearCache() + let vocabulary: Range + if case .shard(let r) = role { vocabulary = plan.vocabularyRange(rank: r) } else { vocabulary = 0 ..< plan.vocabularySize } + guard model.textModel.headVocabularyRange == vocabulary else { + throw ProbeError("Gemma tensor parallel load: the head does not project the plan's vocabulary rows") + } + return Gemma4TensorParallelModel(role: role, plan: plan, vocabularyRange: vocabulary, + configurationSHA256: sha256(configurationData), + loadSeconds: Double(DispatchTime.now().uptimeNanoseconds - started) / 1e9, + loadedParameterBytes: (parameters + extra).reduce(0) { $0 + $1.nbytes }, + model: model, reduction: reduction) + } + + private init(role: Role, plan: Gemma4TensorParallelPlan, vocabularyRange: Range, + configurationSHA256: String, loadSeconds: Double, loadedParameterBytes: Int, + model: Gemma4Model, reduction: QwenTensorParallelReduction?) { + self.role = role; self.plan = plan; self.vocabularyRange = vocabularyRange + self.configurationSHA256 = configurationSHA256; self.loadSeconds = loadSeconds + self.loadedParameterBytes = loadedParameterBytes; self.model = model; self.reduction = reduction + } + + /// The head's selections over this model's vocabulary rows. + public var selection: Gemma4TensorParallelSelection { + Gemma4TensorParallelSelection(vocabularyRange: vocabularyRange, vocabularySize: plan.vocabularySize, + reduction: reduction, splitsWholeRow: role == .splitSum) + } + + func newCache() -> [KVCache] { model.newCache(parameters: nil) } + + /// The model over `input` `[1, T]`: logits `[1, T, V or V/2]` (FP32 after + /// the softcap), not evaluated. + func forward(_ input: MLXArray, cache: [KVCache]) -> MLXArray { model(input, cache: cache) } + + /// The prompt through the model in chunks; the last position's logits + /// `[1, V or V/2]`, not evaluated. + func prefill(_ prompt: [Int], chunk: Int, cache: [KVCache]) -> MLXArray { + var logits: MLXArray? + var offset = 0 + while offset < prompt.count { + let end = min(prompt.count, offset + chunk) + let out = forward(MLXArray(prompt[offset ..< end].map { Int32($0) }).reshaped(1, end - offset), cache: cache) + if end < prompt.count { + eval(cache.flatMap { $0.innerState() }) + } else { + logits = out[0..., -1, 0...] + } + offset = end + } + return logits! + } + + /// One greedy generation's tokens and per-step evidence. + public struct Generation: Sendable { + public var tokenIDs: [Int] = [] + /// Per step, the top `recordTop` token IDs, their logits and log + /// probabilities over the whole vocabulary, highest first. + public var topTokenIDs: [[Int]] = [] + public var topLogits: [[Float]] = [] + public var topLogprobs: [[Float]] = [] + /// The last step's whole vocabulary row (FP32), when recorded. + public var finalLogits: [Float]? + public var firstTokenSeconds = 0.0 + public var decodeSeconds = 0.0 + public var stepSeconds: [Double] = [] + public var peakActiveBytes = 0 + } + + /// Greedy generation of `outputCount` tokens after `prompt`, prefilled in + /// chunks of `chunk`. `recordTop` > 0 records each step's top logits and + /// log probabilities (a shard through the vocabulary-split top-k gather) + /// and the final step's whole row (a shard through the row gather). Each + /// step's collectives run in one fixed order on every rank: the forward's, + /// the selection, the top-k gather, then the final row. + public func generate(prompt: [Int], outputCount: Int, chunk: Int, recordTop: Int = 0) throws -> Generation { + guard !prompt.isEmpty, outputCount >= 1, chunk >= 1, prompt.allSatisfy({ (0 ..< plan.vocabularySize).contains($0) }) else { + throw ProbeError("Gemma tensor parallel generation: empty or out-of-vocabulary request") + } + guard (0 ... 64).contains(recordTop) else { throw ProbeError("Gemma tensor parallel generation: at most 64 logits per step") } + let selection = self.selection + let cache = newCache() + var result = Generation() + let started = Self.now() + var logits = prefill(prompt, chunk: chunk, cache: cache) + var last = started + for step in 0 ..< outputCount { + let token = selection.greedy(logits) + eval(token) + let id = Int(token.item(Int32.self)) + if recordTop > 0 { + let top = try selection.topK(logits, count: recordTop) + result.topTokenIDs.append(top.tokenIDs) + result.topLogits.append(top.logits) + result.topLogprobs.append(top.logprobs) + if step == outputCount - 1 { + let row = selection.gather(logits) + eval(row) + result.finalLogits = row.asArray(Float.self) + } + } + let time = Self.now() + if step == 0 { result.firstTokenSeconds = time - started } else { result.stepSeconds.append(time - last) } + last = time + result.tokenIDs.append(id) + if step + 1 < outputCount { + logits = forward(token.reshaped(1, 1), cache: cache)[0..., -1, 0...] + } + } + result.decodeSeconds = last - started - result.firstTokenSeconds + result.peakActiveBytes = Memory.peakMemory + return result + } + + static func now() -> Double { Double(DispatchTime.now().uptimeNanoseconds) / 1e9 } +} + +/// Exact copies of a stored tensor's rank part into new row-major buffers +/// (never views, which would keep the whole stored tensor alive), with the +/// plan's zero rows: zero packed words, scales and offsets, so every padded +/// channel's projection is exactly zero. +enum Gemma4TensorParallelSlicer { + static func cut(_ value: MLXArray, _ cut: Gemma4TensorParallelPlan.Cut, key: String, + plan: Gemma4TensorParallelPlan) throws -> MLXArray { + let local = try plan.localShape(key: key, shape: value.shape, cut: cut) + let part: MLXArray + switch cut { + case .replicate: + return value + case .rows(let range, let before, let after): + part = padded(value[range], axis: 0, before: before, after: after) + case .inputColumns(let logical): + let divisor = columnDivisor(key: key, plan: plan) + part = value[0..., (logical.lowerBound / divisor) ..< (logical.upperBound / divisor)] + case .expertRows(let range, let before, let after): + part = padded(value[0..., range], axis: 1, before: before, after: after) + case .expertInputColumns(let logical): + let divisor = columnDivisor(key: key, plan: plan) + part = value[0..., 0..., (logical.lowerBound / divisor) ..< (logical.upperBound / divisor)] + } + let copied = contiguous(part) + guard copied.shape == local else { + throw ProbeError("Gemma tensor parallel slice: \(key) cut to \(copied.shape), not \(local)") + } + return copied + } + + /// Logical input columns per stored column: values per packed word for a + /// weight, the group size for scales and offsets. + static func columnDivisor(key: String, plan: Gemma4TensorParallelPlan) -> Int { + let parts = key.split(separator: ".") + return parts.last == "weight" ? 32 / plan.bits(forModule: parts.dropLast().joined(separator: ".")) : plan.groupSize + } + + private static func padded(_ value: MLXArray, axis: Int, before: Int, after: Int) -> MLXArray { + guard before > 0 || after > 0 else { return value } + func zeros(_ count: Int) -> MLXArray { + var shape = value.shape + shape[axis] = count + return MLXArray.zeros(shape, dtype: value.dtype) + } + var parts: [MLXArray] = [] + if before > 0 { parts.append(zeros(before)) } + parts.append(value) + if after > 0 { parts.append(zeros(after)) } + return concatenated(parts, axis: axis) + } +} + +extension Gemma4TensorParallelModel { + /// Writes a tiny random Gemma 4 MoE checkpoint into `directory` + /// (`config.json`, `model.safetensors` and its index), seeded, with the + /// 26B's structure scaled down: sliding and full layers (window 16), 16 + /// query heads with 8 sliding and 2 full KV heads (head dims 256 and 512, + /// K=V on full layers), a dense GeGLU MLP in parallel with 16 routed + /// experts (top-4), sandwich norms, a tied softcapped head, and affine + /// group-64 quantization (`bits` by default, 8-bit dense MLP and router) + /// whose dense (5) and expert (3) group counts are odd, so both overlap + /// splits run. For model-free equality checks of tensor parallel; never a + /// model pass. + /// + /// `dtype` is the weights' and so the activations' type: BF16 as the + /// artifacts, or FP32, whose rounding is too small to flip a random + /// router's near-tied top-k choice (a random router's scores sit closer + /// together than a trained one's). + /// `experts`/`topK` change the routed bank (with `topK == experts` every + /// token takes every expert, and no rounding can change a route). + public static func writeSyntheticCheckpoint(directory: URL, seed: UInt64 = 7, bits: Int = 4, + dtype: DType = .bfloat16, experts: Int = 16, topK: Int = 4) throws { + guard [4, 8].contains(bits) else { throw ProbeError("Gemma synthetic checkpoint: bits are 4 or 8") } + guard (1 ... 64).contains(experts), (1 ... experts).contains(topK) else { + throw ProbeError("Gemma synthetic checkpoint: 1 to 64 experts, top-k at most the experts") + } + guard [.bfloat16, .float32].contains(dtype) else { + throw ProbeError("Gemma synthetic checkpoint: weights are bfloat16 or float32") + } + let layers = 6 + let kinds = (0 ..< layers).map { ($0 + 1) % 3 == 0 ? "full_attention" : "sliding_attention" } + let text: [String: Any] = [ + "model_type": "gemma4_text", "hidden_size": 256, "num_hidden_layers": layers, "layer_types": kinds, + "intermediate_size": 320, "moe_intermediate_size": 192, "num_experts": experts, "top_k_experts": topK, + "num_attention_heads": 16, "num_key_value_heads": 8, "num_global_key_value_heads": 2, + "head_dim": 256, "global_head_dim": 512, "sliding_window": 16, "vocab_size": 512, + "vocab_size_per_layer_input": 0, "hidden_size_per_layer_input": 0, "num_kv_shared_layers": 0, + "attention_k_eq_v": true, "enable_moe_block": true, "tie_word_embeddings": true, + "use_double_wide_mlp": false, "attention_bias": false, "final_logit_softcapping": 30.0, + "rms_norm_eps": 1e-6, "max_position_embeddings": 4096, "hidden_activation": "gelu_pytorch_tanh", + "use_bidirectional_attention": "vision", "dtype": dtype == .float32 ? "float32" : "bfloat16", + "rope_parameters": [ + "sliding_attention": ["rope_type": "default", "rope_theta": 10000.0], + "full_attention": ["rope_type": "proportional", "rope_theta": 1_000_000.0, "partial_rotary_factor": 0.25], + ], + ] + var quantization: [String: Any] = ["group_size": 64, "bits": bits, "mode": "affine"] + for layer in 0 ..< layers { + for module in ["mlp.gate_proj", "mlp.up_proj", "mlp.down_proj", "router.proj"] { + quantization["language_model.model.layers.\(layer).\(module)"] = ["group_size": 64, "bits": 8] + } + } + let root: [String: Any] = ["model_type": "gemma4", "text_config": text, "tie_word_embeddings": true, + "vocab_size": 512, "quantization": quantization, "quantization_config": quantization] + let configurationData = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys, .prettyPrinted]) + let plan = try Gemma4TensorParallelPlan(configuration: root) + let configuration = try JSONDecoder().decode(Gemma4Configuration.self, from: configurationData) + let arrays: [String: MLXArray] = withRandomState(MLXRandom.RandomState(seed: seed)) { + let model = Gemma4Model(configuration) + var values: [(String, MLXArray)] = [] + for (key, value) in model.parameters().flattened() { + let shape = value.shape + let generated: MLXArray + if key.hasSuffix("embed_tokens.weight") { + generated = MLXRandom.normal(shape) * 0.1 + } else if key.hasSuffix("layer_scalar") { + generated = MLXRandom.uniform(low: 0.5, high: 1.0, shape) + } else if key.hasSuffix("per_expert_scale") { + generated = MLXRandom.uniform(low: 0.5, high: 1.5, shape) + } else if key.hasSuffix("q_norm.weight") || key.hasSuffix("k_norm.weight") { + // Gemma 4 attends at scale 1: small per-head norms keep + // scores near unit spread, as a trained model's do, so + // softmax is not an argmax that rounding can flip. + generated = MLXRandom.uniform(low: 0.2, high: 0.3, shape) + } else if key.hasSuffix("norm.weight") || key.hasSuffix("router.scale") { + generated = MLXRandom.uniform(low: 0.6, high: 1.4, shape) + } else { + let fanIn = Float(shape.last ?? 1) + generated = MLXRandom.normal(shape) * (1 / fanIn.squareRoot()) + } + values.append((key, generated.asType(dtype))) + } + model.update(parameters: ModuleParameters.unflattened(values)) + quantize(model: model) { path, module in + guard module is Linear || module is SwitchLinear || module is Embedding else { return nil } + return (64, plan.bits(forModule: path), .affine) + } + let flat = Dictionary(uniqueKeysWithValues: model.parameters().flattened()) + eval(Array(flat.values)) + return flat + } + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try configurationData.write(to: directory.appendingPathComponent("config.json")) + try save(arrays: arrays, url: directory.appendingPathComponent("model.safetensors")) + let index: [String: Any] = ["metadata": [:] as [String: Any], + "weight_map": Dictionary(uniqueKeysWithValues: arrays.keys.map { ($0, "model.safetensors") })] + try JSONSerialization.data(withJSONObject: index, options: [.sortedKeys, .prettyPrinted]) + .write(to: directory.appendingPathComponent("model.safetensors.index.json")) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPlan.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPlan.swift new file mode 100644 index 0000000000..f4b34bfd7b --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPlan.swift @@ -0,0 +1,443 @@ +import Foundation + +/// How a Gemma 4 MoE text model (`gemma4_text` inside the `gemma4` wrapper, +/// tied head; the registered 26B A4B artifacts at 4 and 8 bits) is split +/// across two ranks by heads and channels with equal shares: +/// `gemma4_heads_and_expert_channels_v1`. +/// +/// - Attention: contiguous halves of the query heads with the KV heads they +/// read: `q_proj`, `k_proj` and (sliding layers) `v_proj` by output rows, +/// `o_proj` by input columns. Query head `h` reads KV head `h / (Hq / Hkv)`, +/// so halves keep each group whole (26B: sliding 8 query and 4 KV heads per +/// rank, full 8 and 1). Full layers have K=V and store no `v_proj`. +/// - Dense MLP and every routed expert: each rank computes a contiguous half +/// of the channels (gate/up output rows). The down projection is quantized +/// in groups along its input axis, so its stored input columns widen to +/// whole groups; with an odd group count (2112 = 33 x 64, 704 = 11 x 64) +/// both ranks store the middle group, and each rank's gate and up carry +/// zero rows (zero weights, scales and offsets) for the other rank's half +/// of it. Those channels are exactly zero, the shared columns add nothing +/// on the rank that does not own them, and both ranks hold the same width +/// (1088 and 384): equal shares, no unequal-share contract. +/// - Replicated: every norm, `layer_scalar`, the router (`proj`, `scale`, +/// `per_expert_scale`; both ranks route identically), the per-head +/// `q_norm`/`k_norm`, the final norm and the tied embedding. The head +/// projects this rank's half of the embedding's vocabulary rows (views). +/// +/// Collectives: per layer the attention partial before +/// `post_attention_layernorm`, and one packed feed-forward collective carrying +/// the dense partial and every selected expert's FP32 row (each summed before +/// rounding, router weighting and its branch's post-norm); one per step for +/// the vocabulary-split selection. Vision tower tensors are refused: the +/// plan covers the text model only, as the pipeline stages do. +public struct Gemma4TensorParallelPlan: Sendable, Equatable { + public static let name = "gemma4_heads_and_expert_channels_v1" + public let size = 2 + + public enum LayerKind: String, Sendable, Equatable { + case sliding = "sliding_attention" + case full = "full_attention" + } + + public let hiddenSize: Int + public let layerCount: Int + public let layerKinds: [LayerKind] + public let vocabularySize: Int + public let queryHeads: Int + public let slidingKVHeads: Int + public let fullKVHeads: Int + public let slidingHeadDim: Int + public let fullHeadDim: Int + public let denseWidth: Int + public let expertWidth: Int + public let expertCount: Int + public let expertsPerToken: Int + public let groupSize: Int + public let defaultBits: Int + /// Explicit per-module bits (`language_model.model.layers.N.`). + private let overrideBits: [String: Int] + + /// One rank's equal share of a channel-parallel width (see the type note). + public struct ChannelSplit: Sendable, Equatable { + public let width: Int + public let groupSize: Int + public let rank: Int + /// Channels of the full width this rank computes. + public let channels: Range + /// Input columns of the down projection this rank stores. + public let storedColumns: Range + + public init(width: Int, groupSize: Int, rank: Int) throws { + guard (0 ..< 2).contains(rank), width > 0, groupSize > 0, width % groupSize == 0, width % 2 == 0 else { + throw ProbeError("Gemma tensor parallel plan: width \(width) is not whole groups of \(groupSize)") + } + let half = width / 2 + self.width = width; self.groupSize = groupSize; self.rank = rank + channels = rank == 0 ? 0 ..< half : half ..< width + storedColumns = (channels.lowerBound / groupSize * groupSize) + ..< ((channels.upperBound + groupSize - 1) / groupSize * groupSize) + } + + public var localWidth: Int { storedColumns.count } + public var zeroBefore: Int { channels.lowerBound - storedColumns.lowerBound } + public var zeroAfter: Int { storedColumns.upperBound - channels.upperBound } + } + + /// A stored tensor's cut for one rank. + public enum Cut: Equatable, Sendable { + /// Every rank holds the whole tensor. + case replicate + /// Output rows (axis 0) in order, with all-zero rows before and after. + case rows(Range, zeroBefore: Int, zeroAfter: Int) + /// Logical input columns (axis 1) of a quantized linear: packed words + /// and per-group scales/offsets are cut accordingly. + case inputColumns(Range) + /// Every expert's output rows (axis 1 of `[E, out, in]`), with all-zero + /// rows before and after. + case expertRows(Range, zeroBefore: Int, zeroAfter: Int) + /// Every expert's logical input columns (axis 2, quantized). + case expertInputColumns(Range) + } + + /// `root` is the artifact's whole `config.json` object. + public init(configuration root: [String: Any]) throws { + guard root["model_type"] as? String == "gemma4", let text = root["text_config"] as? [String: Any], + text["model_type"] as? String == "gemma4_text" else { + throw ProbeError("Gemma tensor parallel plan: expected a gemma4 wrapper around gemma4_text") + } + func integer(_ key: String) throws -> Int { + guard let number = text[key] as? NSNumber, CFNumberIsFloatType(number) == false, number.intValue > 0 else { + throw ProbeError("Gemma tensor parallel plan: text configuration lacks a positive \(key)") + } + return number.intValue + } + func flag(_ value: Any?) -> Bool? { + guard let number = value as? NSNumber, String(cString: number.objCType) == "c" else { return nil } + return number.boolValue + } + guard flag(text["tie_word_embeddings"]) ?? true, flag(root["tie_word_embeddings"]) ?? true else { + throw ProbeError("Gemma tensor parallel plan: only the tied head is covered") + } + guard flag(text["enable_moe_block"]) == true else { + throw ProbeError("Gemma tensor parallel plan: only the MoE text model is covered") + } + guard flag(text["attention_k_eq_v"]) == true else { + throw ProbeError("Gemma tensor parallel plan: full layers must reuse K as V") + } + guard (text["num_kv_shared_layers"] as? Int ?? 0) == 0, (text["hidden_size_per_layer_input"] as? Int ?? 0) == 0, + flag(text["attention_bias"]) != true else { + throw ProbeError("Gemma tensor parallel plan: shared KV, per-layer embeddings and attention biases are not covered") + } + hiddenSize = try integer("hidden_size") + layerCount = try integer("num_hidden_layers") + vocabularySize = try integer("vocab_size") + queryHeads = try integer("num_attention_heads") + slidingKVHeads = try integer("num_key_value_heads") + fullKVHeads = try integer("num_global_key_value_heads") + slidingHeadDim = try integer("head_dim") + fullHeadDim = try integer("global_head_dim") + denseWidth = try integer("intermediate_size") + expertWidth = try integer("moe_intermediate_size") + expertCount = try integer("num_experts") + expertsPerToken = try integer("top_k_experts") + guard expertsPerToken <= expertCount else { + throw ProbeError("Gemma tensor parallel plan: more experts per token than experts") + } + guard let types = text["layer_types"] as? [String], types.count == layerCount else { + throw ProbeError("Gemma tensor parallel plan: every layer needs an explicit attention kind") + } + layerKinds = try types.map { + guard let kind = LayerKind(rawValue: $0) else { + throw ProbeError("Gemma tensor parallel plan: unknown layer kind \($0)") + } + return kind + } + + guard let quantization = (root["quantization"] ?? root["quantization_config"]) as? [String: Any], + let group = quantization["group_size"] as? Int, let bits = quantization["bits"] as? Int, + (quantization["mode"] as? String ?? "affine") == "affine", [4, 8].contains(bits), [32, 64, 128].contains(group) else { + throw ProbeError("Gemma tensor parallel plan: requires an affine 4- or 8-bit quantized checkpoint") + } + groupSize = group + defaultBits = bits + let quantizedModules = Set(["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj", + "mlp.gate_proj", "mlp.up_proj", "mlp.down_proj", "router.proj", + "experts.switch_glu.gate_proj", "experts.switch_glu.up_proj", + "experts.switch_glu.down_proj"]) + var overrides: [String: Int] = [:] + for (key, value) in quantization where !["group_size", "bits", "mode"].contains(key) { + let prefix = "language_model.model.layers." + guard key.hasPrefix(prefix), let entry = value as? [String: Any], + Set(entry.keys).isSubset(of: ["group_size", "bits", "mode"]), + entry["group_size"] as? Int == group, let moduleBits = entry["bits"] as? Int, [4, 8].contains(moduleBits), + (entry["mode"] as? String ?? "affine") == "affine" else { + throw ProbeError("Gemma tensor parallel plan: quantization override \(key) is not an affine 4/8-bit entry of the default group size") + } + let rest = key.dropFirst(prefix.count) + guard let dot = rest.firstIndex(of: "."), let layer = Int(rest[.. String { "language_model.model.layers.\(layer)." } + + public func headDim(layer: Int) -> Int { layerKinds[layer] == .full ? fullHeadDim : slidingHeadDim } + public func kvHeads(layer: Int) -> Int { layerKinds[layer] == .full ? fullKVHeads : slidingKVHeads } + + /// Per layer, the KV heads one rank holds (26B: 4 sliding, 1 full). + public var kvHeadsPerRank: [Int] { (0 ..< layerCount).map { kvHeads(layer: $0) / size } } + public var queryHeadsPerRank: Int { queryHeads / size } + + /// Bits of a quantized module (`language_model.model.layers.N.mlp.down_proj`). + public func bits(forModule path: String) -> Int { overrideBits[path] ?? defaultBits } + + public func denseSplit(rank: Int) throws -> ChannelSplit { + try ChannelSplit(width: denseWidth, groupSize: groupSize, rank: rank) + } + + public func expertSplit(rank: Int) throws -> ChannelSplit { + try ChannelSplit(width: expertWidth, groupSize: groupSize, rank: rank) + } + + /// Vocabulary rows this rank's head projects. + public func vocabularyRange(rank: Int) -> Range { + let half = vocabularySize / size + return (rank * half) ..< ((rank + 1) * half) + } + + // MARK: - Collective facts + + /// Collectives per layer (the attention partial, the packed feed-forward) + /// and per decode step (the vocabulary-split selection). + public let reductionsPerLayer = 2 + public let reductionsPerStep = 1 + /// FP32 bytes one token's attention collective carries. + public var attentionPartialBytesPerToken: Int { hiddenSize * 4 } + /// FP32 bytes one token's packed feed-forward collective carries: every + /// selected expert's row and the dense branch's row. + public var feedForwardPartialBytesPerToken: Int { (expertsPerToken + 1) * hiddenSize * 4 } + public var layerPartialBytesPerToken: Int { attentionPartialBytesPerToken + feedForwardPartialBytesPerToken } + /// Collectives one forward issues. + public var reductionsPerForward: Int { reductionsPerLayer * layerCount } + + /// What two ranks must agree on before they serve together: the plan, + /// where each sum is taken and what it carries. A peer with any other + /// schedule refuses to load with this one. + public static let arithmeticAgreementFields = [ + name, + "gemma4-attention-f32-sum-before-post-attention-norm-v1", + "gemma4-dense-and-expert-f32-rows-one-collective-before-branch-norms-v1", + "gemma4-odd-group-channels-overlap-zero-padded-v1", + "gemma4-tied-head-vocabulary-halves-v1", + ] + + // MARK: - Configuration + + /// The text configuration `rank` constructs: half the query and KV heads + /// of each layer kind, the local channel widths. Everything else is whole. + public func shardTextConfiguration(_ text: [String: Any], rank: Int) throws -> [String: Any] { + var shard = text + shard["num_attention_heads"] = queryHeads / size + shard["num_key_value_heads"] = slidingKVHeads / size + shard["num_global_key_value_heads"] = fullKVHeads / size + shard["intermediate_size"] = try denseSplit(rank: rank).localWidth + shard["moe_intermediate_size"] = try expertSplit(rank: rank).localWidth + return shard + } + + // MARK: - Stored tensors + + /// True for the artifact's vision tower and its embedder, which no + /// tensor-parallel rank loads (the loader skips them; `cut` refuses them). + public static func isVisionTensor(_ key: String) -> Bool { + key.hasPrefix("vision_tower.") || key.hasPrefix("embed_vision.") || key.hasPrefix("multi_modal_projector.") + || key.hasPrefix("audio_tower.") || key.hasPrefix("embed_audio.") + } + + private static let replicatedLayerTensors: Set = [ + "input_layernorm.weight", "post_attention_layernorm.weight", "pre_feedforward_layernorm.weight", + "post_feedforward_layernorm.weight", "post_feedforward_layernorm_1.weight", + "pre_feedforward_layernorm_2.weight", "post_feedforward_layernorm_2.weight", "layer_scalar", + "router.scale", "router.per_expert_scale", "self_attn.q_norm.weight", "self_attn.k_norm.weight", + ] + + /// The cut of one stored text tensor (`language_model.` keys, as the + /// registered checkpoints store them) for `rank`. Unknown, vision and + /// untied-head tensors throw. + public func cut(key: String, rank: Int) throws -> Cut { + guard (0 ..< size).contains(rank) else { + throw ProbeError("Gemma tensor parallel plan: rank \(rank) is outside the group") + } + if Self.isVisionTensor(key) { + throw ProbeError("Gemma tensor parallel plan: vision tensors are not part of the tensor-parallel text model (\(key))") + } + if ["language_model.model.embed_tokens.weight", "language_model.model.embed_tokens.scales", + "language_model.model.embed_tokens.biases", "language_model.model.norm.weight"].contains(key) { + return .replicate + } + let prefix = "language_model.model.layers." + guard key.hasPrefix(prefix) else { throw ProbeError("Gemma tensor parallel plan: unknown checkpoint key \(key)") } + let rest = key.dropFirst(prefix.count) + guard let dot = rest.firstIndex(of: "."), let layer = Int(rest[..= 2, ["weight", "scales", "biases"].contains(parts.last!) else { + throw ProbeError("Gemma tensor parallel plan: unknown layer key \(key)") + } + let module = parts.dropLast().joined(separator: ".") + let full = layerKinds[layer] == .full + let headDim = self.headDim(layer: layer) + let queries = queryHeads / size, kv = self.kvHeads(layer: layer) / size + switch module { + case "router.proj": + return .replicate + case "self_attn.q_proj": + return .rows((rank * queries * headDim) ..< ((rank + 1) * queries * headDim), zeroBefore: 0, zeroAfter: 0) + case "self_attn.k_proj": + return .rows((rank * kv * headDim) ..< ((rank + 1) * kv * headDim), zeroBefore: 0, zeroAfter: 0) + case "self_attn.v_proj" where !full: + return .rows((rank * kv * headDim) ..< ((rank + 1) * kv * headDim), zeroBefore: 0, zeroAfter: 0) + case "self_attn.o_proj": + return .inputColumns((rank * queries * headDim) ..< ((rank + 1) * queries * headDim)) + case "mlp.gate_proj", "mlp.up_proj": + let split = try denseSplit(rank: rank) + return .rows(split.channels, zeroBefore: split.zeroBefore, zeroAfter: split.zeroAfter) + case "mlp.down_proj": + return .inputColumns(try denseSplit(rank: rank).storedColumns) + case "experts.switch_glu.gate_proj", "experts.switch_glu.up_proj": + let split = try expertSplit(rank: rank) + return .expertRows(split.channels, zeroBefore: split.zeroBefore, zeroAfter: split.zeroAfter) + case "experts.switch_glu.down_proj": + return .expertInputColumns(try expertSplit(rank: rank).storedColumns) + default: + throw ProbeError("Gemma tensor parallel plan: unknown layer key \(key)") + } + } + + /// The stored shape the plan expects for a text tensor of the whole + /// model (affine packing: `in / (32 / bits)` words, `in / group` scales). + public func expectedShape(key: String) throws -> [Int] { + if key.hasPrefix("language_model.model.embed_tokens.") { + return try packed(key, [vocabularySize, hiddenSize], bits: defaultBits) + } + if key == "language_model.model.norm.weight" { return [hiddenSize] } + let prefix = "language_model.model.layers." + guard key.hasPrefix(prefix) else { throw ProbeError("Gemma tensor parallel plan: unknown checkpoint key \(key)") } + let rest = key.dropFirst(prefix.count) + guard let dot = rest.firstIndex(of: "."), let layer = Int(rest[.. [Int] { + guard let last = logical.last else { throw ProbeError("Gemma tensor parallel plan: empty shape for \(key)") } + let leaf = key.split(separator: ".").last.map(String.init) ?? "" + switch leaf { + case "weight": return logical.dropLast() + [last / (32 / bits)] + case "scales", "biases": return logical.dropLast() + [last / groupSize] + default: throw ProbeError("Gemma tensor parallel plan: unknown quantized leaf in \(key)") + } + } + + /// The shape one rank stores for a text tensor of `shape` under `cut`, + /// refusing a cut that leaves the tensor or splits a packed word or group. + public func localShape(key: String, shape: [Int], cut: Cut) throws -> [Int] { + let leaf = key.split(separator: ".").last.map(String.init) ?? "" + let module = key.split(separator: ".").dropLast().joined(separator: ".") + let divisor = leaf == "weight" ? 32 / bits(forModule: module) : groupSize + var local = shape + switch cut { + case .replicate: + return shape + case .rows(let range, let before, let after): + guard !shape.isEmpty, range.lowerBound >= 0, range.upperBound <= shape[0], !range.isEmpty else { + throw ProbeError("Gemma tensor parallel plan: rows \(range) do not fit \(key) \(shape)") + } + local[0] = before + range.count + after + case .inputColumns(let logical): + guard shape.count == 2, ["weight", "scales", "biases"].contains(leaf), + logical.lowerBound % groupSize == 0, logical.upperBound % groupSize == 0, + logical.lowerBound % divisor == 0, logical.upperBound % divisor == 0, + logical.upperBound / divisor <= shape[1] else { + throw ProbeError("Gemma tensor parallel plan: columns \(logical) split a group or word of \(key) \(shape)") + } + local[1] = logical.count / divisor + case .expertRows(let range, let before, let after): + guard shape.count == 3, range.lowerBound >= 0, range.upperBound <= shape[1], !range.isEmpty else { + throw ProbeError("Gemma tensor parallel plan: expert rows \(range) do not fit \(key) \(shape)") + } + local[1] = before + range.count + after + case .expertInputColumns(let logical): + guard shape.count == 3, ["weight", "scales", "biases"].contains(leaf), + logical.lowerBound % groupSize == 0, logical.upperBound % groupSize == 0, + logical.lowerBound % divisor == 0, logical.upperBound % divisor == 0, + logical.upperBound / divisor <= shape[2] else { + throw ProbeError("Gemma tensor parallel plan: expert columns \(logical) split a group or word of \(key) \(shape)") + } + local[2] = logical.count / divisor + } + return local + } + + /// The module paths whose outputs are partial sums under this plan: each + /// layer's attention output and its dense and expert down projections + /// (the last two share one packed collective). + public func rowParallelModulePaths() -> [String] { + (0 ..< layerCount).flatMap { layer -> [String] in + let base = Self.layerRoot(layer) + return [base + "self_attn.o_proj", base + "mlp.down_proj", base + "experts.switch_glu.down_proj"] + } + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSelection.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSelection.swift new file mode 100644 index 0000000000..2b92a50710 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSelection.swift @@ -0,0 +1,133 @@ +import Foundation +import MLX + +/// Choices from a tied head whose vocabulary rows are split across ranks. +/// Each rank holds its rows' FP32 (softcapped) logits `[1, V/2]`; one small +/// collective per choice makes the same choice on every rank, and no rank +/// holds the whole row. Without a reduction the rows are the whole +/// vocabulary and the same functions are the plain choices of a whole model. +public struct Gemma4TensorParallelSelection { + public let vocabularyRange: Range + public let vocabularySize: Int + let reduction: QwenTensorParallelReduction? + /// A whole row normalized as two ranks normalize it (each half's top + /// `count` and log-sum-exp, merged): the split-sum oracle's head. + let splitsWholeRow: Bool + + public init(vocabularyRange: Range, vocabularySize: Int, reduction: QwenTensorParallelReduction?, + splitsWholeRow: Bool = false) { + self.vocabularyRange = vocabularyRange + self.vocabularySize = vocabularySize + self.reduction = reduction + self.splitsWholeRow = splitsWholeRow && reduction == nil + } + + /// Greedy: the argmax over every rank's rows, ties to the lowest token ID + /// as a whole row's argmax breaks them. One collective of two values per + /// rank. An `[1]` int32 token, not evaluated. + public func greedy(_ logits: MLXArray) -> MLXArray { + argmaxAcrossRanks(logits.asType(.float32)) + } + + /// Sampling with keyed noise (Gumbel-max): exactly the token + /// `argMax(MLXRandom.gumbel([1, V], key: key) + whole * (1 / temperature))` + /// of the whole row. Every rank generates the whole vocabulary's noise + /// from the shared `key`, adds its rows' part, and the argmax collective + /// of `greedy` chooses. An `[1]` int32 token, not evaluated. The pinned + /// MLX samples a single row by its inverse CDF instead + /// (`categorical_inverse_cdf`), so token-for-token parity with the + /// product's sampler takes the whole row (`gather`) and that sampler. + public func sample(_ logits: MLXArray, temperature: Float, key: MLXArray) -> MLXArray { + let scaled = logits.asType(.float32) * (1 / temperature) + let noise = MLXRandom.gumbel([1, vocabularySize], key: key)[0..., vocabularyRange] + return argmaxAcrossRanks(noise + scaled) + } + + /// One choice's candidates: the top `count` tokens of the whole row with + /// their logits and log probabilities (each logit minus the whole row's + /// log-sum-exp), highest first, equal logits by token ID. Each rank + /// contributes its own top `count` and its rows' log-sum-exp in one + /// collective of `2 count + 1` values per rank. Evaluated. + public func topK(_ logits: MLXArray, count: Int) throws -> (tokenIDs: [Int], logits: [Float], logprobs: [Float]) { + let values = logits.asType(.float32).reshaped(-1) + guard values.dim(0) == vocabularyRange.count, count >= 1, + count <= values.dim(0) / (splitsWholeRow ? 2 : 1) else { + throw ProbeError("Gemma vocabulary-split top-k: \(count) of a \(values.dim(0))-row slice") + } + func candidates(_ slice: MLXArray, offset: Int) -> MLXArray { + let order = argPartition(-slice, kth: count - 1)[.. $1.logit : $0.id < $1.id }.prefix(count) + return (chosen.map(\.id), chosen.map(\.logit), chosen.map { $0.logit - total }) + } + + /// The whole row on every rank, every bit kept: each rank's rows at their + /// place and -0 elsewhere (x + -0 is x), in one collective of V values. + /// Not evaluated. + public func gather(_ logits: MLXArray) -> MLXArray { + let values = logits.asType(.float32) + guard let reduction else { return values } + func negativeZeros(_ count: Int) -> MLXArray { + MLXArray.full([values.dim(0), count], values: MLXArray(Float(-0.0))) + } + var parts: [MLXArray] = [] + if vocabularyRange.lowerBound > 0 { parts.append(negativeZeros(vocabularyRange.lowerBound)) } + parts.append(values) + if vocabularyRange.upperBound < vocabularySize { parts.append(negativeZeros(vocabularySize - vocabularyRange.upperBound)) } + return reduction.allSum(concatenated(parts, axis: -1)) + } + + /// Each rank's local maximum and its token ID in slots of a `2 size` + /// collective; the strictly greater value wins, so ties go to the lower + /// rank, which holds the lower IDs. + private func argmaxAcrossRanks(_ values: MLXArray) -> MLXArray { + guard let reduction else { return argMax(values, axis: -1).asType(.int32) } + let localIndex = argMax(values, axis: -1).asType(.float32) + MLXArray(Float(vocabularyRange.lowerBound)) + let mine = concatenated([values.max(axis: -1), localIndex], axis: 0) + let zeros = MLXArray.zeros([2], dtype: .float32) + let all = reduction.allSum(concatenated((0 ..< reduction.size).map { $0 == reduction.rank ? mine : zeros }, axis: 0)) + var best = all[0], token = all[1] + for other in 1 ..< reduction.size { + let better = all[2 * other] .> best + best = which(better, all[2 * other], best) + token = which(better, all[2 * other + 1], token) + } + return token.asType(.int32).reshaped(1) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSplitSum.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSplitSum.swift new file mode 100644 index 0000000000..3527896d91 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSplitSum.swift @@ -0,0 +1,172 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +/// The single-process oracle of Gemma 4's row-parallel projections. Each +/// rank's part reads that rank's stored input columns of the whole input, +/// zero outside the rank's own channels (as the rank's zero-padded channels +/// are), through its column slice of the quantized weight with the input +/// widened to FP32 (the arithmetic a rank's partial uses); the two partials +/// are added in FP32 and rounded once. Installed over a whole model, it is +/// the `splitSum` oracle of the decomposition. +enum Gemma4TensorParallelSplitSum { + struct Part: Equatable { + /// Input columns the rank stores. + let stored: Range + /// Input columns the rank owns; the rest of `stored` reads zero. + let channels: Range + } + + /// Replaces every row-parallel projection of the whole `model`; returns + /// the parts' arrays, for evaluation with the model's parameters. + static func install(in model: Gemma4Model, plan: Gemma4TensorParallelPlan) throws -> [MLXArray] { + let leaves = Dictionary(uniqueKeysWithValues: model.leafModules().flattened()) + var replacements: [(String, Module)] = [] + var arrays: [MLXArray] = [] + let dense = try (0 ..< plan.size).map { rank -> Part in + let split = try plan.denseSplit(rank: rank) + return Part(stored: split.storedColumns, channels: split.channels) + } + let experts = try (0 ..< plan.size).map { rank -> Part in + let split = try plan.expertSplit(rank: rank) + return Part(stored: split.storedColumns, channels: split.channels) + } + for layer in 0 ..< plan.layerCount { + let base = "language_model.model.layers.\(layer)." + let width = plan.queryHeadsPerRank * plan.headDim(layer: layer) + let attention = (0 ..< plan.size).map { Part(stored: ($0 * width) ..< (($0 + 1) * width), + channels: ($0 * width) ..< (($0 + 1) * width)) } + guard let output = leaves[base + "self_attn.o_proj"] as? QuantizedLinear, + let down = leaves[base + "mlp.down_proj"] as? QuantizedLinear, + let expertDown = leaves[base + "experts.switch_glu.down_proj"] as? QuantizedSwitchLinear else { + throw ProbeError("Gemma split-sum oracle: layer \(layer) lacks a quantized row-parallel projection") + } + let attentionOracle = try Gemma4SplitSumLinear(output, parts: attention) + let denseOracle = try Gemma4SplitSumLinear(down, parts: dense) + let expertOracle = try Gemma4SplitSumSwitchLinear(expertDown, parts: experts) + replacements += [(base + "self_attn.o_proj", attentionOracle), (base + "mlp.down_proj", denseOracle), + (base + "experts.switch_glu.down_proj", expertOracle)] + arrays += attentionOracle.partArrays + denseOracle.partArrays + expertOracle.partArrays + } + try model.update(modules: ModuleChildren.unflattened(replacements), verify: .none) + return arrays + } + + /// `x`'s last-axis columns `part.stored`, every column outside + /// `part.channels` zero. + static func block(_ x: MLXArray, _ part: Part) -> MLXArray { + let core = x[.ellipsis, part.channels] + let before = part.channels.lowerBound - part.stored.lowerBound + let after = part.stored.upperBound - part.channels.upperBound + guard before > 0 || after > 0 else { return core } + func zeros(_ count: Int) -> MLXArray { + var shape = x.shape + shape[shape.count - 1] = count + return MLXArray.zeros(shape, dtype: x.dtype) + } + return concatenated((before > 0 ? [zeros(before)] : []) + [core] + (after > 0 ? [zeros(after)] : []), axis: -1) + } + + /// Stored input columns `columns` of packed `[..., out, in / perWord]` + /// words and `[..., out, in / group]` scales or offsets, copied row-major. + static func columns(_ value: MLXArray, _ columns: Range, divisor: Int) throws -> MLXArray { + guard columns.lowerBound % divisor == 0, columns.upperBound % divisor == 0, + columns.upperBound / divisor <= value.dim(-1) else { + throw ProbeError("Gemma split-sum oracle: columns \(columns) split a packed word or group") + } + return contiguous(value[.ellipsis, (columns.lowerBound / divisor) ..< (columns.upperBound / divisor)]) + } +} + +/// A dense row-parallel projection's oracle (`o_proj`, the dense MLP's +/// `down_proj`). +final class Gemma4SplitSumLinear: QuantizedLinear { + private final class Parts { + let modules: [QuantizedLinear] + let parts: [Gemma4TensorParallelSplitSum.Part] + init(_ modules: [QuantizedLinear], _ parts: [Gemma4TensorParallelSplitSum.Part]) { + self.modules = modules; self.parts = parts + } + } + + private let split: Parts + + init(_ source: QuantizedLinear, parts: [Gemma4TensorParallelSplitSum.Part]) throws { + guard source.bias == nil, source.mode == .affine, let offsets = source.biases else { + throw ProbeError("Gemma split-sum oracle: an affine projection without bias is required") + } + let modules = try parts.map { part in + QuantizedLinear( + weight: try Gemma4TensorParallelSplitSum.columns(source.weight, part.stored, divisor: 32 / source.bits), + bias: nil, + scales: try Gemma4TensorParallelSplitSum.columns(source.scales, part.stored, divisor: source.groupSize), + biases: try Gemma4TensorParallelSplitSum.columns(offsets, part.stored, divisor: source.groupSize), + groupSize: source.groupSize, bits: source.bits, mode: source.mode) + } + split = Parts(modules, parts) + super.init(weight: source.weight, bias: nil, scales: source.scales, biases: offsets, + groupSize: source.groupSize, bits: source.bits, mode: source.mode) + freeze() + } + + var partArrays: [MLXArray] { split.modules.flatMap { [$0.weight, $0.scales] + ($0.biases.map { [$0] } ?? []) } } + + override func callAsFunction(_ x: MLXArray) -> MLXArray { + var sum: MLXArray? + for (module, part) in zip(split.modules, split.parts) { + let partial = Gemma4TensorParallelProjection.partial(module, Gemma4TensorParallelSplitSum.block(x, part)) + sum = sum.map { $0 + partial } ?? partial + } + return sum!.asType(x.dtype) + } +} + +/// The routed experts' down projection oracle: every selected expert's row +/// summed over both ranks' parts in FP32 and rounded before the owning +/// SwitchGLU restores route order and weights it, as the packed collective +/// does on two ranks. +final class Gemma4SplitSumSwitchLinear: QuantizedSwitchLinear, SwitchLinearPartialSum { + private final class Parts { + let modules: [QuantizedSwitchLinear] + let parts: [Gemma4TensorParallelSplitSum.Part] + init(_ modules: [QuantizedSwitchLinear], _ parts: [Gemma4TensorParallelSplitSum.Part]) { + self.modules = modules; self.parts = parts + } + } + + private let split: Parts + + init(_ source: QuantizedSwitchLinear, parts: [Gemma4TensorParallelSplitSum.Part]) throws { + guard type(of: source) == QuantizedSwitchLinear.self, source.mode == .affine, + !source.parameters().flattened().contains(where: { $0.0 == "bias" }), + let offsets = source.biases, source.globalScales == nil else { + throw ProbeError("Gemma split-sum oracle: an affine expert bank without bias is required") + } + let modules = try parts.map { part in + try QuantizedSwitchLinear( + inputDims: part.stored.count, outputDims: source.shape.outputDims, numExperts: source.shape.numExperts, + weight: try Gemma4TensorParallelSplitSum.columns(source.weight, part.stored, divisor: 32 / source.bits), + scales: try Gemma4TensorParallelSplitSum.columns(source.scales, part.stored, divisor: source.groupSize), + biases: try Gemma4TensorParallelSplitSum.columns(offsets, part.stored, divisor: source.groupSize), + groupSize: source.groupSize, bits: source.bits) + } + split = Parts(modules, parts) + try super.init(inputDims: source.shape.inputDims, outputDims: source.shape.outputDims, + numExperts: source.shape.numExperts, weight: source.weight, scales: source.scales, + biases: offsets, groupSize: source.groupSize, bits: source.bits) + } + + var partArrays: [MLXArray] { split.modules.flatMap { [$0.weight, $0.scales] + ($0.biases.map { [$0] } ?? []) } } + + override func callAsFunction(_ x: MLXArray, _ indices: MLXArray, sortedIndices: Bool = false) -> MLXArray { + var sum: MLXArray? + for (module, part) in zip(split.modules, split.parts) { + let block = Gemma4TensorParallelSplitSum.block(x, part).asType(.float32) + let partial = module(block, indices, sortedIndices: sortedIndices) + sum = sum.map { $0 + partial } ?? partial + } + return sum!.asType(x.dtype) + } +} diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelTests.swift new file mode 100644 index 0000000000..89eea2117f --- /dev/null +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelTests.swift @@ -0,0 +1,565 @@ +import Foundation +import MLX +@_spi(GemmaEncoder) @testable import MLXLLM +import MLXLMCommon +import MLXNN +import Testing +@testable import DarkbloomClusterRuntime + +/// Gemma 4 MoE tensor parallel (`gemma4_heads_and_expert_channels_v1`): the +/// plan against the registered 26B's real tensor names and shapes, the cut +/// shards against independent slices of the whole tensors, two real ranks +/// (two threads whose all-sum adds both ranks' FP32 elements in rank order) +/// against the single-process oracle bit for bit, the packed feed-forward +/// collective against separate ones, and the vocabulary-split head against +/// the whole head. CPU only; synthetic weights, never a model pass. +@Suite("Gemma 4 tensor parallel", .serialized) +struct Gemma4TensorParallelTests { + // MARK: - Registered artifact fixture (safetensors headers, no payload) + + static let inputs = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("StageMetadataChecks/Inputs") + + struct StoredTensor { let name: String; let shape: [Int]; let dtype: String } + + /// The QAT 4-bit artifact's 1,697 stored tensors from its three headers. + static func registeredTensors() throws -> [StoredTensor] { + var tensors: [StoredTensor] = [] + for index in 1 ... 3 { + let url = inputs.appendingPathComponent("model-0000\(index)-of-00003.safetensors.header.json") + let header = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) + for (name, value) in header where name != "__metadata__" { + let entry = try #require(value as? [String: Any]) + tensors.append(.init(name: name, shape: try #require(entry["shape"] as? [Int]), + dtype: try #require(entry["dtype"] as? String))) + } + } + return tensors.sorted { $0.name < $1.name } + } + + /// The registered configuration (QAT 4-bit, SHA-256 29910322…); the 8-bit + /// artifact's differs only in its default bits. + static func registeredConfiguration(bits: Int) throws -> [String: Any] { + var root = try #require(try JSONSerialization.jsonObject( + with: Data(contentsOf: inputs.appendingPathComponent("config.json"))) as? [String: Any]) + for key in ["quantization", "quantization_config"] { + var table = try #require(root[key] as? [String: Any]) + table["bits"] = bits + root[key] = table + } + return root + } + + static func elements(_ shape: [Int]) -> Int { shape.reduce(1, *) } + + /// Each rank's local logical shape of a module, from the plan's local geometry. + static func localLogical(_ plan: Gemma4TensorParallelPlan, layer: Int, module: String) throws -> [Int] { + let h = plan.hiddenSize, d = plan.headDim(layer: layer) + let dense = try plan.denseSplit(rank: 0).localWidth, expert = try plan.expertSplit(rank: 0).localWidth + switch module { + case "self_attn.q_proj": return [plan.queryHeadsPerRank * d, h] + case "self_attn.k_proj", "self_attn.v_proj": return [plan.kvHeadsPerRank[layer] * d, h] + case "self_attn.o_proj": return [h, plan.queryHeadsPerRank * d] + case "mlp.gate_proj", "mlp.up_proj": return [dense, h] + case "mlp.down_proj": return [h, dense] + case "experts.switch_glu.gate_proj", "experts.switch_glu.up_proj": return [plan.expertCount, expert, h] + case "experts.switch_glu.down_proj": return [plan.expertCount, h, expert] + case "router.proj": return [plan.expertCount, h] + default: throw ProbeError("no local shape for \(module)") + } + } + + /// Every text tensor of `tensors` (`shape` the whole stored shape) is the + /// shape the plan expects; each rank's part has the shape the rank's local + /// configuration constructs; rows, owned channels and replicated tensors + /// cover every tensor exactly once across the two ranks (an odd group + /// count overlaps one stored group, its other half zero); vision tensors + /// are refused. Returns each rank's stored bytes and the text bytes. + static func checkCoverage(_ plan: Gemma4TensorParallelPlan, _ tensors: [StoredTensor]) throws + -> (rankBytes: [Int], textBytes: Int, vision: Int) { + var rankBytes = [0, 0], textBytes = 0, vision = 0 + for tensor in tensors { + let width = tensor.dtype == "U32" || tensor.dtype == "F32" ? 4 : 2 + if !tensor.name.hasPrefix("language_model.") { + #expect(Gemma4TensorParallelPlan.isVisionTensor(tensor.name), "\(tensor.name) is neither text nor vision") + #expect(throws: (any Error).self) { try plan.cut(key: tensor.name, rank: 0) } + vision += 1 + continue + } + textBytes += elements(tensor.shape) * width + #expect(try plan.expectedShape(key: tensor.name) == tensor.shape, "\(tensor.name): \(tensor.shape)") + let cuts = try (0 ..< 2).map { try plan.cut(key: tensor.name, rank: $0) } + let locals = try (0 ..< 2).map { try plan.localShape(key: tensor.name, shape: tensor.shape, cut: cuts[$0]) } + for rank in 0 ..< 2 { rankBytes[rank] += elements(locals[rank]) * width } + let parts = tensor.name.split(separator: ".").map(String.init) + let leaf = parts.last! + switch (cuts[0], cuts[1]) { + case (.replicate, .replicate): + #expect(locals[0] == tensor.shape && locals[1] == tensor.shape) + continue + case (.rows(let a, let a0, let a1), .rows(let b, let b0, let b1)), + (.expertRows(let a, let a0, let a1), .expertRows(let b, let b0, let b1)): + let axis = tensor.shape.count == 3 ? 1 : 0 + #expect(a.lowerBound == 0 && a.upperBound == b.lowerBound && b.upperBound == tensor.shape[axis], + "\(tensor.name): rows \(a), \(b) do not cover \(tensor.shape[axis]) exactly once") + #expect(a.count + a0 + a1 == b.count + b0 + b1, "\(tensor.name): unequal shares") + case (.inputColumns(let a), .inputColumns(let b)), (.expertInputColumns(let a), .expertInputColumns(let b)): + let module = parts.dropLast().joined(separator: ".") + let divisor = leaf == "weight" ? 32 / plan.bits(forModule: module) : plan.groupSize + let logical = tensor.shape.last! * divisor + #expect(a.lowerBound == 0 && b.upperBound == logical && a.count == b.count, "\(tensor.name): \(a) \(b)") + // Stored columns overlap by at most one group (an odd group count). + #expect(a.upperBound - b.lowerBound == 0 || a.upperBound - b.lowerBound == plan.groupSize, + "\(tensor.name): stored columns \(a), \(b) overlap by more than one group") + default: + Issue.record("\(tensor.name): the ranks' cuts are of different kinds") + continue + } + // The local shape is the local configuration's module, packed. + let layer = Int(parts[3])! + let module = parts[4 ..< parts.count - 1].joined(separator: ".") + let logical = try localLogical(plan, layer: layer, module: module) + let divisor = leaf == "weight" ? 32 / plan.bits(forModule: parts.dropLast().joined(separator: ".")) : plan.groupSize + #expect(locals[0] == logical.dropLast() + [logical.last! / divisor], "\(tensor.name): local \(locals[0])") + #expect(locals[1] == locals[0]) + } + return (rankBytes, textBytes, vision) + } + + @Test func planCoversTheRegisteredQAT4BitArtifactExactly() throws { + let tensors = try Self.registeredTensors() + let plan = try Gemma4TensorParallelPlan(configuration: try Self.registeredConfiguration(bits: 4)) + #expect(tensors.count == 1697) + let coverage = try Self.checkCoverage(plan, tensors) + #expect(coverage.vision == 358) + #expect(coverage.textBytes == 14_467_688_508, "the registered QAT 4-bit text bytes") + // Equal shares: with the replicated tensors, the shared group and its + // zero rows, each rank stores 55.6% of the text bytes. + #expect(coverage.rankBytes == [8_040_450_108, 8_040_450_108]) + #expect(plan.kvHeadsPerRank == (0 ..< 30).map { ($0 + 1) % 6 == 0 ? 1 : 4 }) + #expect(plan.queryHeadsPerRank == 8) + #expect(try plan.denseSplit(rank: 0).localWidth == 1088 && plan.expertSplit(rank: 1).localWidth == 384) + #expect(plan.reductionsPerForward == 60 && plan.reductionsPerStep == 1) + #expect(plan.layerPartialBytesPerToken == (1 + 8 + 1) * 2816 * 4) + } + + /// The 8-bit artifact (`gemma-4-26b-8bit`): the same names; the shapes the + /// plan expects at its default bits add up to its registered text bytes. + @Test func planCoversTheRegistered8BitArtifactExactly() throws { + let plan = try Gemma4TensorParallelPlan(configuration: try Self.registeredConfiguration(bits: 8)) + let tensors = try Self.registeredTensors().map { tensor -> StoredTensor in + guard tensor.name.hasPrefix("language_model.") else { return tensor } + return .init(name: tensor.name, shape: try plan.expectedShape(key: tensor.name), dtype: tensor.dtype) + } + let coverage = try Self.checkCoverage(plan, tensors) + #expect(coverage.textBytes == 26_810_869_820, "the registered 8-bit text bytes") + #expect(coverage.rankBytes == [14_915_635_260, 14_915_635_260]) + #expect(try plan.expectedShape(key: "language_model.model.embed_tokens.weight") == [262_144, 704]) + } + + @Test func planRefusesUnknownMisalignedAndVisionTensors() throws { + let plan = try Gemma4TensorParallelPlan(configuration: try Self.registeredConfiguration(bits: 4)) + for key in ["language_model.lm_head.weight", "language_model.model.layers.5.self_attn.v_proj.weight", + "language_model.model.layers.30.input_layernorm.weight", "language_model.model.layers.0.experts.gate_up_proj", + "language_model.model.layers.00.layer_scalar", "vision_tower.encoder.layers.0.mlp.fc1.weight", + "embed_vision.embedding_projection.weight", "model.layers.0.mlp.down_proj.weight"] { + #expect(throws: (any Error).self, "\(key)") { try plan.cut(key: key, rank: 0) } + } + #expect(throws: (any Error).self) { try plan.cut(key: "language_model.model.norm.weight", rank: 2) } + // A cut that would split a packed word or a group is refused. + #expect(throws: (any Error).self) { + try plan.localShape(key: "language_model.model.layers.0.mlp.down_proj.weight", shape: [2816, 528], + cut: .inputColumns(0 ..< 1056)) + } + func refuses(_ change: (inout [String: Any]) -> Void) throws { + var root = try Self.registeredConfiguration(bits: 4) + var text = try #require(root["text_config"] as? [String: Any]) + change(&text) + root["text_config"] = text + #expect(throws: (any Error).self) { try Gemma4TensorParallelPlan(configuration: root) } + } + try refuses { $0["intermediate_size"] = 2112 + 32 } // not whole groups + try refuses { $0["head_dim"] = 36 } // attention shard off a group + try refuses { $0["num_global_key_value_heads"] = 1 } // a KV head would split + try refuses { $0["tie_word_embeddings"] = false } // untied head + try refuses { $0["enable_moe_block"] = false } // dense variants + try refuses { $0["num_kv_shared_layers"] = 4 } // shared KV + try refuses { $0["layer_types"] = ["sliding_attention"] } // kinds per layer + var root = try Self.registeredConfiguration(bits: 4) + var table = try #require(root["quantization"] as? [String: Any]) + table["language_model.model.layers.0.experts.switch_glu.down_proj"] = ["group_size": 32, "bits": 8] + root["quantization"] = table + #expect(throws: (any Error).self) { try Gemma4TensorParallelPlan(configuration: root) } + } + + /// The plan's arithmetic and the SDK's (`Gemma4ChannelShard`, + /// `Gemma4TensorShard.localConfiguration`) are one split; the per-rank KV + /// geometry the SDK derives for the 26B is 4 sliding and 1 full head. + @Test func planAndSDKShardAgreeOnGeometry() throws { + for (width, group) in [(2112, 64), (704, 64), (320, 64), (192, 64), (256, 64), (2048, 128)] { + for rank in 0 ..< 2 { + let plan = try Gemma4TensorParallelPlan.ChannelSplit(width: width, groupSize: group, rank: rank) + let sdk = try Gemma4ChannelShard(width: width, groupSize: group, rank: rank) + #expect(plan.channels == sdk.channels && plan.storedColumns == sdk.storedColumns) + #expect(plan.zeroBefore == sdk.paddingBefore && plan.zeroAfter == sdk.paddingAfter) + #expect(sdk.localWidth == (width / group + 1) / 2 * group) + } + } + let root = try Self.registeredConfiguration(bits: 4) + let plan = try Gemma4TensorParallelPlan(configuration: root) + let full = try JSONDecoder().decode(Gemma4Configuration.self, + from: JSONSerialization.data(withJSONObject: root)).textConfiguration + for rank in 0 ..< 2 { + let local = try Gemma4TensorShard(rank: rank).localConfiguration(full) + let text = try plan.shardTextConfiguration(try #require(root["text_config"] as? [String: Any]), rank: rank) + #expect(local.numAttentionHeads == text["num_attention_heads"] as? Int) + #expect(local.numKeyValueHeads == text["num_key_value_heads"] as? Int) + #expect(local.numGlobalKeyValueHeads == text["num_global_key_value_heads"] as? Int) + #expect(local.intermediateSize == text["intermediate_size"] as? Int) + #expect(local.moeIntermediateSize == text["moe_intermediate_size"] as? Int) + #expect(local.cbv2LayerKinds.map(\.kvHeads) == plan.kvHeadsPerRank) + #expect(try Gemma4TensorShard(rank: rank).vocabularyRange(full) == plan.vocabularyRange(rank: rank)) + } + } + + // MARK: - Synthetic two-rank runs (CPU) + + /// The in-process pair's reduction for one rank. + private typealias Pair = Gemma4TensorParallelLocalPair + + private final class Box: @unchecked Sendable { var value: T; init(_ value: T) { self.value = value } } + + private static func synthetic(bits: Int, dtype: DType = .bfloat16) throws -> URL { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("gemma4-tp-\(bits)-\(dtype)-\(UUID().uuidString)") + try Device.withDefaultDevice(.cpu) { + try Gemma4TensorParallelModel.writeSyntheticCheckpoint(directory: directory, bits: bits, dtype: dtype) + } + return directory + } + + private static let prompt = (0 ..< 40).map { ($0 * 37 + 11) % 512 } + + /// Both ranks' generations, each rank on its own thread and stream. + private static func ranks(_ directory: URL, pack: Bool = true, steps: Int = 6, recordTop: Int = 4) + throws -> (generations: [Gemma4TensorParallelModel.Generation], payloads: [[Int]], models: [Gemma4TensorParallelModel]) { + let pair = Pair() + let models = try (0 ..< 2).map { rank in + try Device.withDefaultDevice(.cpu) { + try Gemma4TensorParallelModel.load(modelDirectory: directory, role: .shard(rank: rank), + reduction: pair.reduction(rank: rank), packFeedForward: pack) + } + } + let shared = Box(models) + let generations = try Pair.run(device: .cpu) { rank in + try shared.value[rank].generate(prompt: prompt, outputCount: steps, chunk: 16, recordTop: recordTop) + } + return (generations, pair.payloads, models) + } + + private static func single(_ directory: URL, role: Gemma4TensorParallelModel.Role, steps: Int = 6, + recordTop: Int = 4) throws -> Gemma4TensorParallelModel.Generation { + try Device.withDefaultDevice(.cpu) { + let model = try Gemma4TensorParallelModel.load(modelDirectory: directory, role: role, reduction: nil) + return try model.generate(prompt: prompt, outputCount: steps, chunk: 16, recordTop: recordTop) + } + } + + private static func bits(_ rows: [[Float]]) -> [[UInt32]] { rows.map { $0.map(\.bitPattern) } } + + /// Every parameter of each rank's shard equals an independent slice of the + /// whole stored tensor (rows, stored columns, zero rows for the other + /// rank's half of an overlapped group), and a zero row dequantizes to zero. + @Test(arguments: [4, 8]) func shardParametersEqualReferenceSlices(bits: Int) throws { + let directory = try Self.synthetic(bits: bits) + defer { try? FileManager.default.removeItem(at: directory) } + try Device.withDefaultDevice(.cpu) { + let whole = try loadArrays(url: directory.appendingPathComponent("model.safetensors")) + let plan = try Gemma4TensorParallelPlan(configuration: try #require(try JSONSerialization.jsonObject( + with: Data(contentsOf: directory.appendingPathComponent("config.json"))) as? [String: Any])) + let pair = Pair() + for rank in 0 ..< 2 { + let model = try Gemma4TensorParallelModel.load(modelDirectory: directory, role: .shard(rank: rank), + reduction: pair.reduction(rank: rank)) + let parameters = Dictionary(uniqueKeysWithValues: model.model.parameters().flattened()) + #expect(Set(parameters.keys) == Set(whole.keys)) + let dense = try plan.denseSplit(rank: rank), expert = try plan.expertSplit(rank: rank) + for (key, value) in whole.sorted(by: { $0.key < $1.key }) { + let local = try #require(parameters[key]) + let leaf = key.split(separator: ".").last! + let module = key.split(separator: ".").dropLast().joined(separator: ".") + let divisor = leaf == "weight" ? 32 / plan.bits(forModule: module) : plan.groupSize + let layer = key.hasPrefix("language_model.model.layers.") ? Int(key.split(separator: ".")[3])! : 0 + let d = plan.headDim(layer: layer), q = plan.queryHeadsPerRank, kv = plan.kvHeadsPerRank[layer] + func zeros(_ shape: [Int]) -> MLXArray { MLXArray.zeros(shape, dtype: value.dtype) } + var expected: MLXArray + if key.contains(".self_attn.q_proj.") { + expected = value[(rank * q * d) ..< ((rank + 1) * q * d)] + } else if key.contains(".self_attn.k_proj.") || key.contains(".self_attn.v_proj.") { + expected = value[(rank * kv * d) ..< ((rank + 1) * kv * d)] + } else if key.contains(".self_attn.o_proj.") { + expected = value[0..., (rank * q * d / divisor) ..< ((rank + 1) * q * d / divisor)] + } else if key.contains(".mlp.gate_proj.") || key.contains(".mlp.up_proj.") { + let rows = value[dense.channels] + let pad = zeros([dense.localWidth - dense.channels.count, value.dim(1)]) + expected = concatenated(rank == 0 ? [rows, pad] : [pad, rows], axis: 0) + } else if key.contains(".mlp.down_proj.") { + expected = value[0..., (dense.storedColumns.lowerBound / divisor) ..< (dense.storedColumns.upperBound / divisor)] + } else if key.contains(".experts.switch_glu.gate_proj.") || key.contains(".experts.switch_glu.up_proj.") { + let rows = value[0..., expert.channels] + let pad = zeros([value.dim(0), expert.localWidth - expert.channels.count, value.dim(2)]) + expected = concatenated(rank == 0 ? [rows, pad] : [pad, rows], axis: 1) + } else if key.contains(".experts.switch_glu.down_proj.") { + expected = value[0..., 0..., (expert.storedColumns.lowerBound / divisor) ..< (expert.storedColumns.upperBound / divisor)] + } else { + expected = value + } + #expect(local.shape == expected.shape && local.dtype == expected.dtype, "\(key) rank \(rank)") + #expect(arrayEqual(local, expected).item(Bool.self), "\(key) rank \(rank) differs from its slice") + } + // A padded channel of the dense and expert gate projections dequantizes to zero. + let gate = try #require(model.textModel.model.layers[0].mlp.gateProj as? QuantizedLinear) + let padded = rank == 0 ? dense.localWidth - 1 : 0 + let row = dequantized(gate.weight[padded ..< padded + 1], scales: gate.scales[padded ..< padded + 1], + biases: gate.biases?[padded ..< padded + 1], groupSize: gate.groupSize, bits: gate.bits) + #expect(row.abs().max().item(Float.self) == 0) + #expect(model.textModel.kvHeads == plan.kvHeadsPerRank) + } + } + } + + /// Two real ranks, a 40-token prompt in 16-token chunks (sorted expert + /// gathers) and greedy steps: every token, recorded top logit and log + /// probability and the final row on both ranks equal the single-process + /// oracle bit for bit, with two collectives a layer plus the head's. + @Test(arguments: [4, 8]) func tensorParallelRanksEqualTheSplitSumOracleBitwise(bits: Int) throws { + let directory = try Self.synthetic(bits: bits) + defer { try? FileManager.default.removeItem(at: directory) } + let splitSum = try Self.single(directory, role: .splitSum) + let pair = try Self.ranks(directory) + for (rank, generation) in pair.generations.enumerated() { + #expect(generation.tokenIDs == splitSum.tokenIDs, "rank \(rank) tokens differ from the oracle") + #expect(generation.topTokenIDs == splitSum.topTokenIDs) + #expect(Self.bits(generation.topLogits) == Self.bits(splitSum.topLogits), "rank \(rank) logits") + #expect(Self.bits(generation.topLogprobs) == Self.bits(splitSum.topLogprobs), "rank \(rank) log probabilities") + #expect(generation.finalLogits.map { $0.map(\.bitPattern) } == splitSum.finalLogits.map { $0.map(\.bitPattern) }) + } + let layers = pair.models[0].plan.layerCount, hidden = pair.models[0].plan.hiddenSize + let forwards = 3 + 5 // three prompt chunks, five decode steps + let heads = 6 * 2 + 1 // a selection and a top-k per step, the final row + #expect(pair.payloads.count == forwards * 2 * layers + heads) + // A decode step's packed feed-forward collective: four expert rows and the dense row. + #expect(pair.payloads.contains([5, hidden])) + // A prefill chunk's: 16 x 4 expert rows and 16 dense rows. + #expect(pair.payloads.contains([16 * 4 + 16, hidden])) + } + + /// The dense partial packed in the experts' collective against its own + /// collective: the same bits, two collectives a layer against three. + @Test func packedFeedForwardCollectiveEqualsTwoCollectives() throws { + let directory = try Self.synthetic(bits: 4) + defer { try? FileManager.default.removeItem(at: directory) } + let packed = try Self.ranks(directory, pack: true, steps: 4, recordTop: 0) + let separate = try Self.ranks(directory, pack: false, steps: 4, recordTop: 0) + for rank in 0 ..< 2 { + #expect(packed.generations[rank].tokenIDs == separate.generations[rank].tokenIDs) + } + let layers = packed.models[0].plan.layerCount, forwards = 3 + 3 + #expect(packed.payloads.count == forwards * 2 * layers + 4) + #expect(separate.payloads.count == forwards * 3 * layers + 4) + } + + /// Each oracle projection against the whole projection it replaces, on + /// random inputs: the split sums change only rounding. + @Test(arguments: [DType.float32, .bfloat16]) func splitSumProjectionsEqualWholeProjections(dtype: DType) throws { + let directory = try Self.synthetic(bits: 4, dtype: dtype) + defer { try? FileManager.default.removeItem(at: directory) } + try Device.withDefaultDevice(.cpu) { + let full = try Gemma4TensorParallelModel.load(modelDirectory: directory, role: .full, reduction: nil) + let splitSum = try Gemma4TensorParallelModel.load(modelDirectory: directory, role: .splitSum, reduction: nil) + let tolerance: Float = dtype == .float32 ? 1e-4 : 2e-2 + for layer in [0, 2] { + let a = full.textModel.model.layers[layer], b = splitSum.textModel.model.layers[layer] + #expect(b.selfAttn.oProj is Gemma4SplitSumLinear && b.mlp.downProj is Gemma4SplitSumLinear) + for (whole, oracle) in [(a.selfAttn.oProj, b.selfAttn.oProj), (a.mlp.downProj, b.mlp.downProj)] { + let input = withRandomState(MLXRandom.RandomState(seed: UInt64(layer + 1))) { + MLXRandom.normal([1, 3, (whole as! QuantizedLinear).shape.1]).asType(dtype) + } + let expected = whole(input).asType(.float32), actual = oracle(input).asType(.float32) + let scale = expected.abs().max().item(Float.self) + let error = (expected - actual).abs().max().item(Float.self) + #expect(error <= tolerance * max(1, scale), "layer \(layer): \(error) of \(scale)") + } + let wholeExperts = try #require(a.experts?.switchGLU), oracleExperts = try #require(b.experts?.switchGLU) + let x = withRandomState(MLXRandom.RandomState(seed: 9)) { MLXRandom.normal([20, 256]).asType(dtype) } + let indices = withRandomState(MLXRandom.RandomState(seed: 10)) { + MLXRandom.randInt(low: 0, high: 16, [20, 4]).asType(.uint32) + } + let expected = wholeExperts(x, indices).asType(.float32), actual = oracleExperts(x, indices).asType(.float32) + let scale = expected.abs().max().item(Float.self) + let error = (expected - actual).abs().max().item(Float.self) + #expect(error <= tolerance * max(1, scale), "layer \(layer) experts: \(error) of \(scale)") + } + } + } + + /// Diagnostic (`GEMMA_TP_DIAG=1`, `GEMMA_TP_DIAG_DEVICE=gpu` with + /// `mlx.metallib` beside the test bundle): each column-parallel operation + /// of a rank against the same rows of the whole operation, bit for bit. + @Test(.enabled(if: ProcessInfo.processInfo.environment["GEMMA_TP_DIAG"] == "1")) + func diagnosticShardOperationsEqualWholeOperations() throws { + let directory = try Self.synthetic(bits: 4) + defer { try? FileManager.default.removeItem(at: directory) } + let device: Device = ProcessInfo.processInfo.environment["GEMMA_TP_DIAG_DEVICE"] == "gpu" ? .gpu : .cpu + try Device.withDefaultDevice(device) { try Self.compareOperations(directory, label: "\(device)") } + } + + private static func report(_ label: String, _ a: MLXArray, _ b: MLXArray) { + guard a.shape == b.shape else { print("DIAG \(label): SHAPES \(a.shape) \(b.shape)"); return } + let equal = arrayEqual(a, b).item(Bool.self) + let error = (a.asType(.float32) - b.asType(.float32)).abs().max().item(Float.self) + print("DIAG \(label): \(equal ? "bitwise" : "DIFFERS max \(error)")") + } + + private static func compareOperations(_ directory: URL, label: String) throws { + let full = try Gemma4TensorParallelModel.load(modelDirectory: directory, role: .full, reduction: nil) + let shard = try Gemma4TensorParallelModel.load(modelDirectory: directory, role: .shard(rank: 0), + reduction: QwenTensorParallelLocalReduction(rank: 0, size: 2)) + for tokens in [1, 16] { + let x = withRandomState(MLXRandom.RandomState(seed: 3)) { MLXRandom.normal([1, tokens, 256]).asType(.bfloat16) } + for layer in [0, 2] { + let f = full.textModel.model.layers[layer], s = shard.textModel.model.layers[layer] + let tag = "\(label) T\(tokens) L\(layer)" + let qs = s.selfAttn.qProj(x), qf = f.selfAttn.qProj(x) + report("\(tag) q_proj", qf[.ellipsis, 0 ..< qs.dim(-1)], qs) + let ks = s.selfAttn.kProj!(x), kf = f.selfAttn.kProj!(x) + report("\(tag) k_proj", kf[.ellipsis, 0 ..< ks.dim(-1)], ks) + report("\(tag) gate_proj", f.mlp.gateProj(x)[.ellipsis, 0 ..< 160], s.mlp.gateProj(x)[.ellipsis, 0 ..< 160]) + let headDim = qs.dim(-1) / 8 + let qd = qs.reshaped(1, tokens, 8, headDim).transposed(0, 2, 1, 3) + let kd = ks.reshaped(1, tokens, ks.dim(-1) / headDim, headDim).transposed(0, 2, 1, 3) + let qw = qf.reshaped(1, tokens, 16, headDim).transposed(0, 2, 1, 3) + let kw = kf.reshaped(1, tokens, kf.dim(-1) / headDim, headDim).transposed(0, 2, 1, 3) + let half = MLXFast.scaledDotProductAttention(queries: qd, keys: kd, values: kd, scale: 1, mask: .causal) + let whole = MLXFast.scaledDotProductAttention(queries: qw, keys: kw, values: kw, scale: 1, mask: .causal) + report("\(tag) sdpa", whole[0..., 0 ..< 8], half) + } + let hidden = withRandomState(MLXRandom.RandomState(seed: 5)) { MLXRandom.normal([1, tokens, 256]).asType(.bfloat16) } + report("\(label) T\(tokens) head", full.textModel.applyLMHead(hidden)[.ellipsis, 0 ..< 256], + shard.textModel.applyLMHead(hidden)) + } + } + + /// The whole model against the oracle: an FP32 synthetic model (a random + /// router's top-k ties are too close for BF16 rounding to keep) agrees on + /// every token; the split sums change only rounding. + @Test func wholeModelAndSplitSumOracleAgreeOnTokensInFloat32() throws { + let directory = try Self.synthetic(bits: 4, dtype: .float32) + defer { try? FileManager.default.removeItem(at: directory) } + let full = try Self.single(directory, role: .full, steps: 8) + let splitSum = try Self.single(directory, role: .splitSum, steps: 8) + #expect(full.tokenIDs == splitSum.tokenIDs) + for (a, b) in zip(full.topLogits, splitSum.topLogits) { + for (x, y) in zip(a, b) { #expect(abs(x - y) <= 1e-3 * max(1, abs(x))) } + } + } + + // MARK: - Vocabulary-split head + + /// Runs `body` on two rank threads, each with its own selection over its + /// half of `logits`; returns both ranks' results. + private static func splitHead(_ logits: MLXArray, _ body: @escaping (Gemma4TensorParallelSelection, MLXArray) throws -> T) + throws -> [T] { + let pair = Pair() + let vocabulary = logits.dim(-1) + eval(logits) + let shared = Box((logits, body)) + return try Pair.run(device: .cpu) { rank in + let range = (rank * vocabulary / 2) ..< ((rank + 1) * vocabulary / 2) + let selection = Gemma4TensorParallelSelection(vocabularyRange: range, vocabularySize: vocabulary, + reduction: pair.reduction(rank: rank)) + return try shared.value.1(selection, shared.value.0[0..., range]) + } + } + + private static func headLogits(seed: UInt64, tieAt planted: [Int] = []) -> MLXArray { + Device.withDefaultDevice(.cpu) { + var logits = withRandomState(MLXRandom.RandomState(seed: seed)) { MLXRandom.normal([1, 512]) * 3 } + if !planted.isEmpty { + let peak = logits.max().item(Float.self) + 1 + var values = logits.asArray(Float.self) + for index in planted { values[index] = peak } + logits = MLXArray(values, [1, 512]) + } + return logits + } + } + + @Test func splitVocabularyGreedyEqualsTheWholeHead() throws { + for (seed, planted) in [(1, []), (2, [37, 300]), (3, [300, 400]), (4, [255, 256]), (5, [511])] as [(UInt64, [Int])] { + let logits = Self.headLogits(seed: seed, tieAt: planted) + let whole = Device.withDefaultDevice(.cpu) { Int(argMax(logits, axis: -1).item(Int32.self)) } + let split = try Self.splitHead(logits) { selection, local -> Int in + let token = selection.greedy(local) + eval(token) + return Int(token.item(Int32.self)) + } + #expect(split == [whole, whole], "seed \(seed): \(split) against \(whole)") + if let first = planted.first { #expect(whole == first) } + } + } + + @Test func splitVocabularyTopKLogprobsEqualTheWholeHead() throws { + for seed in [11, 12, 13] as [UInt64] { + let logits = Self.headLogits(seed: seed) + let whole = try Device.withDefaultDevice(.cpu) { + try Gemma4TensorParallelSelection(vocabularyRange: 0 ..< 512, vocabularySize: 512, reduction: nil) + .topK(logits, count: 16) + } + let reference = Device.withDefaultDevice(.cpu) { (logits - logSumExp(logits, axis: -1, keepDims: true)).asArray(Float.self) } + let split = try Self.splitHead(logits) { selection, local in try selection.topK(local, count: 16) } + for result in split { + #expect(result.tokenIDs == whole.tokenIDs) + #expect(Self.bits([result.logits]) == Self.bits([whole.logits])) + for (index, id) in result.tokenIDs.enumerated() { + #expect(abs(result.logprobs[index] - reference[id]) <= 2e-6, "seed \(seed) token \(id)") + #expect(abs(whole.logprobs[index] - reference[id]) <= 2e-6) + } + } + #expect(split[0].logprobs.map(\.bitPattern) == split[1].logprobs.map(\.bitPattern)) + } + } + + /// Keyed noise: each rank's part of the whole vocabulary's Gumbel noise + /// and the argmax collective draw exactly the whole row's Gumbel-max + /// sample under the same key; the row gather keeps every bit, so the + /// product's sampler draws the whole row's token from it on every rank. + @Test func keyedSamplingAndRowGatherEqualTheWholeHead() throws { + let logits = Self.headLogits(seed: 21) + for (seed, temperature) in [(1, 0.7), (2, 1.0), (3, 1.3), (4, 0.2)] as [(UInt64, Float)] { + let key = MLXRandom.key(seed) + let whole = Device.withDefaultDevice(.cpu) { + Int(argMax(MLXRandom.gumbel([1, 512], key: key) + logits * (1 / temperature), axis: -1).item(Int32.self)) + } + let split = try Self.splitHead(logits) { selection, local -> Int in + let token = selection.sample(local, temperature: temperature, key: key) + eval(token) + return Int(token.item(Int32.self)) + } + #expect(split == [whole, whole], "key \(seed) temperature \(temperature)") + } + let rows = try Self.splitHead(logits) { selection, local -> [UInt32] in + let row = selection.gather(local) + eval(row) + return row.asArray(Float.self).map(\.bitPattern) + } + let expected = Device.withDefaultDevice(.cpu) { logits.asArray(Float.self).map(\.bitPattern) } + #expect(rows == [expected, expected]) + let key = MLXRandom.key(9) + let product = Device.withDefaultDevice(.cpu) { Int(MLXRandom.categorical(logits * (1 / Float(0.8)), key: key).item(Int32.self)) } + let gathered = try Self.splitHead(logits) { selection, local -> Int in + Int(MLXRandom.categorical(selection.gather(local) * (1 / Float(0.8)), key: key).item(Int32.self)) + } + #expect(gathered == [product, product]) + } +} diff --git a/libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/GemmaTensorParallelPlanCheck.swift b/libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/GemmaTensorParallelPlanCheck.swift new file mode 100644 index 0000000000..22cb81f00c --- /dev/null +++ b/libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/GemmaTensorParallelPlanCheck.swift @@ -0,0 +1,94 @@ +import Foundation + +// Model-free checks of `Gemma4TensorParallelPlan` against the registered +// Gemma 4 26B QAT 4-bit artifact's safetensors headers (no payload) and the +// 8-bit artifact's shapes derived from them: every text tensor has the shape +// the plan expects; the two ranks' cuts cover it exactly once (rows, owned +// channels) or replicate it, with equal local shapes; the text bytes equal +// the registered totals; vision, unknown and misaligned inputs are refused. + +nonisolated(unsafe) var failures = 0 +func check(_ condition: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String) rethrows { + if try !condition() { failures += 1; print("FAIL: \(message())") } +} +func refuses(_ label: String, _ body: () throws -> Void) { + do { try body(); failures += 1; print("FAIL: expected a refusal: \(label)") } catch {} +} + +@main enum GemmaTensorParallelPlanCheck { + static func main() throws { + let inputs = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true) + var tensors: [(name: String, shape: [Int], dtype: String)] = [] + for index in 1 ... 3 { + let url = inputs.appendingPathComponent("model-0000\(index)-of-00003.safetensors.header.json") + let header = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as! [String: Any] + for (name, value) in header where name != "__metadata__" { + let entry = value as! [String: Any] + tensors.append((name, entry["shape"] as! [Int], entry["dtype"] as! String)) + } + } + func configuration(bits: Int) throws -> [String: Any] { + var root = try JSONSerialization.jsonObject(with: Data(contentsOf: inputs.appendingPathComponent("config.json"))) as! [String: Any] + for key in ["quantization", "quantization_config"] { + var table = root[key] as! [String: Any] + table["bits"] = bits + root[key] = table + } + return root + } + for (bits, registered) in [(4, 14_467_688_508), (8, 26_810_869_820)] { + let plan = try Gemma4TensorParallelPlan(configuration: try configuration(bits: bits)) + var text = 0, ranks = [0, 0], vision = 0 + for tensor in tensors { + let width = tensor.dtype == "U32" ? 4 : 2 + if !tensor.name.hasPrefix("language_model.") { + check(Gemma4TensorParallelPlan.isVisionTensor(tensor.name), "\(tensor.name) is neither text nor vision") + refuses("vision \(tensor.name)") { _ = try plan.cut(key: tensor.name, rank: 0) } + vision += 1 + continue + } + let shape = bits == 4 ? tensor.shape : try plan.expectedShape(key: tensor.name) + try check(try plan.expectedShape(key: tensor.name) == shape, "\(tensor.name): \(tensor.shape)") + text += shape.reduce(width, *) + let cuts = try (0 ..< 2).map { try plan.cut(key: tensor.name, rank: $0) } + let locals = try (0 ..< 2).map { try plan.localShape(key: tensor.name, shape: shape, cut: cuts[$0]) } + check(locals[0] == locals[1], "\(tensor.name): unequal local shapes \(locals)") + for rank in 0 ..< 2 { ranks[rank] += locals[rank].reduce(width, *) } + switch (cuts[0], cuts[1]) { + case (.replicate, .replicate): + break + case (.rows(let a, _, _), .rows(let b, _, _)), (.expertRows(let a, _, _), .expertRows(let b, _, _)): + let axis = shape.count == 3 ? 1 : 0 + check(a.lowerBound == 0 && a.upperBound == b.lowerBound && b.upperBound == shape[axis], + "\(tensor.name): rows \(a) \(b) do not cover \(shape[axis]) once") + case (.inputColumns(let a), .inputColumns(let b)), (.expertInputColumns(let a), .expertInputColumns(let b)): + let overlap = a.upperBound - b.lowerBound + check(a.lowerBound == 0 && a.count == b.count && (overlap == 0 || overlap == plan.groupSize), + "\(tensor.name): columns \(a) \(b)") + default: + check(false, "\(tensor.name): the ranks' cuts differ in kind") + } + } + check(vision == 358, "\(vision) vision tensors") + check(text == registered, "\(bits)-bit text bytes \(text), registered \(registered)") + check(plan.kvHeadsPerRank == (0 ..< 30).map { ($0 + 1) % 6 == 0 ? 1 : 4 }, "per-rank KV heads") + try check(try plan.denseSplit(rank: 1).localWidth == 1088 && plan.expertSplit(rank: 0).localWidth == 384, "local widths") + print("\(bits)-bit: \(tensors.count - vision) text tensors, \(text) bytes, \(ranks[0]) bytes per rank") + } + let plan = try Gemma4TensorParallelPlan(configuration: try configuration(bits: 4)) + for key in ["language_model.lm_head.weight", "language_model.model.layers.5.self_attn.v_proj.weight", + "language_model.model.layers.30.layer_scalar", "embed_vision.embedding_projection.weight"] { + refuses(key) { _ = try plan.cut(key: key, rank: 0) } + } + for (key, value) in [("intermediate_size", 2144 as Any), ("head_dim", 36), ("num_global_key_value_heads", 1), + ("tie_word_embeddings", false), ("enable_moe_block", false)] { + var root = try configuration(bits: 4) + var text = root["text_config"] as! [String: Any] + text[key] = value + root["text_config"] = text + refuses(key) { _ = try Gemma4TensorParallelPlan(configuration: root) } + } + print(failures == 0 ? "Gemma tensor-parallel plan checks passed" : "\(failures) Gemma plan check failures") + exit(failures == 0 ? 0 : 1) + } +} diff --git a/libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/gemma-run.sh b/libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/gemma-run.sh new file mode 100755 index 0000000000..a64caf123b --- /dev/null +++ b/libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/gemma-run.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Model-free checks of the Gemma 4 tensor-parallel plan (no MLX, no GPU, no +# SwiftPM) against the registered 26B artifact's safetensors headers in +# Tests/StageMetadataChecks/Inputs. Swift 6, warnings as errors. +# bash libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/gemma-run.sh +set -euo pipefail +package="$(cd "$(dirname "$0")/../.." && pwd)" +build="$(mktemp -d "${TMPDIR:-/tmp}/cluster-gemma-tp-plan.XXXXXXXX")" +trap 'rm -rf "$build"' EXIT +xcrun swiftc -swift-version 6 -warnings-as-errors -target "$(uname -m)-apple-macos14.0" -parse-as-library \ + "$package/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPlan.swift" \ + "$package/Sources/DarkbloomClusterRuntime/Support/ClusterRuntimeError.swift" \ + "$package/Tests/TensorParallelPlanChecks/GemmaTensorParallelPlanCheck.swift" -o "$build/gemma-tp-plan-check" +"$build/gemma-tp-plan-check" "$package/Tests/StageMetadataChecks/Inputs" diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 7933a0faad..6544d45a52 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 7933a0faad62559a010a1126241c61a1822315d9 +Subproject commit 6544d45a52a0e180d7190da2644c3f7e91f79cd4 From fdabade31a5433186c022d5be270925df7368ba3 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:04:05 -0700 Subject: [PATCH 0029/1441] perf(cluster): MiMo pipeline decode in 100-operation command buffers MiMo stage decode now encodes its Metal command buffers as GLM's and Qwen's tensor-parallel decode do: up to 100 operations a buffer with no input-size bound (MiMoLayerStageSession.decodeCommandBuffers), on the thread that encodes the step. That covers plain and compact decode frames, phase-split and alone-route decode (MiMoLayerStageSession.decode), lane steps (decodeBatch) and pipeline_mtp_v1 rounds, drafts included (MiMoMTPGeneration.runProducer/runConsumer). Prefill keeps the rank's 16-operation guard and MLX's per-chip size bound. Each routed layer's expert launch takes a whole 1 GiB bank, so under those limits a decode step committed a buffer every few launches. Only commit points move. MiMoDecodeCommandBufferTests drives two random stages as the session does (tiny BF16, and quantized like the registered row: MXFP4 experts, affine 8-bit projections, K/V widths 192/128) on ordinary caches, request-owned pages and two lanes, with a verify window rolled back on both stages. Residuals, logits rows and every cache and page array are byte-equal under the guard and the decode limits. Memory: MLX keeps up to ten command buffers in flight, so a whole stage step can now be in flight. MiMoRequestStateBudget charges every full-attention layer's decode-row scores at once (decodeRows: 1, or the verify window). The LOAD quote is unchanged; requests with prompts shorter than that window are charged slightly more. Planner: MiMoPlacementFamily states its routing (8 of 256 experts, the mlp.switch_mlp banks and scales). The hardware prior then reads 10,767,036,288 bytes a decode step instead of 166,600,109,952. The prior prices tensor parallel only, so MiMo plans are unchanged. The golden layout gains routedExperts. The four golden plan digests change only by the layout the plan echoes; MiMoRoutedExpertChecks proves that, and that without the block the plans are the recorded ones byte for byte. Not validated: the registered weights, the real pair and any speed. On one Mac a synthetic 8-layer stage stepped about 13% slower under the decode limits (encode-bound, KB-sized launches). The real pair A/B decides. Co-Authored-By: Claude Opus 5.5 --- changelog.d/mimo-pipeline-decode-buffers.md | 14 ++ docs/architecture/hardware-support.md | 6 +- docs/architecture/inference.md | 44 +++- docs/developer/test.md | 30 ++- .../Generation/MiMoLayerStageSession.swift | 21 +- .../Models/MiMo/MTP/MiMoMTPGeneration.swift | 29 ++- .../MiMo/Metadata/MiMoPlacementFamily.swift | 11 + .../Metadata/MiMoRequestStateBudget.swift | 16 +- .../MiMo/Resident/MiMoResidentAdmission.swift | 2 +- .../MiMoDecodeCommandBufferTests.swift | 215 ++++++++++++++++++ .../MiMoPagedAdmissionTests.swift | 2 +- .../MiMoResidentAdmissionTests.swift | 21 ++ .../PlacementChecks/Golden/expected.json | 4 +- .../mimo-v2.6-flash-mopd-2026-09-28-r1.json | 2 +- .../pairs/m3ultra-m5ultra/expected.json | 4 +- .../Tests/PlacementChecks/Main.swift | 1 + .../MiMoRoutedExpertChecks.swift | 75 ++++++ 17 files changed, 475 insertions(+), 22 deletions(-) create mode 100644 changelog.d/mimo-pipeline-decode-buffers.md create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoDecodeCommandBufferTests.swift create mode 100644 libs/darkbloom-cluster/Tests/PlacementChecks/MiMoRoutedExpertChecks.swift diff --git a/changelog.d/mimo-pipeline-decode-buffers.md b/changelog.d/mimo-pipeline-decode-buffers.md new file mode 100644 index 0000000000..fcc19cdbf2 --- /dev/null +++ b/changelog.d/mimo-pipeline-decode-buffers.md @@ -0,0 +1,14 @@ +### MiMo pipeline decode command buffers and expert routing + +- MiMo V2.6 Flash pairs encode decode steps, lane steps and speculative rounds + in Metal command buffers of up to 100 operations with no input-size bound, as + GLM and Qwen tensor parallel already do. Prefill keeps the rank's limits. + Tokens, logits and caches are byte-identical on synthetic stages. The speed + effect on the registered model has not been measured yet. +- A MiMo request's memory charge now covers every full-attention layer's decode + scores at once, which the larger command buffers can keep alive together. The + LOAD quote is unchanged; requests with prompts shorter than that window are + charged slightly more. +- The planner's hardware prior now counts MiMo's routed experts at the 8 of 256 + a token uses: 10.77 GB read per decode step instead of 166.6 GB. MiMo has no + tensor-parallel plan yet, so MiMo placements are unchanged. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index c91f96c2e6..338d70ee7b 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1,6 +1,6 @@ # Hardware support and the provider memory model -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 What hardware the provider runs on and how it decides, in bytes, whether a model may load and how much KV cache each resident model may use. Read this to @@ -1050,6 +1050,10 @@ attention views and sliding repack storage. Keys and values are priced with their distinct registered widths. Host prompt/selected-token histories and shared native decode workspace remain additional. Both MTP target ranks price the larger of the prompt chunk and the admitted `depth + 1` verification window. +Every MiMo rank's workspace also holds each of its full-attention layers' +scores for the decode rows at once, because decode command buffers keep a +whole step in flight (`MiMoRequestStateBudget`, `decodeRows`; +[MiMo pipeline decode command buffers](inference.md#mimo-pipeline-decode-command-buffers)). The trained assistant preserves its whole previous allocation envelope and adds separately rounded resident and working pages. Phase rank 1 prices every target layer; both ranks retain the moving-state allowance during transfer. Image diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..702162367b 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -4775,6 +4775,48 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Reside and `MiMoV26IndependentHistoryCache.swift`. See [MiMo independent-history checks](../developer/test.md#mimo-independent-history-batch-checks). +### MiMo pipeline decode command buffers + +MiMo stage decode encodes its Metal command buffers as GLM's and Qwen's +tensor-parallel decode do: up to 100 operations a buffer with no input-size +bound (`MiMoLayerStageSession.decodeCommandBuffers`), on the thread that encodes +the step. The rank's own limits are the worker's 16-operation guard +(`ClusterWorkerEnvironmentGuards`) and MLX's per-chip size bound, and each +routed layer's expert launch takes a whole 1 GiB expert bank as input, so under +those limits a decode step commits a buffer every few launches. Prefill frames +keep the rank's limits. + +| Work | Where the limits apply | +|---|---| +| Plain and compact decode frames, phase-split and alone-route decode | `MiMoLayerStageSession.decode` | +| Lane steps of independent histories | `MiMoLayerStageSession.decodeBatch` | +| Speculative rounds of `pipeline_mtp_v1`: drafts, verify windows, settlement | `MiMoMTPGeneration.runProducer`, `MiMoMTPGeneration.runConsumer` | + +Only the commit points move: every kernel, input and rounded value is the +same. `MiMoDecodeCommandBufferTests` compares residuals, logits rows and every +cache and page array byte for byte under both limits on synthetic stages. + +MLX keeps up to ten command buffers in flight (`MLX_MAX_ACTIVE_TASKS`), so under +the decode limits a whole stage step can be in flight at once. A request's +workspace therefore holds every full-attention layer's scores for its decode +rows at the same time (`MiMoRequestStateBudget.estimate`, `decodeRows`: one row, +or the verify window's `depth + 1`). It never charges less than one prompt +frame's scores on one layer. Gathered page views are already charged for every +layer (`MiMoPagedKVAllowance.pages`). The decode speed effect on the registered +model is not measured yet. + +### MiMo routed experts in placement + +`MiMoPlacementFamily` states MiMo's routing: each of the 47 routed layers sends +a token to 8 of its 256 experts (`expertRouting`). Its routed-expert tensors are +each layer's `mlp.switch_mlp` banks and their block scales (`isRoutedExpert`). +The router and its score correction are read on every step. The layout then +carries `routedExperts`, and the hardware prior +(`ClusterHardwarePrior.decodeBytesPerToken`) counts 10,767,036,288 bytes for one +decode step instead of every expert's 166,600,109,952. The prior prices tensor +parallel only. MiMo has no tensor-parallel plan, so its pipeline plans are +unchanged. + ### Gemma paged prefix restoration Installed plain Gemma pipelines retain the paged KV default at every supported diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..20f95f38d0 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -2186,6 +2186,34 @@ salt's digest); a repeat under another tenant must report no reused tokens. These are synthetic checks: tenant isolation on a real model and pair, and GLM bit-identity with no partition, are hardware gates. +## MiMo pipeline decode command buffers + +`MiMoDecodeCommandBufferTests` (cluster runtime, GPU) drives two random MiMo +stages as `MiMoLayerStageSession` drives them. The prompt runs under the rank's +16-operation guard. Decode steps, a verify window rolled back to two rows and +lane steps then run twice: once under the guard and once under +`MiMoLayerStageSession.decodeCommandBuffers`. Every residual crossing the cut, +every logits row and every cache or page array must be byte-equal. The tests +cover a tiny BF16 model and one quantized like the registered row (MXFP4 +experts, affine 8-bit projections, key width 192, value width 128), each on +ordinary caches and on request-owned pages. Build and stage the runtime tests +as described for the cluster runtime tests above, then, with the same build +flags: + +```bash +swift test --package-path libs/darkbloom-cluster -c release --skip-build --no-parallel \ + --filter 'MiMoDecodeCommandBufferTests|MiMoResidentAdmissionTests|MiMoPagedAdmissionTests' +bash libs/darkbloom-cluster/Tests/PlacementChecks/run.sh +``` + +The admission tests check that every full-attention layer's decode-row scores +are charged at once (`MiMoRequestStateBudget`). The placement run includes +`MiMoRoutedExpertChecks`: the MiMo layout built from the registered headers +names 282 routed-expert tensors (160,859,947,008 bytes). The hardware prior +reads 10,767,036,288 bytes for one decode step, and the golden plans change only +by the layout they echo. These are synthetic and metadata checks. They run no +registered weights and measure no speed. + ## MiMo paged speculative and phase checks Run `MiMoV26MTPPagedHistoryTests` and `MiMoV26IndependentHistoryTests` in the diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoLayerStageSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoLayerStageSession.swift index f3b1ecc887..86d6163aed 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoLayerStageSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoLayerStageSession.swift @@ -16,6 +16,19 @@ import MLXLMCommon /// sliding-window layer. Positions come from each cache's own offset, which /// both stages advance by the same token counts. final class MiMoLayerStageSession { + /// Command-buffer commit limits of a decode step, a lane step and a + /// speculative round on the thread that encodes them, as GLM's and Qwen's + /// tensor-parallel decode keep them + /// (`GLM5NextTensorParallelResidentRuntime.decodeCommandBuffers`). Under + /// the rank's 16-operation guard (`ClusterWorkerEnvironmentGuards`) and + /// MLX's per-chip input-size bound, which each routed layer's expert + /// launch passes alone (it takes a whole expert bank), a decode step + /// commits a buffer every few launches, each a GPU gap. Prefill keeps the + /// rank's limits. Synchronization only: results never depend on the + /// partitioning. MLX keeps up to ten buffers in flight, so a step's + /// in-flight work spans the stage's layers (`MiMoRequestStateBudget`). + static let decodeCommandBuffers = GPU.CommandBufferLimits(operations: 100, megabytes: 1 << 20) + let identity: QwenLayerStageSessionIdentity let request: QwenLayerStageGenerationRequest private let stage: LoadedMiMoLayerStage @@ -178,7 +191,9 @@ final class MiMoLayerStageSession { do { try requireOpen() let frame = try schedule.admitDecode(offset: offset) - return try perform(tokens: [token], frame: frame, incoming: incoming, check: check) + return try GPU.withCommandBufferLimits(Self.decodeCommandBuffers) { + try perform(tokens: [token], frame: frame, incoming: incoming, check: check) + } } catch { try fail(error) } } @@ -611,7 +626,7 @@ extension MiMoLayerStageSession: IndependentHistoryBatchSession { frames.append(try session.schedule.admitDecode(offset: session.committedTokens)) histories.append(pages) } - return try MLX.withError { error in + return try GPU.withCommandBufferLimits(decodeCommandBuffers) { try MLX.withError { error in func checked() throws { try error.check(); try check() } try checked() let last = first.stage.layerCount - 1 @@ -636,7 +651,7 @@ extension MiMoLayerStageSession: IndependentHistoryBatchSession { } if rank == 0 { Stream.gpu.synchronize(); try checked() } return output - } + } } } catch { var failure: Error = error for session in sessions { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoMTPGeneration.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoMTPGeneration.swift index da00e26b35..8b61c79125 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoMTPGeneration.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoMTPGeneration.swift @@ -232,9 +232,30 @@ enum MiMoMTPGeneration { } /// Rank 0: run each window rank 1 asks for, check what it keeps, publish. + /// Every round encodes as a decode step does (`MiMoLayerStageSession.decodeCommandBuffers`). static func runProducer(session: MiMoLayerStageSession, control: QwenLayerStageGenerationControl, terms: MiMoMTPTerms, collective: Collective, onCommittedToken: (Int) throws -> Bool, check: () throws -> Void) throws -> Outcome { + try GPU.withCommandBufferLimits(MiMoLayerStageSession.decodeCommandBuffers) { + try producerRounds(session: session, control: control, terms: terms, collective: collective, + onCommittedToken: onCommittedToken, check: check) + } + } + + /// Rank 1: draft, verify each window rank 0 runs, keep, and follow rank + /// 0's publication. Every round, drafts included, encodes as a decode + /// step does (`MiMoLayerStageSession.decodeCommandBuffers`). + static func runConsumer(session: MiMoLayerStageSession, decoder: MiMoMTPDecoder, + control: QwenLayerStageGenerationControl, collective: Collective, + check: () throws -> Void) throws -> Outcome { + try GPU.withCommandBufferLimits(MiMoLayerStageSession.decodeCommandBuffers) { + try consumerRounds(session: session, decoder: decoder, control: control, collective: collective, check: check) + } + } + + private static func producerRounds(session: MiMoLayerStageSession, control: QwenLayerStageGenerationControl, + terms: MiMoMTPTerms, collective: Collective, + onCommittedToken: (Int) throws -> Bool, check: () throws -> Void) throws -> Outcome { let agreement = control.agreement guard collective.rank == 0 else { throw ProbeError("Only rank 0 runs the producer side of a speculative round") } var selected: [Int] = [], discarded = 0 @@ -295,11 +316,9 @@ enum MiMoMTPGeneration { return .init(selected: selected, finalDecision: finalDecision, discardedDecodeForwards: discarded, statistics: nil) } - /// Rank 1: draft, verify each window rank 0 runs, keep, and follow rank - /// 0's publication. - static func runConsumer(session: MiMoLayerStageSession, decoder: MiMoMTPDecoder, - control: QwenLayerStageGenerationControl, collective: Collective, - check: () throws -> Void) throws -> Outcome { + private static func consumerRounds(session: MiMoLayerStageSession, decoder: MiMoMTPDecoder, + control: QwenLayerStageGenerationControl, collective: Collective, + check: () throws -> Void) throws -> Outcome { let agreement = control.agreement, request = agreement.request guard collective.rank == 1 else { throw ProbeError("Only rank 1 runs the consumer side of a speculative round") } let stopTokens = Set(request.stopTokenIDs) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift index 848ce31596..7aac45eddd 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift @@ -105,6 +105,17 @@ struct MiMoPlacementFamily: ClusterPlacementFamily { name.hasPrefix(MiMoLayerStagePlan.sourceNamespace + "model.mtp.") } + /// Each routed layer sends a token to `expertsPerToken` of its `experts`. + var expertRouting: ClusterExpertRouting? { + ClusterExpertRouting(selected: specification.expertsPerToken, experts: specification.experts) + } + + /// A routed layer's packed expert banks and their block scales; its router + /// and score correction are read on every step. + func isRoutedExpert(storedTensor name: String) -> Bool { + layer(ofStoredTensor: name) != nil && name.contains(".mlp.switch_mlp.") + } + /// The text tensors (every indexed tensor no stage excludes) are the /// registered inventory. func requireRegisteredInventory(_ tensors: [ClusterPlacementStoredTensor]) throws { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRequestStateBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRequestStateBudget.swift index 59ef8e4ac0..98f4a40c4b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRequestStateBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRequestStateBudget.swift @@ -11,7 +11,10 @@ import Foundation /// plus the chunk just appended, the same way. A stage also holds one residual /// chunk coming or going, and stage 1 one vocabulary row. The workspace term /// is the largest transient a forward is known to build: one full-attention -/// layer's score matrix for a chunk against the whole history, in float32. +/// layer's score matrix for a chunk against the whole history, in float32, +/// and never less than every full-attention layer's scores for the decode +/// rows at once (a decode step's command buffers keep the whole step in +/// flight, `MiMoLayerStageSession.decodeCommandBuffers`). struct MiMoRequestStateBudget: Encodable, Equatable { static let activationBytes = 2, growthStep = 256 let fullAttentionLayers: Int, slidingLayers: Int @@ -39,12 +42,16 @@ struct MiMoRequestStateBudget: Encodable, Equatable { reservedBytes: try QwenLongPrefillCheckedBytes.sum([reservedBytes, extra])) } + /// `decodeRows`: the most rows one decode forward runs (1, or a verify + /// window's `depth + 1`). static func estimate(specification spec: MiMoRegisteredSpecification, layers: Range, rank: Int, - maximumTokens: Int, chunkSize: Int, bound: (Int) throws -> Int) throws -> Self { + maximumTokens: Int, chunkSize: Int, decodeRows: Int = 1, + bound: (Int) throws -> Int) throws -> Self { let limits = try spec.contextLimits() guard (0...1).contains(rank), !layers.isEmpty, layers.lowerBound >= 0, layers.upperBound <= spec.layers, (1...limits.maximumContextTokens).contains(maximumTokens), - (1...limits.maximumChunkTokens).contains(chunkSize) else { + (1...limits.maximumChunkTokens).contains(chunkSize), + (1...limits.maximumChunkTokens).contains(decodeRows) else { throw MiMoProfileError("MiMo request state is outside the registered request scope") } let sum = QwenLongPrefillCheckedBytes.sum, product = QwenLongPrefillCheckedBytes.product @@ -66,7 +73,8 @@ struct MiMoRequestStateBudget: Encodable, Equatable { let boundary = try allowance(try product([chunkSize, spec.hidden, activationBytes]), 2) let row = rank == 1 ? try allowance(try product([spec.vocabulary, 4]), 2) : 0 // 64 query heads; the registered attention geometry fixes it. - let workspace = full == 0 ? 0 : try allowance(try product([64, chunkSize, capacity, 4]), 1) + let scoreRows = max(chunkSize, try product([decodeRows, full])) + let workspace = full == 0 ? 0 : try allowance(try product([64, scoreRows, capacity, 4]), 1) return .init(fullAttentionLayers: full, slidingLayers: sliding, fullAttentionStateBytes: fullState, slidingStateBytes: slidingState, boundaryBytes: boundary, rowBytes: row, workspaceBytes: workspace, reservedBytes: try sum([fullState, slidingState, boundary, row, workspace])) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentAdmission.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentAdmission.swift index a5f3a5ef14..981ba65d28 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentAdmission.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentAdmission.swift @@ -150,7 +150,7 @@ struct MiMoResidentRequestAllowance { let forwardTokens = max(chunkSize, verificationTokens) let layers = phaseSplit && rank == 1 ? 0..`) cannot complete a stop - sequence on its own. +- With tools declared, tool-call frames are not cut either. Without declared + tools a literal tool tag in an answer is text, and stops still apply to it. + Whitespace before the answer's first character (the blank line after + ``) cannot complete a stop sequence on its own. +- A stop sequence that names a marker no longer fires on it: ``, or + `` with tools declared. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 14d92783c4..6bd6d29fdf 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -2119,7 +2119,7 @@ disabled for this hybrid model. | `logit_bias` | `logitBias` — string keys parsed to non-negative `Int`; invalid keys dropped and counted | `[:]` | | `logprobs` + `top_logprobs` | `topLogprobs = logprobs ? min(20, max(1, top_logprobs ?? 0)) : 0` | `0` | | `max_tokens` | `maxTokens = max_tokens ?? 4096` | 4096 | -| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match. Gemma 4 and `` parsers exclude their reasoning and tool-call spans per request instead, starting inside reasoning when the prompt opened a think block (`ReasoningStopScope`). The native block engine (diffusion Gemma) matches the whole output, so its requests carry no scope. The reported sequence replays the request's scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | +| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match. Gemma 4 and `` parsers exclude their reasoning spans per request instead, starting inside reasoning when the prompt opened a think block, and their tool-call spans when the request parses tool calls (`ReasoningStopScope`). Without declared tools a literal tool tag in an answer is text the client receives, so stops still apply to it. The native block engine (diffusion Gemma) matches the whole output, so its requests carry no scope. The reported sequence replays the request's scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | | `min_p` | `minP`, forwarded by `EngineV2Bridge.submitTokenized` after translation | `0` | | `priority` | **Ignored**: always `0` | — | | `n`, `best_of` | **Not represented**: one alternative | — | diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index 7eed4bc348..e1e4b213b8 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -820,7 +820,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { mediaKind: visionPrepared.mediaKind, stopStringScope: ReasoningStopScope.scope( reasoningParser: visionRequest.reasoningParser, - reasoningPrefix: reasoningPrefix), + reasoningPrefix: reasoningPrefix, + parsesToolCalls: toolHandler != nil), donationDemand: donationDemand, firstContentDeadline: firstContentDeadline, profile: profile, @@ -1041,7 +1042,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { usageSignal: requestUsage, tokenConstraint: tokenConstraint, stopStringScope: ReasoningStopScope.scope( - reasoningParser: request.reasoningParser, reasoningPrefix: reasoningPrefix), + reasoningParser: request.reasoningParser, reasoningPrefix: reasoningPrefix, + parsesToolCalls: toolHandler != nil), donationDemand: donationDemand, firstContentDeadline: firstContentDeadline, profile: profile, @@ -1424,7 +1426,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { logitBias:engineV2Sampling?.logitBias,seed:engineV2Sampling?.seed), requestId:id,cacheScope:cacheScope,cacheEnabled:false,usageSignal:requestUsage, multimodal:native.request.multimodal, - stopStringScope:ReasoningStopScope.scope(reasoningParser:request.reasoningParser,reasoningPrefix:nil), + stopStringScope:ReasoningStopScope.scope(reasoningParser:request.reasoningParser,reasoningPrefix:nil,parsesToolCalls:toolHandler != nil), firstContentDeadline:firstContentDeadline,profile:profile, measurementPurpose:measurementPurpose) // Install the ONE existing router/forwarder before any post-submit diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift index ee0eddee8d..80bb50c6c3 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift @@ -4,7 +4,9 @@ // against all generated text, a stop the model happened to write while it // reasoned ended the request before any answer: finish_reason "stop", // reasoning only, empty content. Each scope mirrors the request's reasoning -// parser, so text it returns as reasoning, and tool-call frames, never match. +// parser, so text it returns as reasoning never matches. Tool-call frames don't +// either when the request parses tool calls; without declared tools a literal +// tool tag in an answer is text the client receives, so stops still apply. import Foundation import MLXLMCommon @@ -22,16 +24,18 @@ enum ReasoningStopScope { /// `ReasoningPromptProbe` state: an open think block means output starts /// inside reasoning. nil keeps the model's scope (GPT-OSS's Harmony final /// channel) or, without a reasoning parser, whole-output matching. + /// `parsesToolCalls` is whether the request has a tool stream handler. static func scope( - reasoningParser: ReasoningParserFormat?, reasoningPrefix: String? + reasoningParser: ReasoningParserFormat?, reasoningPrefix: String?, parsesToolCalls: Bool ) -> CBv2StopStringScope? { switch reasoningParser { case .qwen3?, .deepseekR1?: return CBv2StopStringScope( - excluding: [think, thinkToolCall], + excluding: parsesToolCalls ? [think, thinkToolCall] : [think], startingInside: reasoningPrefix == ReasoningPromptProbe.thinkOpen) case .gemma4?: - return CBv2StopStringScope(excluding: [gemmaThought, gemmaToolCall]) + return CBv2StopStringScope( + excluding: parsesToolCalls ? [gemmaThought, gemmaToolCall] : [gemmaThought]) default: return nil } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift index 4a5aebc122..8ded8dd4fa 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2BridgeTests.swift @@ -846,11 +846,11 @@ struct EngineV2MatchedStopSequenceTests { @Test("a scoped report names the stop that matched, not one that only starts there") func scopedReportNamesTheMatchingCandidate() { - let inside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "") + let inside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "", parsesToolCalls: true) #expect(EngineV2Bridge.matchedStopSequence( candidates: ["\n", "\nUser:"], generatedText: "r\n\nUser: hi", scope: inside ) == "\nUser:", "a bare newline before the answer does not stop it") - let outside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: nil) + let outside = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: nil, parsesToolCalls: true) #expect(EngineV2Bridge.matchedStopSequence( candidates: ["Ar", scope: outside ) == "A", "a stop never matches into a span") @@ -867,7 +867,7 @@ struct EngineV2MatchedStopSequenceTests { .finished(reason: .stop, usage: CBv2Usage(promptTokens: 5, completionTokens: 4)), ])) let bridge = makeBridge(engine: engine, tokenizer: tokenizer) - let scope = ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil) + let scope = ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil, parsesToolCalls: true) let signal = EngineV2RequestUsageSignal() _ = await record(await bridge.submitTokenized( promptTokens: [1, 2, 3], @@ -882,7 +882,7 @@ struct EngineV2MatchedStopSequenceTests { @Test("a request's scope replaces the model's, which applies otherwise") func modelScopeIsTheDefault() async { let harmony = ModelEOSPolicy.stopStringScope(modelId: "gpt-oss-20b") - let think = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "") + let think = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "", parsesToolCalls: true) for (modelScope, requestScope, expected) in [ (harmony, nil, harmony), (nil, nil, nil), (harmony, think, think), ] { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift index d63307e4ed..13821848c5 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeBlockRetirementBridgeTests.swift @@ -110,7 +110,7 @@ struct NativeBlockRetirementBridgeTests { let signal = EngineV2RequestUsageSignal() let result = await collect(await bridge.submitTokenized(promptTokens: [1], request: request, requestId: "scoped", cacheEnabled: false, usageSignal: signal, - stopStringScope: ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil))) + stopStringScope: ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil, parsesToolCalls: true))) #expect(result.text == "<|channel>thought\nIt is A" && result.error.isEmpty) #expect(signal.matchedStopSequence == ".") await bridge.shutdown() diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift index 65e457d5ae..119192c41a 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift @@ -19,13 +19,13 @@ struct ReasoningStopScopeTests { func thinkParsers() { for parser in [ReasoningParserFormat.qwen3, .deepseekR1] { #expect( - ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: "") + ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: "", parsesToolCalls: true) == CBv2StopStringScope( excluding: [ReasoningStopScope.think, ReasoningStopScope.thinkToolCall], startingInside: true)) for prefix in ["", nil] { #expect( - ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: prefix) + ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: prefix, parsesToolCalls: true) == CBv2StopStringScope( excluding: [ReasoningStopScope.think, ReasoningStopScope.thinkToolCall])) } @@ -35,17 +35,47 @@ struct ReasoningStopScopeTests { @Test("Gemma 4 excludes its thought channel and tool calls") func gemma() { #expect( - ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil) + ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil, parsesToolCalls: true) == CBv2StopStringScope(excluding: [ .init(opener: "<|channel>", closers: [""]), .init(opener: "<|tool_call>", closers: [""]), ])) } + @Test("without declared tools a literal tool tag in an answer is text, so stops still apply") + func toolTagsWithoutTools() { + let qwen = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: nil, parsesToolCalls: false) + #expect(qwen == CBv2StopStringScope(excluding: [ReasoningStopScope.think])) + #expect( + run("Use the tag. Close it. Done.", stops: ["."], scope: qwen) + == "Use the tag") + let gemma = ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil, parsesToolCalls: false) + #expect(gemma == CBv2StopStringScope(excluding: [ReasoningStopScope.gemmaThought])) + #expect( + run("Use the <|tool_call> tag. Close it. Done.", stops: ["."], scope: gemma) + == "Use the <|tool_call> tag") + // Reasoning still never matches, with or without tools. + #expect( + run("One. Two.Three. Four.", stops: ["."], scope: qwen) + == "One. Two.Three") + } + + @Test("with declared tools a stop never cuts a tool frame") + func toolTagsWithTools() { + let qwen = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: nil, parsesToolCalls: true) + #expect( + run("{\"a\": \"b.c\"}Done. More.", stops: ["."], scope: qwen) + == "{\"a\": \"b.c\"}Done") + } + @Test("Harmony keeps the model's scope; no parser keeps whole-output matching") func otherParsers() { for parser in [ReasoningParserFormat.harmony, ReasoningParserFormat.none, nil] { - #expect(ReasoningStopScope.scope(reasoningParser: parser, reasoningPrefix: "") == nil) + for parsesToolCalls in [true, false] { + #expect( + ReasoningStopScope.scope( + reasoningParser: parser, reasoningPrefix: "", parsesToolCalls: parsesToolCalls) == nil) + } } } @@ -55,7 +85,7 @@ struct ReasoningStopScopeTests { let output = "Capital of Australia. Canberra.\n\nKeep it short.\n\n\n" + "The capital of Australia is Canberra.\n\nIt is in the ACT." - let scope = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "") + let scope = ReasoningStopScope.scope(reasoningParser: .qwen3, reasoningPrefix: "", parsesToolCalls: true) #expect(run(output, stops: ["."], scope: nil) == "Capital of Australia") #expect( run(output, stops: ["."], scope: scope) @@ -72,7 +102,7 @@ struct ReasoningStopScopeTests { let output = "<|channel>thought\nCapital of Australia. Canberra.\n\nKeep it short." + "The capital of Australia is Canberra.\n\nIt is in the ACT." - let scope = ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil) + let scope = ReasoningStopScope.scope(reasoningParser: .gemma4, reasoningPrefix: nil, parsesToolCalls: true) #expect(run(output, stops: ["."], scope: nil) == "<|channel>thought\nCapital of Australia") #expect( run(output, stops: ["\n\n"], scope: scope) From 0b847bc484bba4e197357390db7ded2c674020c9 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:40:49 -0800 Subject: [PATCH 0090/1441] perf(provider): GPT-OSS plain decode commits by operation count Pins the SDK commit that declares decode command-buffer limits on GPTOSSModel, with docs and a changelog fragment. No provider source changes. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gptoss-decode-command-buffers.md | 3 +++ docs/architecture/inference.md | 11 +++++++++++ libs/mlx-swift-lm | 2 +- 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 changelog.d/gptoss-decode-command-buffers.md diff --git a/changelog.d/gptoss-decode-command-buffers.md b/changelog.d/gptoss-decode-command-buffers.md new file mode 100644 index 0000000000..986e75d062 --- /dev/null +++ b/changelog.d/gptoss-decode-command-buffers.md @@ -0,0 +1,3 @@ +### GPT-OSS plain decode commits by operation count + +- Plain decode steps of GPT-OSS commit a Metal command buffer every 100 operations instead of after almost every MoE layer. Outputs are bitwise identical. Prefill keeps MLX's defaults. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..b811f5f18e 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4813,6 +4813,17 @@ replace full-artifact qualification. Preserve earlier solo/pair reports and failed records; remeasure the candidate with the original comparator and qualification schedules. See [the test guide](../developer/test.md). +## GPT-OSS decode command buffers + +GPT-OSS's plain decode steps (every row one token) commit a Metal command buffer +every 100 operations with no input-size bound (`GPTOSSDecodeCommandBuffers`, +through `CBv2DecodeCommandBufferLimitsProviding`). MLX's defaults commit every 40 +to 50 operations or 40 to 50 M distinct input elements, and a step's inputs include +the expert banks and each 64 MiB KV segment its history reads, so decode committed +after almost every MoE layer and waited on MLX's limit of ten command buffers in +flight. Results do not depend on the partitioning. Prefill chunks keep MLX's +defaults. + ## Nemotron prefix chunk arithmetic The registered Nemotron 3.5 Lightning stage preserves the original global diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 7933a0faad..63baac23b1 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 7933a0faad62559a010a1126241c61a1822315d9 +Subproject commit 63baac23b19997be1051994926a9b0decaff2455 From 8fa6cbf8599047d27c372d54fde09f30b96c46ec Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:54:23 -0800 Subject: [PATCH 0091/1441] docs: freshness stamp for the GPT-OSS decode section Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index b811f5f18e..a76cbf75d0 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` From 7d085fe0e7341240eac67fd43772fd3ee953ea4a Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:54:24 -0800 Subject: [PATCH 0092/1441] docs: the stop scope depends on a tool handler, not only on declared tools tool_choice none and generic vision media with tools have no handler, and MiMo always has one. Comment and docs only. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 4 ++-- .../ProviderCore/Inference/Prompting/ReasoningStopScope.swift | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 6bd6d29fdf..57cc7d6d88 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -2119,7 +2119,7 @@ disabled for this hybrid model. | `logit_bias` | `logitBias` — string keys parsed to non-negative `Int`; invalid keys dropped and counted | `[:]` | | `logprobs` + `top_logprobs` | `topLogprobs = logprobs ? min(20, max(1, top_logprobs ?? 0)) : 0` | `0` | | `max_tokens` | `maxTokens = max_tokens ?? 4096` | 4096 | -| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match. Gemma 4 and `` parsers exclude their reasoning spans per request instead, starting inside reasoning when the prompt opened a think block, and their tool-call spans when the request parses tool calls (`ReasoningStopScope`). Without declared tools a literal tool tag in an answer is text the client receives, so stops still apply to it. The native block engine (diffusion Gemma) matches the whole output, so its requests carry no scope. The reported sequence replays the request's scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | +| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match. Gemma 4 and `` parsers exclude their reasoning spans per request instead, starting inside reasoning when the prompt opened a think block, and their tool-call spans when the request parses tool calls (`ReasoningStopScope`). Otherwise a literal tool tag in an answer is text the client receives, so stops still apply to it. The native block engine (diffusion Gemma) matches the whole output, so its requests carry no scope. The reported sequence replays the request's scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | | `min_p` | `minP`, forwarded by `EngineV2Bridge.submitTokenized` after translation | `0` | | `priority` | **Ignored**: always `0` | — | | `n`, `best_of` | **Not represented**: one alternative | — | diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift index 80bb50c6c3..0162d04e6e 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift @@ -5,8 +5,8 @@ // reasoned ended the request before any answer: finish_reason "stop", // reasoning only, empty content. Each scope mirrors the request's reasoning // parser, so text it returns as reasoning never matches. Tool-call frames don't -// either when the request parses tool calls; without declared tools a literal -// tool tag in an answer is text the client receives, so stops still apply. +// either when the request parses tool calls; otherwise a literal tool tag in an +// answer is text the client receives, so stops still apply. import Foundation import MLXLMCommon From 31fe79c7506c014ea1c288a0ed6539e1d90bcb90 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:54:24 -0800 Subject: [PATCH 0093/1441] docs: freshness stamp for the Gemma decode section Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 156bbdac12..01d78a0f03 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` From 637d643a3784524b663945680f0e7c44e5e2be20 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:00:58 -0800 Subject: [PATCH 0094/1441] cluster: say held-back tensor parallel can be chosen once measured Refactor pass over the fastest-plan evidence rule (d3fa4ce18, 43c9890ee, 709630c31). Text and comments only: the planner's logic is unchanged, and Qwen and GLM plans are byte-identical. - The `predictedFasterOnPriorOnly` plan line said tensor parallel "is chosen once its step is measured on both Macs", but a measurement can still find it slower. It now says "can be chosen". The Gemma PlacementCheck and the MiMo setup check that pin the line, and the two docs that quote it, follow. - PlacementSetupCheck: the MiMo plan-lines doc comment had been left on the new shared `capability(...)` builder. It is back on `mimoFastestPlanLines`. - The new changelog fragment says the device index alone "does not" choose tensor parallel: the behavior it replaces is unreleased. - inference.md: a speed record's shard rates count for every Mac of its chip and OS build, not only for one Mac. Co-Authored-By: Claude Opus 5.5 --- changelog.d/fastest-plan-evidence.md | 2 +- docs/architecture/inference.md | 9 +++++---- docs/provider/two-mac-cluster.md | 2 +- .../ClusterRequestMix.swift | 2 +- .../GemmaTensorParallelChecks.swift | 2 +- .../PlacementSetupCheck.swift | 14 +++++++------- 6 files changed, 16 insertions(+), 15 deletions(-) diff --git a/changelog.d/fastest-plan-evidence.md b/changelog.d/fastest-plan-evidence.md index f21137540f..ddb96316e8 100644 --- a/changelog.d/fastest-plan-evidence.md +++ b/changelog.d/fastest-plan-evidence.md @@ -1,6 +1,6 @@ ### Tensor parallel for Gemma 4 and MiMo only on measured speed -- Gemma 4 and MiMo V2.6 Flash pairs choose tensor parallel only once tensor parallel's own speed is measured on both Macs: each Mac's half timed by a tensor-parallel load (Gemma), or requests this Darkbloom build served in tensor parallel. An estimate from the Macs' device index alone no longer chooses it, because the index overstates what half a model saves on big Macs: on two M5 Ultra it predicts a short Gemma request 6% faster in tensor parallel, where the plans expect decode 6-8% slower. +- Gemma 4 and MiMo V2.6 Flash pairs choose tensor parallel only once tensor parallel's own speed is measured on both Macs: each Mac's half timed by a tensor-parallel load (Gemma), or requests this Darkbloom build served in tensor parallel. An estimate from the Macs' device index alone does not choose it, because the index overstates what half a model saves on big Macs: on two M5 Ultra it predicts a short Gemma request 6% faster in tensor parallel, where the plans expect decode 6-8% slower. - When the estimate says tensor parallel would be faster, the pair keeps the pipeline. The plan's "Tensor parallel or pipeline" line says the predicted gain and that it comes from the device index, and the model list says "tensor parallel: not measured yet". - Normal setups do not load tensor parallel to measure it, so these pairs keep the pipeline for now. MiMo does not yet time its halves at load, so MiMo pairs reach tensor parallel only from requests the same build served in tensor parallel. - Qwen and GLM still choose tensor parallel wherever it fits. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index b0b6f03ed3..e838c2265e 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4199,8 +4199,9 @@ sums cross the link: about 0.67-0.93x one M5 Ultra's decode, unmeasured **Evidence before tensor parallel.** A `fastest` family takes tensor parallel only when every rank of the placement has a measured share step (`ClusterDecodeSplit.measured`): a share probe of this model on that Mac -(`ClusterShareProbeHistory`, or a speed record's shard rates), or the shard -rates that requests this worker build served in tensor parallel corrected +(`ClusterShareProbeHistory`; a speed record of this model's shard rates counts +for every Mac of its chip and OS build), or the shard rates that requests this +worker build served in tensor parallel corrected (`ClusterServedCalibration.tensorParallelMeasurements`). Before that, a Mac's share step comes from its device index (`ClusterHardwarePrior.weightSeconds`). The index times each operation with its launch latency inside, so it overstates @@ -4213,8 +4214,8 @@ goes behind the best placement in another mode of its hardware group `measured` or `priorOnly`; it is omitted for every other family. The plan's "Tensor parallel or pipeline" line says, for example, "Pipeline: tensor parallel is predicted 6% faster for requests of 128 prompt and 128 answer tokens (...), -but from the device index, not its own measured step; it is chosen once its step -is measured on both Macs (a share probe at a tensor-parallel load, or requests +but from the device index, not its own measured step; it can be chosen once its +step is measured on both Macs (a share probe at a tensor-parallel load, or requests this build served in tensor parallel)." A plan that chooses tensor parallel on measured steps adds ", on its own step as measured on both Macs". The setup's model list says `tensor parallel: not measured yet`. diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index a2fc046a37..4b5ab3f955 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -355,7 +355,7 @@ on big Macs. Until then the pair serves the pipeline, as follows: - Where the estimate says tensor parallel would be faster, the plan's "Tensor parallel or pipeline" line says so and keeps the pipeline ("Pipeline: tensor parallel is predicted 6% faster ..., but from the device index, not its own - measured step; it is chosen once its step is measured on both Macs ..."). The + measured step; it can be chosen once its step is measured on both Macs ..."). The model list then says "tensor parallel: not measured yet". This holds for short prompts with longer answers on two M5 Ultra once the link is measured, and on smaller Macs whose decode is limited by memory bandwidth (for example two 24 diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift index 89f8e117f7..e9259f999b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift @@ -107,7 +107,7 @@ extension ClusterPlacementExplanation { case .predictedFasterOnPriorOnly: // A family chosen only where faster (`ClusterTensorParallelChoice.fastest`) waits for its own measured step. let basis = "from the device index, not its own measured step" - let until = "; it is chosen once its step is measured on both Macs (a share probe at a tensor-parallel load, " + let until = "; it can be chosen once its step is measured on both Macs (a share probe at a tensor-parallel load, " + "or requests this build served in tensor parallel)." guard let tp = assessment.tensorParallel, !estimated else { return "\(name): tensor parallel is predicted faster for \(request) \(basis)\(estimated ? note : "")" + until diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift index 58000cc5c3..83f965101b 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift @@ -226,7 +226,7 @@ private func checkGemmaFastestPlan(_ layout: ClusterModelLayout, _ checks: Place held(ultraShort) && short.tensor > short.other * 0.85) checks.require("Gemma evidence rule: its plan line says the predicted gain, that it comes from the device index, and what measures it (\(reason(ultraShort)))", reason(ultraShort).hasPrefix("Pipeline: tensor parallel is predicted 6% faster for requests of 128 prompt and 128 answer tokens (") - && reason(ultraShort).contains(", but from the device index, not its own measured step; it is chosen once its step is measured on both Macs") + && reason(ultraShort).contains(", but from the device index, not its own measured step; it can be chosen once its step is measured on both Macs") && ClusterPlacementExplanation.tensorParallelNote(ultraShort) == .notMeasuredYet && ultraShort.shards?.options.first { $0.kind == .tensorParallel }?.verdict == .predictedFasterOnPriorOnly) // A share probe of this model on both Macs (a tensor-parallel load records one): the measured split decides. 10.3 ms diff --git a/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift b/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift index 43489b94cd..63283d2ecb 100644 --- a/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift +++ b/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift @@ -812,12 +812,6 @@ import Foundation require("owner pilot: the same model on 2x M4 Max 128 GB is planned", fits.result.chosen != nil && fits.setup != nil) } - /// MiMo V2.6's plan, on its golden layout (read from the real headers, with the family's tensor-parallel facts - /// and `fastest_v1`) with the mode list its row now advertises and its MTP head as those headers give it - /// (`PipelineSpeculativeChecks`): the guided step's "Tensor parallel or pipeline" lines say the model runs - /// tensor parallel only where predicted faster, and that only tensor parallel keeps committed-token logprobs; - /// a capability without tensor parallel prints neither. The plan credits MiMo's speculative pipeline the - /// speed-up its shipped records measured, the pipeline that tensor parallel must beat. /// A worker capability for `layout` (one partition per admitted cut) in `modes`, and the pair description that pins it. static func capability(layout: ClusterModelLayout, adapterID: String, profileID: String, vocabularySize: Int, arithmeticPolicyID: String, modes: [ClusterGenerationMode], publicModelID: String, @@ -872,6 +866,12 @@ import Foundation measuredUTC: "2026-10-31T00:00:00Z", provenance: "check: the model alone on one Mac") } + /// MiMo V2.6's plan, on its golden layout (read from the real headers, with the family's tensor-parallel facts + /// and `fastest_v1`) with the mode list its row now advertises and its MTP head as those headers give it + /// (`PipelineSpeculativeChecks`): the guided step's "Tensor parallel or pipeline" lines say the model runs + /// tensor parallel only where predicted faster, and that only tensor parallel keeps committed-token logprobs; + /// a capability without tensor parallel prints neither. The plan credits MiMo's speculative pipeline the + /// speed-up its shipped records measured, the pipeline that tensor parallel must beat. static func mimoFastestPlanLines(description base: [String: Any]) throws { let golden = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent( "../../../libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/mimo-v2.6-flash-mopd-2026-09-28-r1.json") @@ -930,7 +930,7 @@ import Foundation let priorOnly = try decide([]) require("MiMo evidence rule: 2x 256 GB on the measured link, nothing served in tensor parallel: the speculative pipeline is kept, and the line says tensor parallel is predicted faster only from the device index (\(line(priorOnly, " Pipeline:")))", priorOnly.result.chosen?.mode == .pipelineMTP && priorOnly.result.tensorParallel?.verdict == .predictedFasterOnPriorOnly - && line(priorOnly, " Pipeline:").contains(", but from the device index, not its own measured step; it is chosen once its step is measured on both Macs") + && line(priorOnly, " Pipeline:").contains(", but from the device index, not its own measured step; it can be chosen once its step is measured on both Macs") && priorOnly.lines.contains(fastestLine) && priorOnly.setup != nil) let fast = try decide(served(95, build: hash("a"))) require("MiMo evidence rule: three requests this build served in tensor parallel at 95 tok/s: tensor parallel, chosen on its own measured step, and the line says so (\(line(fast, " Tensor parallel:")))", From 5ae782613f5a63a99072befb5d08a037f227ba86 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:10:03 -0800 Subject: [PATCH 0095/1441] cluster: MiMo TP rounds gate their per-request bytes at LOAD With --mtp-depth, READY's capacity and every reservation added the drafter's bounded state and the window's extra rows, but the LOAD gate checked only the shard, the heads and the plain request reserve: a load could advertise about 0.47 GB per rank (registered geometry, depth 2) that no gate had found free. The charge is now computed from the artifact's configuration before anything is read (the product's declaration, MiMoV26MTPAssistant.boundedRequestAllocation(configuration:limits:), public in the SDK) and joins the LOAD gate at the profile's longest request; READY and each reservation use the same function. A test pins that the configuration-only declaration equals what the loaded heads declare. The drafter's fence and finalize evaluations now run under MLX.withError, so a native fault throws instead of exiting the worker, as the engine's other evaluations do. Plain launches are unchanged. Gitlink libs/mlx-swift-lm -> 04c7d4c1 (feat/mimo-v26-tp-speculative). Co-Authored-By: Claude Opus 5.5 --- .../MiMoTensorParallelResidentRuntime.swift | 47 +++++++++++-------- .../MiMoTensorParallelSpeculation.swift | 29 ++++++++---- .../MiMoTensorParallelSpeculativeTests.swift | 9 ++++ libs/mlx-swift-lm | 2 +- 4 files changed, 57 insertions(+), 30 deletions(-) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift index 1573641b6f..c3c8b71688 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift @@ -72,6 +72,8 @@ public final class MiMoTensorParallelResidentRuntime { let lifecycle = QwenLayerStageResidentLifecycle() let loadAgreement: String let plan: MiMoTensorParallelPlan + /// The artifact's whole configuration (the drafter's charge reads it). + let textConfiguration: MiMoV26Configuration let slidingWindow: Int /// What the live gate asks for beside every held request: the rank's /// activation floor, freed-buffer cache and sealed frames. @@ -119,11 +121,15 @@ public final class MiMoTensorParallelResidentRuntime { // The rank's reserve at the profile's longest request: the planner's quote beside the shard. let budget = try requestBudget(plan: plan, slidingWindow: window, contextTokens: profile.maximumContextTokens, chunkTokens: profile.maximumChunkTokens) + // Rounds add the drafter's state and the window's rows to that request, from the configuration alone. + let speculativeRequestBytes = try speculative.map { + try Self.speculativeRequestBytes(configuration: decoded, terms: $0, plan: plan, slidingWindow: window, + chunkTokens: profile.maximumChunkTokens) + } ?? 0 let control = QwenResidentControl(deadline: configuration.deadlineUptimeNanoseconds, lease: configuration.lease) try QwenResidentProcessLease.shared.acquire() var loaded: MiMoTensorParallelModel? var draftHead: MiMoTensorParallelDraftHead? - var speculativeRequestBytes = 0 weak var retired: MiMoTensorParallelModel? var residency: ClusterStageResidency? do { @@ -170,8 +176,9 @@ public final class MiMoTensorParallelResidentRuntime { // freed-buffer cache, sealed frames) beside it: the planner's quote. The read's largest slice // (half an expert bank) lives only while loading, inside the reserve no request holds yet. let shardBytes = try Self.shardBytes(plan: plan, descriptors: source.descriptors) - // Speculative rounds: the three heads whole on every rank, beside the shard. The source's - // descriptors hold text tensors only; the heads' inventory is the pipeline's, from the headers. + // Speculative rounds: the three heads whole on every rank, beside the shard, and that request's + // speculative bytes. The source's descriptors hold text tensors only; the heads' inventory is the + // pipeline's, from the headers. var headDescriptors: [String: TensorDescriptor] = [:] var headInventory: MiMoMTPHeadInventory? if speculative != nil { @@ -186,7 +193,7 @@ public final class MiMoTensorParallelResidentRuntime { } let headBytes = headDescriptors.values.reduce(0) { $0 + $1.byteCount } try requireLiveMemory(bytes: try QwenLongPrefillCheckedBytes.sum([shardBytes, headBytes, - budget.allowance.reservedBytes])) + budget.allowance.reservedBytes, speculativeRequestBytes])) let value = try autoreleasepool { try MiMoTensorParallelVerifiedLoad.load(checkpoint: source.checkpoint, configurationData: admission.configBytes, role: .shard(rank: collective.rank), reduction: group, @@ -196,7 +203,7 @@ public final class MiMoTensorParallelResidentRuntime { guard value.receipt.verifiedAggregateSHA256 == admission.specification.artifactSHA256 else { throw ProbeError("MiMo tensor-parallel shard was not read from the registered artifact") } - if let speculative { + if speculative != nil { let head = try autoreleasepool { try MiMoTensorParallelDraftHead.load(descriptors: headDescriptors, checkpoint: source.checkpoint, configurationData: admission.configBytes, target: value.model, @@ -206,8 +213,6 @@ public final class MiMoTensorParallelResidentRuntime { throw ProbeError("MiMo tensor-parallel draft heads differ from the artifact's") } draftHead = head - speculativeRequestBytes = try Self.speculativeRequestBytes(head: head, terms: speculative, - plan: plan, slidingWindow: window, chunkTokens: profile.maximumChunkTokens) } Memory.clearCache() residency = try ClusterStageResidency(bytes: try QwenLongPrefillCheckedBytes.sum([ @@ -240,9 +245,9 @@ public final class MiMoTensorParallelResidentRuntime { guard let model = loaded else { throw ProbeError("MiMo tensor-parallel load returned no shard") } try control.loaded() return try MiMoTensorParallelResidentRuntime(admission: admission, control: control, collective: collective, - group: group, codec: codec, model: model, residency: residency, plan: plan, slidingWindow: window, - rankReserveBytes: budget.rankBytes, capacity: capacity, loadAgreement: loadAgreement, linkProbe: probe, - speculative: speculative, draftHead: draftHead) + group: group, codec: codec, model: model, residency: residency, plan: plan, textConfiguration: decoded, + slidingWindow: window, rankReserveBytes: budget.rankBytes, capacity: capacity, + loadAgreement: loadAgreement, linkProbe: probe, speculative: speculative, draftHead: draftHead) } catch { let primary = error; control.fail(); loaded = nil; draftHead = nil do { @@ -298,11 +303,12 @@ public final class MiMoTensorParallelResidentRuntime { /// One request's speculative charge: the drafter's own bounded state (the /// product's declaration at the allocator's bound) and the window's extra /// rows (`MiMoTensorParallelRequestBudget.speculativeWindowBytes`). - static func speculativeRequestBytes(head: MiMoTensorParallelDraftHead, terms: MiMoMTPTerms, + static func speculativeRequestBytes(configuration: MiMoV26Configuration, terms: MiMoMTPTerms, plan: MiMoTensorParallelPlan, slidingWindow: Int, chunkTokens: Int) throws -> Int { let bound = QwenResidentResourceEnvironment.allocationBound return try QwenLongPrefillCheckedBytes.sum([ - head.requestBytes(chunkSize: chunkTokens, depth: terms.depth, bound: bound), + MiMoTensorParallelDraftHead.requestBytes(configuration: configuration, chunkSize: chunkTokens, + depth: terms.depth, bound: bound), MiMoTensorParallelRequestBudget.speculativeWindowBytes(plan: plan, slidingWindow: slidingWindow, depth: terms.depth, allocationBound: bound)]) } @@ -321,13 +327,15 @@ public final class MiMoTensorParallelResidentRuntime { private init(admission: MiMoResidentAdmission, control: QwenResidentControl, collective: Collective, group: QwenTensorParallelGroup, codec: QwenTensorParallelSealCodec?, model: MiMoTensorParallelModel, - residency: ClusterStageResidency?, plan: MiMoTensorParallelPlan, slidingWindow: Int, - rankReserveBytes: Int, capacity: Int, loadAgreement: String, linkProbe: ClusterWorkerLinkProbe?, - speculative: MiMoMTPTerms?, draftHead: MiMoTensorParallelDraftHead?) throws { + residency: ClusterStageResidency?, plan: MiMoTensorParallelPlan, textConfiguration: MiMoV26Configuration, + slidingWindow: Int, rankReserveBytes: Int, capacity: Int, loadAgreement: String, + linkProbe: ClusterWorkerLinkProbe?, speculative: MiMoMTPTerms?, + draftHead: MiMoTensorParallelDraftHead?) throws { self.admission = admission; self.control = control; self.collective = collective; self.group = group self.codec = codec; self.model = model; self.residency = residency self.speculative = speculative; self.draftHead = draftHead - self.plan = plan; self.slidingWindow = slidingWindow; self.rankReserveBytes = rankReserveBytes + self.plan = plan; self.textConfiguration = textConfiguration + self.slidingWindow = slidingWindow; self.rankReserveBytes = rankReserveBytes self.loadAgreement = loadAgreement; self.linkProbe = linkProbe baseReady = .init(identity: admission.configuration.identity, rank: collective.rank, profile: admission.wireProfile, executionPlanSHA256: admission.plan.fingerprint, @@ -371,9 +379,10 @@ public final class MiMoTensorParallelResidentRuntime { let request = try admission.request(value, id: requestID, now: DispatchTime.now().uptimeNanoseconds) var charge = try Self.requestBudget(plan: plan, slidingWindow: slidingWindow, contextTokens: request.maximumTokens, chunkTokens: request.chunkSize).requestBytes - if let speculative, let draftHead { - charge = try QwenLongPrefillCheckedBytes.sum([charge, Self.speculativeRequestBytes(head: draftHead, - terms: speculative, plan: plan, slidingWindow: slidingWindow, chunkTokens: request.chunkSize)]) + if let speculative { + charge = try QwenLongPrefillCheckedBytes.sum([charge, Self.speculativeRequestBytes( + configuration: textConfiguration, terms: speculative, plan: plan, slidingWindow: slidingWindow, + chunkTokens: request.chunkSize)]) } try control.check(); try control.reserve(requestID) return try control.reserving(requestID, rank: collective.rank, deadline: value.deadlineUptimeNanoseconds) { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSpeculation.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSpeculation.swift index 41f3447f84..d9a60b96c1 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSpeculation.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSpeculation.swift @@ -105,10 +105,13 @@ final class MiMoTensorParallelDraftHead { } /// One request's drafter state at the allocator's bound: the product's own - /// bounded declaration for this head (`maximumPrefillTokens` = the chunk). - func requestBytes(chunkSize: Int, depth: Int, bound: (Int) throws -> Int) throws -> Int { - guard let spec = assistant.boundedRequestAllocation(limits: .init(maximumPrefillTokens: chunkSize, - maximumDraftTokens: depth)) else { + /// bounded declaration for these heads (`maximumPrefillTokens` = the chunk). + /// It needs the artifact's configuration only, so a rank gates it before + /// reading anything. + static func requestBytes(configuration: MiMoV26Configuration, chunkSize: Int, depth: Int, + bound: (Int) throws -> Int) throws -> Int { + guard let spec = MiMoV26MTPAssistant.boundedRequestAllocation(configuration: configuration, + limits: .init(maximumPrefillTokens: chunkSize, maximumDraftTokens: depth)) else { throw ProbeError("MiMo speculative head declares no bounded request allocation") } var total = spec.hostBytes @@ -179,9 +182,12 @@ final class MiMoTensorParallelDrafter { } } - private func fence() { + private func fence() throws { guard fencePending, case .heads(let head) = speculation.proposer, let state else { return } - eval(head.assistant.evaluationTargets(for: state)) + try MLX.withError { error in + eval(head.assistant.evaluationTargets(for: state)) + try error.check() + } fencePending = false } @@ -191,7 +197,7 @@ final class MiMoTensorParallelDrafter { throw ProbeError("MiMo tensor-parallel drafter observed a row outside its prompt") } guard case .heads(let head) = speculation.proposer, let state else { return } - fence() + try fence() head.assistant.observeCommittedTarget(.init(tokens: MLXArray(tokens.map(Int32.init)).reshaped([1, tokens.count]), hidden: hidden), requestState: state) let last = tokens.count - 1 @@ -205,7 +211,7 @@ final class MiMoTensorParallelDrafter { guard !released, carry == nil else { throw ProbeError("MiMo tensor-parallel drafter began twice") } if case .heads = speculation.proposer { guard let promptFrontier else { throw ProbeError("MiMo tensor-parallel drafter starts without a prompt") } - fence() + try fence() carry = (firstToken, promptFrontier) self.promptFrontier = nil } @@ -226,7 +232,7 @@ final class MiMoTensorParallelDrafter { return ids case .heads(let head): guard let state, let carry, carry.token == lastToken else { self.carry = nil; return [] } - fence() + try fence() var feed = (tokens: MLXArray([Int32(lastToken)]).reshaped([1, 1]), hidden: carry.hidden) var drafted: [MLXArray] = [] for _ in 0 ..< count { @@ -263,7 +269,10 @@ final class MiMoTensorParallelDrafter { head.assistant.finalizeRound(requestState: state, confirmedInputTokens: 1 + acceptedDrafts, committedDraftTokens: draftArray[0..., 0 ..< acceptedDrafts], committedTargetHidden: hidden[0..., 0 ..< acceptedDrafts, 0...]) - eval(head.assistant.evaluationTargets(for: state) + [carryHidden]) + try MLX.withError { error in + eval(head.assistant.evaluationTargets(for: state) + [carryHidden]) + try error.check() + } carry = (tokens[tokens.count - 1], carryHidden) } diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift index 1cb94c6f7f..aabbfc3f73 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift @@ -227,6 +227,13 @@ struct MiMoTensorParallelSpeculativeTests { #expect(Set(inventory.head.map(\.name)) == Set(selected.keys) && inventory.head.count == 42) let head = try #require(models.value[0].draftHead) #expect(inventory.head.reduce(0) { $0 + $1.byteCount } == head.headBytes && head.headTensors == 42) + // The LOAD gate charges the drafter from the configuration alone: what the loaded heads declare. + let decoded = try JSONDecoder().decode(MiMoV26Configuration.self, from: configuration) + for (chunk, depth) in [(4, 1), (16, 2), (512, 3)] { + let limits = CBv2MTPAllocationLimits(maximumPrefillTokens: chunk, maximumDraftTokens: depth) + let loaded = try #require(head.assistant.boundedRequestAllocation(limits: limits)) + #expect(MiMoV26MTPAssistant.boundedRequestAllocation(configuration: decoded, limits: limits) == loaded) + } // A descriptor set that is not the heads' is refused before any read. #expect(throws: (any Error).self) { _ = try MiMoTensorParallelDraftHead.load(descriptors: indexed.filter { !$0.key.hasPrefix("language_model.model.mtp.") }, @@ -256,6 +263,8 @@ struct MiMoTensorParallelSpeculativeTests { limits: .init(maximumPrefillTokens: 512, maximumDraftTokens: 2))) let drafter = (spec.resident + spec.working).reduce(spec.hostBytes) { $0 + $1.logicalBytes * $1.allocationCount } #expect(drafter == 438_426_984) + #expect(try MiMoTensorParallelDraftHead.requestBytes(configuration: configuration, chunkSize: 512, depth: 2, + bound: exact) == drafter) typealias Runtime = MiMoTensorParallelResidentRuntime let plain = Runtime.loadAgreementFields(plan: plan, chunkTokens: 512) #expect(Runtime.loadAgreementFields(plan: plan, chunkTokens: 512, speculative: nil) == plain) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index b44a7084c9..04c7d4c192 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit b44a7084c90206b6dbdc477b1dba67f6003724d8 +Subproject commit 04c7d4c1928276663602b821687a4e30da85e2d3 From a145280956ce28cdc9de212c181755bf34aed8a7 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:10:21 -0800 Subject: [PATCH 0096/1441] cluster: share MiMo TP prefill and stop handling between steps and rounds Behavior-preserving cleanup of the speculative rounds: - one prefill for both loops, handing each chunk's post-final-norm rows to the drafter only when rounds follow (the one-token path builds the same forward as before); - one endAtStop for a step's or a round's stop slot; - a plain step inside rounds calls the drafter's plainStep instead of finalizing a window with a zero placeholder row; finalize now requires drafts. Coverage: - greedy logprobs published inside rounds equal the one-token path's; - the oracle's mtp matrix requires sampled rounds (the heads, and misses scripted from the sampled one-token run) bitwise equal to the sampled one-token path: tokens, rows and caches. Column j's target sample is keyed at output index next + j, the one-token path's key. Co-Authored-By: Claude Opus 5.5 --- .../Tests/MiMoTensorParallelOracles/run.sh | 23 +++++++++---- .../MiMoTensorParallelDecoding.swift | 29 ++++++++++------- .../MiMoTensorParallelRounds.swift | 32 +------------------ .../MiMoTensorParallelSpeculation.swift | 11 +++++-- .../MiMoTensorParallelSpeculativeTests.swift | 11 +++++-- 5 files changed, 53 insertions(+), 53 deletions(-) diff --git a/libs/darkbloom-cluster-worker/Tests/MiMoTensorParallelOracles/run.sh b/libs/darkbloom-cluster-worker/Tests/MiMoTensorParallelOracles/run.sh index db7e14c0fa..02a7c8f7c0 100755 --- a/libs/darkbloom-cluster-worker/Tests/MiMoTensorParallelOracles/run.sh +++ b/libs/darkbloom-cluster-worker/Tests/MiMoTensorParallelOracles/run.sh @@ -38,8 +38,10 @@ # the one-token path (tokens, rows, caches: lossless greedy), with the heads' # own proposals (random, so mostly rejected), with proposals scripted from the # one-token tokens (forced acceptance: every draft kept) and with every fifth -# scripted proposal moved off (accepts, rejects and rollback); and each tp -# rank bitwise equal to `simulated` for the heads, the script and a sampled run. +# scripted proposal moved off (accepts, rejects and rollback); sampled rounds +# (temperature 0.8: the heads, and the misses scripted from the sampled +# one-token run) bitwise equal to the sampled one-token path; and each tp rank +# bitwise equal to `simulated` for the heads, the misses and a sampled run. set -euo pipefail tp_check="$1" scratch="$2" @@ -273,11 +275,20 @@ mtp_matrix() { done done done - # Sampled rounds (the product's keyed target sample per column over the gathered rows): tp == simulated. + # Sampled rounds (the product's keyed target sample per column over the gathered rows): every round run + # equals the sampled one-token path bit for bit, and tp == simulated. dir="$scratch/kernel-mtp" - nice -n 19 "$tp_check" mimo run --mode simulated --path paged --model-dir "$dir" --request "$dir/request.json" \ - --report "$dir/sampled-heads-simulated.json" --temperature 0.8 --sample-seed 11 --mtp-depth 2 \ - >"$dir/sampled-heads-simulated.log" 2>&1 + sampled() { local tag="$1"; shift + nice -n 19 "$tp_check" mimo run --mode simulated --path paged --model-dir "$dir" --request "$dir/request.json" \ + --report "$dir/sampled-$tag-simulated.json" --temperature 0.8 --sample-seed 11 "$@" \ + >"$dir/sampled-$tag-simulated.log" 2>&1; } + sampled plain + sampled heads --mtp-depth 2 + sampled misses --mtp-depth 3 --mtp-script "$dir/sampled-plain-simulated.json" --mtp-misses 5 + for tag in heads misses; do + same_bits "$dir/sampled-plain-simulated.json" "$dir/sampled-$tag-simulated.json" \ + "mtp kernel/request sampled $tag ($(grep -o 'speculative rounds.*' "$dir/sampled-$tag-simulated.log" || echo 'no rounds')) == one-token path" + done tp_pair "$dir" request sampled-heads-tp-ring ring "" --path paged --temperature 0.8 --sample-seed 11 --mtp-depth 2 for rank in 0 1; do same_bits "$dir/sampled-heads-simulated.json" "$dir/sampled-heads-tp-ring-rank$rank.json" \ diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelDecoding.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelDecoding.swift index 75329370cd..9fc0c6d437 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelDecoding.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelDecoding.swift @@ -174,13 +174,7 @@ struct MiMoTensorParallelDecoding { let position = caches[0].offset let choice = try select(logits, request: request, stop: stopKeep, position: position) routes?.flush() - if let slot = choice.stop { - // A rank asked both to stop: both keep the tokens it named. - let stop = QwenTensorParallelStopRule.stop(slot: slot) - outcome.tokens = Array(outcome.tokens.prefix(stop.keep)) - outcome.finish = stop.finish - break - } + if let slot = choice.stop { endAtStop(slot, &outcome); break } if index == 0 { outcome.firstTokenSeconds = MiMoTensorParallelModel.now() - started } try observe?(choice.step(index)) request.sampler?.commit(choice.token) @@ -209,13 +203,26 @@ struct MiMoTensorParallelDecoding { return outcome } - /// The prompt in chunks; the last position's logits `[1, V or V/2]`, not evaluated. - func prefill(_ prompt: [Int], chunk: Int, caches: [MiMoV26IndependentHistoryCache]) throws -> MLXArray { + /// A rank asked both to stop: both keep the tokens it named. + func endAtStop(_ slot: Float, _ outcome: inout Outcome) { + let stop = QwenTensorParallelStopRule.stop(slot: slot) + outcome.tokens = Array(outcome.tokens.prefix(stop.keep)) + outcome.finish = stop.finish + } + + /// The prompt in chunks, each chunk's post-final-norm rows handed to the + /// drafter when rounds follow; the last position's logits `[1, V or V/2]`, not evaluated. + func prefill(_ prompt: [Int], chunk: Int, caches: [MiMoV26IndependentHistoryCache], + drafter: MiMoTensorParallelDrafter? = nil) throws -> MLXArray { var offset = 0 while true { let end = min(prompt.count, offset + chunk) - let logits = try forward(Array(prompt[offset ..< end]), caches: caches) - if end == prompt.count { return logits } + let tokens = Array(prompt[offset ..< end]) + let output = try model.model.forwardIndependentHistory( + inputIDs: MLXArray(tokens.map(Int32.init)).reshaped(1, tokens.count), caches: caches, + logitsStart: tokens.count - 1) + try drafter?.observePrompt(tokens: tokens, hidden: output.normalizedHiddenStates) + if end == prompt.count { return output.logits[0..., -1, 0...] } try MLX.withError { error in eval(caches.flatMap { $0.innerState() } + (routes?.pending ?? [])) try error.check() diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRounds.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRounds.swift index 7f502e90e0..9862d04b9e 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRounds.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRounds.swift @@ -102,8 +102,7 @@ extension MiMoTensorParallelDecoding { let choice = try select(logits, request: request, stop: stopKeep, position: caches[0].offset) routes?.flush() if let slot = choice.stop { endAtStop(slot, &outcome); break } - try drafter.finalize(drafts: [], tokens: [choice.token], acceptedDrafts: 0, - hidden: MLXArray.zeros([1, 1, model.plan.hiddenSize], dtype: .bfloat16)) + try drafter.plainStep() try observe?(choice.step(agreed)) request.sampler?.commit(choice.token) ended = try commit([choice.token], logprobs: [choice.logprobs]) @@ -139,35 +138,6 @@ extension MiMoTensorParallelDecoding { return (outcome, drafter.statistics) } - /// A rank asked both to stop: both keep the tokens it named. - private func endAtStop(_ slot: Float, _ outcome: inout Outcome) { - let stop = QwenTensorParallelStopRule.stop(slot: slot) - outcome.tokens = Array(outcome.tokens.prefix(stop.keep)) - outcome.finish = stop.finish - } - - /// The prompt in chunks, each chunk's post-final-norm rows handed to the - /// drafter; the last position's logits `[1, V or V/2]`, not evaluated. - func prefill(_ prompt: [Int], chunk: Int, caches: [MiMoV26IndependentHistoryCache], - drafter: MiMoTensorParallelDrafter) throws -> MLXArray { - var offset = 0 - while true { - let end = min(prompt.count, offset + chunk) - let tokens = Array(prompt[offset ..< end]) - let output = try model.model.forwardIndependentHistory( - inputIDs: MLXArray(tokens.map(Int32.init)).reshaped(1, tokens.count), caches: caches, - logitsStart: tokens.count - 1) - try drafter.observePrompt(tokens: tokens, hidden: output.normalizedHiddenStates) - if end == prompt.count { return output.logits[0..., -1, 0...] } - try MLX.withError { error in - eval(caches.flatMap { $0.innerState() } + (routes?.pending ?? [])) - try error.check() - } - routes?.flush() - offset = end - } - } - /// One round's agreement over a window's logits `[1, n, V or V/2]`: per /// rank `[maxima (n), tokens (n), stop, position]`, evaluated. Greedy rows /// put each column's FP32 maximum and its global ID (the strictly greater diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSpeculation.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSpeculation.swift index d9a60b96c1..fe0c272dc2 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSpeculation.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSpeculation.swift @@ -258,13 +258,12 @@ final class MiMoTensorParallelDrafter { /// After both ranks kept `tokens` of a window `[last] + drafts` whose /// post-final-norm rows are `hidden`. func finalize(drafts: [Int], tokens: [Int], acceptedDrafts: Int, hidden: MLXArray) throws { - guard !released, !tokens.isEmpty, hidden.dim(1) >= tokens.count else { + guard !released, !drafts.isEmpty, !tokens.isEmpty, hidden.dim(1) >= tokens.count else { throw ProbeError("MiMo tensor-parallel drafter finalized rows the window did not keep") } statistics.record(drafts: drafts.count, acceptedDrafts: acceptedDrafts, emitted: tokens.count) guard case .heads(let head) = speculation.proposer, let state else { return } let carryHidden = hidden[0..., (tokens.count - 1) ..< tokens.count, 0...] - guard !drafts.isEmpty else { carry = nil; return } let draftArray = MLXArray(drafts.map(Int32.init)).reshaped([1, drafts.count]) head.assistant.finalizeRound(requestState: state, confirmedInputTokens: 1 + acceptedDrafts, committedDraftTokens: draftArray[0..., 0 ..< acceptedDrafts], @@ -276,6 +275,14 @@ final class MiMoTensorParallelDrafter { carry = (tokens[tokens.count - 1], carryHidden) } + /// After a plain step: the heads draft no more for this request, as the + /// pipeline's decoder (they would need the history the step skipped). + func plainStep() throws { + guard !released else { throw ProbeError("MiMo tensor-parallel drafter stepped past its request") } + statistics.record(drafts: 0, acceptedDrafts: 0, emitted: 1) + carry = nil + } + func release() { guard !released else { return } released = true diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift index aabbfc3f73..0ff76dc184 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift @@ -91,7 +91,8 @@ struct MiMoTensorParallelSpeculativeTests { } /// `script`: proposals scripted from these tokens (all kept); nil: the trained heads. - private static func run(_ models: Box<[MiMoTensorParallelModel]>, script: [Int]? = nil, + /// `rounds` false: the one-token path. + private static func run(_ models: Box<[MiMoTensorParallelModel]>, script: [Int]? = nil, rounds: Bool = true, rule: MiMoTensorParallelSelectionRule = .greedy, stops: Set = [], answer: @escaping @Sendable (Int, Int) -> Bool = { _, _ in true }, stopAfter: @escaping @Sendable (Int, Int) -> Bool = { _, _ in false }) throws -> [Ran] { @@ -99,7 +100,7 @@ struct MiMoTensorParallelSpeculativeTests { let model = models.value[rank] let proposer: MiMoTensorParallelProposer = try script.map { .scripted(script: $0, missEvery: 0) } ?? .heads(try #require(model.draftHead)) - let speculation = try MiMoTensorParallelSpeculation(depth: 2, proposer: proposer) + let speculation = rounds ? try MiMoTensorParallelSpeculation(depth: 2, proposer: proposer) : nil var published: [(ordinal: Int, token: Int, logprobs: ClusterWorkerTokenLogprobs?)] = [] var checks = 0 let outcome = try MiMoTensorParallelDecoding(model: model).run( @@ -154,13 +155,17 @@ struct MiMoTensorParallelSpeculativeTests { let local = try Self.run(models, script: script, stopAfter: { rank, checks in rank == 1 && checks == 3 }) for ran in local { #expect(ran.outcome.tokens == Array(tokens.prefix(7)) && ran.outcome.finish == .clientStop) } #expect(local[1].outcome.stoppedHere && !local[0].outcome.stoppedHere) - // Greedy logprobs for every kept column, the token first, the same tokens. + // Greedy logprobs for every kept column, the token first, the same tokens, and exactly the + // logprobs the one-token path publishes. let logprobs = try Self.run(models, script: script, rule: .greedyLogprobs(top: 3)) #expect(logprobs[0].outcome.tokens == tokens && logprobs[0].published.count == tokens.count) for entry in logprobs[0].published { let value = try #require(entry.logprobs) #expect(value.top.count == 3 && value.top[0].tokenID == entry.token && value.logprob == value.top[0].logprob) } + let stepped = try Self.run(models, rounds: false, rule: .greedyLogprobs(top: 3)) + #expect(stepped[0].outcome.statistics == nil && stepped[0].published.map(\.token) == tokens) + #expect(logprobs[0].published.map(\.logprobs) == stepped[0].published.map(\.logprobs)) // The trained (random) heads, with the same stop token: both end there. let heads = try Self.run(models, stops: [tokens[inside]]) for ran in heads { #expect(ran.outcome.tokens == Array(tokens.prefix(inside + 1)) && ran.outcome.finish == .eos) } From 11e44973ec8dad8883bf370afc0f8b069054f92f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:10:30 -0800 Subject: [PATCH 0097/1441] docs: MiMo TP rounds' LOAD gate, sampler rule and off-by-default wording - inference.md, hardware-support.md: the LOAD gate now adds the drafter's state and the window's rows before anything is read; READY and each reservation add the same per-request terms. - inference.md, changelog: greedy requests draft with or without logprobs; penalties, a logit bias or a sampled request's logprobs decode one token a step; sampled rounds draw the one-token path's tokens (keyed at each column's own output index; bitwise on the synthetic checks). - Off by default, said exactly: only a hand-launched worker with --mtp-depth runs rounds; the installed provider passes a depth only for Qwen's tensor assistant, never to MiMo. - test.md: the new checks (logprobs equal to the one-token path's, the configuration-only drafter charge, sampled rounds in the mtp matrix). Co-Authored-By: Claude Opus 5.5 --- changelog.d/mimo-tp-speculative.md | 5 ++-- docs/architecture/hardware-support.md | 7 ++++-- docs/architecture/inference.md | 33 +++++++++++++++++---------- docs/developer/test.md | 12 ++++++---- 4 files changed, 37 insertions(+), 20 deletions(-) diff --git a/changelog.d/mimo-tp-speculative.md b/changelog.d/mimo-tp-speculative.md index 155588240e..49ae266648 100644 --- a/changelog.d/mimo-tp-speculative.md +++ b/changelog.d/mimo-tp-speculative.md @@ -1,6 +1,7 @@ ### MiMo V2.6 Flash tensor parallel with speculative decoding -- A MiMo V2.6 Flash tensor-parallel pair can decode with MiMo's three trained draft heads: each round checks up to three drafted tokens in one pass through the pair, so every token a round keeps shares that pass's link and weight costs. It is off by default and turned on per launch (`--mtp-depth`); the planner does not count it yet. -- Greedy output is identical to tensor parallel without drafting, token for token and bit for bit on the synthetic checks, and greedy logprobs and every kind of stop work inside a round. Sampled requests follow the speculative pipeline's rule: they draft unless they ask for logprobs or use penalties or a logit bias, in which case they decode one token at a time. +- A MiMo V2.6 Flash tensor-parallel pair can decode with MiMo's three trained draft heads: each round checks up to three drafted tokens in one pass through the pair, so every token a round keeps shares that pass's link and weight costs. +- It is off by default. Only a worker launched by hand with `--mtp-depth` uses it: the installed provider never passes that flag to a MiMo tensor-parallel worker, and the planner does not count it. +- Output is identical to tensor parallel without drafting, token for token and bit for bit on the synthetic checks: greedy (with or without logprobs) and sampled. Every kind of stop works inside a round. Requests with penalties or a logit bias, and sampled requests that ask for logprobs, decode one token at a time, as in the speculative pipeline. - Each Mac holds the draft heads whole (about 2 GB more, still within two 128 GB Macs) and reserves their per-request state. - Not yet measured on a real pair: the speed-up, the heads' acceptance rate and qualification records. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 8841ee7551..7452c0ffb3 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1170,8 +1170,11 @@ headroom. That fits a 128 GB Mac. A reservation asks the live gate for its own r per-rank charges. Nothing here is measured on a pair; see [inference](inference.md#mimo-tensor-parallel-placement). -A rank launched with speculative rounds (`--mtp-depth`) adds, in its own gates -only (the planner's quote does not count them yet): +A rank launched with speculative rounds (`--mtp-depth`) adds the charges below +to its own gates only; the planner's quote does not count them yet. The LOAD +gate adds all three before anything is read, with the per-request terms at the +profile's longest request; READY's capacity and each reservation add the two +per-request terms. | Charge | Held | Bytes | |---|---|---| diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index aef2ec3251..da00c0b86e 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4336,8 +4336,10 @@ the gate. A MiMo tensor-parallel worker launched with `--mtp-depth N` (1 to 3; MiMo's `MiMoMTPTerms`) decodes in `pipeline_mtp_v1`'s rounds through the -tensor-parallel sums. Nothing launches it by default yet: the installed provider -passes no depth in tensor parallel, and the planner credits no speed-up. +tensor-parallel sums. It is off by default: the installed provider passes no +depth to a MiMo tensor-parallel worker +(`DistributedInstalledGenerationSelection` passes one only for Qwen's tensor +assistant), and the planner credits no speed-up. - **Heads.** Both ranks hold the three trained BF16 heads whole (3 × 658,546,816 B), named by the pipeline's head inventory @@ -4363,10 +4365,14 @@ passes no depth in tensor parallel, and the planner credits no speed-up. column's maximum and token (or rank 0's keyed target sample over the gathered rows, `QwenStageTokenSampler.verifyRound`), the stop slot and the position. `MiMoMTPAcceptance.kept` keeps drafts while each equals the target before it, - then the target, cut at a stop token and the output limit. A request whose - sampler does not admit verification (`ClusterWorkerSampling.admitsSpeculativeVerification`: - history-dependent transforms, or a sampled request that asks for logprobs) - decodes one token a step, as in the pipeline's rounds. + then the target, cut at a stop token and the output limit. Column j's target + sample is keyed at output index `next + j`, the key the one-token path uses + there, so sampled rounds draw the one-token path's tokens too (bit for bit + on the synthetic checks). Greedy requests, with or without logprobs, always + draft. A gathered-row request drafts only when its sampler admits verification + (`ClusterWorkerSampling.admitsSpeculativeVerification`). Penalties, a logit + bias, or a sampled request's logprobs make it decode one token a step, as in + the pipeline's rounds. - **Rollback.** Each cache takes a checkpoint before the window (pages are immutable arrays). Unless every row is kept, the cache returns to it and replays the kept rows' keys and values as one-token appends @@ -4376,12 +4382,15 @@ passes no depth in tensor parallel, and the planner credits no speed-up. round's agreement; when that round already ends the request, rank 1 adopts rank 0's count and finish in the end agreement (`QwenTensorParallelStopRule.reconcile`). - **Logprobs.** A greedy request takes one vocabulary-split top-k gather per - kept column, led by the column's agreed maximum; a sampled request with - logprobs decodes one token a step, so its logprobs are the step path's. -- **Memory.** The LOAD gate adds the heads' bytes; each reservation and READY's - capacity add the drafter's bounded request state and the window's extra rows - (`MiMoTensorParallelResidentRuntime.speculativeRequestBytes`). The activation - floor stays the conservative default. + kept column, led by the column's agreed maximum. The rows are the one-token + step's, so the published logprobs are the one-token path's. A sampled request + with logprobs decodes one token a step, so its logprobs are the step path's. +- **Memory.** Before anything is read, the LOAD gate adds the heads' bytes and, + at the profile's longest request, the drafter's bounded request state and the + window's extra rows (`MiMoTensorParallelResidentRuntime.speculativeRequestBytes`, + from the configuration alone). READY's capacity and each reservation add the + same two per-request terms. The activation floor stays the conservative + default. - **Agreement.** The load agreement adds the depth, the verification rule and the head and window contracts (`speculativeAgreementFields`); a load without a depth keeps its agreement unchanged. diff --git a/docs/developer/test.md b/docs/developer/test.md index 2702ef9d41..68ab6e2bbb 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1351,8 +1351,10 @@ registered artifact for them. every third moved off) equal the one-token path bit for bit, caches included; a stop token inside a window, the owner's stop inside a round (and just before a stop token of the same round), a cancel between rounds - and greedy logprobs for every kept column end both ranks together; and - exactly tied columns and draft readouts choose the lowest token ID. + and greedy logprobs for every kept column (the one-token path's own) end + both ranks together; the LOAD gate's configuration-only drafter charge is + what the loaded heads declare; and exactly tied columns and draft readouts + choose the lowest token ID. `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh` also runs `MiMoTensorParallelChecks.swift` (model-free). It builds the layout from the @@ -1418,8 +1420,10 @@ registered artifact for them. the heads' own proposals (random, so mostly rejected), proposals scripted from the one-token run's tokens (`--mtp-script REPORT`, all kept) and every fifth scripted proposal moved off (`--mtp-misses 5`: accepts, rejects and - rollback). Two `tp` ranks over the ring must equal `simulated` for the heads, - the misses and a sampled run. + rollback). Sampled rounds (temperature 0.8: the heads, and the misses scripted + from the sampled one-token run) must equal the sampled one-token path bit for + bit. Two `tp` ranks over the ring must equal `simulated` for the heads, the + misses and a sampled run. `MIMO_ORACLE_PATHS=paged` runs one matrix. From 2b3cc0b718f09e6a03a02415012b3f0dcc33029e Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:17:12 -0800 Subject: [PATCH 0098/1441] cluster: test MiMo TP window rollback on the registered 128-row ring The synthetic checkpoints' sliding window is 8 rows (one page), so no check exercised a rollback on the registered geometry's ring: 128 rows over two 64-token pages. The new CPU test drives MiMoV26VerifyWindow.settle directly against one-token appends, for a sliding and a full layer, after a 150-token prompt chunk, through windows of 2 to 4 rows keeping 1 to 4, across the ring's page boundary and its wrap: the same rows in the same physical order, offset, ring index and page count every round. With the replay order reversed (a deliberate mutation, not committed) it fails. Co-Authored-By: Claude Opus 5.5 --- docs/developer/test.md | 7 ++- .../MiMoTensorParallelSpeculativeTests.swift | 60 +++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/docs/developer/test.md b/docs/developer/test.md index 68ab6e2bbb..91ad63f6f6 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1353,8 +1353,11 @@ registered artifact for them. (and just before a stop token of the same round), a cancel between rounds and greedy logprobs for every kept column (the one-token path's own) end both ranks together; the LOAD gate's configuration-only drafter charge is - what the loaded heads declare; and exactly tied columns and draft readouts - choose the lowest token ID. + what the loaded heads declare; a window's rollback + (`MiMoV26VerifyWindow.settle`) leaves exactly the cache of one-token + appends on the registered 128-row ring (two 64-token pages, across its + page boundary and wrap) and on a full layer; and exactly tied columns and + draft readouts choose the lowest token ID. `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh` also runs `MiMoTensorParallelChecks.swift` (model-free). It builds the layout from the diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift index 0ff76dc184..8e601342a6 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift @@ -279,6 +279,66 @@ struct MiMoTensorParallelSpeculativeTests { #expect(two.contains("depth=2") && two.contains("windows=row-exact-one-token-bits")) } + /// A window's settle at the registered sliding window (a 128-row ring over two 64-token + /// pages) and on a full layer leaves exactly the cache that one-token appends leave: the + /// same rows in the same physical order, offset and ring index, for every window size and + /// kept count, across the ring's page boundary and its wrap, after a prompt chunk longer + /// than the window. + @Test func settleEqualsOneTokenAppendsOnTheRegisteredRing() throws { + try Device.withDefaultDevice(.cpu) { + let model = UUID() + for window in [128, nil] as [Int?] { + func cache() -> MiMoV26IndependentHistoryCache { + MiMoV26IndependentHistoryCache(modelIdentity: model, requestIdentity: UUID(), layerIndex: 0, + maximumContext: 4096, heads: 1, keyWidth: 2, valueWidth: 2, dtype: .bfloat16, window: window) + } + // Each position's row is unique: (position mod 64, position / 64), exact in BF16. + func rows(_ start: Int, _ count: Int) -> (keys: MLXArray, values: MLXArray) { + let values = (start ..< (start + count)).flatMap { [Float($0 % 64), Float($0 / 64)] } + let keys = MLXArray(values).reshaped(1, 1, count, 2).asType(.bfloat16) + return (keys, -keys) + } + let windowed = cache(), stepped = cache() + let prompt = rows(0, 150) + _ = windowed.update(keys: prompt.keys, values: prompt.values) + _ = stepped.update(keys: prompt.keys, values: prompt.values) + var position = 150, round = 0 + while position < 470 { + let width = 2 + round % 3, keep = 1 + (round / 3) % width + let checkpoint = windowed.checkpoint() + var written: [(keys: MLXArray, values: MLXArray)] = [] + if window == nil { + let all = rows(position, width) + _ = windowed.update(keys: all.keys, values: all.values) + written = (0 ..< width).map { j in + (all.keys[0..., 0..., j ..< (j + 1), 0...], all.values[0..., 0..., j ..< (j + 1), 0...]) + } + } else { + for j in 0 ..< width { + let row = rows(position + j, 1) + _ = windowed.update(keys: row.keys, values: row.values) + written.append(row) + } + } + try MiMoV26VerifyWindow(logits: MLXArray.zeros([1, width, 1]), + normalizedHiddenStates: MLXArray.zeros([1, width, 1]), firstPosition: position, + caches: [windowed], checkpoints: [checkpoint], written: [written]).settle(keeping: keep) + for j in 0 ..< keep { + let row = rows(position + j, 1) + _ = stepped.update(keys: row.keys, values: row.values) + } + position += keep; round += 1 + let label = "window \(window.map(String.init) ?? "none") at \(position)" + #expect(windowed.offset == stepped.offset && windowed.metaState == stepped.metaState, "\(label)") + #expect(windowed.pageCount == stepped.pageCount, "\(label)") + let (a, b) = (windowed.state, stepped.state) + #expect(a.map { $0.asType(.float32).asArray(Float.self) } == b.map { $0.asType(.float32).asArray(Float.self) }, + "\(label)") + } + } + } + } + /// Exactly tied maxima in a window's columns: inside one rank's half the /// lower ID wins, across halves rank 0's (the lower IDs); a column's /// logprobs lead with its agreed maximum even when a tied token leads the From 26ca2971d5ef349ec72546f274219b01011bdf65 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:26:33 -0800 Subject: [PATCH 0099/1441] Wait for fdesetup through ProcessExitObserver Master added this waitUntilExit() in the cluster wizard's FileVault check after this branch was written; the convention test here rejects it. Same five-second limit and same answers, and the poll goes away with it. Co-Authored-By: Claude Opus 5.5 --- .../Onboarding/ClusterOnboardingLive.swift | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift index 0c36b8ddce..12130f1724 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift @@ -444,10 +444,13 @@ final class OnboardingLive: @unchecked Sendable { process.arguments = ["isactive"] process.standardOutput = FileHandle.nullDevice process.standardError = FileHandle.nullDevice - do { try process.run() } catch { return nil } - let deadline = Date().addingTimeInterval(5) - while process.isRunning && Date() < deadline { usleep(20_000) } - guard !process.isRunning else { process.terminate(); process.waitUntilExit(); return nil } + let childExit = ProcessExitObserver() + do { try childExit.run(process) } catch { return nil } + guard childExit.wait(timeout: 5) || !process.isRunning else { + process.terminate() + childExit.wait() + return nil + } switch process.terminationStatus { case 0: return true case 1: return false From 8e39a3d75ca61056fa37af9109797356aa61d717 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:26:37 -0800 Subject: [PATCH 0100/1441] ci: fresh run after a flaky Qwen media test Shard 3 failed in DistributedQwenMediaIngressTests, which this test-only branch does not touch; the same family failed on other branches today. Co-Authored-By: Claude Opus 5.5 From 1028a95811ab38669d8f394707dc2b797229977b Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:47:57 -0800 Subject: [PATCH 0101/1441] ci: fresh run after Docs Lint stopped reporting Docs Lint on ec6e911a9 stayed in progress for 53 minutes (20 s on the sibling branches) with every other job finished. A re-run would trip Release Integrity through GITHUB_RUN_ATTEMPT, so this is an empty commit. Co-Authored-By: Claude Opus 5.5 From b240b4e2e3f5350c59d536b1e6adee1211e1b44b Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:11:10 -0800 Subject: [PATCH 0102/1441] Bound the wait after terminating fdesetup A child that ignores SIGTERM would still hold the cluster wizard forever here, as waitUntilExit() did. Give it two seconds and answer "could not read"; nothing later depends on the child having gone. Co-Authored-By: Claude Opus 5.5 --- .../Distributed/Onboarding/ClusterOnboardingLive.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift index 12130f1724..d865e3ae9c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift @@ -448,7 +448,7 @@ final class OnboardingLive: @unchecked Sendable { do { try childExit.run(process) } catch { return nil } guard childExit.wait(timeout: 5) || !process.isRunning else { process.terminate() - childExit.wait() + _ = childExit.wait(timeout: 2) return nil } switch process.terminationStatus { From e62928b943a19c537f490e28ccaaad5db42e1034 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:11:15 -0800 Subject: [PATCH 0103/1441] cluster: regression tests for a committed start that outlives its session The production GLM-5.3-Flash pair (2026-11-01 03:37Z) stopped serving for 13 hours: after a peer loss the leader's session ended while its stop was still waiting, and every later committed start was refused with "a committed start is already served". These tests drive the leader's real serve/stop state machine with a scripted pair: - a session that ends while its serve cannot finish must release the start for the next one, and the stale serve must stand down; - the start is released while the slot's drain still runs; - a start whose session already stopped is never served. They fail on origin/master and pass with the fix that follows. Co-Authored-By: Claude Opus 5.5 --- .../ClusterPairServingTests.swift | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairServingTests.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairServingTests.swift index a20170de2f..f24dcdbf78 100644 --- a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairServingTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairServingTests.swift @@ -38,13 +38,17 @@ final class InertWorkerEndpoint: ClusterWorkerEndpoint, @unchecked Sendable { final class ScriptedPairBuilder: @unchecked Sendable { private let lock = NSLock() private var owners: [ScriptedPairOwner] = [] + private var makes = 0 var hold: DispatchSemaphore? /// Set on each built owner: its requests wait for one signal each. var ownerHold: DispatchSemaphore? var failure: Error? var built: [ScriptedPairOwner] { lock.withLock { owners } } + /// Builds begun, including one still held. + var begun: Int { lock.withLock { makes } } func make(_ start: NativePairMemberServingStart) throws -> any DistributedResidentExecutionOwner { + let hold = lock.withLock { () -> DispatchSemaphore? in makes += 1; return self.hold } hold?.wait() if let failure { throw failure } let wire = start.identity @@ -219,6 +223,77 @@ struct ClusterPairServingTests { await fixture.loop.stopServingCommittedStart(epoch: next.membershipEpoch) } + /// Production, 2026-11-01: after a peer loss the session's stop did not + /// complete within the session's own bounded wait; the session sent its + /// receipt anyway, and every later committed start was refused with "a + /// committed start is already served" until a restart. The session's stop + /// releases the start at once; the stale serve stands down by itself. + @Test func aStartWhoseServeCannotFinishDoesNotOutliveItsSession() async throws { + let fixture = try await ServingFixture.make() + try await fixture.loop.installClusterPairServing(fixture.context()) + let hold = DispatchSemaphore(value: 0) + defer { hold.signal() } + fixture.builder.hold = hold + let first = try fixture.start() + let stale = Task { try await fixture.loop.serveCommittedStart(first) } + #expect(await clusterPairWait { fixture.builder.begun == 1 }) + await fixture.loop.stopServingCommittedStart(epoch: first.membershipEpoch) + #expect(await fixture.loop.clusterPairServingSnapshot.epoch == nil) + + // The coordinator's next committed start is served while the stale serve is still out. + fixture.builder.hold = nil + let next = try fixture.start(epoch: UUID()) + try await fixture.loop.serveCommittedStart(next) + #expect(await fixture.loop.clusterPairServingSnapshot.slotEpoch == next.membershipEpoch) + + // The stale serve comes back: it shuts its pair down and touches nothing of the next start. + hold.signal() + await #expect(throws: ClusterPairSlotError.self) { try await stale.value } + let snapshot = await fixture.loop.clusterPairServingSnapshot + #expect(snapshot.epoch == next.membershipEpoch && snapshot.slotEpoch == next.membershipEpoch && !snapshot.refusing) + let staleOwner = fixture.builder.built.first { $0.identity.membershipEpoch == first.membershipEpoch } + #expect(staleOwner?.shutdownCount == 1) + await fixture.loop.stopServingCommittedStart(epoch: next.membershipEpoch) + #expect(await fixture.loop.clusterPairServingSnapshot.epoch == nil) + } + + /// The slot's drain (a request in flight) outlasts the session's wait: the + /// start is already released while the stop still waits for the drain. + @Test func theStartIsReleasedBeforeTheSlotsDrainEnds() async throws { + let fixture = try await ServingFixture.make() + try await fixture.loop.installClusterPairServing(fixture.context()) + await fixture.loop.setClusterPairWarmupForTesting(timeoutSeconds: 30) + let hold = DispatchSemaphore(value: 0) + defer { hold.signal() } + fixture.builder.ownerHold = hold + let start = try fixture.start() + let serve = Task { try await fixture.loop.serveCommittedStart(start) } + #expect(await clusterPairWait { fixture.builder.built.first?.reserveCount == 1 }) + let stop = Task { await fixture.loop.stopServingCommittedStart(epoch: start.membershipEpoch) } + #expect(await clusterPairWait { await fixture.loop.clusterPairServingSnapshot.epoch == nil }) + #expect(fixture.builder.built.first?.shutdownCount == 0) // still draining + hold.signal() + await stop.value + try await serve.value + #expect(await fixture.loop.clusterPairSlotSnapshot.slots.isEmpty) + #expect(fixture.builder.built.first?.shutdownCount == 1) + } + + /// The session's stop reached the host before its serve did: that start is never served. + @Test func aStartWhoseSessionAlreadyStoppedIsNeverServed() async throws { + let fixture = try await ServingFixture.make() + try await fixture.loop.installClusterPairServing(fixture.context()) + let start = try fixture.start() + await fixture.loop.stopServingCommittedStart(epoch: start.membershipEpoch) + await #expect(throws: ClusterPairSlotError.self) { try await fixture.loop.serveCommittedStart(start) } + let snapshot = await fixture.loop.clusterPairServingSnapshot + #expect(snapshot.epoch == nil && snapshot.slotEpoch == nil && fixture.builder.built.isEmpty) + let next = try fixture.start(epoch: UUID()) + try await fixture.loop.serveCommittedStart(next) + #expect(await fixture.loop.clusterPairServingSnapshot.slotEpoch == next.membershipEpoch) + await fixture.loop.stopServingCommittedStart(epoch: next.membershipEpoch) + } + @Test func onlyTheLeaderWithAContextServesAndAFailedPairLeavesNothing() async throws { let leader = try await ServingFixture.make() await #expect(throws: ClusterPairSlotError.self) { try await leader.loop.serveCommittedStart(try leader.start()) } From 660610221b5ee34a7d0224365e4e6855bcdadc6e Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:11:15 -0800 Subject: [PATCH 0104/1441] cluster: release a committed start when its session ends The leader's one-start token (clusterPairServingEpoch) was cleared only once the session's stop had retired the pair slot, and never while a serve was still forming. After a peer loss or fence, the slot's drain or the serve could outlast the session's bounded wait (stopServing gives up at the grant's cleanup deadline); the session sent its release receipt anyway, and the token outlived it. Nothing else cleared it, so every later committed start was refused until a restart. The session's stop now releases the token at once and records the epoch as ended. Every stop call still waits for the slot to retire before the receipt. A serve re-checks that it still holds its start after each suspension and stands down (shuts its owner down, retires what it published) without touching a newer start. The stopped and forming flags are gone: the token is the ownership. The slot-level guard against two published slots is unchanged. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-pair-serving-epoch.md | 11 +++++ docs/reference/cluster-control-protocol.md | 3 +- .../Coordinator/NativePairMemberServing.swift | 3 +- .../ProviderLoop+ClusterPairServing.swift | 48 +++++++++++-------- .../Sources/ProviderCore/ProviderLoop.swift | 9 ++-- 5 files changed, 46 insertions(+), 28 deletions(-) create mode 100644 changelog.d/cluster-pair-serving-epoch.md diff --git a/changelog.d/cluster-pair-serving-epoch.md b/changelog.d/cluster-pair-serving-epoch.md new file mode 100644 index 0000000000..1c3ce62979 --- /dev/null +++ b/changelog.d/cluster-pair-serving-epoch.md @@ -0,0 +1,11 @@ +### Two-Mac pairs recover after a lost rank + +- A two-Mac pair no longer stays unable to serve after it loses a rank, is + fenced, or has a request cancelled before it started. The leader released + its committed start only after the old pair slot had fully drained. When the + drain outlasted the session's own wait, the leader refused every later start + with "a committed start is already served" until the provider was restarted. +- The leader now releases a start as soon as its session ends, and an + unfinished serve of that start stands down without touching the next one. + The release receipt still waits for the slot to retire. A pair still never + serves two slots at once. diff --git a/docs/reference/cluster-control-protocol.md b/docs/reference/cluster-control-protocol.md index 7331c8e124..b7a9efd5ea 100644 --- a/docs/reference/cluster-control-protocol.md +++ b/docs/reference/cluster-control-protocol.md @@ -1,6 +1,6 @@ # Experimental cluster control protocol -> Last updated: 2026-10-29 +> Last updated: 2026-11-01 Exact member-role and native-pair public-control shapes on the provider WebSocket, as staged in draft pull requests: the provider side in this @@ -204,6 +204,7 @@ policy bytes the control requires in a prepare frame | Prepare | The payload's policy must equal the installed policy byte for byte, the start must name this rank, and the frame must leave at most 30 seconds to prepare by this Mac's clock. The member then verifies its installed owner, native executable, metallib and resource library under the device gate and answers `native_pair_prepared` | `provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberSession.swift`, `init` / `runOwned` | | Committed start | `native_pair_owner_start` launches this Mac's installed owner; the owner's native child drives `native_pair_hello` and `native_pair_confirmation`, and `native_pair_owner_released` is sent only after native cleanup, the owner's lease release and the owner's exit were all observed | `runOwned` / `exchange` | | Cancel or expiry | Requests native cleanup at once, independently of signing or the socket. An uncommitted session is dropped and the member can prepare again; a committed one that cannot deliver its release stays quarantined in the control, which then refuses every later attachment | `cancel`; `NativePairMemberControl.finished` | +| Serving on the leader | The leader serves one committed start at a time, from its serve until its session's stop. The stop releases the start at once, then waits for the pair slot to retire before the receipt. After a lost rank or a fence, the next committed start is served once the old slot has retired, even if a serve or the slot's drain outlasts the session's bounded wait. A start whose session already stopped is never served | `provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift`, `serveCommittedStart` / `stopServingCommittedStart` | **What a real member does in this build.** The installed owner (`darkbloom cluster worker-owner --stdio`) admits a start the coordinator diff --git a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift index 5f2fb22126..2709a0cc76 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift @@ -48,7 +48,8 @@ public protocol NativePairMemberServingHost: AnyObject, Sendable { func serveCommittedStart(_ start: NativePairMemberServingStart) async throws /// The session is ending: retire what `serveCommittedStart` published for /// this epoch (or stop a serve still under way) and return once it is - /// retired. Idempotent; an unknown epoch does nothing. + /// retired. The epoch is released at once, so a later start never waits + /// on this one's cleanup, and is never served afterwards. Idempotent. func stopServingCommittedStart(epoch: UUID) async } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift index 6163b503fd..732d6f10df 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift @@ -136,10 +136,13 @@ extension ProviderLoop: NativePairMemberServingHost { guard let context = clusterPairServing, start.rank == 0 else { throw ClusterPairSlotError.notServing("this member serves no committed start") } - guard clusterPairServingEpoch == nil else { throw ClusterPairSlotError.notServing("a committed start is already served") } let epoch = start.membershipEpoch - clusterPairServingEpoch = epoch; clusterPairServingStopped = false; clusterPairServingForming = true - defer { clusterPairServingForming = false } + // Its session's stop can reach this actor before its serve does. + guard epoch != clusterPairServingEndedEpoch else { + throw ClusterPairSlotError.notServing("the committed start already ended") + } + guard clusterPairServingEpoch == nil else { throw ClusterPairSlotError.notServing("a committed start is already served") } + clusterPairServingEpoch = epoch let owner: any DistributedResidentExecutionOwner do { owner = try await Task.detached { try context.makeOwner(start) }.value } catch { @@ -147,9 +150,10 @@ extension ProviderLoop: NativePairMemberServingHost { recordClusterPairIncident(.activationLaunchFailed, error: error, context: context, start: start) endClusterPairServing(epoch); throw error } - // A stop that arrived while the pair formed wins: nothing publishes. - guard clusterPairServingEpoch == epoch, !clusterPairServingStopped else { - await owner.shutdown(); endClusterPairServing(epoch) + // A stop that arrived while the pair formed wins: nothing publishes, + // and the next start may already hold the member. + guard clusterPairServingEpoch == epoch else { + await owner.shutdown() throw ClusterPairSlotError.notServing("the committed start ended while the pair formed") } let wire = start.identity @@ -169,25 +173,27 @@ extension ProviderLoop: NativePairMemberServingHost { modelDirectory: context.modelDirectory, pairTelemetry: telemetry) do { try await publishClusterPairSlot(specification, owner: owner) } catch { await owner.shutdown(); endClusterPairServing(epoch); throw error } - clusterPairServingForming = false // A stop during the publication hops retires what was just published. - if clusterPairServingStopped { await stopServingCommittedStart(epoch: epoch) } + if clusterPairServingEpoch != epoch { await retireCommittedStartSlot(epoch) } } public func stopServingCommittedStart(epoch: UUID) async { - guard clusterPairServingEpoch == epoch else { return } - clusterPairServingStopped = true - // The session sends its release receipt once this returns, so the - // slot retires first, even while the serve still forms the pair (its - // publication and warmup canary can take minutes). Retirement is - // idempotent and the publication stops at a retired slot. - if let handle = clusterPairSlot, handle.membershipEpoch == epoch { - await retireClusterPairSlot(handle.id, reason: "committed start ended") - } - // A serve still forming sees the stop and ends the start itself; - // ending it here would let the next start begin under it. - guard !clusterPairServingForming else { return } + // The start ends with its session, now: not when the slot's drain or + // a serve still under way ends, which can outlast the session's own + // bounded wait (its receipt then lets the coordinator commit the next + // start). A serve that lost its start stands down by itself. + clusterPairServingEndedEpoch = epoch endClusterPairServing(epoch) + // The session sends its release receipt once this returns, so every + // call waits until the slot retired, even while the serve still forms + // the pair (its publication and warmup canary can take minutes). + // Retirement is idempotent and the publication stops at a retired slot. + await retireCommittedStartSlot(epoch) + } + + private func retireCommittedStartSlot(_ epoch: UUID) async { + guard let handle = clusterPairSlot, handle.membershipEpoch == epoch else { return } + await retireClusterPairSlot(handle.id, reason: "committed start ended") } /// One incident about a committed start this leader serves (S24), with @@ -206,6 +212,6 @@ extension ProviderLoop: NativePairMemberServingHost { /// Clears the served epoch, once, for this epoch only. func endClusterPairServing(_ epoch: UUID) { guard clusterPairServingEpoch == epoch else { return } - clusterPairServingEpoch = nil; clusterPairServingStopped = false; clusterPairServingForming = false + clusterPairServingEpoch = nil } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index 3d8265a633..fce440f8f8 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -725,13 +725,12 @@ public actor ProviderLoop { /// When the pair slot's engine was first seen wedged ("crashed"), for the /// supervisor's liveness guard (S18). internal var clusterPairWedgedSince: ContinuousClock.Instant? - /// The leader's serving context for committed starts (S10), and the one - /// start it serves: its epoch, whether the session asked it to stop, and - /// whether the pair is still forming. + /// The leader's serving context for committed starts (S10), the one + /// start it serves (held from its serve until its session's stop), and + /// the last start whose session stopped, which is never served after. internal var clusterPairServing: ClusterPairServingContext? internal var clusterPairServingEpoch: UUID? - internal var clusterPairServingStopped = false - internal var clusterPairServingForming = false + internal var clusterPairServingEndedEpoch: UUID? /// The follower member's link serving of its committed starts; retained /// here because the session control holds its serving host weakly. internal var clusterPairFollower: DistributedMemberLinkFollower? From d08eb0069092b4e4fb0024bb920b85c4883f5b58 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Sun, 1 Nov 2026 09:19:52 -0800 Subject: [PATCH 0105/1441] docs(provider): state how the provider waits for child processes Docs Impact maps LogsCommand, ReportCommand, ClusterOnboardingLive, DarkbloomMDMRemoval and SecurityHardening to these pages. Each line states what the merged code does: where the exit comes from, and which waits have a limit. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 5 ++++- docs/architecture/security/provider-trust.md | 4 +++- docs/provider/cli-reference.md | 4 +++- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..f67012a5a7 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -2961,6 +2961,9 @@ live line (`ClusterOnboardingDriver.move`, `ClusterOnboardingProgress.live`), laid out by `TransferProgressLine` through `ClusterTransferReports`; a transcript without a live line keeps only the reports `TransferProgressLine.takeLogLine` marks and the lines for the record. +Its restart line reads FileVault with `fdesetup isactive` +(`OnboardingLive.fileVaultOn`): five seconds, then SIGTERM and two more, and no +answer reads as unknown. The exit comes from `ProcessExitObserver`, which does not run the calling thread's run loop. After a Darkbloom update changes a Mac's worker digest, the control leader's cluster service re-plans and re-adopts the same model by itself (`ClusterService.checkForUpdate`, `ClusterOnboardingUpdate`). A model change of diff --git a/docs/architecture/security/provider-trust.md b/docs/architecture/security/provider-trust.md index 78b40333a8..7a10efa310 100644 --- a/docs/architecture/security/provider-trust.md +++ b/docs/architecture/security/provider-trust.md @@ -1,6 +1,6 @@ # Provider trust during MDM and App Attest coexistence -> Last updated: 2026-10-13 +> Last updated: 2026-11-01 Darkbloom supports two independent provider authorization paths: legacy MDM/APNs verification and qualified App Attest. A connection can satisfy either or both. This explanation separates those paths from their shared dispatch checks and from claims neither path proves. The [authorization reference](../../reference/provider-authorization.md) owns configuration, deadlines and migration procedures. @@ -123,6 +123,8 @@ and [coordinator/registry/autopilot_reward_snapshot.go](https://github.com/Layr- Platform security, signed-artifact qualification and physical SIP/boot transitions need adversarial evidence on supported hardware. Synthetic tests establish code behavior, not resistance to every host compromise. Legacy trust-reuse timing premises likewise remain qualification assumptions. The [encryption explanation](encryption.md) owns the plaintext and key-lifetime model; attestation does not alter it. +`verifyBundleSignature` (`SecurityHardening.swift`) waits for `codesign`, and `DarkbloomMDMRemoval.readProfiles` waits for `profiles`, with no time limit, so a stuck child holds up that check or removal. The exit comes from `ProcessExitObserver`, which does not run the calling thread's run loop. + ## Code map | Concern | Entry points | diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index abab9afda0..8b7ef5a68d 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1,6 +1,6 @@ # Provider CLI reference -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Reference for the `darkbloom` command-line tool: every subcommand and flag, the files and identifiers it creates, the `provider.toml` keys it reads with their @@ -784,6 +784,8 @@ grants serving authorization or removes an existing profile. Without flags: `log stream --predicate 'subsystem == "dev.darkbloom.provider"' --level info`. +Where `logs` and [`report`](#darkbloom-report) wait for a `log` child to finish, they take its exit from `ProcessExitObserver` (its termination handler), which does not run the calling thread's run loop. + | Flag | Description | |------|-------------| | `--coordinator-url ` | Override the coordinator WebSocket URL | From 85feca41d6f1a2df095f0a998df0f077a4d86d30 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:27:08 -0800 Subject: [PATCH 0106/1441] cluster: regression tests for the pair engine's cancellation deadlock Mac B's member (production GLM pair, 2026-11-01) sampled 2,245 of 2,245 times in one stack: retireClusterPairSlot -> EngineV2Bridge.shutdown -> swift_task_cancelImpl (holding the pump task's status lock) -> the stream's onTermination in DistributedCBv2Engine.admit -> DispatchQueue.sync, while the engine queue, publishing the pair's peer loss to that pump (readyCapacity -> stop -> publishFailure -> yield), waited for the same lock. Both tests drive the real engine with a fabricated owner whose step on the engine queue can be held: - a readiness check holds the queue while the suspended consumer is cancelled and the owner invalidates; the check then reports the peer lost (the production cycle, through the stream's onTermination); - a refused reservation's release holds the queue while the submission waiting for its retirement is cancelled (the same lock order through the admission cancellation). Every wait is bounded and polled, so a deadlock fails the test instead of hanging the suite. Both fail on origin/master and pass with the fix. Co-Authored-By: Claude Opus 5.5 --- ...ributedCBv2CancellationDeadlockTests.swift | 192 ++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2CancellationDeadlockTests.swift diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2CancellationDeadlockTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2CancellationDeadlockTests.swift new file mode 100644 index 0000000000..4de08f43a6 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2CancellationDeadlockTests.swift @@ -0,0 +1,192 @@ +import Foundation +import MLXLMCommon +import Testing +@testable import ProviderCore + +/// Production, 2026-11-01: retiring a pair slot (`EngineV2Bridge.shutdown`) +/// cancelled a request's stream consumer while the engine queue published the +/// pair's peer loss to that consumer. Cancellation runs its handlers holding +/// the task's status lock; the stream's termination waited for the engine +/// queue, and the queue waited for that lock to resume the consumer. Every +/// wait here is bounded and polled, so a regression fails instead of hanging. +/// Fabricated owner only: no model, GPU or peer process. +@Suite(.timeLimit(.minutes(1))) +struct DistributedCBv2CancellationDeadlockTests { + @Test func cancellingAConsumerWhileItsPeerLossIsPublishedCannotDeadlock() async throws { + let owner = HeldReadinessOwner() + let engine = try DistributedCBv2Engine(owner: owner, expectedIdentity: owner.base.identity, + profile: distributedTestProfile(), detokenizers: DistributedTestDetokenizers()) + let stream = try engine.submit(distributedTestRequest(maxTokens: 8)) + let lease = owner.base.last + let probe = DeadlockProbe() + // The consumer (the bridge's pump) takes a token, then waits in the stream. + let consumer = Task { + var events = stream.makeAsyncIterator() + _ = await events.next() + probe.mark("first token") + while await events.next() != nil {} + probe.mark("consumer ended") + } + #expect(lease.send(.token(4))) + #expect(await probe.wait("first token", seconds: 5)) + try await Task.sleep(for: .milliseconds(200)) + + // The next token holds the engine queue in its readiness check, which + // then reports the peer lost: a failure published to the consumer. + let release = owner.holdNextReadiness(probe) + DispatchQueue.global().async { _ = lease.send(.token(5)); probe.mark("token returned") } + #expect(await probe.wait("queue held", seconds: 5)) + // Meanwhile the owner invalidates and the slot's retirement cancels the consumer. + DispatchQueue.global().async { owner.base.losePeer(); probe.mark("invalidation returned") } + DispatchQueue.global().async { consumer.cancel(); probe.mark("cancel returned") } + _ = await probe.wait("cancel returned", seconds: 1) + release.signal() + + var ended = true + for mark in ["cancel returned", "token returned", "invalidation returned", "consumer ended"] { + let reached = await probe.wait(mark, seconds: 5) + #expect(reached, "\(mark): the consumer's cancellation and the engine queue deadlocked") + ended = ended && reached + } + // A deadlocked engine is left as it is: its queue would hang the suite. + guard ended else { return } + #expect(lease.cancelCount == 1) // the peer loss took the failure path, once + lease.acknowledge() + await engine.shutdown() + #expect(lease.releaseCount == 1) + #expect(owner.base.shutdownCount == 1) + } + + /// The same lock order through the admission cancellation: a submission + /// that waits for its refused reservation's retirement is cancelled while + /// the engine queue retires it and resumes that submission. + @Test func cancellingASubmissionWhileItsRetirementResumesItCannotDeadlock() async throws { + let owner = HeldReadinessOwner() + let clock = DistributedTestClock() + let engine = try DistributedCBv2Engine(owner: owner, expectedIdentity: owner.base.identity, + profile: distributedTestProfile(), detokenizers: DistributedTestDetokenizers(), clock: clock.clock) + owner.base.onReserve = { clock.advance(.seconds(5)) } // refused after reserve: the deadline passed + let probe = DeadlockProbe() + let submission = Task { + _ = try? await engine.submit(distributedTestRequest(), + firstTokenDeadline: distributedTestDeadline(clock.now.advanced(by: .seconds(3)))) + probe.mark("submission ended") + } + let end = ContinuousClock.now.advanced(by: .seconds(5)) + while (owner.base.reserveCount == 0 || owner.base.last.cancelCount == 0) && ContinuousClock.now < end { + try await Task.sleep(for: .milliseconds(5)) + } + let lease = owner.base.last + #expect(lease.cancelCount == 1) + try await Task.sleep(for: .milliseconds(200)) // the submission now waits for the retirement + + // The retirement holds the engine queue while it releases the + // reservation, then resumes the submission; the caller cancels meanwhile. + let release = owner.holdNextRelease(probe) + lease.acknowledge() + #expect(await probe.wait("queue held", seconds: 5)) + DispatchQueue.global().async { submission.cancel(); probe.mark("cancel returned") } + _ = await probe.wait("cancel returned", seconds: 1) + release.signal() + + var ended = true + for mark in ["cancel returned", "submission ended"] { + let reached = await probe.wait(mark, seconds: 5) + #expect(reached, "\(mark): the submission's cancellation and the engine queue deadlocked") + ended = ended && reached + } + guard ended else { return } + #expect(lease.releaseCount == 1) + #expect(lease.startCount == 0) + await engine.shutdown() + #expect(owner.base.shutdownCount == 1) + } +} + +/// Marks set from any thread, awaited by polling: no cooperative thread ever +/// waits on a queue that may be deadlocked. +private final class DeadlockProbe: @unchecked Sendable { + private let lock = NSLock() + private var marks = Set() + + func mark(_ name: String) { _ = lock.withLock { marks.insert(name) } } + + func wait(_ name: String, seconds: Double) async -> Bool { + let end = ContinuousClock.now.advanced(by: .milliseconds(Int(seconds * 1000))) + while !lock.withLock({ marks.contains(name) }) && ContinuousClock.now < end { + try? await Task.sleep(for: .milliseconds(5)) + } + return lock.withLock { marks.contains(name) } + } +} + +/// One held step: it marks the probe, then waits (bounded) for the test. +private final class HeldStep: @unchecked Sendable { + private let lock = NSLock() + private var next: (probe: DeadlockProbe, release: DispatchSemaphore)? + + func arm(_ probe: DeadlockProbe) -> DispatchSemaphore { + let release = DispatchSemaphore(value: 0) + lock.withLock { next = (probe, release) } + return release + } + + /// True when this call was the held one. + func pass() -> Bool { + let held = lock.withLock { () -> (probe: DeadlockProbe, release: DispatchSemaphore)? in + defer { next = nil } + return next + } + guard let held else { return false } + held.probe.mark("queue held") + _ = held.release.wait(timeout: .now() + 30) + return true + } +} + +/// The fabricated owner with one step held where the engine calls it on its +/// queue: a readiness check (`readyCapacity`), which then reports the peer +/// lost, or a reservation's release (`retire`). +private final class HeldReadinessOwner: DistributedResidentExecutionOwner, @unchecked Sendable { + let base = DistributedTestOwner() + private let readinessStep = HeldStep() + private let releaseStep = HeldStep() + + func holdNextReadiness(_ probe: DeadlockProbe) -> DispatchSemaphore { readinessStep.arm(probe) } + func holdNextRelease(_ probe: DeadlockProbe) -> DispatchSemaphore { releaseStep.arm(probe) } + + func readiness() -> DistributedResidentReadiness? { + if readinessStep.pass() { base.losePeer(notify: false) } + return base.readiness() + } + func setReadinessInvalidationHandler(_ handler: @escaping @Sendable () -> Void) { + base.setReadinessInvalidationHandler(handler) + } + func projectFirstToken(_ request: CBv2Request, admission: CBv2FirstTokenDeadlineAdmission) -> CBv2FirstTokenProjectedWork { + base.projectFirstToken(request, admission: admission) + } + func reserve(_ request: CBv2Request, identity: DistributedResidentIdentity, + profileID: String, capacityLimit: Int) throws -> any DistributedResidentRequestLease { + HeldReleaseLease(try base.reserve(request, identity: identity, profileID: profileID, + capacityLimit: capacityLimit), release: releaseStep) + } + func shutdown() async { await base.shutdown() } +} + +/// The fabricated lease, its release held when the owner armed it. +private final class HeldReleaseLease: DistributedResidentRequestLease, @unchecked Sendable { + private let inner: any DistributedResidentRequestLease + private let release: HeldStep + + init(_ inner: any DistributedResidentRequestLease, release: HeldStep) { self.inner = inner; self.release = release } + + var identity: DistributedResidentIdentity { inner.identity } + var requestID: CBv2RequestID { inner.requestID } + var reservedBytes: Int { inner.reservedBytes } + var bytesInUse: Int { inner.bytesInUse } + func start(emit: @escaping @Sendable (DistributedResidentEvent) -> Bool) throws { try inner.start(emit: emit) } + func cancel() { inner.cancel() } + func requestCleanStop() -> Bool { inner.requestCleanStop() } + func waitUntilRetired() async { await inner.waitUntilRetired() } + func releaseResources() { _ = release.pass(); inner.releaseResources() } +} From d062a1b3d9ddc29f312782303e273c94bbb8e74f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:27:27 -0800 Subject: [PATCH 0107/1441] cluster: never wait for the pair engine's queue from a cancellation DistributedCBv2Engine ran three closures from task cancellation or from a detached task with a blocking DispatchQueue.sync onto its serial queue: - the request stream's onTermination, which AsyncStream runs from the consumer task's cancellation handler, holding that task's status lock; - the admission cancellation armed in admit, run from submit's withTaskCancellationHandler, under the same kind of lock; - the retirement task, which blocked a cooperative thread. The engine queue in turn resumes those tasks (every stream yield and the retirement latch), which needs the task's status lock. When a pair slot retired (EngineV2Bridge.shutdown cancelling its pumps) while the queue published the pair's peer loss to the same pump, each side held what the other waited for, and the retirement never ended. onQueueWithoutWaiting runs inline on the queue (so a cancellation consumed during reserve still stops the request before it starts) and otherwise hops with queue.async. The retirement task hops with queue.async. Event delivery (the lease's emit), the owner's invalidation and the public calls keep their synchronous queue order. Two engine tests that read the result of a termination right after it now flush the queue first. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-pair-serving-epoch.md | 17 ++++++++++------- docs/architecture/inference.md | 16 +++++++++++++++- docs/reference/cluster-control-protocol.md | 2 +- .../DistributedCBv2Engine+Admission.swift | 14 +++++++++----- .../Engine/DistributedCBv2Engine.swift | 8 ++++++++ .../DistributedCBv2DeadlineTests.swift | 1 + .../DistributedCBv2EngineTests.swift | 1 + 7 files changed, 45 insertions(+), 14 deletions(-) diff --git a/changelog.d/cluster-pair-serving-epoch.md b/changelog.d/cluster-pair-serving-epoch.md index 1c3ce62979..54506e12e1 100644 --- a/changelog.d/cluster-pair-serving-epoch.md +++ b/changelog.d/cluster-pair-serving-epoch.md @@ -1,11 +1,14 @@ ### Two-Mac pairs recover after a lost rank - A two-Mac pair no longer stays unable to serve after it loses a rank, is - fenced, or has a request cancelled before it started. The leader released - its committed start only after the old pair slot had fully drained. When the - drain outlasted the session's own wait, the leader refused every later start - with "a committed start is already served" until the provider was restarted. -- The leader now releases a start as soon as its session ends, and an - unfinished serve of that start stands down without touching the next one. - The release receipt still waits for the slot to retire. A pair still never + fenced, or has a request cancelled before it started. +- Fixed a deadlock in the pair's request engine. Stopping the pair slot + cancelled a request's stream while the engine was telling that request the + pair had lost a rank. The stream's cancellation waited for the engine, and the + engine waited for the cancellation to finish, so the slot never stopped. + Cancellation and stream termination now never wait for the engine. +- The leader also releases a committed start as soon as its session ends, + instead of after the old slot has fully stopped, so a slow stop can no longer + make it refuse every later start with "a committed start is already served". + The release receipt still waits for the slot to retire, and a pair still never serves two slots at once. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..f8a2eea150 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -57,6 +57,20 @@ Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/DistributedR `provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledSession.swift`, and `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterMemberPreparation+PairServing.swift`. +The cluster request engine owns one serial queue. Every stream `yield` and its +retirement latch resume their tasks from it, and resuming a task needs that +task's status lock. Task cancellation holds the same lock while its handlers +run. So the engine never waits for its queue from a cancellation path: a +request stream's `onTermination` and the admission cancellation hop onto the +queue without waiting, or run in place when already on it. The retirement task +never blocks a cooperative thread. Waiting there deadlocked a pair slot's +retirement: `EngineV2Bridge.shutdown` cancelled a pump while the queue +published that request's peer loss. Lease events, the owner's invalidation and +the public calls keep their synchronous queue order. Source: +`provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift` +(`onQueueWithoutWaiting`) and +`provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift`. + The cluster setup liveness probe uses the same request validation as ordinary chat completions. `ClusterSetupProbeRequest` sends no family-specific thinking override, so each model’s prompt policy remains authoritative. diff --git a/docs/reference/cluster-control-protocol.md b/docs/reference/cluster-control-protocol.md index b7a9efd5ea..64ebe8c2d5 100644 --- a/docs/reference/cluster-control-protocol.md +++ b/docs/reference/cluster-control-protocol.md @@ -204,7 +204,7 @@ policy bytes the control requires in a prepare frame | Prepare | The payload's policy must equal the installed policy byte for byte, the start must name this rank, and the frame must leave at most 30 seconds to prepare by this Mac's clock. The member then verifies its installed owner, native executable, metallib and resource library under the device gate and answers `native_pair_prepared` | `provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberSession.swift`, `init` / `runOwned` | | Committed start | `native_pair_owner_start` launches this Mac's installed owner; the owner's native child drives `native_pair_hello` and `native_pair_confirmation`, and `native_pair_owner_released` is sent only after native cleanup, the owner's lease release and the owner's exit were all observed | `runOwned` / `exchange` | | Cancel or expiry | Requests native cleanup at once, independently of signing or the socket. An uncommitted session is dropped and the member can prepare again; a committed one that cannot deliver its release stays quarantined in the control, which then refuses every later attachment | `cancel`; `NativePairMemberControl.finished` | -| Serving on the leader | The leader serves one committed start at a time, from its serve until its session's stop. The stop releases the start at once, then waits for the pair slot to retire before the receipt. After a lost rank or a fence, the next committed start is served once the old slot has retired, even if a serve or the slot's drain outlasts the session's bounded wait. A start whose session already stopped is never served | `provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift`, `serveCommittedStart` / `stopServingCommittedStart` | +| Serving on the leader | The leader serves one committed start at a time, from its serve until its session's stop. The stop releases the start at once, then waits for the pair slot to retire before the receipt. After a lost rank or a fence, the next committed start is served once the old slot has retired, even if a serve or the slot's drain outlasts the session's bounded wait. A start whose session already stopped is never served. The slot's engine never waits for its queue from a cancellation or a stream's termination, so cancelling a request while its peer loss is published cannot deadlock the retirement | `provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift`, `serveCommittedStart` / `stopServingCommittedStart`; `provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift`, `onQueueWithoutWaiting` | **What a real member does in this build.** The installed owner (`darkbloom cluster worker-owner --stdio`) admits a start the coordinator diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift index d4478d00ae..edcf91c9d2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift @@ -44,21 +44,25 @@ extension DistributedCBv2Engine { admissionStartedAt: admissionStartedAt, reservedAt: clock.now()) actives[state.generation] = state observe(state, phase: .reserved) + // Both run from task cancellation: they never wait for the queue (a + // cancellation already consumed here, during reserve, still runs at once). cancellation?.arm { [weak self, weak state] in guard let self, let state else { return } - self.onQueue { self.stop(state, reason: .cancelled) } + self.onQueueWithoutWaiting { self.stop(state, reason: .cancelled) } } continuation.onTermination = { [weak self, generation = state.generation] _ in - self?.onQueue { - guard self?.actives[generation] != nil else { return } - self?.stop(state, reason: .cancelled) + guard let self else { return } + self.onQueueWithoutWaiting { + guard self.actives[generation] != nil else { return } + self.stop(state, reason: .cancelled) } } // Always retain the engine and lease until acknowledgement, even if the // consumer drops the stream or the owner throws after partially starting. + // A cooperative thread never waits for the queue. Task { [self, state] in await state.lease.waitUntilRetired() - onQueue { retire(state) } + queue.async { [self] in retire(state) } } var refused = false let admittedAt = clock.now() diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift index 8171ad022c..88ae9490f5 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift @@ -74,6 +74,14 @@ public final class DistributedCBv2Engine: CBv2Engine, @unchecked Sendable { return try queue.sync(execute: body) } + /// `onQueue` for a caller that must never wait for the queue: a task's + /// cancellation handler, and a stream's termination that cancellation runs. + /// Those run holding the task's status lock, which the queue needs to resume + /// that task (every `yield` to its stream): waiting here deadlocked both. + func onQueueWithoutWaiting(_ body: @escaping @Sendable () -> Void) { + if DispatchQueue.getSpecific(key: queueKey) != nil { body() } else { queue.async(execute: body) } + } + public func cancel(_ id: CBv2RequestID) { onQueue { guard let state = actives.values.first(where: { $0.request.id == id }) else { return } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2DeadlineTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2DeadlineTests.swift index ee222dadbe..cb29c6e22c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2DeadlineTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2DeadlineTests.swift @@ -200,6 +200,7 @@ struct DistributedCBv2DeadlineTests { _ = await distributedCollect(first) let second = try engine.submit(distributedTestRequest(maxTokens: 1)) oldTermination?(.cancelled) + engine.onQueue {} // the termination reaches the queue without waiting for it #expect(owner.last.cancelCount == 0) owner.last.send(.token(5)) owner.last.acknowledge() diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2EngineTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2EngineTests.swift index c3444e20ef..e6710ecbe7 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2EngineTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2EngineTests.swift @@ -392,6 +392,7 @@ struct DistributedCBv2EngineTests { let consumer = Task { await distributedCollect(stream) } consumer.cancel() _ = await consumer.value + engine.onQueue {} // the stream's termination reaches the queue without waiting for it #expect(owner.last.cancelCount == 1) #expect(owner.last.releaseCount == 0) #expect(engine.capacity().activeRequests == 1) From cefbf3f3708e4fe7f57dea9a7bf079a62eff038c Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:54:06 -0800 Subject: [PATCH 0108/1441] cluster: MiMo tensor parallel keeps every partial FP32 until its sum MiMo tensor parallel stored each rank's o_proj, dense down_proj and half-width expert rows as BF16 before the FP32 cross-rank sum, so a pair rounded each product twice where one Mac rounds it once (the owner directive: no precision reduction against the single-Mac reference). SDK d264a039: every row-parallel product takes an exact FP32 widening of its BF16 input, so the partial is FP32 and the only rounding is the one after the sum. The link carries the same FP32 row per token. The arithmetic contract is v2 (MiMoTensorParallelPlan .arithmeticAgreementFields: "...-stored-float32-...-rounded-once-v2"). It is in the load agreement and the plan fingerprint, so ranks on v1 and v2 refuse each other before loading. MiMoTensorParallelFloat32PartialTests (GPU, synthetic): two ranks' expert rows add up bit for bit to the exact full-width row that one Mac rounds once, through the decode-expert kernel (1 and 4 rows) and MLX's sorted gather (16 rows); per-half BF16 rows fail it. Every partial a rank sums is FP32, and the routed combine equals the whole layer's FP32 combine up to FP32 reassociation. inference.md, test.md and the changelog fragment say so. Co-Authored-By: Claude Opus 5.5 --- changelog.d/mimo-tensor-parallel.md | 1 + docs/architecture/inference.md | 40 +++- docs/developer/test.md | 8 +- .../MiMoTensorParallelPlan.swift | 10 +- ...iMoTensorParallelFloat32PartialTests.swift | 192 ++++++++++++++++++ libs/mlx-swift-lm | 2 +- 6 files changed, 237 insertions(+), 16 deletions(-) create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift diff --git a/changelog.d/mimo-tensor-parallel.md b/changelog.d/mimo-tensor-parallel.md index f885aefeb8..4804af2097 100644 --- a/changelog.d/mimo-tensor-parallel.md +++ b/changelog.d/mimo-tensor-parallel.md @@ -1,6 +1,7 @@ ### MiMo V2.6 Flash tensor parallel on two-Mac clusters - MiMo V2.6 Flash text can run tensor parallel on a pair: each Mac holds half of every layer's heads and expert channels and half of the output head, both share every token over the encrypted link, and on the synthetic checks the two Macs agree bit for bit with a one-process simulation of both halves. The image candidate stays a pipeline. +- Each Mac's half of a layer's attention output and feed-forward is kept at full 32-bit precision until both halves are added, then rounded once, so a pair never rounds more than one Mac does. On the synthetic checks, the two halves of an expert's output add up bit for bit to the full output that one Mac rounds once. - The planner chooses tensor parallel for MiMo only where it predicts it faster than the pipeline with speculative decoding, which MiMo's qualification records credit 1.37x. Every pair keeps the pipeline until a load has measured the link; on a fast link, two 128 GB Macs (which cannot hold MiMo alone) and two 256 GB Macs then get tensor parallel unless the prompt is long and the answer short. Qwen and GLM still choose tensor parallel wherever it fits. - In tensor parallel, MiMo returns logprobs (`logprobs` / `top_logprobs`), serves one request at a time without speculative decoding, and each Mac reserves memory for its own half: 84.0 GB of weights plus its own KV, work and buffers, with a conservative 5.5 GiB activation reserve until a pair measures one (about 98 GiB per Mac at the longest request). - No MiMo tensor-parallel qualification record exists yet, and speed on a real pair is not measured. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 03f95b8f20..1ca1c9a651 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4240,9 +4240,9 @@ are excluded by name and refused as text, as is any unknown or misaligned name: | Part | Cut per rank | Collective | |---|---|---| | `q_proj`, `k_proj`, `v_proj`, sliding sink bias | Rows of 32 query heads and the KV heads they read (2 full, 4 sliding); head dims 192/128 as stored | — | -| `o_proj` | Input columns of those heads (4,096) | BF16 partial, summed in FP32, rounded once, before `post_attention_layernorm` | +| `o_proj` | Input columns of those heads (4,096) | FP32 partial (its BF16 input widened exactly), summed in FP32, rounded once, before `post_attention_layernorm` | | Dense layer 0 (16,384) | Gate/up rows, down input columns (8,192) | Same contract as `o_proj` | -| Routed experts (`[256, out, in]` banks) | Gate/up axis 1, down axis 2: 1,024 channels, 32 MXFP4 groups | Each rank's 8 expert rows from the stock banks and decode kernels, combined locally in FP32 with the router's weights; one FP32 row summed, rounded once | +| Routed experts (`[256, out, in]` banks) | Gate/up axis 1, down axis 2: 1,024 channels, 32 MXFP4 groups | Each rank's 8 expert rows from the stock banks and decode kernels, stored as FP32, combined locally in FP32 with the router's weights; one FP32 row summed, rounded once | | Router, norms, embedding | Replicated | — | | Untied `lm_head` | This rank's 76,288 vocabulary rows | One per selection | @@ -4256,14 +4256,34 @@ selected expert's FP32 row across ranks (`TensorParallelSwitchLinear`). A MiMo rank keeps the stock half bank, so decode stays on the MXFP4 expert kernel (`MiMoV26DecodeExperts` takes only a plain `QuantizedSwitchLinear`), and one FP32 row crosses per token instead of eight: 16,384 B instead of -131,072 B per routed layer at the registered width. The cost is one more -rounding. Each expert's down projection over this rank's channels is rounded -to BF16 before the FP32 combine, where one Mac rounds each expert's whole -projection once. That is the rounding class of the `o_proj` partial, so -comparisons against one Mac read `tokensEqualLogitsDiffer` or -`divergedAtNearTie`. Per-expert FP32 rows would remove only this rounding: -the `o_proj` partial keeps its own, so ranks would still not be bit-exact -with one Mac, and routes could still flip. +131,072 B per routed layer at the registered width. + +Every row-parallel product takes an exact FP32 widening of its BF16 input, so +its partial is stored as FP32 and the only rounding is the one after the +cross-rank sum. This is arithmetic contract v2 +(`MiMoTensorParallelPlan.arithmeticAgreementFields`, in the load agreement and +the plan fingerprint); v1 stored each partial as BF16 first, and ranks on +different contracts refuse each other. + +- Expert rows: `SwitchGLU.float32ExpertRows`, through the decode-expert + kernel's FP32-output twin (`MiMoV26DecodeExperts`, `float32Rows`) or MLX's + FP32 gather. +- `o_proj` and the dense `down_proj`: MLX's FP32 qmv and qmm + (`MiMoV26DecoderLayer.attentionOutput`, `MiMoV26DenseMLP.tensorParallelPartial`). + `MiMoV26TensorParallelContext.sum` takes nothing but an FP32 partial. + +FP32 holds every BF16 value exactly, and MLX's FP32 MXFP4 and affine kernels +accumulate in FP32 as the BF16 ones do. On M5 the NAX path runs FP32 inputs at +TF32 (`MLX_ENABLE_TF32=1`, which every cluster contract requires). Its 10 +mantissa bits keep a BF16-sourced activation and an MXFP4 weight exactly, and an +affine 8-bit weight at least as precisely as the BF16 kernel's BF16 weight tile. +So no rank rounds more than one Mac: an expert row is rounded once, after the +sum, where one Mac rounds each expert's whole projection to BF16 before its +combine. Ranks are still not bit-exact with one Mac, because the halves +reassociate the FP32 sums and a near tie can flip a route. Comparisons against +one Mac read `tokensEqualLogitsDiffer` or `divergedAtNearTie`. +`MiMoTensorParallelFloat32PartialTests` checks on the GPU that two ranks' rows +add up bit for bit to the exact full-width row that one Mac rounds once. `MiMoV26TensorShard` derives each rank's configuration (half the heads of both layer kinds and both channel widths, no MTP heads or towers) and cuts stored diff --git a/docs/developer/test.md b/docs/developer/test.md index c880ad91de..84e4cfb565 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1322,7 +1322,9 @@ These checks use synthetic weights on one Mac, over loopback only. They prove neither real-weight numerics, a pair qualification nor speed. Never load the registered artifact for them. -1. Run the CPU unit tests: +1. Run the unit tests. The FP32-partial suite runs on the GPU, so stage the + source-matched `mlx.metallib` in the test bundle first + (`scripts/stage-test-metallib.sh`): ```bash swift test --package-path libs/darkbloom-cluster --filter MiMoTensorParallel @@ -1337,6 +1339,10 @@ registered artifact for them. - the shard configuration and per-rank KV geometry; - shard cuts and byte runs against independent slices; - two in-process ranks against each other and the whole model; + - FP32 partials (`MiMoTensorParallelFloat32PartialTests`, on the GPU): two + ranks' expert rows add up bit for bit to the exact full-width row that + one Mac rounds once, through the decode-expert kernel and MLX's sorted + gather, and every partial a rank sums is FP32; - the vocabulary-split head against the whole head; - the resident runtime's verified load: each rank reads exactly its shard's bytes, and a tampered or foreign checkpoint is refused; diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelPlan.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelPlan.swift index 3b76bb886b..b452650552 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelPlan.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelPlan.swift @@ -242,12 +242,14 @@ public struct MiMoTensorParallelPlan: Sendable, Equatable { public var reductionsPerForward: Int { reductionsPerLayer * layerCount } /// What two ranks must agree on before they serve together: the plan, - /// where each sum is taken and what it carries. + /// where each sum is taken and what it carries. Each row-parallel product + /// takes an exact FP32 widening of its input, so its partial is stored as + /// FP32 and rounded only once, after the sum (v2; v1 stored BF16 partials). public static let arithmeticAgreementFields = [ name, - "mimo-v26-o-proj-partial-stored-bfloat16-sum-float32-rounded-once-v1", - "mimo-v26-dense-down-partial-stored-bfloat16-sum-float32-rounded-once-v1", - "mimo-v26-expert-rows-local-float32-combine-sum-float32-rounded-once-v1", + "mimo-v26-o-proj-partial-stored-float32-sum-float32-rounded-once-v2", + "mimo-v26-dense-down-partial-stored-float32-sum-float32-rounded-once-v2", + "mimo-v26-expert-rows-stored-float32-local-float32-combine-sum-float32-rounded-once-v2", "mimo-v26-untied-head-vocabulary-halves-v1", "mimo-v26-mtp-off-v1", ] diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift new file mode 100644 index 0000000000..26d52f2ea1 --- /dev/null +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift @@ -0,0 +1,192 @@ +import Foundation +import MLX +@testable import MLXLLM +@testable import MLXLMCommon +import MLXNN +import Testing +@testable import DarkbloomClusterRuntime + +/// MiMo V2.6 tensor parallel's arithmetic contract v2: every row-parallel +/// partial (routed expert rows, the dense `down_proj`, `o_proj`) is stored as +/// FP32 and rounded once, after the cross-rank sum. On the GPU's production +/// kernels (the MXFP4 decode-expert kernel for 1 to 7 rows, MLX's sorted +/// gather for prompt rows, NAX at TF32 on M5), two ranks' expert rows add up +/// bit for bit to the exact full-width row, which the single Mac rounds once. +/// The weights and inputs make every sum an exact FP32 integer whose halves +/// need more than BF16's 8 significant bits, so a per-half BF16 store (v1) +/// fails here. Synthetic weights only. +@Suite("MiMo V2.6 tensor-parallel FP32 partials", .serialized) +struct MiMoTensorParallelFloat32PartialTests { + private typealias Pair = Gemma4TensorParallelLocalPair + + private static let hidden = 1024, width = 1024, experts = 16, topK = 8 + + /// The kernel variant's whole model and both ranks, loaded on the GPU. + private static func models() throws -> (whole: MiMoTensorParallelModel, ranks: [MiMoTensorParallelModel], directory: URL) { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("mimo-tp-fp32-partials-\(UUID().uuidString)") + try MiMoTensorParallelModel.writeSyntheticCheckpoint(directory: directory, variant: .kernel) + let pair = Pair() + let whole = try MiMoTensorParallelModel.load(modelDirectory: directory, role: .full, reduction: nil) + let ranks = try (0 ..< 2).map { + try MiMoTensorParallelModel.load(modelDirectory: directory, role: .shard(rank: $0), reduction: pair.reduction(rank: $0)) + } + return (whole, ranks, directory) + } + + private static func routed(_ model: MiMoTensorParallelModel, layer: Int = 1) throws -> MiMoV26MoE { + guard let moe = model.model.model.layers[layer].mlp as? MiMoV26MoE else { throw ProbeError("layer \(layer) is not routed") } + return moe + } + + /// Random MXFP4 values (E2M1 times `scale`) with a ±6·scale in every group of 32, so + /// each group's E8M0 scale is exactly `scale` and quantization is exact. + private static func exactMXFP4(_ shape: [Int], scale: Float, seed: UInt64) -> MLXArray { + let keys = MLXRandom.split(key: MLXRandom.key(seed), into: 2) + let table = MLXArray([0, 0.5, 1, 1.5, 2, 3, 4, 6] as [Float]) + let magnitude = take(table, MLXRandom.randInt(0 ..< 8, shape, key: keys[0])) + let sign = MLXRandom.randInt(0 ..< 2, shape, key: keys[1]).asType(.float32) * 2 - 1 + let groupLead = (MLXArray(Array(Int32(0) ..< Int32(shape.last!))) % 32) .== 0 + return which(groupLead, MLXArray(Float(6)), magnitude) * sign * scale + } + + private static func pack(_ values: MLXArray) throws -> (weight: MLXArray, scales: MLXArray) { + let (weight, scales, _) = quantized(values, groupSize: 32, bits: 4, mode: .mxfp4) + let back = dequantized(weight, scales: scales, biases: nil, groupSize: 32, bits: 4, mode: .mxfp4, dtype: .float32) + guard arrayEqual(back, values).item(Bool.self) else { throw ProbeError("the synthetic MXFP4 values must quantize exactly") } + return (weight, scales) + } + + /// Installs one packed expert bank into a routed layer, cut for `shard` as the loader cuts it. + private static func install(_ banks: [String: (weight: MLXArray, scales: MLXArray)], into moe: MiMoV26MoE, + shard: MiMoV26TensorShard?) throws { + var parameters: [(String, MLXArray)] = [] + for (module, bank) in banks { + let axis = try MiMoV26TensorShard.splitAxis("model.layers.1.mlp.switch_mlp.\(module).weight") + for (leaf, value) in [("weight", bank.weight), ("scales", bank.scales)] { + parameters.append(("switch_mlp.\(module).\(leaf)", try shard.map { try $0.slice(value, axis: axis) } ?? value)) + } + } + try moe.update(parameters: ModuleParameters.unflattened(parameters), verify: [.noUnusedKeys, .shapeMismatch]) + eval(moe) + } + + /// Contract v2 is in the plan's arithmetic fields and so in the load agreement and the + /// plan fingerprint: a rank on v1 (BF16 partials) disagrees and both refuse before loading. + @Test func theLoadAgreementCarriesContractVersion2() throws { + let fields = MiMoTensorParallelPlan.arithmeticAgreementFields + for part in ["o-proj-partial", "dense-down-partial", "expert-rows"] { + #expect(fields.contains { $0.hasPrefix("mimo-v26-\(part)-stored-float32-") && $0.hasSuffix("-rounded-once-v2") }, "\(part)") + } + #expect(!fields.contains { $0.contains("bfloat16") || $0.hasSuffix("-v1") && $0.contains("partial") }) + let plan = try MiMoTensorParallelPlan(configuration: JSONSerialization.data( + withJSONObject: MiMoTensorParallelModel.syntheticConfiguration(.kernel), options: [.sortedKeys])) + let agreement = MiMoTensorParallelResidentRuntime.loadAgreementFields(plan: plan, chunkTokens: 16) + #expect(fields.allSatisfy(agreement.contains) && agreement.contains(plan.fingerprint)) + } + + /// Two ranks' FP32 expert rows sum to the exact full-width row, bit for bit, and the + /// single Mac's BF16 row is that row rounded once. Rows 1 and 4 run the MXFP4 + /// decode-expert kernel; 16 rows run MLX's sorted gather (NAX at TF32 on M5). + @Test func rankExpertRowsSumToTheExactFullWidthRow() throws { + let (whole, ranks, directory) = try Self.models() + defer { try? FileManager.default.removeItem(at: directory) } + // gate 12: SiLU(12) rounds to 12 in BF16, so each activation is exactly 12·up (≤ 144). + let up = Self.exactMXFP4([Self.experts, Self.width, Self.hidden], scale: 2, seed: 21) + let down = Self.exactMXFP4([Self.experts, Self.hidden, Self.width], scale: 1, seed: 22) + let banks = [ + "gate_proj": try Self.pack(MLXArray.full([Self.experts, Self.width, Self.hidden], values: MLXArray(Float(12)))), + "up_proj": try Self.pack(up), "down_proj": try Self.pack(down), + ] + try Self.install(banks, into: Self.routed(whole), shard: nil) + for rank in 0 ..< 2 { try Self.install(banks, into: Self.routed(ranks[rank]), shard: MiMoV26TensorShard(rank: rank)) } + + for rows in [1, 4, 16] { + // One-hot BF16 rows select one input column per token. + let columns = (0 ..< rows).map { ($0 * 97 + 5) % Self.hidden } + var onehot = [Float](repeating: 0, count: rows * Self.hidden) + for (row, column) in columns.enumerated() { onehot[row * Self.hidden + column] = 1 } + let x = MLXArray(onehot, [1, rows, Self.hidden]).asType(.bfloat16) + let chosen = (0 ..< rows).flatMap { row in (0 ..< Self.topK).map { UInt32((row + 2 * $0) % Self.experts) } } + let indices = MLXArray(chosen, [1, rows, Self.topK]) + + let rankRows = try (0 ..< 2).map { try Self.routed(ranks[$0]).switchMLP.float32ExpertRows(x, indices) } + let product = try Self.routed(whole).switchMLP(x, indices) + eval(rankRows + [product]) + #expect(rankRows.allSatisfy { $0.dtype == .float32 } && product.dtype == .bfloat16) + if rows <= 7 { + // The decode-expert kernel produced these rows (not a fallback). + let kernel = try #require(MiMoV26DecodeExperts.tryProject( + x, indices: indices, glu: Self.routed(ranks[0]).switchMLP, enabled: true, float32Rows: true)) + #expect(arrayEqual(kernel.output, rankRows[0]).item(Bool.self), "\(rows) rows") + } + + // The exact row on the CPU: every partial sum is an integer below 2^21. + let reference = Device.withDefaultDevice(.cpu) { () -> MLXArray in + let selected = MLXArray(chosen.map { Int32($0) }) + let tokenColumns = MLXArray(columns.flatMap { column in [Int32](repeating: Int32(column), count: Self.topK) }) + let activation = (up.transposed(0, 2, 1)[selected, tokenColumns] * 12).expandedDimensions(axis: 1) + let value = gatherMM(activation, down.swappedAxes(-1, -2), rhsIndices: selected) + .reshaped([1, rows, Self.topK, Self.hidden]) + eval(value) + return value + } + func bits(_ value: MLXArray) -> [UInt32] { + Device.withDefaultDevice(.cpu) { value.asType(.float32).asArray(Float.self).map(\.bitPattern) } + } + let combined = rankRows[0] + rankRows[1] + #expect(bits(combined) == bits(reference), "\(rows) rows: the FP32 sum of both halves is the exact full-width row") + #expect(bits(product) == bits(reference.asType(.bfloat16)), "\(rows) rows: one Mac rounds that row once") + // Contract v1 stored each half as BF16 first: that is not the full-width row. + let halvesRounded = rankRows[0].asType(.bfloat16).asType(.float32) + rankRows[1].asType(.bfloat16).asType(.float32) + let differ = zip(bits(halvesRounded), bits(reference)).filter { $0 != $1 }.count + #expect(differ > 0, "\(rows) rows: the data must catch a per-half BF16 rounding") + } + } + + /// Every partial a rank hands its sum is FP32 (`o_proj`, the dense and the routed + /// feed-forward), and the result is rounded once to the activation dtype. The routed + /// layer's two partials equal the whole layer's FP32 combine up to FP32 reassociation, + /// far inside the BF16 error per-half rows carried before. + @Test func everyRankPartialIsFloat32AndRoundsOnceAfterTheSum() throws { + let (whole, ranks, directory) = try Self.models() + defer { try? FileManager.default.removeItem(at: directory) } + final class Recorder: @unchecked Sendable { var dtypes: [DType] = [] } + let recorder = Recorder() + let x = withRandomState(MLXRandom.RandomState(seed: 9)) { MLXRandom.normal([1, 3, Self.hidden]) }.asType(.bfloat16) + var partials: [MLXArray] = [] + for rank in ranks { + let context = MiMoV26TensorParallelContext( + reduce: { recorder.dtypes.append($0.dtype); return $0 }, vocabularyRows: rank.vocabularyRange) + let dense = rank.model.model.layers[0], moe = rank.model.model.layers[1] + #expect(dense.mlp is MiMoV26DenseMLP) + let outputs = [ + dense.tensorParallelFeedForward(x, context), + dense.tensorParallelFeedForward(x, context, rowLocal: true), + moe.tensorParallelFeedForward(x, context), + ] + let installed = moe.tensorParallel + moe.tensorParallel = context + let attention = moe.attentionOutput(x, mask: .none, cache: nil) + moe.tensorParallel = installed + eval(outputs + [attention]) + #expect((outputs + [attention]).allSatisfy { $0.dtype == .bfloat16 }) + partials.append(try Self.routed(rank).tensorParallelPartial(x)) + } + #expect(recorder.dtypes == [DType](repeating: .float32, count: 8)) + #expect(partials.allSatisfy { $0.dtype == .float32 }) + + let wholeMoE = try Self.routed(whole) + let route = wholeMoE.gate(x) + let reference = MiMoV26MoE.combinePartial(wholeMoE.switchMLP.float32ExpertRows(x, route.indices), weights: route.weights) + let rowsRounded = try (0 ..< 2).map { rank -> MLXArray in + let rows = try Self.routed(ranks[rank]).switchMLP.float32ExpertRows(x, route.indices) + return MiMoV26MoE.combinePartial(rows.asType(.bfloat16).asType(.float32), weights: route.weights) + } + let scale = abs(reference).max().item(Float.self) + let error = abs(partials[0] + partials[1] - reference).max().item(Float.self) + let perHalfError = abs(rowsRounded[0] + rowsRounded[1] - reference).max().item(Float.self) + #expect(error <= scale * 0x1p-16, "FP32 reassociation only: \(error) of \(scale)") + #expect(perHalfError > 16 * error, "per-half BF16 rows (v1) err \(perHalfError), FP32 rows \(error)") + } +} diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 6943680152..d264a0390c 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 6943680152e391001258d9c8505a2214ce1d0399 +Subproject commit d264a0390c341f7085542782df0c0cbd4870186d From d80b5ac43a9376abf52773b1f60d876b7e3f322f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:58:32 -0800 Subject: [PATCH 0109/1441] cluster: declare each mode's serving features in the capability record The worker's capability record can now say what each generation mode keeps of the model's serving features (`ClusterServingFeatures`): resident prompt-prefix reuse and its SSD tier, speculative (MTP) rounds, the widest batch-lane width, request media, penalties and logit bias, stop handling and committed-token logprobs. `ClusterServingFeatures.dropped(by:)` names what another mode would drop of them; what that mode adds never counts. - `ClusterRuntimeCapability.modeFeatures`: one entry per supported mode (validated), written as `modeFeatures` only when declared, so every other record keeps its bytes. - Gemma 4 declares them in `Gemma4ResidentAdapterDefinition`: tensor parallel keeps no prompt prefix yet. `tensorParallelKeepsPromptPrefixes` is now what its load agreement binds. - MiMo V2.6's text row declares them from its loads' own settings (`MiMoBatchSettings`; `MiMoTensorParallelResidentRuntime.servingFeatures`, whose lane count and prefix setting its serving agreement now binds, bytes unchanged). The image candidate declares none. - Qwen, GLM and every other record are unchanged. - Tests: what each Gemma mode and each MiMo text mode declares, tied to the load agreements. Co-Authored-By: Claude Opus 5.5 --- .../ClusterRuntimeCapability.swift | 11 ++- .../ClusterRuntimeCapabilityCodec.swift | 13 ++- .../ClusterRuntimeCapabilityValidation.swift | 5 ++ .../ClusterServingFeatures.swift | 88 +++++++++++++++++++ .../Gemma4ResidentAdapterDefinition.swift | 13 +++ .../Gemma4ResidentCapabilityMetadata.swift | 3 +- .../Gemma4TensorParallelResidentRuntime.swift | 4 +- .../MiMoResidentCapabilityMetadata.swift | 18 +++- .../MiMoTensorParallelResidentRuntime.swift | 11 ++- .../Gemma4TensorParallelRuntimeTests.swift | 18 ++++ .../MiMoTensorParallelResidentTests.swift | 15 ++++ 11 files changed, 191 insertions(+), 8 deletions(-) create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterServingFeatures.swift diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapability.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapability.swift index 80f6dbc5ca..f1422bb9b6 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapability.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapability.swift @@ -167,6 +167,12 @@ public struct ClusterRuntimeCapability: Equatable, Sendable { public let speculation: String public static let decodingRankSpeculation = "decodingRankHeadExactGreedy" public let prefixReuse = false + /// What each supported mode keeps of the model's serving features + /// (`ClusterServingFeatures`), one entry per mode, as the adapter declares + /// them; the placement step plans a mode only where it keeps every feature + /// of the mode it would replace. Nil, written as no field: the adapter + /// declares none (its record reads byte for byte as before). + public let modeFeatures: [ClusterGenerationMode: ClusterServingFeatures]? public init(runtimeBinarySHA256: String, adapterID: String, adapterVersion: Int, runtimeModelID: String, artifactSHA256: String, configurationSHA256: String, @@ -175,8 +181,9 @@ public struct ClusterRuntimeCapability: Equatable, Sendable { arithmeticPolicySHA256: String, supportedPrefillSchedules: [ClusterPrefillSchedule] = [.serial], supportedGenerationModes: [ClusterGenerationMode] = [.pipeline], - media: ClusterMiMoImageCandidate? = nil, glmImages: ClusterGLMImageCandidate? = nil) throws { - self.media = media; self.glmImages = glmImages + media: ClusterMiMoImageCandidate? = nil, glmImages: ClusterGLMImageCandidate? = nil, + modeFeatures: [ClusterGenerationMode: ClusterServingFeatures]? = nil) throws { + self.media = media; self.glmImages = glmImages; self.modeFeatures = modeFeatures self.runtimeBinarySHA256 = runtimeBinarySHA256; self.adapterID = adapterID; self.adapterVersion = adapterVersion self.runtimeModelID = runtimeModelID; self.artifactSHA256 = artifactSHA256 self.configurationSHA256 = configurationSHA256; self.manifestSHA256 = manifestSHA256 diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityCodec.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityCodec.swift index 4fed84dedd..d7b9b7a3f0 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityCodec.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityCodec.swift @@ -46,6 +46,10 @@ public enum ClusterRuntimeCapabilityCodec { } if value.media != nil { object["media"] = ClusterMiMoImageCandidate.fields } if value.glmImages != nil { object["glmImages"] = ClusterGLMImageCandidate.fields } + // Written only by an adapter that declares its modes' features, so every other record keeps its bytes. + if let features = value.modeFeatures { + object["modeFeatures"] = Dictionary(uniqueKeysWithValues: features.map { ($0.key.rawValue, $0.value.wireObject) }) + } var data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes]) try workerRequire(data.count < maximumBytes, "Runtime capability exceeds its byte bound") data.append(10); return data @@ -106,13 +110,20 @@ public enum ClusterRuntimeCapabilityCodec { } else { modes = [.pipeline] } let media = r.values["media"] == nil ? nil : try ClusterMiMoImageCandidate.decode(r.object("media")) let glmImages = r.values["glmImages"] == nil ? nil : try ClusterGLMImageCandidate.decode(r.object("glmImages")) + let modeFeatures = r.values["modeFeatures"] == nil ? nil : try Dictionary(uniqueKeysWithValues: + r.object("modeFeatures").map { name, entry -> (ClusterGenerationMode, ClusterServingFeatures) in + guard let mode = ClusterGenerationMode(rawValue: name), let object = entry as? [String: Any] else { + throw ClusterWorkerProtocolError.invalid("Unknown generation mode or malformed serving features") + } + return (mode, try ClusterServingFeatures.decode(wire: object)) + }) let value = try ClusterRuntimeCapability(runtimeBinarySHA256: r.string("runtimeBinarySHA256"), adapterID: r.string("adapterID"), adapterVersion: r.int("adapterVersion"), runtimeModelID: r.string("runtimeModelID"), artifactSHA256: r.string("artifactSHA256"), configurationSHA256: r.string("configurationSHA256"), manifestSHA256: r.string("manifestSHA256"), profile: profile, profileFingerprint: r.string("profileFingerprint"), partitions: partitions, arithmeticPolicyID: r.string("arithmeticPolicyID"), arithmeticPolicySHA256: r.string("arithmeticPolicySHA256"), supportedPrefillSchedules: schedules, - supportedGenerationModes: modes,media:media,glmImages:glmImages) + supportedGenerationModes: modes,media:media,glmImages:glmImages, modeFeatures: modeFeatures) try workerRequire(try r.string("stateSemantics") == value.stateSemantics && r.int("rankCount") == value.rankCount && r.int("batchSize") == value.batchSize && r.int("maxActiveRequests") == value.maxActiveRequests diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityValidation.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityValidation.swift index 989356f953..25389ae3b2 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityValidation.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityValidation.swift @@ -19,6 +19,11 @@ enum ClusterRuntimeCapabilityValidation { try workerRequire(value.supportedGenerationModes.first == .pipeline && value.supportedGenerationModes == ClusterGenerationMode.allCases.filter(value.supportedGenerationModes.contains), "Missing, duplicate or unordered generation modes") + if let features = value.modeFeatures { + try workerRequire(Set(features.keys) == Set(value.supportedGenerationModes), + "Serving features must name exactly the supported generation modes") + for entry in features.values { try entry.validate() } + } let imageCandidate = adapter == .mimoV26ImageCandidate try workerRequire(imageCandidate == (value.media != nil),"Candidate adapter requires its closed media contract") if imageCandidate { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterServingFeatures.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterServingFeatures.swift new file mode 100644 index 0000000000..7851b1036a --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterServingFeatures.swift @@ -0,0 +1,88 @@ +import Foundation + +/// What one generation mode keeps of a model's serving features as this worker +/// build runs it, declared by the adapter beside its modes +/// (`ClusterRuntimeCapability.modeFeatures`) from the facts its loads bind (a +/// load agreement without a prompt-prefix cache, a lane count it refuses above +/// one). The placement step compares modes by these and keeps no table of its +/// own: a mode is chosen only where it keeps every feature of the mode it would +/// replace (`dropped(by:)`; owner, 2026-11-01). +public struct ClusterServingFeatures: Equatable, Sendable { + public enum Media: String, CaseIterable, Sendable { case images, video } + + /// Resident prompt-prefix reuse: a prompt that starts with one served + /// before restores that prefix's state instead of prefilling it again. + public let promptPrefixReuse: Bool + /// The owner's SSD tier of that cache. + public let ssdPrefixTier: Bool + /// Decode in speculative rounds: the model's own head drafts and the + /// target verifies the window, keeping only its greedy tokens. + public let speculativeRounds: Bool + /// The widest batch-lane width a load of the mode accepts; 1 serves one + /// request at a time. + public let maximumLanes: Int + /// Media a request may carry beside text, in `Media` order. + public let requestMedia: [Media] + /// Repetition, presence and frequency penalties and logit bias, applied by + /// the product's sampler. + public let penaltiesAndLogitBias: Bool + /// Stop token IDs and stop strings. + public let stopHandling: Bool + /// Committed-token logprobs. + public let logprobs: Bool + + public static let maximumLaneWidth = 8 + + public init(promptPrefixReuse: Bool, ssdPrefixTier: Bool, speculativeRounds: Bool, maximumLanes: Int, + requestMedia: [Media] = [], penaltiesAndLogitBias: Bool = true, stopHandling: Bool = true, logprobs: Bool) { + self.promptPrefixReuse = promptPrefixReuse; self.ssdPrefixTier = ssdPrefixTier + self.speculativeRounds = speculativeRounds; self.maximumLanes = maximumLanes; self.requestMedia = requestMedia + self.penaltiesAndLogitBias = penaltiesAndLogitBias; self.stopHandling = stopHandling; self.logprobs = logprobs + } + + /// What `other` would drop of these features, in plain words and this + /// order; empty when it keeps every one. What `other` has beyond them + /// (logprobs these lack, wider lanes) is a gain and never counts. + public func dropped(by other: ClusterServingFeatures) -> [String] { + var dropped: [String] = [] + if promptPrefixReuse && !other.promptPrefixReuse { dropped.append("prompt-prefix reuse") } + if ssdPrefixTier && !other.ssdPrefixTier { dropped.append("the SSD prefix tier") } + if speculativeRounds && !other.speculativeRounds { dropped.append("speculative (MTP) rounds") } + if other.maximumLanes < maximumLanes { dropped.append("batch lanes up to \(maximumLanes) (it serves \(other.maximumLanes))") } + dropped += requestMedia.filter { !other.requestMedia.contains($0) }.map(\.rawValue) + if penaltiesAndLogitBias && !other.penaltiesAndLogitBias { dropped.append("penalties and logit bias") } + if stopHandling && !other.stopHandling { dropped.append("stop handling") } + if logprobs && !other.logprobs { dropped.append("committed-token logprobs") } + return dropped + } + + func validate() throws { + try workerRequire((1...Self.maximumLaneWidth).contains(maximumLanes) + && requestMedia == Media.allCases.filter(requestMedia.contains) && (promptPrefixReuse || !ssdPrefixTier), + "Malformed serving features") + } + + var wireObject: [String: Any] { + ["promptPrefixReuse": promptPrefixReuse, "ssdPrefixTier": ssdPrefixTier, "speculativeRounds": speculativeRounds, + "maximumLanes": maximumLanes, "requestMedia": requestMedia.map(\.rawValue), "penaltiesAndLogitBias": penaltiesAndLogitBias, + "stopHandling": stopHandling, "logprobs": logprobs] + } + + static func decode(wire object: [String: Any]) throws -> Self { + var r = WorkerObject(object) + guard let names = try r.take("requestMedia") as? [String] else { + throw ClusterWorkerProtocolError.invalid("Expected media names") + } + let requestMedia = try names.map { + guard let kind = Media(rawValue: $0) else { throw ClusterWorkerProtocolError.invalid("Unknown media kind") } + return kind + } + let value = try Self(promptPrefixReuse: r.bool("promptPrefixReuse"), ssdPrefixTier: r.bool("ssdPrefixTier"), + speculativeRounds: r.bool("speculativeRounds"), maximumLanes: r.int("maximumLanes"), requestMedia: requestMedia, + penaltiesAndLogitBias: r.bool("penaltiesAndLogitBias"), stopHandling: r.bool("stopHandling"), + logprobs: r.bool("logprobs")) + try r.finish() + try value.validate() + return value + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentAdapterDefinition.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentAdapterDefinition.swift index 58232ba543..686647fc88 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentAdapterDefinition.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentAdapterDefinition.swift @@ -13,6 +13,19 @@ enum Gemma4ResidentAdapterDefinition { /// parallel only where it predicts it faster than the pipeline /// (`Gemma4PlacementFamily.tensorParallelPlan`, `ClusterTensorParallelChoice.fastest`). static let supportedGenerationModes: [ClusterGenerationMode] = [.pipeline, .tensorParallel] + /// Tensor parallel keeps no prompt prefix yet; its load agreement binds this (`Gemma4TensorParallelResidentRuntime`). + static let tensorParallelKeepsPromptPrefixes = false + /// What each mode keeps (`ClusterServingFeatures`), as its load runs it: the pipeline's stage owner keeps + /// prompt prefixes resident and on the owner's SSD tier (`QwenStagePrefixCache`, native KV); tensor parallel + /// keeps none yet (`tensorParallelKeepsPromptPrefixes`) and adds logprobs. Both serve up to + /// `QwenBatchWire.maximumLanes` lanes; neither decodes in speculative rounds or takes media. + static let servingFeatures: [ClusterGenerationMode: ClusterServingFeatures] = [ + .pipeline: .init(promptPrefixReuse: true, ssdPrefixTier: true, speculativeRounds: false, + maximumLanes: QwenBatchWire.maximumLanes, logprobs: false), + .tensorParallel: .init(promptPrefixReuse: tensorParallelKeepsPromptPrefixes, + ssdPrefixTier: tensorParallelKeepsPromptPrefixes, speculativeRounds: false, + maximumLanes: QwenBatchWire.maximumLanes, logprobs: true), + ] static func profileID(_ model: Gemma4RegisteredModel) -> String { model.rawValue + "_greedy_generation_v1" } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentCapabilityMetadata.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentCapabilityMetadata.swift index 4d3c2d1bc2..98653d45fc 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentCapabilityMetadata.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentCapabilityMetadata.swift @@ -41,6 +41,7 @@ public enum Gemma4ResidentCapabilityMetadata { arithmeticPolicyID: Gemma4ArithmeticEnvironment.contract, arithmeticPolicySHA256: sha256(try canonicalJSONData(arithmetic)), supportedPrefillSchedules: Gemma4ResidentAdapterDefinition.supportedPrefillSchedules, - supportedGenerationModes: Gemma4ResidentAdapterDefinition.supportedGenerationModes) + supportedGenerationModes: Gemma4ResidentAdapterDefinition.supportedGenerationModes, + modeFeatures: Gemma4ResidentAdapterDefinition.servingFeatures) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift index 3b0e8fa8da..50593c718f 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift @@ -115,7 +115,9 @@ public final class Gemma4TensorParallelResidentRuntime { try admission.jaccl.requireUnchanged(environment: ProcessInfo.processInfo.environment, read: read) try admission.jaccl.requireInitialized(rank: collective.rank, worldSize: collective.size, transport: collective.transport) - let terms = Gemma4TensorParallelLoadAgreement(lanes: lanes, kv: kv, kvQuantization: kvQuantization, prefixCache: false) + // What the capability declares (`Gemma4ResidentAdapterDefinition.servingFeatures`). + let terms = Gemma4TensorParallelLoadAgreement(lanes: lanes, kv: kv, kvQuantization: kvQuantization, + prefixCache: Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes) let loadAgreement = try terms.fingerprint(admission: try admission.loadAgreementFingerprint()) try ClusterDataPlaneAgreement.establish(collective: collective, credential: credential, loadAgreement: loadAgreement, tamper: nil, tensorParallelSeal: true, check: { try control.check() }) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentCapabilityMetadata.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentCapabilityMetadata.swift index 8752c45115..171e970b27 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentCapabilityMetadata.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentCapabilityMetadata.swift @@ -38,6 +38,22 @@ public enum MiMoResidentCapabilityMetadata { arithmeticPolicySHA256: sha256(try canonicalJSONData(arithmetic)), supportedPrefillSchedules: spec.supportedPrefillSchedules, supportedGenerationModes: imageCandidate ? spec.supportedGenerationModes.filter { [.pipeline,.pipelineCompactDecode,.pipelineMTP].contains($0) } : spec.supportedGenerationModes, - media:imageCandidate ? .init() : nil) + media:imageCandidate ? .init() : nil, + modeFeatures: imageCandidate ? nil : try servingFeatures(spec.supportedGenerationModes)) + } + + /// What each text mode keeps (`ClusterServingFeatures`), asked of the loads' own settings: the widest lanes a + /// load accepts (`MiMoBatchSettings`, only the plain pipeline batches), no prompt prefix where histories are + /// paged or handed off (as `MiMoResidentRuntime` builds its cache), rounds in the speculative modes, and + /// tensor parallel's own (`MiMoTensorParallelResidentRuntime.servingFeatures`). + static func servingFeatures(_ modes: [ClusterGenerationMode]) throws -> [ClusterGenerationMode: ClusterServingFeatures] { + let widest = [QwenBatchSettings.lanesEnvironmentName: String(QwenBatchWire.maximumLanes)] + return try Dictionary(uniqueKeysWithValues: modes.map { mode in + if mode == .tensorParallel { return (mode, MiMoTensorParallelResidentRuntime.servingFeatures) } + let batch = try MiMoBatchSettings.fromEnvironment(widest, mode: mode) + let prefixes = !(mode.isPhaseSplit || batch.usesPagedHistory) + return (mode, ClusterServingFeatures(promptPrefixReuse: prefixes, ssdPrefixTier: prefixes, + speculativeRounds: mode.usesSpeculativeHead, maximumLanes: batch.lanes, logprobs: false)) + }) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift index 05f0f5b66f..8e060ee71c 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift @@ -35,14 +35,21 @@ import MLXLLM /// positions), logprobs from the split top-k gather (greedy rows) or the /// product's own gather (sampled rows). No prompt-prefix reuse yet. public final class MiMoTensorParallelResidentRuntime { + /// What this owner keeps of the model's serving features, as the capability declares it + /// (`MiMoResidentCapabilityMetadata.servingFeatures`): one lane and no prompt prefix (both bound below), no + /// speculative rounds (no rank holds the trained heads), and committed-token logprobs. + static let servingFeatures = ClusterServingFeatures(promptPrefixReuse: false, ssdPrefixTier: false, + speculativeRounds: false, maximumLanes: 1, logprobs: true) + /// Everything about serving both ranks must have been told the same, /// beside the plan: one lane, paged KV, the chunk grid, the selection /// rules and the decode command buffers. public static func servingAgreementFields(chunkTokens: Int) -> [String] { - ["mimo-v26-tensor-parallel-serving-v1", "lanes=1", + ["mimo-v26-tensor-parallel-serving-v1", "lanes=\(servingFeatures.maximumLanes)", "kv=paged-\(MiMoTensorParallelRequestBudget.pageTokens)", "chunk=\(chunkTokens)", "selection=split-argmax-agreement-gathered-row-rank0-draw-split-topk-logprobs-v1", - "decode-buffers=\(MiMoTensorParallelDecoding.decodeCommandBuffers.operations)", "prefix=off"] + "decode-buffers=\(MiMoTensorParallelDecoding.decodeCommandBuffers.operations)", + servingFeatures.promptPrefixReuse ? "prefix=on" : "prefix=off"] } /// The load agreement's fields after the admission's fingerprint. diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift index 310ee52b60..c367caafe1 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift @@ -668,6 +668,24 @@ struct Gemma4TensorParallelRuntimeTests { #expect(Set(others + [fingerprint]).count == 5) } + /// What the capability declares of each mode is what the loads run: tensor parallel binds no prompt-prefix cache + /// into its agreement and declares none, both modes take the batch wire's lanes, and only tensor parallel captures + /// logprobs. The provider's setup check plans with these values (`PlacementSetupCheck.gemmaFeatures`). + @Test func capabilityDeclaresWhatEachModeKeeps() throws { + let features = Gemma4ResidentAdapterDefinition.servingFeatures + #expect(features == [ + .pipeline: .init(promptPrefixReuse: true, ssdPrefixTier: true, speculativeRounds: false, maximumLanes: 8, logprobs: false), + .tensorParallel: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 8, logprobs: true), + ]) + #expect(Set(features.keys) == Set(Gemma4ResidentAdapterDefinition.supportedGenerationModes)) + #expect(features[.tensorParallel]?.promptPrefixReuse == Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes + && Gemma4TensorParallelLoadAgreement().prefixCache == Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes + && features[.pipeline]?.maximumLanes == QwenBatchWire.maximumLanes) + let pipeline = try #require(features[.pipeline]), tensor = try #require(features[.tensorParallel]) + #expect(pipeline.dropped(by: tensor) == ["prompt-prefix reuse", "the SSD prefix tier"]) + #expect(tensor.dropped(by: pipeline) == ["committed-token logprobs"]) + } + // MARK: - Modes and planning /// Gemma advertises tensor parallel, its worker routes it to this runtime, diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelResidentTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelResidentTests.swift index 26106614e4..2aff9d4750 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelResidentTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelResidentTests.swift @@ -367,6 +367,21 @@ struct MiMoTensorParallelResidentTests { #expect(fields != Runtime.loadAgreementFields(plan: registered, chunkTokens: 256)) } + /// What the text row's capability declares of each mode is what its loads run: no mode keeps prompt prefixes + /// (paged or handed-off histories), only the plain pipeline takes lanes, the speculative pipeline decodes in + /// rounds, and tensor parallel serves one lane without rounds and adds logprobs. The provider's setup check plans + /// with these values (`PlacementSetupCheck.mimoFeatures`). + @Test func capabilityDeclaresWhatEachTextModeKeeps() throws { + let modes: [ClusterGenerationMode] = [.pipeline, .pipelineCompactDecode, .phaseSplit, .tensorParallel, .pipelineMTP] + let features = try MiMoResidentCapabilityMetadata.servingFeatures(modes) + func entry(lanes: Int, rounds: Bool = false, logprobs: Bool = false) -> ClusterServingFeatures { + .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: rounds, maximumLanes: lanes, logprobs: logprobs) + } + #expect(features == [.pipeline: entry(lanes: 8), .pipelineCompactDecode: entry(lanes: 1), .phaseSplit: entry(lanes: 1), + .tensorParallel: entry(lanes: 1, logprobs: true), .pipelineMTP: entry(lanes: 1, rounds: true)]) + #expect(features[.pipelineMTP]?.dropped(by: MiMoTensorParallelResidentRuntime.servingFeatures) == ["speculative (MTP) rounds"]) + } + /// The registered plan's per-rank reserve: paged history (full layers grow /// by 9 x 2 KV heads x (192 + 128) x 2 B = 11,520 B a token, a page at a /// time; sliding layers stop at the window plus a chunk, twice), every From 795193c15ef790413bf1b65986fd19021b2b60e1 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:58:40 -0800 Subject: [PATCH 0110/1441] provider: plan tensor parallel only where it keeps every feature it replaces Owner directive, 2026-11-01: a mode may be chosen only if it keeps every feature and caching behavior of the mode it would replace. - `ClusterModeParity`, in `ClusterPlacementFlow.decide` beside `ClusterModelFeaturePolicy.admissibleModes`. For a fastest-plan family (Gemma 4, MiMo V2.6) the mode tensor parallel would replace is the one the plan chooses without it, or every other mode where none places. A tensor-parallel mode that drops any feature the worker declares for it leaves the policy's modes before anything is ranked, so no margin, evidence hold, kept mode or better hardware group brings it back. A record without features holds it back too. - Where only tensor parallel places, the plan refuses and saves nothing ("Only tensor parallel fits these Macs, and it would drop ... No reduced-feature setup was saved."). `modesReason` carries it to the setup screen's refusal words. - The developer's forced mode still places tensor parallel, and the plan says exactly what it drops. - Planner: `ClusterPlacementPolicy.tensorParallelHeldForFeatures`, the verdict `dropsFeatures` (assessment and shard table), the model-list note "tensor parallel: drops a feature", and the line "Pipeline: tensor parallel would drop ... that the pipeline keeps; held back until it keeps them." - Qwen and GLM (tensor parallel first) are not gated: their plans and lines are unchanged. Applied to them, the rule would move Qwen3.5 9B from tensor parallel to its credited speculative pipeline; that is left to the owner. - Checks: Gemma held back with and without share probes, after an update and with nothing measured, re-admitted once its record keeps prefixes; MiMo held back with its rounds off (also on served records), admitted with them on; the forced mode's line; the only-reduced-mode refusal and its re-admission; a record without features; the codec; a GLM record declaring a gap plans exactly as without it; the planner's verdict, line, note and shard verdict. Co-Authored-By: Claude Opus 5.5 --- .../ClusterPlacementPlanner.swift | 7 + .../ClusterRequestMix.swift | 6 +- .../ClusterShardAssessment.swift | 4 + .../ClusterTensorParallel.swift | 3 + .../TensorParallelNoteChecks.swift | 14 + .../Console/ClusterSetupWizardPlanning.swift | 2 + .../Placement/ClusterModeParity.swift | 90 +++++++ .../Placement/ClusterPlacementFlow.swift | 25 ++ .../PlacementSetupCheck.swift | 252 +++++++++++++++--- .../Tests/ClusterPlacementChecks/run.sh | 1 + 10 files changed, 366 insertions(+), 38 deletions(-) create mode 100644 provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift index fa9add2fab..996e4cf27d 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift @@ -130,6 +130,12 @@ public struct ClusterPlacementPolicy: Sendable { public var tensorParallelAssumesUnmeasuredLink = false /// Why the mode is kept, in plain words: the plan's reason line when the hold decides the choice. public var keptModeReason: String? + /// Feature parity (owner, 2026-11-01: a mode may be chosen only if it keeps every feature and caching behavior + /// of the mode it would replace): why the caller left the tensor-parallel modes out of `modes`, in plain words + /// ("tensor parallel would drop prompt-prefix reuse that the pipeline keeps; held back until it keeps them"). + /// The plan says it (`ClusterTensorParallelAssessment.Verdict.dropsFeatures`). Nil, the default: no mode was + /// left out for its features. + public var tensorParallelHeldForFeatures: String? public init() {} } @@ -568,6 +574,7 @@ public enum ClusterPlacementPlanner { (policy.modes?.contains(mode) ?? true) && (policy.forcedMode?.admits(mode) ?? true) } guard !modes.isEmpty else { + if let held = policy.tensorParallelHeldForFeatures { return unavailable(.dropsFeatures, held) } let why = implemented.contains(where: { policy.modes?.contains($0) == false }) ? policy.modesReason.map { " (\($0))" } ?? "" : "" return unavailable(.notQualified, "the placement policy excludes the model's tensor-parallel modes\(why); using pipeline candidates") } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift index e9259f999b..e01f6e0cf0 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift @@ -124,7 +124,7 @@ extension ClusterPlacementExplanation { return "\(name): tensor parallel does not fit in these Macs' memory." case .notExecutedByRuntime: return "\(name): \(assessment.reason)." - case .notQualified: + case .notQualified, .dropsFeatures: return "\(name): \(assessment.reason)." } } @@ -151,6 +151,9 @@ extension ClusterPlacementExplanation { case pipelineKept = "tensor parallel: pipeline kept" /// The placement policy leaves tensor parallel out (`modesReason` says why, when it says). case excluded = "tensor parallel: excluded here" + /// It would drop a feature of the mode it would replace (feature parity, + /// `ClusterTensorParallelAssessment.Verdict.dropsFeatures`). + case dropsFeature = "tensor parallel: drops a feature" /// This runtime does not execute tensor parallel for this model or rank count. case notForThisModel = "no tensor parallel for this model" } @@ -186,6 +189,7 @@ extension ClusterPlacementExplanation { guard let best, best.prediction(regime).requestSeconds < chosen.prediction(regime).requestSeconds else { return .slower } return .aboutAsFast case .predictedFasterOnPriorOnly: return .notMeasuredYet + case .dropsFeatures: return .dropsFeature } } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterShardAssessment.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterShardAssessment.swift index 97f4740c88..b3e355a8db 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterShardAssessment.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterShardAssessment.swift @@ -44,6 +44,9 @@ public struct ClusterShardOption: Codable, Equatable, Sendable { case adapterHasNoTensorParallel /// A qualification check failed at this shape, so the records keep it out. case failedQualification + /// It would drop a feature of the mode it would replace + /// (`ClusterTensorParallelAssessment.Verdict.dropsFeatures`). + case dropsFeatures case doesNotFit /// Tensor parallel x pipeline needs three or more members. case needsMoreMembers @@ -191,6 +194,7 @@ extension ClusterPlacementPlanner { case .predictedFasterOnPriorOnly: verdict = .predictedFasterOnPriorOnly case .notExecutedByRuntime: verdict = .notExecutedByRuntime case .notQualified: verdict = .failedQualification + case .dropsFeatures: verdict = .dropsFeatures case .doesNotFit: verdict = .doesNotFit case .reductionNotMeasured: verdict = .reductionNotMeasured } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterTensorParallel.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterTensorParallel.swift index 993a264413..86fdd2625b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterTensorParallel.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterTensorParallel.swift @@ -392,6 +392,9 @@ public struct ClusterTensorParallelAssessment: Codable, Equatable, Sendable { case notExecutedByRuntime /// The policy excludes this mode or every executable shape on these chips. case notQualified + /// Left out before ranking because it would drop a feature of the mode + /// it would replace (`ClusterPlacementPolicy.tensorParallelHeldForFeatures`). + case dropsFeatures /// No placement in this mode fits. case doesNotFit /// The reduction over the link was not measured on the keyed data diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/TensorParallelNoteChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/TensorParallelNoteChecks.swift index 55631a1358..0af27debcb 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/TensorParallelNoteChecks.swift +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/TensorParallelNoteChecks.swift @@ -66,6 +66,20 @@ func checkTensorParallelNotes(_ inputs: RetainedQwenInputs, golden: URL, _ check == "Pipeline: the placement policy excludes the model's tensor-parallel modes (concurrent requests are quoted for the pipeline only); using pipeline candidates.") let doubled = ClusterPlacementExplanation.deploymentReason(excludedWhy) ?? "" checks.require("TP note: the policy's reason is said once", doubled.components(separatedBy: "concurrent requests").count == 2) + // Feature parity (`ClusterPlacementPolicy.tensorParallelHeldForFeatures`): left out because it would drop a feature + // of the mode it would replace, said in the caller's words in the reason line, the note and the shard table. + var held = policy + held.modes = [.pipeline] + held.tensorParallelHeldForFeatures = "tensor parallel would drop prompt-prefix reuse that the pipeline keeps; held back until it keeps them" + let dropped = try plan(linkCosts(reductionMicroseconds: 10), policy: held) + checks.require("TP note: tensor parallel held back for a feature it would drop is said as such (\(ClusterPlacementExplanation.deploymentReason(dropped) ?? "-"))", + dropped.chosen?.mode == .pipeline && dropped.tensorParallel?.verdict == .dropsFeatures && note(dropped) == .dropsFeature + && dropped.shards?.options.first { $0.kind == .tensorParallel }?.verdict == .dropsFeatures && dropped.modesReason == nil + && ClusterPlacementExplanation.deploymentReason(dropped) + == "Pipeline: tensor parallel would drop prompt-prefix reuse that the pipeline keeps; held back until it keeps them.") + held.modes = nil + checks.require("TP note: the parity reason alone leaves nothing out (the caller removes the modes)", + try plan(linkCosts(reductionMicroseconds: 10), policy: held) == chosen) // A model whose layout has no tensor-parallel plan: no row at all. let nemotron = try ClusterModelLayout.decode(Data(contentsOf: golden.appendingPathComponent("layouts/nvidia-nemotron-3.5-lightning-2026-09-30-r1.json"))) let profiles = try ["mac-a", "mac-b"].map { try ClusterDeviceProfile.decode(Data(contentsOf: golden.appendingPathComponent("profile-\($0).json"))) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift index 111da1b1df..b587bf5571 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift @@ -218,6 +218,8 @@ enum ClusterSetupPlanning { /// Why a model is not offered, plain action or fact first (the screen cuts long reasons). static func refusalWords(_ result: ClusterPlacementResult, localMemberID: String, names: [String: String] = [:]) -> String { func name(_ device: String) -> String { names[device] ?? device } + // Only tensor parallel fits, and it would drop a feature of the model's other modes (`ClusterModeParity`). + if result.tensorParallel?.verdict == .dropsFeatures, let why = result.modesReason { return why } if let excluded = result.unqualifiedPossible, excluded > 0 { let alone = result.alone.first(where: { $0.fit.possible }) .map { " \(name($0.device)) can serve it alone in single-Mac Darkbloom." } ?? "" diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift new file mode 100644 index 0000000000..bc91fc897e --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift @@ -0,0 +1,90 @@ +import DarkbloomClusterPlacement +import DarkbloomClusterProtocol + +/// Feature parity (owner, 2026-11-01: "no compromise in security stack, caching behaviors or anything else"): a mode +/// may be chosen only if it keeps every feature and caching behavior of the mode it would replace. Each mode's +/// features are the worker's own (`ClusterRuntimeCapability.modeFeatures`), never a table here. The mode tensor +/// parallel would replace is the one the plan chooses without it; where no other mode places, every other mode the +/// plan could place. A tensor-parallel mode that drops any feature of it is left out of the policy's modes before the +/// planner ranks anything, so no ordering (the margin, the evidence hold, a kept mode, a better hardware group) brings +/// it back. What it adds (its logprobs, wider lanes) never counts against it. +/// +/// Applied to the families whose plan is chosen only where faster (`ClusterTensorParallelChoice.fastest`: Gemma 4 and +/// MiMo V2.6). The tensor-parallel-first families (Qwen, GLM) keep their plans: their records declare no features, +/// and what the rule would change for them is the owner's decision (docs/architecture/inference.md). +enum ClusterModeParity { + struct Hold: Equatable { + /// The tensor-parallel modes left out. + let modes: [ClusterGenerationMode] + /// What they would replace: the mode the plan places without them, or every other mode when none places. + let replaced: [ClusterGenerationMode] + /// The plan places another mode without them. + let otherModePlaces: Bool + /// What they would drop of it, in plain words; nil when the worker declares no features to compare. + let dropped: [String]? + + /// "prompt-prefix reuse and the SSD prefix tier that the pipeline keeps"; nil when nothing is declared. + var drops: String? { + dropped.map { list($0) + " that " + + (replaced.count == 1 ? ClusterModeParity.words(replaced[0]) + " keeps" : "the model's other modes keep") } + } + + /// The plan's reason (`ClusterPlacementPolicy.tensorParallelHeldForFeatures`). + var reason: String { + drops.map { "tensor parallel would drop \($0); held back until it keeps them" } + ?? "this worker build declares no serving features for its modes, so tensor parallel is held back until it does" + } + + /// Where tensor parallel is the only mode that places. + var refusal: String { + "Only tensor parallel fits these Macs, and " + + (drops.map { "it would drop " + $0 } ?? "this worker build declares no serving features for its modes") + + ". No reduced-feature setup was saved." + } + } + + /// The hold for `policy` as the caller would plan it, or nil when every tensor-parallel mode keeps every feature + /// of the mode it would replace, or the rule does not apply. `plan` plans a policy as the caller would. + static func hold(capability: ClusterRuntimeCapability, layout: ClusterModelLayout, policy: ClusterPlacementPolicy, + plan: (ClusterPlacementPolicy) throws -> ClusterPlacementResult) -> Hold? { + guard layout.tensorParallel?.family.choosesFastest == true else { return nil } + let listed = layout.generationModes.filter { (policy.modes?.contains($0) ?? true) && (policy.handOffModes || !$0.isHandOff) } + let tensor = listed.filter(\.usesTensorParallelDecode), others = listed.filter { !$0.usesTensorParallelDecode } + guard !tensor.isEmpty, !others.isEmpty else { return nil } + var without = policy + without.modes = others; without.forcedMode = nil + let placed = (try? plan(without))?.chosen?.mode + let replaced = placed.map { [$0] } ?? others + let kept = replaced.compactMap { capability.modeFeatures?[$0] }, candidates = tensor.compactMap { capability.modeFeatures?[$0] } + // A mode the record does not name has no declared features: nothing shows it keeps them. + guard kept.count == replaced.count, candidates.count == tensor.count else { + return Hold(modes: tensor, replaced: replaced, otherModePlaces: placed != nil, dropped: nil) + } + var dropped: [String] = [] + for candidate in candidates { + for reference in kept { dropped += reference.dropped(by: candidate).filter { !dropped.contains($0) } } + } + return dropped.isEmpty ? nil : Hold(modes: tensor, replaced: replaced, otherModePlaces: placed != nil, dropped: dropped) + } + + /// The rule, as a plan of a family it applies to says it. + static let ruleLine = "A mode is chosen only where it keeps every feature and caching behavior of the mode it would " + + "replace, as this worker build declares them: prompt-prefix and SSD reuse, speculative rounds, batch lanes, " + + "media, penalties and logit bias, and stop handling." + /// The mode a plan would place instead, in words. + static func words(_ mode: ClusterGenerationMode) -> String { + switch mode { + case .pipeline: "the pipeline" + case .pipelineCompactDecode: "the compact-decode pipeline" + case .pipelineMTP: "the speculative pipeline" + case .phaseSplit: "the phase split" + case .phaseSplitMTP: "the speculative phase split" + case .tensorParallel: "tensor parallel" + case .pipelinePrefillTensorDecode: "the pipeline-prefill, tensor-decode hybrid" + } + } + + static func list(_ items: [String]) -> String { + items.count <= 2 ? items.joined(separator: " and ") : items.dropLast().joined(separator: ", ") + " and " + items.last! + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift index 52d02c1458..bed07f6c09 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift @@ -275,6 +275,25 @@ public enum ClusterPlacementFlow { policy.modesReason = policy.modesReason ?? "a capacity change keeps the running tensor-parallel shares" policy.requiredTensorShares = incumbentTensorShares } + // Feature parity (`ClusterModeParity`): tensor parallel is planned only where it keeps every feature of the + // mode it would replace, as the worker's capability record declares them, and is left out before anything is + // ranked. A developer's forced mode is placed anyway, and the plan says what it drops. + let parity = ClusterModeParity.hold(capability: capability, layout: layout, policy: policy) { + try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: $0, link: link) + } + var parityRefusal: String? + if let parity, forced == nil { + // Where tensor parallel is the only mode that places, the plan refuses rather than save a reduced setup + // (owner, 2026-11-01), and says so where a refusal is read (`modesReason`). + if !parity.otherModePlaces, + let only = (try? ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: policy, link: link))?.chosen, + parity.modes.contains(only.mode) { + parityRefusal = parity.refusal + policy.modesReason = policy.modesReason ?? parity.refusal + } + policy.modes = (policy.modes ?? layout.generationModes).filter { !parity.modes.contains($0) } + policy.tensorParallelHeldForFeatures = parity.reason + } let result = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: policy, link: link) var lines = (forced.map(ClusterForcedModeSetting.lines) ?? []) + (benchCap.map(ClusterPlannerBenchCap.lines(capBytes:)) ?? []) + (benchChip.map(ClusterBenchChip.lines(chipName:)) ?? []) @@ -291,9 +310,15 @@ public enum ClusterPlacementFlow { lines.append(" This model runs tensor parallel only where it is predicted faster than a pipeline on its own step " + "as measured on both Macs, never on the device index alone; until a load measures the link, tensor parallel " + "is priced on a slow assumed link.") + lines.append(" " + ClusterModeParity.ruleLine) if let note = ClusterModelFeaturePolicy.modeFeatureNote(capability) { lines.append(" " + note) } } } + if let parity, forced != nil, let chosen = result.chosen, parity.modes.contains(chosen.mode) { + lines += ["Feature parity", " Developer setting: tensor parallel is placed because it is forced; it drops " + + (parity.drops ?? "features this worker build does not declare") + "."] + } + if let parityRefusal { lines += ["Feature parity", " " + parityRefusal] } if handOff { lines += ClusterHandOffModes.lines(enabled: true) } else if let note = lines.firstIndex(where: { $0.hasPrefix(" Phase split, phase split + MTP") }) { diff --git a/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift b/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift index 63283d2ecb..52928e3963 100644 --- a/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift +++ b/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift @@ -547,21 +547,27 @@ import Foundation constructionConfigurationSHA256: hash("4"))]) } let adapter = ClusterRuntimeAdapter.glm5NextLayerStage - let capability = try ClusterRuntimeCapability(runtimeBinarySHA256: build, adapterID: adapter.rawValue, adapterVersion: adapter.version, - runtimeModelID: layout.runtimeModelID, artifactSHA256: layout.artifactSHA256, configurationSHA256: layout.configurationSHA256, - manifestSHA256: hash("d"), profile: .init(id: ClusterGLMImageCandidate.textProfileID, vocabularySize: 154_880, - maximumPromptTokens: 1_048_575, maximumOutputTokens: 65_536, maximumChunkTokens: 2048, maximumContextTokens: 1_048_576), - profileFingerprint: hash("e"), partitions: partitions, arithmeticPolicyID: adapter.arithmeticPolicyID, - arithmeticPolicySHA256: hash("5"), supportedPrefillSchedules: [.serial], supportedGenerationModes: [.pipeline, .tensorParallel]) - let description = ClusterPairDescription(schema: ClusterPairDescription.schemaName, clusterID: "fixture", - publicModelID: "EigenLabs/GLM-5.3-Flash-MLX-NVFP4-mtp", - capabilitySHA256: ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(capability)), - chunkTokens: 2048, requestTimeoutSeconds: 900, coordinatorPort: 5577, members: ["ultra-a", "ultra-b"].enumerated().map { index, id in - .init(id: id, host: "192.0.2.\(index + 1)", port: 22, user: "fixture", ownerExecutable: "/fixture/darkbloom", - workerExecutable: "/fixture/darkbloom-cluster-worker", modelDirectory: "/fixture/model", runtimeBinarySHA256: build, - jacclDevice: "rdma_en\(index + 1)", linkAddress: "192.0.2.\(index + 1)", trust: nil, linkSecretFile: "/fixture/\(id).secret") - }, tokenizerFiles: [.init(path: "tokenizer.json", sha256: hash("6"), purpose: .tokenizer)], - linkControl: .init(port: 5578, linkEpoch: "00000000-0000-4000-8000-000000000001", edgeID: "00000000-0000-4000-8000-000000000002")) + func record(_ features: [ClusterGenerationMode: ClusterServingFeatures]?) throws -> ClusterRuntimeCapability { + try ClusterRuntimeCapability(runtimeBinarySHA256: build, adapterID: adapter.rawValue, adapterVersion: adapter.version, + runtimeModelID: layout.runtimeModelID, artifactSHA256: layout.artifactSHA256, configurationSHA256: layout.configurationSHA256, + manifestSHA256: hash("d"), profile: .init(id: ClusterGLMImageCandidate.textProfileID, vocabularySize: 154_880, + maximumPromptTokens: 1_048_575, maximumOutputTokens: 65_536, maximumChunkTokens: 2048, maximumContextTokens: 1_048_576), + profileFingerprint: hash("e"), partitions: partitions, arithmeticPolicyID: adapter.arithmeticPolicyID, + arithmeticPolicySHA256: hash("5"), supportedPrefillSchedules: [.serial], supportedGenerationModes: [.pipeline, .tensorParallel], + modeFeatures: features) + } + func describe(_ capability: ClusterRuntimeCapability) throws -> ClusterPairDescription { + ClusterPairDescription(schema: ClusterPairDescription.schemaName, clusterID: "fixture", + publicModelID: "EigenLabs/GLM-5.3-Flash-MLX-NVFP4-mtp", + capabilitySHA256: ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(capability)), + chunkTokens: 2048, requestTimeoutSeconds: 900, coordinatorPort: 5577, members: ["ultra-a", "ultra-b"].enumerated().map { index, id in + .init(id: id, host: "192.0.2.\(index + 1)", port: 22, user: "fixture", ownerExecutable: "/fixture/darkbloom", + workerExecutable: "/fixture/darkbloom-cluster-worker", modelDirectory: "/fixture/model", runtimeBinarySHA256: build, + jacclDevice: "rdma_en\(index + 1)", linkAddress: "192.0.2.\(index + 1)", trust: nil, linkSecretFile: "/fixture/\(id).secret") + }, tokenizerFiles: [.init(path: "tokenizer.json", sha256: hash("6"), purpose: .tokenizer)], + linkControl: .init(port: 5578, linkEpoch: "00000000-0000-4000-8000-000000000001", edgeID: "00000000-0000-4000-8000-000000000002")) + } + let capability = try record(nil), description = try describe(capability) let measured = ClusterLinkCosts(probe: ClusterWorkerLinkProbe(transport: "jaccl", keyed: true, pointToPointSmallBytes: 64, pointToPointSmallMicroseconds: 167, pointToPointLargeBytes: 4 << 20, pointToPointLargeMicroseconds: 2_622, allSumSmallBytes: 20_480, allSumSmallMicroseconds: 38, allSumLargeBytes: 10_485_760, allSumLargeMicroseconds: 1_296), @@ -578,6 +584,18 @@ import Foundation && chosen?.ranks.allSatisfy({ $0.fit == .now }) == true && saved.count == 2 && saved.allSatisfy { $0.selectedGenerationMode == .tensorParallel && $0.tensorShares == nil && $0.batchLanes == nil }) } + // Feature parity is the fastest-plan families' rule (`ClusterModeParity`): a GLM record declaring a tensor-parallel + // gap (a hypothetical one: no prompt prefix) plans exactly what production does, line for line. + let gapped = try record([ + .pipeline: .init(promptPrefixReuse: true, ssdPrefixTier: true, speculativeRounds: false, maximumLanes: 1, logprobs: false), + .tensorParallel: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: true, maximumLanes: 8, + requestMedia: [.images, .video], logprobs: true)]) + let plain = try ClusterPlacementFlow.decide(description: description, capability: capability, localMemberID: "ultra-a", + localProfile: m5, peerProfile: m5, layout: layout, link: measured, environment: [:], benchDebugBuild: false) + let declared = try ClusterPlacementFlow.decide(description: try describe(gapped), capability: gapped, localMemberID: "ultra-a", + localProfile: m5, peerProfile: m5, layout: layout, link: measured, environment: [:], benchDebugBuild: false) + require("glm pair: a declared tensor-parallel gap changes nothing for a tensor-parallel-first family (same choice, same plan, same lines)", + declared.result.chosen?.mode == .tensorParallel && declared.result == plain.result && declared.lines == plain.lines) } /// The universal rule of qualification records (`ClusterPairQualificationRecords`, chip-agnostic since @@ -812,9 +830,11 @@ import Foundation require("owner pilot: the same model on 2x M4 Max 128 GB is planned", fits.result.chosen != nil && fits.setup != nil) } - /// A worker capability for `layout` (one partition per admitted cut) in `modes`, and the pair description that pins it. + /// A worker capability for `layout` (one partition per admitted cut) in `modes`, each keeping `features` (those + /// of its modes; nil declares none), and the pair description that pins it. static func capability(layout: ClusterModelLayout, adapterID: String, profileID: String, vocabularySize: Int, arithmeticPolicyID: String, modes: [ClusterGenerationMode], publicModelID: String, + features: [ClusterGenerationMode: ClusterServingFeatures]? = nil, description base: [String: Any]) throws -> (ClusterRuntimeCapability, ClusterPairDescription) { let cuts = layout.admittedCuts, layers = layout.layerCount let value = try ClusterRuntimeCapability(runtimeBinarySHA256: hash("a"), adapterID: adapterID, adapterVersion: 1, @@ -830,13 +850,45 @@ import Foundation .init(rank: 1, sourceLayerStart: cut, sourceLayerEnd: layers, stagePlanSHA256: String(repeating: "3", count: 62) + String(format: "%02d", cut), constructionConfigurationSHA256: hash("4"))]) }, arithmeticPolicyID: arithmeticPolicyID, arithmeticPolicySHA256: hash("5"), - supportedPrefillSchedules: [.serial, .oneChunkLookahead], supportedGenerationModes: modes) + supportedPrefillSchedules: [.serial, .oneChunkLookahead], supportedGenerationModes: modes, + modeFeatures: features?.filter { modes.contains($0.key) }) var description = base description["capabilitySHA256"] = ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(value)) description["publicModelID"] = publicModelID return (value, try ClusterPairDescription.decode(JSONSerialization.data(withJSONObject: description))) } + /// Gemma 4's modes as its worker declares them (`Gemma4ResidentAdapterDefinition.servingFeatures`, pinned by + /// `Gemma4TensorParallelRuntimeTests`): tensor parallel keeps no prompt prefix yet, and adds logprobs. + static let gemmaFeatures: [ClusterGenerationMode: ClusterServingFeatures] = [ + .pipeline: .init(promptPrefixReuse: true, ssdPrefixTier: true, speculativeRounds: false, maximumLanes: 8, logprobs: false), + .tensorParallel: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 8, logprobs: true), + ] + /// MiMo V2.6's text modes as its worker declares them (`MiMoResidentCapabilityMetadata.servingFeatures`, pinned + /// by `MiMoTensorParallelResidentTests`): no mode keeps prompt prefixes, only the plain pipeline batches lanes, the + /// speculative pipeline decodes in rounds, and tensor parallel serves one lane without rounds and adds logprobs. + static let mimoFeatures: [ClusterGenerationMode: ClusterServingFeatures] = [ + .pipeline: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 8, logprobs: false), + .pipelineCompactDecode: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 1, logprobs: false), + .phaseSplit: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 1, logprobs: false), + .tensorParallel: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 1, logprobs: true), + .pipelineMTP: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: true, maximumLanes: 1, logprobs: false), + ] + /// `features` with tensor parallel's entry changed, as a later worker build might declare it. + static func with(_ features: [ClusterGenerationMode: ClusterServingFeatures], tensorParallelPrefixes prefixes: Bool? = nil, + tensorParallelRounds rounds: Bool? = nil) -> [ClusterGenerationMode: ClusterServingFeatures] { + var value = features + guard let tp = features[.tensorParallel] else { return value } + value[.tensorParallel] = .init(promptPrefixReuse: prefixes ?? tp.promptPrefixReuse, ssdPrefixTier: prefixes ?? tp.ssdPrefixTier, + speculativeRounds: rounds ?? tp.speculativeRounds, maximumLanes: tp.maximumLanes, requestMedia: tp.requestMedia, + penaltiesAndLogitBias: tp.penaltiesAndLogitBias, stopHandling: tp.stopHandling, logprobs: tp.logprobs) + return value + } + /// The plan's line where tensor parallel would drop a feature of the mode it would replace. + static func heldLine(_ drops: String) -> String { + " Pipeline: tensor parallel would drop \(drops); held back until it keeps them." + } + /// The line the guided step prints for a model chosen only where faster (`ClusterTensorParallelChoice.fastest`). static let fastestLine = " This model runs tensor parallel only where it is predicted faster than a pipeline on its own step " + "as measured on both Macs, never on the device index alone; until a load measures the link, tensor parallel " @@ -881,10 +933,11 @@ import Foundation object["speculativeHead"] = ["storedBytes": 1_975_640_448, "loadedBytes": 1_975_640_448, "largestTensorBytes": 134_217_728, "tensorCount": 42, "requestWorkBytes": 0] let layout = try ClusterModelLayout.decode(JSONSerialization.data(withJSONObject: object)) - func capability(_ modes: [ClusterGenerationMode]) throws -> (ClusterRuntimeCapability, ClusterPairDescription) { + func capability(_ modes: [ClusterGenerationMode], features: [ClusterGenerationMode: ClusterServingFeatures] = mimoFeatures) throws + -> (ClusterRuntimeCapability, ClusterPairDescription) { try Self.capability(layout: layout, adapterID: "mimo-v26-layer-stage", profileID: "registered_mimo_v26_flash_mopd_greedy_generation_v1", vocabularySize: 152_576, arithmeticPolicyID: "mimo_v26_text_ordinary_cache_bf16_defaults_v1", modes: modes, - publicModelID: "fixture/mimo", description: base) + publicModelID: "fixture/mimo", features: features, description: base) } let local = try device("mac-one", physicalGiB: 128, freeGiB: 116, prefill: 400, decode: 40).profile let peer = try device("mac-two", physicalGiB: 128, freeGiB: 116, prefill: 400, decode: 40).profile @@ -910,7 +963,11 @@ import Foundation // The evidence rule through the guided step (`ClusterTensorParallelChoice.fastest`): two 256 GB Macs with the M5 // Ultra's index, MiMo alone at 57 tok/s and the pair's measured link. On the index alone tensor parallel is // predicted faster than the credited rounds for 128 + 128, so the speculative pipeline is kept. MiMo's runtime - // takes no share probe: requests this build served in tensor parallel are its only evidence. + // takes no share probe: requests this build served in tensor parallel are its only evidence. Feature parity + // comes first: tensor parallel as this build runs it has no speculative rounds, which the speculative pipeline + // it would replace keeps, so it is held back whatever the evidence; the evidence rule is checked on a record + // whose tensor parallel decodes in rounds, as a later build's may. + let (roundsOn, roundsDescription) = try capability(rowModes, features: with(mimoFeatures, tensorParallelRounds: true)) let ultras = try indexedUltras(), alone = try aloneSpeed(layout, prefill: 1_000, decode: 57) func served(_ decode: Double, build: String) -> [ClusterServedSpeedRecords.Entry] { let setup = ClusterServedSpeedRecords.Setup(modelID: bothDescription.publicModelID, mode: ClusterGenerationMode.tensorParallel.rawValue, @@ -919,22 +976,35 @@ import Foundation return (0..<3).map { .init(setup: setup, sample: .init(route: .pair, member: nil, promptTokens: 128, outputTokens: 128, firstTokenSeconds: 0.08, decodeTokensPerSecond: decode, finishedAt: Double($0))) } } - func decide(_ records: [ClusterServedSpeedRecords.Entry]) throws -> (lines: [String], result: ClusterPlacementResult, setup: ClusterPlacementSetup?) { - try ClusterPlacementFlow.decide(description: bothDescription, capability: both, localMemberID: "mac-one", - localProfile: ultras.local, peerProfile: ultras.peer, layout: layout, measurements: [alone], + func decide(_ records: [ClusterServedSpeedRecords.Entry], asBuilt: Bool = false) + throws -> (lines: [String], result: ClusterPlacementResult, setup: ClusterPlacementSetup?) { + try ClusterPlacementFlow.decide(description: asBuilt ? bothDescription : roundsDescription, capability: asBuilt ? both : roundsOn, + localMemberID: "mac-one", localProfile: ultras.local, peerProfile: ultras.peer, layout: layout, measurements: [alone], promptTokens: 128, outputTokens: 128, served: records, link: ultras.link, environment: [:], benchDebugBuild: false) } func line(_ decided: (lines: [String], result: ClusterPlacementResult, setup: ClusterPlacementSetup?), _ prefix: String) -> String { decided.lines.first { $0.hasPrefix(prefix) } ?? "-" } + let roundsLine = heldLine("speculative (MTP) rounds that the speculative pipeline keeps") + for (name, records) in [("nothing served in tensor parallel", [ClusterServedSpeedRecords.Entry]()), + ("three requests this build served in tensor parallel at 95 tok/s", served(95, build: hash("a")))] { + let held = try decide(records, asBuilt: true) + require("MiMo parity: as this build declares it, tensor parallel has no speculative rounds, so with \(name) the speculative pipeline is kept and the line says what tensor parallel would drop (\(line(held, " Pipeline:")))", + held.result.chosen?.mode == .pipelineMTP && held.result.tensorParallel?.verdict == .dropsFeatures + && held.lines.contains(roundsLine) && held.setup != nil + && ClusterPlacementExplanation.tensorParallelNote(held.result) == .dropsFeature + && held.result.shards?.options.first { $0.kind == .tensorParallel }?.verdict == .dropsFeatures + && !held.result.alternatives.contains { $0.mode.usesTensorParallelDecode }) + } let priorOnly = try decide([]) require("MiMo evidence rule: 2x 256 GB on the measured link, nothing served in tensor parallel: the speculative pipeline is kept, and the line says tensor parallel is predicted faster only from the device index (\(line(priorOnly, " Pipeline:")))", priorOnly.result.chosen?.mode == .pipelineMTP && priorOnly.result.tensorParallel?.verdict == .predictedFasterOnPriorOnly && line(priorOnly, " Pipeline:").contains(", but from the device index, not its own measured step; it can be chosen once its step is measured on both Macs") && priorOnly.lines.contains(fastestLine) && priorOnly.setup != nil) let fast = try decide(served(95, build: hash("a"))) - require("MiMo evidence rule: three requests this build served in tensor parallel at 95 tok/s: tensor parallel, chosen on its own measured step, and the line says so (\(line(fast, " Tensor parallel:")))", + require("MiMo parity and evidence: with its rounds on, tensor parallel keeps every feature of the speculative pipeline; three requests this build served in tensor parallel at 95 tok/s: tensor parallel, chosen on its own measured step, and the line says so (\(line(fast, " Tensor parallel:")))", fast.result.chosen?.mode == .tensorParallel && fast.result.tensorParallel?.evidence == .measured + && !fast.lines.contains { $0.contains("would drop") } && line(fast, " Tensor parallel:").hasSuffix(", on its own step as measured on both Macs.") && fast.setup != nil) let slow = try decide(served(60, build: hash("a"))) require("MiMo evidence rule: served in tensor parallel at 60 tok/s: the speculative pipeline, tensor parallel predicted slower on the served split", @@ -946,18 +1016,33 @@ import Foundation && otherBuild.lines.contains { $0.hasPrefix(" 3 record(s) from other worker builds ignored") }) } - /// Gemma 4 QAT 4-bit (its golden layout, with the family's tensor-parallel facts and `fastest_v1`) through the - /// guided step: on two 256 GB Macs with the M5 Ultra's index, Gemma alone at 90 tok/s and the pair's measured link, - /// a 128 + 128 request keeps the pipeline on the device index alone; the share probes a Gemma tensor-parallel load - /// records (`Gemma4TensorParallelShareProbe`, kept by `ClusterShareProbeHistory`) then decide. - static func gemmaEvidenceLines(description base: [String: Any]) throws { + /// The Gemma 4 QAT 4-bit golden layout (with the family's tensor-parallel facts and `fastest_v1`), `adjust`ed, and + /// a worker capability for it whose modes keep `features`. + static func gemma(features: [ClusterGenerationMode: ClusterServingFeatures]?, description base: [String: Any], + adjust: (inout [String: Any]) -> Void = { _ in }) throws + -> (layout: ClusterModelLayout, capability: ClusterRuntimeCapability, description: ClusterPairDescription) { let golden = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent( "../../../libs/darkbloom-cluster/Tests/PlacementChecks/Golden/layouts/gemma-4-26b-qat-4bit.json") - let layout = try ClusterModelLayout.decode(Data(contentsOf: golden)) + var object = try JSONSerialization.jsonObject(with: Data(contentsOf: golden)) as? [String: Any] ?? [:] + adjust(&object) + let layout = try ClusterModelLayout.decode(JSONSerialization.data(withJSONObject: object)) let (capability, description) = try capability(layout: layout, adapterID: "gemma4-layer-stage", profileID: "registered_gemma4_26b_qat_4bit_greedy_generation_v1", vocabularySize: 262_144, arithmeticPolicyID: "gemma4_cbv2_query128_bf16_tf32_weighted_r1_v1", modes: [.pipeline, .tensorParallel], - publicModelID: "fixture/gemma", description: base) + publicModelID: "fixture/gemma", features: features, description: base) + return (layout, capability, description) + } + + /// Gemma 4 QAT 4-bit through the guided step, on two 256 GB Macs with the M5 Ultra's index, Gemma alone at 90 tok/s + /// and the pair's measured link, for a 128 + 128 request. Feature parity first: as this build declares it, Gemma's + /// tensor parallel keeps no prompt prefix, resident or on the SSD tier, which the pipeline it would replace keeps, + /// so it is held back whatever the evidence, a kept mode or the device index say; a developer's forced mode places + /// it and says what it drops. Once its record declares prefix reuse (as a later build's may), the evidence rule + /// decides: the device index alone keeps the pipeline, and the share probes a Gemma tensor-parallel load records + /// (`Gemma4TensorParallelShareProbe`, kept by `ClusterShareProbeHistory`) decide. + static func gemmaEvidenceLines(description base: [String: Any]) throws { + let asBuilt = try gemma(features: gemmaFeatures, description: base) + let (layout, capability, description) = try gemma(features: with(gemmaFeatures, tensorParallelPrefixes: true), description: base) let ultras = try indexedUltras(), alone = try aloneSpeed(layout, prefill: 7_000, decode: 90) func probes(halfStepMicroseconds: Int) -> [String: [ClusterShareRate]] { ClusterShareProbeHistory().recording(["mac-one", "mac-two"].map { @@ -965,25 +1050,117 @@ import Foundation }, artifactSHA256: layout.artifactSHA256, now: 1_000).shareRates(artifactSHA256: layout.artifactSHA256, members: ["mac-one", "mac-two"], now: 1_060) } - func decide(_ shareProbes: [String: [ClusterShareRate]]) throws -> (lines: [String], result: ClusterPlacementResult, setup: ClusterPlacementSetup?) { - try ClusterPlacementFlow.decide(description: description, capability: capability, localMemberID: "mac-one", - localProfile: ultras.local, peerProfile: ultras.peer, layout: layout, measurements: [alone], - promptTokens: 128, outputTokens: 128, link: ultras.link, shareProbes: shareProbes, environment: [:], benchDebugBuild: false) - } + func decide(_ shareProbes: [String: [ClusterShareRate]], asBuilt built: Bool = false, incumbentMode: ClusterGenerationMode? = nil, + environment: [String: String] = [:]) throws -> (lines: [String], result: ClusterPlacementResult, setup: ClusterPlacementSetup?) { + try ClusterPlacementFlow.decide(description: built ? asBuilt.description : description, capability: built ? asBuilt.capability : capability, + localMemberID: "mac-one", localProfile: ultras.local, peerProfile: ultras.peer, layout: layout, measurements: [alone], + promptTokens: 128, outputTokens: 128, link: ultras.link, shareProbes: shareProbes, incumbentMode: incumbentMode, + environment: environment, benchDebugBuild: !environment.isEmpty) + } + let prefixLine = heldLine("prompt-prefix reuse and the SSD prefix tier that the pipeline keeps") + for (name, shareProbes) in [("no share probe", [String: [ClusterShareRate]]()), + ("both Macs' share probes at 7.0 ms a half step", probes(halfStepMicroseconds: 7_000))] { + let held = try decide(shareProbes, asBuilt: true) + require("Gemma parity: as this build declares it, tensor parallel keeps no prompt prefix, so with \(name) the pipeline is kept and the line says what tensor parallel would drop (\(held.lines.first { $0.hasPrefix(" Pipeline:") } ?? "-"))", + held.result.chosen?.mode == .pipeline && held.result.tensorParallel?.verdict == .dropsFeatures + && held.lines.contains(prefixLine) && held.lines.contains(" " + ClusterModeParity.ruleLine) && held.setup != nil + && ClusterPlacementExplanation.tensorParallelNote(held.result) == .dropsFeature + && !held.result.alternatives.contains { $0.mode == .tensorParallel }) + } + let kept = try decide(probes(halfStepMicroseconds: 7_000), asBuilt: true, incumbentMode: .tensorParallel) + require("Gemma parity: a pair that served tensor parallel before an update is planned as the pipeline (parity before the kept mode)", + kept.result.chosen?.mode == .pipeline && kept.result.tensorParallel?.verdict == .dropsFeatures && kept.lines.contains(prefixLine)) + let forced = try decide([:], asBuilt: true, environment: [ClusterForcedModeSetting.environmentName: "tensor_parallel_v1"]) + require("Gemma parity: the developer's forced mode places tensor parallel and the plan says exactly what it drops", + forced.result.chosen?.mode == .tensorParallel && forced.setup != nil + && forced.lines.contains(" Developer setting: tensor parallel is placed because it is forced; it drops " + + "prompt-prefix reuse and the SSD prefix tier that the pipeline keeps.")) let priorOnly = try decide([:]) require("Gemma evidence rule: 2x 256 GB on the measured link, no share probe: the pipeline is kept and the line says why", priorOnly.result.chosen?.mode == .pipeline && priorOnly.result.tensorParallel?.verdict == .predictedFasterOnPriorOnly && priorOnly.lines.contains { $0.hasPrefix(" Pipeline: tensor parallel is predicted") && $0.contains("from the device index") } && priorOnly.lines.contains(fastestLine)) let measured = try decide(probes(halfStepMicroseconds: 7_000)), planned = try decide(probes(halfStepMicroseconds: 10_300)) - require("Gemma evidence rule: both Macs' share probes at 7.0 ms a half step: tensor parallel, chosen on its measured step", + require("Gemma parity and evidence: once its record declares prefix reuse resident and on the SSD tier, tensor parallel is admissible; both Macs' share probes at 7.0 ms a half step: tensor parallel, chosen on its measured step", measured.result.chosen?.mode == .tensorParallel && measured.result.tensorParallel?.evidence == .measured + && !measured.lines.contains { $0.contains("would drop") } && measured.lines.contains { $0.hasPrefix(" Tensor parallel: predicted") && $0.hasSuffix(", on its own step as measured on both Macs.") }) require("Gemma evidence rule: both Macs' share probes at 10.3 ms a half step: the pipeline, tensor parallel predicted slower on its measured step", planned.result.chosen?.mode == .pipeline && planned.result.tensorParallel?.verdict == .predictedSlower && planned.result.tensorParallel?.evidence == .measured) } + /// Feature parity's record and refusals: per-mode features cross the capability codec canonically and a record + /// without them keeps its bytes; a fastest-plan family whose record declares none holds tensor parallel back; + /// where only tensor parallel fits and it drops a feature, the plan refuses and saves nothing (owner, 2026-11-01), + /// and the same Macs place it once its record keeps that feature. + static func featureParity(description base: [String: Any]) throws { + let built = try gemma(features: gemmaFeatures, description: base) + let data = try ClusterRuntimeCapabilityCodec.encode(built.capability) + let decoded = try ClusterRuntimeCapabilityCodec.decode(data) + require("parity record: a capability's per-mode serving features cross the codec canonically", decoded == built.capability + && decoded.modeFeatures?[.tensorParallel]?.promptPrefixReuse == false && decoded.modeFeatures?[.pipeline]?.ssdPrefixTier == true + && String(decoding: data, as: UTF8.self).contains("\"modeFeatures\":{\"pipeline_v1\":{")) + let undeclared = try gemma(features: nil, description: base) + require("parity record: a capability that declares no features writes no field, its bytes as before", + !String(decoding: try ClusterRuntimeCapabilityCodec.encode(undeclared.capability), as: UTF8.self).contains("modeFeatures")) + func record(_ features: [ClusterGenerationMode: ClusterServingFeatures]) throws -> ClusterRuntimeCapability { + let c = built.capability + return try ClusterRuntimeCapability(runtimeBinarySHA256: c.runtimeBinarySHA256, adapterID: c.adapterID, + adapterVersion: c.adapterVersion, runtimeModelID: c.runtimeModelID, artifactSHA256: c.artifactSHA256, + configurationSHA256: c.configurationSHA256, manifestSHA256: c.manifestSHA256, profile: c.profile, + profileFingerprint: c.profileFingerprint, partitions: c.partitions, arithmeticPolicyID: c.arithmeticPolicyID, + arithmeticPolicySHA256: c.arithmeticPolicySHA256, supportedPrefillSchedules: c.supportedPrefillSchedules, + supportedGenerationModes: c.supportedGenerationModes, modeFeatures: features) + } + refuses("parity record: features that leave a supported mode out", because: "Serving features must name exactly the supported generation modes") { + _ = try record(gemmaFeatures.filter { $0.key == .pipeline }) + } + refuses("parity record: an SSD prefix tier without the resident cache, or nine lanes", because: "Malformed serving features") { + _ = try record(gemmaFeatures.merging([.pipeline: .init(promptPrefixReuse: false, ssdPrefixTier: true, speculativeRounds: false, + maximumLanes: 9, logprobs: false)]) { $1 }) + } + let ultras = try indexedUltras(), alone = try aloneSpeed(built.layout, prefill: 7_000, decode: 90) + let blind = try ClusterPlacementFlow.decide(description: undeclared.description, capability: undeclared.capability, + localMemberID: "mac-one", localProfile: ultras.local, peerProfile: ultras.peer, layout: undeclared.layout, + measurements: [alone], promptTokens: 128, outputTokens: 128, link: ultras.link, environment: [:], benchDebugBuild: false) + require("parity: a fastest-plan family whose record declares no features keeps tensor parallel back and says why", + blind.result.chosen?.mode == .pipeline && blind.result.tensorParallel?.verdict == .dropsFeatures + && blind.lines.contains(" Pipeline: this worker build declares no serving features for its modes, so tensor parallel is held back until it does.")) + + // Only tensor parallel fits: the layout admits one cut only, 1, whose last rank holds every layer but one, on two + // equal Macs too small for that rank and large enough for a tensor-parallel half (found by planning each mode alone). + let narrow: (inout [String: Any]) -> Void = { $0["admittedCuts"] = [1] } + let reduced = try gemma(features: gemmaFeatures, description: base, adjust: narrow) + let gained = try gemma(features: with(gemmaFeatures, tensorParallelPrefixes: true), description: base, adjust: narrow) + func macs(_ giB: Int) throws -> [ClusterPlacementDevice] { + try ["mac-one", "mac-two"].map { try device($0, physicalGiB: giB, freeGiB: giB - 4, prefill: 7_000, decode: 90) } + } + func places(_ giB: Int, _ mode: ClusterGenerationMode) throws -> Bool { + var policy = ClusterPlacementPolicy() + policy.modes = [mode]; policy.promptTokens = 128; policy.outputTokens = 128 + return try ClusterPlacementPlanner.plan(devices: macs(giB), layout: reduced.layout, policy: policy, link: ultras.link).chosen != nil + } + guard let giB = try (8...64).first(where: { try places($0, .tensorParallel) && !places($0, .pipeline) }) else { + return require("parity refusal: equal Macs exist that hold a tensor-parallel half and not the pipeline at cut 1", false) + } + func decided(_ record: (layout: ClusterModelLayout, capability: ClusterRuntimeCapability, description: ClusterPairDescription)) + throws -> (lines: [String], result: ClusterPlacementResult, setup: ClusterPlacementSetup?) { + let pair = try macs(giB) + return try ClusterPlacementFlow.decide(description: record.description, capability: record.capability, localMemberID: "mac-one", + localProfile: pair[0].profile, peerProfile: pair[1].profile, layout: record.layout, promptTokens: 128, outputTokens: 128, + link: ultras.link, environment: [:], benchDebugBuild: false) + } + let refused = try decided(reduced), placed = try decided(gained) + let refusal = "Only tensor parallel fits these Macs, and it would drop prompt-prefix reuse and the SSD prefix tier that the " + + "pipeline keeps. No reduced-feature setup was saved." + require("parity refusal: where only tensor parallel fits (two \(giB) GB Macs, cut 1 only), the plan refuses, says why and saves no setup", + refused.result.chosen == nil && refused.setup == nil && refused.lines.contains(" " + refusal) + && refused.result.modesReason == refusal && refused.result.tensorParallel?.verdict == .dropsFeatures) + require("parity refusal: the same Macs place tensor parallel once its record declares prefix reuse", + placed.result.chosen?.mode == .tensorParallel && placed.setup != nil && !placed.lines.contains { $0.contains("would drop") }) + } + static func main() throws { if CommandLine.arguments.count > 1, CommandLine.arguments[1] == "flow" { do { try flow(Array(CommandLine.arguments.dropFirst(2))) } catch { @@ -1103,6 +1280,7 @@ import Foundation try ownerPilot(description: descriptionObject) try mimoFastestPlanLines(description: descriptionObject) try gemmaEvidenceLines(description: descriptionObject) + try featureParity(description: descriptionObject) try benchCap(layout: layout, description: description, capability: capability, slowTwo: slowTwo) try forcedMode(layout: layout, description: description, capability: capability, slowTwo: slowTwo) try requestMix(layout: layout, description: description, capability: capability, slowTwo: slowTwo) diff --git a/provider-swift/Tests/ClusterPlacementChecks/run.sh b/provider-swift/Tests/ClusterPlacementChecks/run.sh index 4ac7ce3d18..321589cae1 100755 --- a/provider-swift/Tests/ClusterPlacementChecks/run.sh +++ b/provider-swift/Tests/ClusterPlacementChecks/run.sh @@ -48,6 +48,7 @@ xcrun swiftc -j 4 "${task_flags[@]}" -D DARKBLOOM_CLUSTER_FIXTURE_ARTIFACTS -par "$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterHandOffModes.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementRequestLimits.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModelFeaturePolicy.swift" \ + "$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/DistributedResidentExecution.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/Requests/DistributedRequestDeadlineContext.swift" \ "$task_provider/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift" -o "$task_build/setup-check" From 779e44d2ad58d6d6478feffd421a0c6eb586d489 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:58:40 -0800 Subject: [PATCH 0111/1441] docs: feature parity before tensor parallel - inference.md: the rule in the Gemma tensor-parallel placement section (each mode's declared features for Gemma and MiMo, where they come from, how the replaced mode is found, the verdict, line, note and refusal, the forced mode, what it means today, and what it would change for Qwen and GLM); the Gemma and MiMo figure tables now say the guided step's parity keeps the pipeline in their tensor-parallel rows. - two-mac-cluster.md: what users see, and the Gemma and MiMo rows. - test.md: the new runtime tests, setup checks and note check. - changelog.d/cluster-feature-parity.md (new); one pointer sentence in fastest-plan-evidence.md. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-feature-parity.md | 6 ++ changelog.d/fastest-plan-evidence.md | 1 + docs/architecture/inference.md | 79 +++++++++++++++++++++++++-- docs/developer/test.md | 24 ++++++-- docs/provider/two-mac-cluster.md | 36 +++++++++--- 5 files changed, 130 insertions(+), 16 deletions(-) create mode 100644 changelog.d/cluster-feature-parity.md diff --git a/changelog.d/cluster-feature-parity.md b/changelog.d/cluster-feature-parity.md new file mode 100644 index 0000000000..32e5208d5a --- /dev/null +++ b/changelog.d/cluster-feature-parity.md @@ -0,0 +1,6 @@ +### Tensor parallel only where it keeps every feature + +- On a two-Mac pair, Gemma 4 and MiMo V2.6 Flash use tensor parallel only where it keeps every feature and caching behavior of the mode it would replace: prompt-prefix and SSD cache reuse, speculative (MTP) rounds, batch lanes, media, penalties and logit bias, and stop handling. What tensor parallel adds, such as logprobs, never counts against it. Each mode's features come from the installed cluster worker's capability record. +- Today Gemma 4's tensor parallel keeps no prompt prefixes and MiMo's has no speculative rounds, so these pairs keep the pipeline, whatever tensor parallel's measured speed. The plan's "Tensor parallel or pipeline" line says what tensor parallel would drop ("Pipeline: tensor parallel would drop prompt-prefix reuse and the SSD prefix tier that the pipeline keeps; held back until it keeps them."), and the model list says "tensor parallel: drops a feature". +- Where only tensor parallel fits the two Macs, the plan refuses with that reason and saves no setup, instead of saving one with fewer features. The developer's forced mode (debug builds) still places tensor parallel, and the plan says exactly what it drops. +- Qwen and GLM plans are unchanged. diff --git a/changelog.d/fastest-plan-evidence.md b/changelog.d/fastest-plan-evidence.md index ddb96316e8..83485417a1 100644 --- a/changelog.d/fastest-plan-evidence.md +++ b/changelog.d/fastest-plan-evidence.md @@ -3,4 +3,5 @@ - Gemma 4 and MiMo V2.6 Flash pairs choose tensor parallel only once tensor parallel's own speed is measured on both Macs: each Mac's half timed by a tensor-parallel load (Gemma), or requests this Darkbloom build served in tensor parallel. An estimate from the Macs' device index alone does not choose it, because the index overstates what half a model saves on big Macs: on two M5 Ultra it predicts a short Gemma request 6% faster in tensor parallel, where the plans expect decode 6-8% slower. - When the estimate says tensor parallel would be faster, the pair keeps the pipeline. The plan's "Tensor parallel or pipeline" line says the predicted gain and that it comes from the device index, and the model list says "tensor parallel: not measured yet". - Normal setups do not load tensor parallel to measure it, so these pairs keep the pipeline for now. MiMo does not yet time its halves at load, so MiMo pairs reach tensor parallel only from requests the same build served in tensor parallel. +- Tensor parallel must also keep every feature of the mode it would replace (see "Tensor parallel only where it keeps every feature"). - Qwen and GLM still choose tensor parallel wherever it fits. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index e838c2265e..2f07155e48 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4196,6 +4196,69 @@ decode step is mostly a per-token floor that two ranks do not halve, while 61 sums cross the link: about 0.67-0.93x one M5 Ultra's decode, unmeasured [INFERENCE]. +**Feature parity before tensor parallel.** The guided step plans a `fastest` +family's tensor parallel only where it keeps every feature and caching behavior +of the mode it would replace (owner, 2026-11-01). Each mode's features come from +the worker's capability record (`ClusterRuntimeCapability.modeFeatures`, one +`ClusterServingFeatures` a mode), which the adapter declares beside its modes +from the facts its loads bind; the provider keeps no table of them: + +| Feature (`ClusterServingFeatures`) | Gemma 4 pipeline / tensor parallel | MiMo V2.6 plain pipeline / `pipeline_mtp_v1` / tensor parallel | +|---|---|---| +| `promptPrefixReuse`, resident | yes / no | no / no / no | +| `ssdPrefixTier` | yes / no | no / no / no | +| `speculativeRounds` (MTP) | no / no | no / yes / no | +| `maximumLanes` | 8 / 8 | 8 / 1 / 1 | +| `requestMedia` | none / none | none | +| `penaltiesAndLogitBias`, `stopHandling` | yes / yes | yes | +| `logprobs` (committed tokens) | no / yes | no / no / yes | + +Gemma's come from `Gemma4ResidentAdapterDefinition.servingFeatures`, whose +`tensorParallelKeepsPromptPrefixes` its tensor-parallel load agreement binds +(`Gemma4TensorParallelLoadAgreement`). MiMo's come from +`MiMoResidentCapabilityMetadata.servingFeatures`: the widest lanes and paged +histories `MiMoBatchSettings` gives each mode, and +`MiMoTensorParallelResidentRuntime.servingFeatures`, whose lanes and prefix +setting its serving agreement binds. A record without features +(`ClusterRuntimeCapabilityCodec` writes no `modeFeatures`) keeps its bytes. + +`ClusterModeParity`, in `ClusterPlacementFlow.decide` beside +`ClusterModelFeaturePolicy.admissibleModes`, applies the rule before the planner +ranks anything: + +1. The mode tensor parallel would replace is the one the plan chooses without + it: the same policy with its tensor-parallel modes left out. Where no other + mode places, every other mode is compared. +2. Tensor parallel must keep every feature of that mode + (`ClusterServingFeatures.dropped(by:)`). What it adds (logprobs, wider lanes) + never counts against it. +3. Otherwise its modes leave the policy, so no ordering (the margin, the + evidence hold, a kept mode, a better hardware group) brings it back. The + assessment's verdict is `dropsFeatures` (`ClusterPlacementPolicy.tensorParallelHeldForFeatures`), + the plan's line says, for example, "Pipeline: tensor parallel would drop + prompt-prefix reuse and the SSD prefix tier that the pipeline keeps; held back + until it keeps them.", and the model list says `tensor parallel: drops a feature`. +4. Where tensor parallel is the only mode that places, the plan refuses rather + than save a reduced setup: "Only tensor parallel fits these Macs, and it would + drop ... No reduced-feature setup was saved." The result's `modesReason` + carries it to the setup screen. +5. The developer's forced mode (`DARKBLOOM_CLUSTER_FORCE_MODE`, debug builds) + still places tensor parallel, and the plan says exactly what it drops. +6. A `fastest` family whose record declares no features keeps tensor parallel + back: nothing shows it keeps them. + +Today the rule holds Gemma's tensor parallel back everywhere, whatever its +evidence, and MiMo's wherever the speculative pipeline is the mode it would +replace; the evidence rule below decides once a worker declares parity. The +tensor-parallel-first families (Qwen, GLM) declare no features and are not +gated. Applied to them, the rule would leave GLM unchanged (its tensor parallel +keeps prompt-prefix and SSD reuse and adds rounds, eight lanes, images, video +and logprobs) but would move Qwen3.5 9B from tensor parallel to its +speculative pipeline, which its records credit 1.74x: Qwen tensor parallel +decodes in rounds only with the explicitly quoted assistant +(`QwenTensorParallelMTPPolicy`, `ClusterQwenTensorAssistantPolicy`). Whether +they adopt it is the owner's decision. + **Evidence before tensor parallel.** A `fastest` family takes tensor parallel only when every rank of the placement has a measured share step (`ClusterDecodeSplit.measured`): a share probe of this model on that Mac @@ -4253,7 +4316,10 @@ tensor-parallel load times a rank's share (`Gemma4TensorParallelShareProbe`) before its ready record, which carries it to the leader. Served records count only for the build that served them (`ClusterServedSpeedRecords.servedBy`). -On the planner's own figures (`PlacementChecks`, `GemmaTensorParallelChecks.swift`): +On the planner's own figures (`PlacementChecks`, `GemmaTensorParallelChecks.swift`), +the comparison and the evidence rule choose as follows; the guided step's feature +parity then keeps the pipeline in every row until Gemma's tensor parallel keeps +prompt prefixes: | Pair | Link | Request | Chosen | |---|---|---|---| @@ -4417,7 +4483,9 @@ qualification records measured, 1.37x (59.18 against 43.05 tok/s; plans for the layout's longest request, 32,768 + 32,768 tokens. On the planner's own figures (`PlacementChecks`, `MiMoTensorParallelChecks.swift`; constructed Macs: M5 Ultra 57 tok/s, the M5 Max 128 GB from its stage probes at -40 tok/s), the provider plans MiMo as follows: +40 tok/s), the comparison and the evidence rule place MiMo as follows; the +guided step's feature parity then keeps the speculative pipeline in the rows +that end in tensor parallel, until MiMo's tensor parallel decodes in rounds: | Pair | Link | Request | Chosen | |---|---|---|---| @@ -4428,7 +4496,9 @@ constructed Macs: M5 Ultra 57 tok/s, the M5 Max 128 GB from its stage probes at | either pair | measured 109 us sums | 32,768 + 32,768 | speculative pipeline | Against the plain pipeline (a capability without `pipeline_mtp_v1`, or no -passing record of the rounds), two M5 Max are predicted faster in tensor +passing record of the rounds), tensor parallel would also drop the plain +pipeline's eight batch lanes (it serves one), so feature parity keeps the +pipeline there too. On speed alone, two M5 Max are predicted faster in tensor parallel even on default link costs for decode-heavy requests (128 + 128: 3.17 s against 3.50 s), on the prior alone, so they keep the pipeline too, as they do inside the 5 % margin (1,024 + 128) or for long prompts; two M5 Ultra @@ -4444,7 +4514,8 @@ MiMo's runtime takes no share probe, so only requests a pair served in tensor parallel with the same worker build give it evidence (`ClusterServedCalibration`). Only the developer's forced mode, in a debug build, serves MiMo tensor parallel before that; a release build cannot force it, -so release builds keep MiMo on the pipeline until MiMo gets a share probe. The +so release builds keep MiMo on the pipeline until MiMo gets a share probe, and +feature parity keeps it there until MiMo's tensor parallel decodes in rounds. The recorded golden layout gains the facts and routed experts beside its recorded bytes; its golden plans keep their placements (pipeline, cut 41 and cut 24), and their tensor-parallel diff --git a/docs/developer/test.md b/docs/developer/test.md index f9d8537093..f5e54aa88a 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1263,6 +1263,8 @@ neither real-weight numerics, a pair qualification nor speed. split top-k, also at an exactly tied maximum whose other ID leads the gather; - the verified load's cut of every text tensor, and its refusals; - the load agreement's fields; + - what the capability declares of each mode (`ClusterServingFeatures`): + tensor parallel's prompt-prefix setting is the one its load agreement binds; - the product's Gemma layout with its tensor-parallel facts: big Macs keep the pipeline on default link costs; on a measured fast link tensor parallel is predicted faster on the device index alone and the pipeline is @@ -1351,7 +1353,8 @@ registered artifact for them. with per-rank paged geometry, the selection rules, logprobs (an exactly tied maximum included), every stop kind (the owner's stop just before a stop token included), the request and load agreements, the request budget - and the text-only launch. + and the text-only launch; + - what the text row's capability declares of each mode (`ClusterServingFeatures`). `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh` also runs `MiMoTensorParallelChecks.swift` (model-free). It builds the layout from the @@ -1372,10 +1375,21 @@ registered artifact for them. 109 us link. Requests served in tensor parallel decide both ways on both pairs. `provider-swift/Tests/ClusterPlacementChecks/run.sh` checks that the guided step credits MiMo's rounds from its shipped records and prints the - fastest-plan and logprob lines. Through the guided step it also checks the - evidence rule: MiMo on two 256 GB Macs keeps the speculative pipeline with no - served record or another build's, and follows this build's served records; - Gemma follows both Macs' share probes. + fastest-plan and logprob lines. Through the guided step it also checks feature + parity (`ClusterModeParity`) before the evidence rule: + - as this build declares them, MiMo's tensor parallel has no rounds, so the + speculative pipeline is kept even with this build's served records; Gemma's + keeps no prompt prefixes, so the pipeline is kept even with both Macs' share + probes, after an update that served tensor parallel, and with nothing + measured; each plan says what tensor parallel would drop; + - with rounds (MiMo) or prefix reuse (Gemma) declared, the evidence rule + decides: MiMo on two 256 GB Macs keeps the speculative pipeline with no + served record or another build's and follows this build's served records, + and Gemma follows both Macs' share probes; + - where only tensor parallel fits, the plan refuses and saves no setup; the + forced mode places it and says what it drops; a record without features + holds it back; per-mode features cross the capability codec canonically; + a GLM record declaring a gap plans exactly as without it. 2. Build `darkbloom-cluster-tp-check` and put a source-matched `mlx.metallib` beside it ([build](build.md)). Then run the GPU oracles: diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 4b5ab3f955..ad05e3f1e7 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -340,10 +340,30 @@ Models that run tensor parallel, and when: |---|---|---| | Qwen3.5 9B, Qwen3.8 27B, Qwen3.5/3.6 35B A3B | wherever it fits | Qwen3.8 27B keeps images, video and logprobs only in tensor parallel | | GLM-5.3-Flash | wherever it fits | Eight concurrent requests by default | -| Gemma 4 26B (QAT 4-bit, 8-bit) | only where the plan predicts it faster than a pipeline from its own measured speed on both Macs | Text only; logprobs in tensor parallel only; one request at a time unless you set `DARKBLOOM_CLUSTER_BATCH_LANES` | -| MiMo V2.6 Flash | only where the plan predicts it faster than a pipeline from its own measured speed on both Macs | Text only; logprobs in tensor parallel only; one request at a time; see [MiMo V2.6 Flash on the pair](#mimo-v26-flash-on-the-pair) | - -For Gemma 4 and MiMo V2.6 Flash the plan uses tensor parallel only when +| Gemma 4 26B (QAT 4-bit, 8-bit) | only where it keeps every feature of the pipeline (not yet: no prompt-prefix or SSD reuse) and the plan predicts it faster from its own measured speed on both Macs | Text only; logprobs in tensor parallel only; one request at a time unless you set `DARKBLOOM_CLUSTER_BATCH_LANES` | +| MiMo V2.6 Flash | only where it keeps every feature of the mode it would replace (not yet: no speculative rounds) and the plan predicts it faster from its own measured speed on both Macs | Text only; logprobs in tensor parallel only; one request at a time; see [MiMo V2.6 Flash on the pair](#mimo-v26-flash-on-the-pair) | + +For Gemma 4 and MiMo V2.6 Flash, tensor parallel must first keep every feature +and caching behavior of the mode it would replace, as the installed cluster +worker declares them: prompt-prefix and SSD cache reuse, speculative rounds, +batch lanes, media, penalties and logit bias, and stop handling. What it adds, +such as logprobs, never counts against it. Today Gemma 4's tensor parallel keeps +no prompt prefixes and MiMo's has no speculative rounds, so these pairs serve the +pipeline: + +- The plan's "Tensor parallel or pipeline" line says what tensor parallel would + drop ("Pipeline: tensor parallel would drop prompt-prefix reuse and the SSD + prefix tier that the pipeline keeps; held back until it keeps them."), and the + model list says "tensor parallel: drops a feature". +- Where only tensor parallel fits the two Macs, the plan refuses and saves no + setup ("Only tensor parallel fits these Macs, and it would drop ... No + reduced-feature setup was saved."). +- The developer's forced mode (`DARKBLOOM_CLUSTER_FORCE_MODE`, debug builds only) + still places tensor parallel, and the plan says exactly what it drops. + +See [feature parity before tensor parallel](../architecture/inference.md#gemma-tensor-parallel-placement). + +Where tensor parallel keeps every feature, the plan also uses it only when tensor parallel's own speed has been measured on both Macs. That measurement is a timing a tensor-parallel load takes of each Mac's half (Gemma), or requests this Darkbloom build served in tensor parallel. An estimate from each Mac's @@ -552,9 +572,11 @@ MiMo V2.6 Flash text can also run tensor parallel: each Mac holds half of every layer, about 84 GB of weights and about 98 GiB in all with its reserves ([rank memory](../architecture/hardware-support.md#mimo-v26-tensor-parallel-rank-memory)), so two 128 GB Macs that cannot hold MiMo alone can serve it. The plan chooses -tensor parallel only where it predicts it faster than the pipeline with -speculative decoding, which MiMo's qualification records credit 1.37x, and only -from tensor parallel's own speed measured on both Macs: +tensor parallel only where it keeps the speculative rounds of the pipeline it +would replace, which it does not yet, so MiMo pairs keep the pipeline with +speculative decoding (above). Speed decides only after that: tensor parallel must +be predicted faster than that pipeline, which MiMo's qualification records +credit 1.37x, from tensor parallel's own speed measured on both Macs: - Before a load has measured the link, two 128 GB Macs and two 256 GB Macs alike keep the pipeline. From 0124b7fa3db24b02788e8dc5827e49ddab71e1f9 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:03:35 -0800 Subject: [PATCH 0112/1441] cluster: make the pair serving fix's docs and comments precise Refactor pass over the cancellation-deadlock and serving-epoch fix. No behavior change: comments, one reference row and the changelog fragment. - Changelog: name the condition a pair could not recover from (it lost a rank while its slot was stopping) and what the operator saw, instead of implying every lost rank, fence or cancelled request left it stuck. - cluster-control-protocol: the next committed start is accepted while the old slot retires, but its slot cannot publish until then (the row read as if the start waited for it). The engine's queue invariant now links its one home in architecture/inference.md instead of restating it. - NativePairMemberServingHost.stopServingCommittedStart: a later start can begin during the retirement; it no longer says the start never waits. - onQueueWithoutWaiting: the queue resumes those tasks through a stream yield or their retirement, so waiting can deadlock. - stopServingCommittedStart: the retirement closes the slot's admission before it suspends, so a released start never admits work. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-pair-serving-epoch.md | 14 ++++++++------ docs/reference/cluster-control-protocol.md | 2 +- .../Coordinator/NativePairMemberServing.swift | 4 ++-- .../Distributed/Engine/DistributedCBv2Engine.swift | 6 +++--- .../ProviderLoop+ClusterPairServing.swift | 3 ++- 5 files changed, 16 insertions(+), 13 deletions(-) diff --git a/changelog.d/cluster-pair-serving-epoch.md b/changelog.d/cluster-pair-serving-epoch.md index 54506e12e1..c267c91d93 100644 --- a/changelog.d/cluster-pair-serving-epoch.md +++ b/changelog.d/cluster-pair-serving-epoch.md @@ -1,7 +1,9 @@ -### Two-Mac pairs recover after a lost rank +### Two-Mac pairs recover after losing a rank during a stop -- A two-Mac pair no longer stays unable to serve after it loses a rank, is - fenced, or has a request cancelled before it started. +- A two-Mac pair no longer stays unable to serve when it loses a rank while + its slot is stopping. Until the provider restarted, its leader refused every + later start, and `darkbloom cluster stop` left that Mac's part still + releasing. - Fixed a deadlock in the pair's request engine. Stopping the pair slot cancelled a request's stream while the engine was telling that request the pair had lost a rank. The stream's cancellation waited for the engine, and the @@ -9,6 +11,6 @@ Cancellation and stream termination now never wait for the engine. - The leader also releases a committed start as soon as its session ends, instead of after the old slot has fully stopped, so a slow stop can no longer - make it refuse every later start with "a committed start is already served". - The release receipt still waits for the slot to retire, and a pair still never - serves two slots at once. + make it refuse later starts with "a committed start is already served". The + release receipt still waits, bounded, for the slot to retire, and a pair still + never serves two slots at once. diff --git a/docs/reference/cluster-control-protocol.md b/docs/reference/cluster-control-protocol.md index 64ebe8c2d5..6c5ad44d4f 100644 --- a/docs/reference/cluster-control-protocol.md +++ b/docs/reference/cluster-control-protocol.md @@ -204,7 +204,7 @@ policy bytes the control requires in a prepare frame | Prepare | The payload's policy must equal the installed policy byte for byte, the start must name this rank, and the frame must leave at most 30 seconds to prepare by this Mac's clock. The member then verifies its installed owner, native executable, metallib and resource library under the device gate and answers `native_pair_prepared` | `provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberSession.swift`, `init` / `runOwned` | | Committed start | `native_pair_owner_start` launches this Mac's installed owner; the owner's native child drives `native_pair_hello` and `native_pair_confirmation`, and `native_pair_owner_released` is sent only after native cleanup, the owner's lease release and the owner's exit were all observed | `runOwned` / `exchange` | | Cancel or expiry | Requests native cleanup at once, independently of signing or the socket. An uncommitted session is dropped and the member can prepare again; a committed one that cannot deliver its release stays quarantined in the control, which then refuses every later attachment | `cancel`; `NativePairMemberControl.finished` | -| Serving on the leader | The leader serves one committed start at a time, from its serve until its session's stop. The stop releases the start at once, then waits for the pair slot to retire before the receipt. After a lost rank or a fence, the next committed start is served once the old slot has retired, even if a serve or the slot's drain outlasts the session's bounded wait. A start whose session already stopped is never served. The slot's engine never waits for its queue from a cancellation or a stream's termination, so cancelling a request while its peer loss is published cannot deadlock the retirement | `provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift`, `serveCommittedStart` / `stopServingCommittedStart`; `provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift`, `onQueueWithoutWaiting` | +| Serving on the leader | The leader serves one committed start at a time, from its serve until its session's stop. The stop releases the start at once, then waits for the pair slot to retire before the receipt. So after a lost rank or a fence, the next committed start is accepted even if a serve or the old slot's drain outlasts the session's bounded wait, and its slot cannot publish until the old slot has retired. A start whose session already stopped is never served. The slot's engine cannot deadlock that retirement ([provider inference engine](../architecture/inference.md)) | `provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift`, `serveCommittedStart` / `stopServingCommittedStart`; `provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift`, `onQueueWithoutWaiting` | **What a real member does in this build.** The installed owner (`darkbloom cluster worker-owner --stdio`) admits a start the coordinator diff --git a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift index 2709a0cc76..3740de188d 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberServing.swift @@ -48,8 +48,8 @@ public protocol NativePairMemberServingHost: AnyObject, Sendable { func serveCommittedStart(_ start: NativePairMemberServingStart) async throws /// The session is ending: retire what `serveCommittedStart` published for /// this epoch (or stop a serve still under way) and return once it is - /// retired. The epoch is released at once, so a later start never waits - /// on this one's cleanup, and is never served afterwards. Idempotent. + /// retired. The epoch is released at once, so a later start can begin + /// during that retirement, and is never served afterwards. Idempotent. func stopServingCommittedStart(epoch: UUID) async } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift index 88ae9490f5..62c71a93e2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift @@ -75,9 +75,9 @@ public final class DistributedCBv2Engine: CBv2Engine, @unchecked Sendable { } /// `onQueue` for a caller that must never wait for the queue: a task's - /// cancellation handler, and a stream's termination that cancellation runs. - /// Those run holding the task's status lock, which the queue needs to resume - /// that task (every `yield` to its stream): waiting here deadlocked both. + /// cancellation handler, or a stream's termination that cancellation runs. + /// Those hold the task's status lock, which the queue needs to resume that + /// task (a `yield` to its stream, its retirement), so waiting can deadlock. func onQueueWithoutWaiting(_ body: @escaping @Sendable () -> Void) { if DispatchQueue.getSpecific(key: queueKey) != nil { body() } else { queue.async(execute: body) } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift index 732d6f10df..f46e6bc827 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift @@ -181,7 +181,8 @@ extension ProviderLoop: NativePairMemberServingHost { // The start ends with its session, now: not when the slot's drain or // a serve still under way ends, which can outlast the session's own // bounded wait (its receipt then lets the coordinator commit the next - // start). A serve that lost its start stands down by itself. + // start). A serve that lost its start stands down by itself, and the + // retirement below closes the slot's admission before it suspends. clusterPairServingEndedEpoch = epoch endClusterPairServing(epoch) // The session sends its release receipt once this returns, so every From 2c00eeaa165e97561d278d07df44ea9ac2b3a43f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:13:33 -0800 Subject: [PATCH 0113/1441] cluster: pin MiMo TP contract v2 and catch BF16-rounded partials Refactor pass on cefbf3f37 (MiMo tensor-parallel FP32 partials). No source or SDK change: the review found the single-Mac graph and the decode-expert kernel source unchanged and the precision argument sound. MiMoTensorParallelFloat32PartialTests: - theLoadAgreementCarriesContractVersion2 pins the arithmetic fields string for string (it matched prefixes and suffixes only) and requires the three v1 strings absent from the load agreement. - everyRankPartialIsFloat32AndRoundsOnceAfterTheSum records each partial, not only its dtype, and requires values BF16 cannot hold. v1 also handed the sum an FP32 array (its BF16 partial widened), so an o_proj or dense down product rounded to BF16 and widened afterwards passed the dtype check. A mutation doing that, plus v1 routed rows, fails 8 expectations: the new check for dense, dense row by row and o_proj on both ranks, and the routed combine's two. inference.md: MLX_ENABLE_TF32=1 is MiMoArithmeticEnvironment's requirement, not every cluster contract's (GLM's has none); a rank never rounds its expert rows, and their combined row is rounded once, after the sum. test.md lists the new checks. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 18 +++++----- docs/developer/test.md | 3 +- ...iMoTensorParallelFloat32PartialTests.swift | 34 ++++++++++++++----- 3 files changed, 37 insertions(+), 18 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 1ca1c9a651..febf273294 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4274,16 +4274,18 @@ different contracts refuse each other. FP32 holds every BF16 value exactly, and MLX's FP32 MXFP4 and affine kernels accumulate in FP32 as the BF16 ones do. On M5 the NAX path runs FP32 inputs at -TF32 (`MLX_ENABLE_TF32=1`, which every cluster contract requires). Its 10 +TF32 (`MLX_ENABLE_TF32=1`, which `MiMoArithmeticEnvironment` requires). Its 10 mantissa bits keep a BF16-sourced activation and an MXFP4 weight exactly, and an affine 8-bit weight at least as precisely as the BF16 kernel's BF16 weight tile. -So no rank rounds more than one Mac: an expert row is rounded once, after the -sum, where one Mac rounds each expert's whole projection to BF16 before its -combine. Ranks are still not bit-exact with one Mac, because the halves -reassociate the FP32 sums and a near tie can flip a route. Comparisons against -one Mac read `tokensEqualLogitsDiffer` or `divergedAtNearTie`. -`MiMoTensorParallelFloat32PartialTests` checks on the GPU that two ranks' rows -add up bit for bit to the exact full-width row that one Mac rounds once. +So no rank rounds more than one Mac. A rank never rounds its expert rows: their +combined row is rounded once, after the sum, where one Mac also rounds each +expert's whole projection to BF16 before its combine. Ranks are still not +bit-exact with one Mac, because the halves reassociate the FP32 sums and a near +tie can flip a route. Comparisons against one Mac read `tokensEqualLogitsDiffer` +or `divergedAtNearTie`. `MiMoTensorParallelFloat32PartialTests` checks on the +GPU that two ranks' rows add up bit for bit to the exact full-width row that one +Mac rounds once, and that no `o_proj` or dense partial was rounded to BF16 +before its sum. `MiMoV26TensorShard` derives each rank's configuration (half the heads of both layer kinds and both channel widths, no MTP heads or towers) and cuts stored diff --git a/docs/developer/test.md b/docs/developer/test.md index 84e4cfb565..e9a7ecb279 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1342,7 +1342,8 @@ registered artifact for them. - FP32 partials (`MiMoTensorParallelFloat32PartialTests`, on the GPU): two ranks' expert rows add up bit for bit to the exact full-width row that one Mac rounds once, through the decode-expert kernel and MLX's sorted - gather, and every partial a rank sums is FP32; + gather; every partial a rank sums is FP32, and no `o_proj` or dense + partial was rounded to BF16 first; the contract v2 strings are pinned; - the vocabulary-split head against the whole head; - the resident runtime's verified load: each rank reads exactly its shard's bytes, and a tampered or foreign checkpoint is refused; diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift index 26d52f2ea1..4fdb1c6472 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift @@ -71,18 +71,28 @@ struct MiMoTensorParallelFloat32PartialTests { eval(moe) } - /// Contract v2 is in the plan's arithmetic fields and so in the load agreement and the - /// plan fingerprint: a rank on v1 (BF16 partials) disagrees and both refuse before loading. + /// Contract v2, string for string. The fields are in the load agreement and the plan + /// fingerprint, so a rank on v1 (BF16 partials) disagrees and both refuse before loading. @Test func theLoadAgreementCarriesContractVersion2() throws { let fields = MiMoTensorParallelPlan.arithmeticAgreementFields - for part in ["o-proj-partial", "dense-down-partial", "expert-rows"] { - #expect(fields.contains { $0.hasPrefix("mimo-v26-\(part)-stored-float32-") && $0.hasSuffix("-rounded-once-v2") }, "\(part)") - } - #expect(!fields.contains { $0.contains("bfloat16") || $0.hasSuffix("-v1") && $0.contains("partial") }) + #expect(fields == [ + "mimo_v26_heads_and_expert_channels_v1", + "mimo-v26-o-proj-partial-stored-float32-sum-float32-rounded-once-v2", + "mimo-v26-dense-down-partial-stored-float32-sum-float32-rounded-once-v2", + "mimo-v26-expert-rows-stored-float32-local-float32-combine-sum-float32-rounded-once-v2", + "mimo-v26-untied-head-vocabulary-halves-v1", + "mimo-v26-mtp-off-v1", + ]) let plan = try MiMoTensorParallelPlan(configuration: JSONSerialization.data( withJSONObject: MiMoTensorParallelModel.syntheticConfiguration(.kernel), options: [.sortedKeys])) let agreement = MiMoTensorParallelResidentRuntime.loadAgreementFields(plan: plan, chunkTokens: 16) #expect(fields.allSatisfy(agreement.contains) && agreement.contains(plan.fingerprint)) + let version1 = [ + "mimo-v26-o-proj-partial-stored-bfloat16-sum-float32-rounded-once-v1", + "mimo-v26-dense-down-partial-stored-bfloat16-sum-float32-rounded-once-v1", + "mimo-v26-expert-rows-local-float32-combine-sum-float32-rounded-once-v1", + ] + #expect(!version1.contains(where: agreement.contains)) } /// Two ranks' FP32 expert rows sum to the exact full-width row, bit for bit, and the @@ -151,13 +161,13 @@ struct MiMoTensorParallelFloat32PartialTests { @Test func everyRankPartialIsFloat32AndRoundsOnceAfterTheSum() throws { let (whole, ranks, directory) = try Self.models() defer { try? FileManager.default.removeItem(at: directory) } - final class Recorder: @unchecked Sendable { var dtypes: [DType] = [] } + final class Recorder: @unchecked Sendable { var summed: [MLXArray] = [] } let recorder = Recorder() let x = withRandomState(MLXRandom.RandomState(seed: 9)) { MLXRandom.normal([1, 3, Self.hidden]) }.asType(.bfloat16) var partials: [MLXArray] = [] for rank in ranks { let context = MiMoV26TensorParallelContext( - reduce: { recorder.dtypes.append($0.dtype); return $0 }, vocabularyRows: rank.vocabularyRange) + reduce: { recorder.summed.append($0); return $0 }, vocabularyRows: rank.vocabularyRange) let dense = rank.model.model.layers[0], moe = rank.model.model.layers[1] #expect(dense.mlp is MiMoV26DenseMLP) let outputs = [ @@ -173,7 +183,13 @@ struct MiMoTensorParallelFloat32PartialTests { #expect((outputs + [attention]).allSatisfy { $0.dtype == .bfloat16 }) partials.append(try Self.routed(rank).tensorParallelPartial(x)) } - #expect(recorder.dtypes == [DType](repeating: .float32, count: 8)) + // Per rank: dense, dense row by row, routed, `o_proj`. A BF16 product widened after + // the fact (v1's dense and `o_proj` partials) would hold BF16 values only. + #expect(recorder.summed.map(\.dtype) == [DType](repeating: .float32, count: 8)) + for (index, summed) in recorder.summed.enumerated() { + let widenedBF16 = summed.asType(.bfloat16).asType(.float32) + #expect(any(summed .!= widenedBF16).item(Bool.self), "partial \(index) holds only BF16 values") + } #expect(partials.allSatisfy { $0.dtype == .float32 }) let wholeMoE = try Self.routed(whole) From de3247dd8aa0b538e05f41460e9a02cef0effc49 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:28:05 -0800 Subject: [PATCH 0114/1441] provider: tighten the parity gate's words (forced line, logprobs) Refactor pass over the feature-parity gate (d80b5ac43..779e44d2a). What the gate holds back, refuses or places is unchanged. - The forced developer mode's line moves beside the gate's other words (`ClusterModeParity.Hold.forcedLine`). For a record that declares no serving features it said tensor parallel "drops features this worker build does not declare"; it now says the build declares none, "so what it drops is not known". A setup check pins that line. - The plan's rule line, the changelog fragment and two-mac-cluster.md list logprobs among the features a mode must keep, as `ClusterServingFeatures.dropped(by:)` counts them and the owner's directive names them. What tensor parallel adds still never counts. - `ClusterModeParity`'s word helpers are private to it. - test.md describes the new check. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-feature-parity.md | 2 +- docs/developer/test.md | 5 +++-- docs/provider/two-mac-cluster.md | 8 ++++---- .../Placement/ClusterModeParity.swift | 16 ++++++++++++---- .../Placement/ClusterPlacementFlow.swift | 3 +-- .../PlacementSetupCheck.swift | 7 +++++++ 6 files changed, 28 insertions(+), 13 deletions(-) diff --git a/changelog.d/cluster-feature-parity.md b/changelog.d/cluster-feature-parity.md index 32e5208d5a..0b23fb5a34 100644 --- a/changelog.d/cluster-feature-parity.md +++ b/changelog.d/cluster-feature-parity.md @@ -1,6 +1,6 @@ ### Tensor parallel only where it keeps every feature -- On a two-Mac pair, Gemma 4 and MiMo V2.6 Flash use tensor parallel only where it keeps every feature and caching behavior of the mode it would replace: prompt-prefix and SSD cache reuse, speculative (MTP) rounds, batch lanes, media, penalties and logit bias, and stop handling. What tensor parallel adds, such as logprobs, never counts against it. Each mode's features come from the installed cluster worker's capability record. +- On a two-Mac pair, Gemma 4 and MiMo V2.6 Flash use tensor parallel only where it keeps every feature and caching behavior of the mode it would replace: prompt-prefix and SSD cache reuse, speculative (MTP) rounds, batch lanes, media, penalties and logit bias, stop handling and logprobs. What tensor parallel adds, such as logprobs where the pipeline has none, never counts against it. Each mode's features come from the installed cluster worker's capability record. - Today Gemma 4's tensor parallel keeps no prompt prefixes and MiMo's has no speculative rounds, so these pairs keep the pipeline, whatever tensor parallel's measured speed. The plan's "Tensor parallel or pipeline" line says what tensor parallel would drop ("Pipeline: tensor parallel would drop prompt-prefix reuse and the SSD prefix tier that the pipeline keeps; held back until it keeps them."), and the model list says "tensor parallel: drops a feature". - Where only tensor parallel fits the two Macs, the plan refuses with that reason and saves no setup, instead of saving one with fewer features. The developer's forced mode (debug builds) still places tensor parallel, and the plan says exactly what it drops. - Qwen and GLM plans are unchanged. diff --git a/docs/developer/test.md b/docs/developer/test.md index f5e54aa88a..2afc301585 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1388,8 +1388,9 @@ registered artifact for them. and Gemma follows both Macs' share probes; - where only tensor parallel fits, the plan refuses and saves no setup; the forced mode places it and says what it drops; a record without features - holds it back; per-mode features cross the capability codec canonically; - a GLM record declaring a gap plans exactly as without it. + holds it back, and the forced mode then says what it drops is not known; + per-mode features cross the capability codec canonically; a GLM record + declaring a gap plans exactly as without it. 2. Build `darkbloom-cluster-tp-check` and put a source-matched `mlx.metallib` beside it ([build](build.md)). Then run the GPU oracles: diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index ad05e3f1e7..ce732bca98 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -346,10 +346,10 @@ Models that run tensor parallel, and when: For Gemma 4 and MiMo V2.6 Flash, tensor parallel must first keep every feature and caching behavior of the mode it would replace, as the installed cluster worker declares them: prompt-prefix and SSD cache reuse, speculative rounds, -batch lanes, media, penalties and logit bias, and stop handling. What it adds, -such as logprobs, never counts against it. Today Gemma 4's tensor parallel keeps -no prompt prefixes and MiMo's has no speculative rounds, so these pairs serve the -pipeline: +batch lanes, media, penalties and logit bias, stop handling and logprobs. What it +adds, such as logprobs where the pipeline has none, never counts against it. +Today Gemma 4's tensor parallel keeps no prompt prefixes and MiMo's has no +speculative rounds, so these pairs serve the pipeline: - The plan's "Tensor parallel or pipeline" line says what tensor parallel would drop ("Pipeline: tensor parallel would drop prompt-prefix reuse and the SSD diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift index bc91fc897e..c4a61948cb 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift @@ -24,7 +24,7 @@ enum ClusterModeParity { let dropped: [String]? /// "prompt-prefix reuse and the SSD prefix tier that the pipeline keeps"; nil when nothing is declared. - var drops: String? { + private var drops: String? { dropped.map { list($0) + " that " + (replaced.count == 1 ? ClusterModeParity.words(replaced[0]) + " keeps" : "the model's other modes keep") } } @@ -41,6 +41,14 @@ enum ClusterModeParity { + (drops.map { "it would drop " + $0 } ?? "this worker build declares no serving features for its modes") + ". No reduced-feature setup was saved." } + + /// Where a developer's forced mode places tensor parallel anyway. + var forcedLine: String { + "Developer setting: tensor parallel is placed because it is forced; " + + (drops.map { "it drops " + $0 } + ?? "this worker build declares no serving features for its modes, so what it drops is not known") + + "." + } } /// The hold for `policy` as the caller would plan it, or nil when every tensor-parallel mode keeps every feature @@ -70,9 +78,9 @@ enum ClusterModeParity { /// The rule, as a plan of a family it applies to says it. static let ruleLine = "A mode is chosen only where it keeps every feature and caching behavior of the mode it would " + "replace, as this worker build declares them: prompt-prefix and SSD reuse, speculative rounds, batch lanes, " - + "media, penalties and logit bias, and stop handling." + + "media, penalties and logit bias, stop handling and logprobs." /// The mode a plan would place instead, in words. - static func words(_ mode: ClusterGenerationMode) -> String { + private static func words(_ mode: ClusterGenerationMode) -> String { switch mode { case .pipeline: "the pipeline" case .pipelineCompactDecode: "the compact-decode pipeline" @@ -84,7 +92,7 @@ enum ClusterModeParity { } } - static func list(_ items: [String]) -> String { + private static func list(_ items: [String]) -> String { items.count <= 2 ? items.joined(separator: " and ") : items.dropLast().joined(separator: ", ") + " and " + items.last! } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift index bed07f6c09..8b1ee4dd09 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift @@ -315,8 +315,7 @@ public enum ClusterPlacementFlow { } } if let parity, forced != nil, let chosen = result.chosen, parity.modes.contains(chosen.mode) { - lines += ["Feature parity", " Developer setting: tensor parallel is placed because it is forced; it drops " - + (parity.drops ?? "features this worker build does not declare") + "."] + lines += ["Feature parity", " " + parity.forcedLine] } if let parityRefusal { lines += ["Feature parity", " " + parityRefusal] } if handOff { diff --git a/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift b/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift index 52928e3963..585774c01c 100644 --- a/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift +++ b/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift @@ -1127,6 +1127,13 @@ import Foundation require("parity: a fastest-plan family whose record declares no features keeps tensor parallel back and says why", blind.result.chosen?.mode == .pipeline && blind.result.tensorParallel?.verdict == .dropsFeatures && blind.lines.contains(" Pipeline: this worker build declares no serving features for its modes, so tensor parallel is held back until it does.")) + let blindForced = try ClusterPlacementFlow.decide(description: undeclared.description, capability: undeclared.capability, + localMemberID: "mac-one", localProfile: ultras.local, peerProfile: ultras.peer, layout: undeclared.layout, + measurements: [alone], promptTokens: 128, outputTokens: 128, link: ultras.link, + environment: [ClusterForcedModeSetting.environmentName: "tensor_parallel_v1"], benchDebugBuild: true) + require("parity: the forced mode places tensor parallel on a record that declares no features, and says nothing shows what it drops", + blindForced.result.chosen?.mode == .tensorParallel && blindForced.lines.contains(" Developer setting: tensor parallel is placed " + + "because it is forced; this worker build declares no serving features for its modes, so what it drops is not known.")) // Only tensor parallel fits: the layout admits one cut only, 1, whose last rank holds every layer but one, on two // equal Macs too small for that rank and large enough for a tensor-parallel half (found by planning each mode alone). From 1657ea26c7db6b7083624928e15886438e7e42f6 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:28:08 -0800 Subject: [PATCH 0115/1441] Serve Qwen27's resident assistant on coordinator pairs once a build declares it A build can now declare Qwen3.8-27B's resident speculative assistant public for its tensor-parallel pairs (ClusterPublicTensorAssistant on the ClusterPublicModels entry: depth, the inline head's inventory fingerprint, singleton verification and the SHA-256 of its evidence report). This build declares none, so nothing changes until the owner signs a declaration after the real-pair evidence. With a declaration: - ClusterConfiguration.validate admits a tensorAssistant beside nativeMember only when it is exactly the declared policy (the leader's and the other Mac's approval checks run it before any part stops). - The guided setup plans a coordinator-served cluster under mtp_mode = auto with the declared assistant (declared depth, singleton verification, no cohort argument) and requires the native quote to return exactly it. - The declared assistant's launch arguments and evidence digest join the model's resource policy (DistributedInstalledNativeStart.resourcePolicySHA256), so release facts, approvals and every committed start name it. Without a declaration the digest is the five-field formula, byte for byte. - A pair slot whose READY names the resident assistant reports MTP as configured in its posture and heartbeats, with the pair runtime's counts. The plan's public-traffic line says a placement with the declared assistant is qualified. Tests cover the declaration's shape, validation beside an approval on both Macs (declared, other depth, inventory, verification or artifact), the resource-policy digest (unchanged without a declaration), the committed start and model-approval runtime block, planning arguments and quote checks, the public-traffic line and the slot's MTP posture. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-public-assistant.md | 19 ++ docs/architecture/inference.md | 19 +- docs/reference/configuration.md | 10 +- .../Config/ClusterConfiguration.swift | 18 +- .../ClusterRuntimeApprovalFacts+Release.swift | 2 +- .../Config/ClusterRuntimeApprovalFacts.swift | 11 +- .../ClusterSetupWizardLiveOperations.swift | 10 +- .../Installed/ClusterPublicModels.swift | 58 +++++ .../DistributedInstalledNativeStart.swift | 15 +- ...DistributedInstalledPairServingGrant.swift | 17 +- .../ClusterApprovalAttachment.swift | 7 +- ...terPlacementTensorAssistantSelection.swift | 60 ++++-- .../Engine/Bridge/EngineV2Bridge+MTP.swift | 5 + .../ProviderLoop+ClusterPairSlot.swift | 6 + .../ClusterPublicTensorAssistantTests.swift | 202 ++++++++++++++++++ ...istributedAutomaticBatchPlannerTests.swift | 58 ++++- .../ProviderLoop/ClusterPairSlotTests.swift | 25 ++- 17 files changed, 480 insertions(+), 62 deletions(-) create mode 100644 changelog.d/qwen27-public-assistant.md create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterPublicTensorAssistantTests.swift diff --git a/changelog.d/qwen27-public-assistant.md b/changelog.d/qwen27-public-assistant.md new file mode 100644 index 0000000000..de5dd9aea0 --- /dev/null +++ b/changelog.d/qwen27-public-assistant.md @@ -0,0 +1,19 @@ +### Qwen3.8-27B pairs can keep their speculative assistant on public traffic once declared + +- A build can now declare Qwen3.8-27B's resident speculative assistant public + for its tensor-parallel pairs, the way the public model declaration names a + model's mode families: the exact depth, head inventory and singleton + verification, with the SHA-256 of its evidence report. This build declares + none, so coordinator-paired setups still carry no assistant and nothing + changes until the owner signs a declaration after the real-pair evidence. +- With a declaration, the guided setup plans a cluster served through + Darkbloom with the declared assistant under `mtp_mode = "auto"`, each Mac + admits a cluster approval beside exactly that assistant (any other is + refused before any part stops), and the release's cluster runtime facts, the + coordinator's approval and every committed start name it in their resource + policy digest. Without a declaration that digest is unchanged. +- A pair whose ranks report the resident assistant ready now shows MTP as + configured in its slot posture and heartbeats, with the counts its runtime + reports, instead of disabled. +- The refusal of an undeclared assistant beside an approval now says it serves + local clusters only unless the build declares it public. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..c1bc133fe2 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -5250,7 +5250,12 @@ types them ([fields](../reference/configuration.md#cluster-runtime-facts), native start of an owner-formed session calls it for its `resourcePolicySHA256`. A coordinator-formed start carries the approval's value, which the member and its owner compare with the installed approval - (`NativePairMemberPolicy.require`). + (`NativePairMemberPolicy.require`). A resident assistant the build declares + public for the model's artifact (`ClusterPublicModels.tensorAssistant`) adds + its launch arguments and evidence digest to the formula, so the approval and + every start under it name the declared assistant + ([Qwen27 resident assistant](#qwen27-tensor-parallel-resident-assistant)); + without one the digest is the five-field formula as before. 4. Every model carries a pair-serving grant when the build qualifies it. A pair member reports only hardware capabilities (`DistributedServingEligibility.memberCapabilities`: `apple_m5` on an M5, @@ -5373,7 +5378,15 @@ The Qwen3.5 9B's artifact ships the same dense one-layer inline head, so its ten For the exact registered Qwen3.8 27B artifact, normal cluster planning discovers the embedded assistant from the catalog manifest, capability identity and bounded inline header inspection. With `backend.mtp_mode` set to `auto` or `on`, `ClusterPlacementTensorAssistantSelection.readAutomatic` asks the native metadata helper for a complete depth-three cohort quote. The returned inventory fingerprint becomes the saved bilateral policy; the provider does not infer it from a model name. Explicit `off`, the existing MTP kill switch, or an absent head retains the completely quoted ordinary TP owner. A malformed declared assistant refuses planning. This policy does not create a hand-off or phase-split deployment. -The assistant serves local clusters only. Its verify windows are a computation that no parity qualification covers: the coordinator qualifies `tensor_parallel_v1` placements by classes, cuts and mode, a pair's registration carries no speculation field, and the bundled tensor-parallel records of the 27B predate the assistant. A setup saved for coordinator pairing therefore carries none (`ClusterConfiguration.validate`). The guided setup plans a cluster served through Darkbloom under `auto` as under `off` (`ClusterPlacementTensorAssistantSelection.discoveryMode`, from the serving scope in `OnboardingLive.localPlanModels`). Explicit `on` is kept; the plan's public-traffic line then says the pair is not offered, and the leader refuses the coordinator's approval before any part stops (`ClusterApprovalAttachment.attachment` runs the setup's full validation). Public speculative decoding needs qualification evidence of the assisted placement. +On a coordinator-formed pair the assistant serves only as the build declares it. Its verify windows are a computation the coordinator does not see: it qualifies `tensor_parallel_v1` placements by classes, cuts and mode, a pair's registration carries no speculation field, and the bundled tensor-parallel records of the 27B predate the assistant. The owner therefore declares a public assistant per artifact beside the public model declaration (`ClusterPublicModel.tensorAssistant`, a `ClusterPublicTensorAssistant`: depth, the inline head's inventory fingerprint, singleton verification and the SHA-256 of its evidence report under `docs/reports/`). This build declares none. + +1. A setup saved for coordinator pairing carries no assistant, or exactly the declared one (`ClusterConfiguration.validate`, refusal `ClusterConfiguration.tensorAssistantServesLocally`). The leader checks a coordinator's approval against this rule before any part stops (`ClusterApprovalAttachment.attachment` runs the setup's full validation), and the other Mac checks it again before it saves. +2. Under `auto` the guided setup plans a cluster served through Darkbloom with the declared assistant, or without one when none is declared (`ClusterPlacementTensorAssistantSelection.discoveryMode`, from the serving scope in `OnboardingLive.localPlanModels`). The quote is asked at the declared depth with singleton verification (no cohort argument), and the native helper must return exactly the declared policy, inventory included (`requireDiscoveredQuote`). Explicit `on` is kept; without a declaration the plan's public-traffic line says the pair is not offered (`ClusterPairOwnerServing.tensorAssistantNotOffered`), and the approval is refused as above. +3. The declared assistant's launch arguments (`--mtp-depth`, `--tp-mtp-inventory-sha256`, the verification) and its evidence digest are part of the model's resource policy (`DistributedInstalledNativeStart.resourcePolicySHA256`, see [cluster runtime facts](#cluster-runtime-facts-of-an-installed-app)). A release's facts, the coordinator's approval and every committed start under it therefore name the declared assistant; without a declaration the digest is unchanged. +4. Singleton verification (`singleton_ready_set_v1`) speculates only for a step whose ready set is one request; wider steps decode as one plain rectangle with the assistant observing each row (`QwenTensorParallelNativeBatchExecutor.decodeRound`). Media rows, samplers that do not admit speculative verification and requested logprobs keep their target paths, as on a local cluster. +5. A pair slot whose ranks report the assistant in READY (`ClusterQwenTensorAssistantReady`) reports MTP as configured in its slot posture and heartbeats, with the counts rank zero's runtime returned request by request (`ProviderLoop.publishClusterPairSlot`, `EngineV2Bridge.mtpStatusSnapshot`, `DistributedCBv2Engine.mtpTotalsSnapshot`). Any other pair keeps the disabled posture. + +The evidence a declaration needs (the fixed greedy answers byte-identical with and without the assistant, concurrent answers equal to solo, sampled and logprob requests against plain tensor parallel) is recorded on a non-production pair; tiny paired-shard fixtures and the checks above do not establish it. The assistant stays resident across admitted widths. Each request owns its history, assistant pages, target frontier and bounded accepted-token queue. Each row's round starts with its own B=1 assistant step over its own history (the step that also feeds its trusted history); the round's later steps run every row of a cohort through one assistant forward (`Qwen35InlineMTPAssistant.draftHiddens`, see [Batch-invariant tensor-parallel decode projections](#batch-invariant-tensor-parallel-decode-projections)). In a cohort, one head call per draft step chooses every row's proposal (`QwenTensorParallelMTPDecoder.stepBatch`; the SDK's `Qwen35InlineMTPAssistant.draftHidden`, `draftHiddens` and `recordDraft`): the rows' hidden states go through the vocabulary-sharded head together, and the cohort's draft step is one evaluation holding two collectives (rank zero's hidden rows, then the score exchange) in the same order on both ranks, instead of one evaluation and two collectives per row. Each row's choice equals its own call's: both collectives are element-wise, the head shard computes every row with the batch-invariant kernel (`QwenTensorParallelMTPProjection.exactRows`; with exact drafts off, each row as its own single-vector MLX product, `rowsAlone`, because one plain multi-row call would let MLX pick `qmv_wide` on Apple GPU family 15 and later and change rows), and the first maximum is taken per row. `QwenTensorParallelMTPHeadRowsTests` checks the head rows byte for byte for two to eight rows, and `QwenTensorParallelBatchMTPTransitionTests.batchedCohortDraftsMatchRowByRowDraftsWithOneHeadCallPerStep` checks tokens, MTP statistics and native state against row-by-row drafting (collective reductions per run: 577 to 401 at two rows, 1,633 to 401 at eight). A one-row round runs the same per-step functions with one row, so a request proposes the same tokens alone and in a cohort. Both ranks read every proposal from the same exchanged (maximum, index) pairs, so no proposal broadcast is needed. Eligible requests then share one captured target rectangle: `QwenTensorParallelMTPDecoder.stepBatch` verifies their seed and proposals, settles every row to its independently accepted prefix, and confirms the entire ordered cohort before publishing any result. Accepted suffixes consume the existing per-token credits without another native step. Request RNG and stopping remain independent. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 0aa1e29379..4b3a0ec93c 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1,6 +1,6 @@ # Configuration reference -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 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. @@ -961,7 +961,7 @@ runtime digest, and the provider computes no facts for it | `models[].artifact_sha256` | the capability's `artifactSHA256`, the catalog aggregate | | `models[].capability_sha256` | SHA-256 of the exact output of `darkbloom-cluster-worker --describe-runtime` | | `models[].profile_sha256` | the capability's `profileFingerprint` | -| `models[].resource_policy_sha256` | `DistributedInstalledNativeStart.resourcePolicySHA256` of the capability, the value a native start carries | +| `models[].resource_policy_sha256` | `DistributedInstalledNativeStart.resourcePolicySHA256` of the capability, the value a native start carries: SHA-256 of `darkbloom/installed-resource-policy/v1`, the arithmetic policy ID and digest, the state semantics and the scheduling policy joined by U+001F; when the build declares a resident assistant public for the model's runtime model and artifact (`ClusterPublicModels.tensorAssistant`), followed by `qwen27_tensor_assistant_v1`, `depth=`, `--tp-mtp-inventory-sha256=`, `verification=` and `evidence=` (`ClusterPublicTensorAssistant.resourcePolicyFields`). This build declares none | | `models[].pair_serving_grant` | `null`, or exactly `evidence_sha256` and `mode_families` (1 to 4 of `hand_off`, `pipeline`, `pipeline_speculative`, `tensor_parallel`, in byte order). A model the build's public declaration (`ClusterPublicModels`) names by runtime model, catalog ID and artifact: its declared families, with the evidence document's SHA-256. Any other model: the families the build's bundled records grant its artifact (`ClusterPairServingGrants.grant`), with the SHA-256 of the records that grant is computed from (the artifact's passing records, without a pass that a divergence of the same shape contradicts) as canonical JSON Lines (`ClusterPairServingGrant.evidenceSHA256`: each record's `encodedLine` in bundle order, joined by `\n`, no trailing newline); `null` when they grant none | | `models[].parity_qualifications` | `[]` unless the model is declared; then one object per declared mode family (in byte order: `pipeline`, then `tensor_parallel`) and schedule (ascending), with the fields below. At most 8 | | `…schedule` | `1` or `2`: the derived approval it qualifies | @@ -1101,7 +1101,7 @@ pair's placement; [serving a pair](cluster-control-protocol.md#serving-a-pair)). | Lifetime | A saved approval with more than `renewWithinSeconds = 86_400` left is kept. Within that day a later matching entry replaces it. An entry that the operator replaced under the same `id` (other bytes, for example a new `not_after`) is no longer the saved approval: a matching entry replaces it, else it is withdrawn (Serve locally). An ended one is removed: each Mac saves its setup without it before its part starts, and its part then serves on the leader's local API (`ClusterService.supervise`) | `ClusterApprovalLifetime.decide` | | Serve locally | Both Macs save their setups without the approval, the other Mac first, and the pair serves on the leader's local API, when: no request gets an HTTP answer for the absence grace (`ClusterService.soloGraceSeconds`: 600 s; `DARKBLOOM_DEBUG_CLUSTER_SOLO_GRACE_SECONDS` in a development build); the coordinator answers (a 404, or a list) without the saved approval as saved and serves no other matching entry; or either Mac's coordinator-paired parts ended `ClusterControlSoloAdmission.maximumQuickEnds = 3` times in a row right after starting (each Mac's status, `memberQuickEnds`). An end the coordinator decided is not counted: one because it was out of reach (`ClusterMemberControlError.coordinatorUnreachable`, which also starts the count again) or because it did not accept the member role in its negotiation window (`negotiationFailed`, which leaves the count as it is; a part that ran `quickEndSeconds = 120` or longer starts it again, as always) (`ClusterApprovalCheck.memberQuickEnds`). It complements a coordinator that ends each pair session before its shutdown closes the members' connections, which makes a deploy's ends cleaner; the rule still covers coordinators without that change, coordinator crashes and slow negotiation. When either Mac cannot save, both keep the approval and the next check tries again. The leader keeps the approval, the reason, the setup's worker digest and the time in its setup record (`approvalSetAside`, `runtimeBinarySHA256`, `setAt`). When an answer lists a matching entry, the pair is registered again through the Save step; after repeated failures, a later entry at once, the same entry `ClusterApprovalFallback.failingSeconds = 3_600` after it was set aside, or the same entry after an update installs another worker. A record without `setAt` (an older build's) is past that bound | `ClusterApprovalCheck.step`, `ClusterApprovalSync.serveLocally`; `ClusterService.checkApproval` | | Both or neither | A send whose reply is lost may come after the other Mac saved: the leader gives it its setup back. Each Mac's status names its saved cluster approval (`approvalID`, `""` for none; a build without the field is unknown and never compared). On every check the leader compares it with its own; while they differ, it gives the other Mac its approval (while offered) or none, and saves its own setup without an approval it does not offer; when the other Mac refuses its approval, it saves its own setup without it too | `ClusterApprovalCheck.peerApprovalID`, `macsDiffer`, `ClusterApprovalSync.converge` | -| Changing | The leader decides under the command lock, from the setup, record and the other Mac's status as they are then. A save is first checked against the leader's own files and with every rule the save applies to the setup with the approval attached (`ClusterConfiguration.validate`, which refuses a saved `tensorAssistant` beside `nativeMember`: "Qwen's speculative assistant serves local clusters only …", `tensorAssistantServesLocally`), so no part stops and nothing is sent for an approval either Mac must refuse. A busy command lock waits for the next check, a minute later | `ClusterService.checkApproval`, `ClusterApprovalSync.apply`, `ClusterApprovalAttachment.attachment` | +| Changing | The leader decides under the command lock, from the setup, record and the other Mac's status as they are then. A save is first checked against the leader's own files and with every rule the save applies to the setup with the approval attached (`ClusterConfiguration.validate`, which refuses a saved `tensorAssistant` beside `nativeMember` unless it is exactly the assistant the build declares public for the artifact: "Qwen's speculative assistant serves local clusters only unless this build declares it public …", `tensorAssistantServesLocally`), so no part stops and nothing is sent for an approval either Mac must refuse. A busy command lock waits for the next check, a minute later | `ClusterService.checkApproval`, `ClusterApprovalSync.apply`, `ClusterApprovalAttachment.attachment` | A coordinator that answers 404, serves no matching entry or serves only ended entries leaves both saved setups byte for byte as they were: nothing is sent @@ -1632,8 +1632,8 @@ Normal setup discovers the embedded assistant from the native quote on a cluster | Setting | Bound and behavior | Source | |---|---|---| -| `[backend] mtp_mode` | Selects embedded-assistant discovery for the 9B and the 27B (`ClusterQwenTensorAssistantPolicy.runtimeModelIDs`) by how the cluster serves (`ClusterServingScope`): `auto` (default) discovers it for a cluster that serves locally only (`darkbloom cluster local`) and plans a cluster served through Darkbloom without it, as the re-plans after an update or a memory refusal do; `on` discovers it either way, and a cluster served through Darkbloom then is not offered to the coordinator (its public-traffic line says so, `ClusterPairOwnerServing.tensorAssistantNotOffered`); `off` retains the ordinary fully quoted target. Automatic discovery selects depth `3` and admitted-cohort verification. The developer six-step wizard and `darkbloom cluster plan` discover it as for a local cluster. | `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift`, `discoveryMode`, `automaticCandidate`, `automaticDepth`; `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift` (`OnboardingLive.localPlanModels`) | -| Saved `tensorAssistant` | Optional `qwen27_tensor_assistant_v1` object containing `depth` 1...4 and native `inventorySHA256`; omitted policy preserves legacy ordinary setup bytes. Never beside `nativeMember`: such a setup is refused when saved or loaded ("Qwen's speculative assistant serves local clusters only …"), and the leader refuses a coordinator's approval for it before any part stops. | `libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterQwenTensorAssistantPolicy.swift`, `ClusterQwenTensorAssistantPolicy`; `provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift` (`tensorAssistantServesLocally`) | +| `[backend] mtp_mode` | Selects embedded-assistant discovery for the 9B and the 27B (`ClusterQwenTensorAssistantPolicy.runtimeModelIDs`) by how the cluster serves (`ClusterServingScope`): `auto` (default) discovers it for a cluster that serves locally only (`darkbloom cluster local`) and plans a cluster served through Darkbloom with the assistant the build declares public for the artifact (`ClusterPublicModels.tensorAssistant`: its depth, singleton verification) or, when none is declared, without one, as the re-plans after an update or a memory refusal do; `on` discovers it either way, and a cluster served through Darkbloom whose assistant is not declared is then not offered to the coordinator (its public-traffic line says so, `ClusterPairOwnerServing.tensorAssistantNotOffered`); `off` retains the ordinary fully quoted target. Automatic discovery for a local cluster selects depth `3` and admitted-cohort verification. The developer six-step wizard and `darkbloom cluster plan` discover it as for a local cluster. | `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift`, `discoveryMode`, `automaticCandidate`, `automaticDepth`; `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift` (`OnboardingLive.localPlanModels`) | +| Saved `tensorAssistant` | Optional `qwen27_tensor_assistant_v1` object containing `depth` 1...4 and native `inventorySHA256`; omitted policy preserves legacy ordinary setup bytes. Beside `nativeMember` only as the exact policy the build declares public for the artifact (`ClusterPublicModels.tensorAssistant`; this build declares none): any other is refused when saved or loaded ("Qwen's speculative assistant serves local clusters only unless this build declares it public …"), and the leader refuses a coordinator's approval for it before any part stops. | `libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterQwenTensorAssistantPolicy.swift`, `ClusterQwenTensorAssistantPolicy`; `provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift` (`tensorAssistantServesLocally`) | | Saved `tensorAssistant.verification` | `singleton_ready_set_v1` is the omitted legacy value; `admitted_target_cohort_v1` verifies eligible rows together up to the completely priced capacity. Unknown/null values are refused. | `libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterQwenTensorAssistantPolicy.swift`, `Verification` | | Native worker `--mtp-depth`, `--tp-mtp-inventory-sha256`, `--tp-mtp-verification` | Installed launch arguments derived from saved policy, bilaterally bound at LOAD. Normal setup does not ask the user to choose them. | `provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledGenerationSelection.swift`; `libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Startup/WorkerConfiguration.swift` | | `DARKBLOOM_QWEN_MTP_SERIAL`, `DARKBLOOM_QWEN_MTP_DOUBLE_FORWARD`, `DARKBLOOM_QWEN_MTP_SHORTLIST` | True serial/double-forward overrides and any shortlist setting other than `0` conflict with this TP policy and are refused; complete vocabulary scores and captured target settlement remain authoritative. | `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPolicy.swift`, `require` | diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift b/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift index eb481decf4..4d2acaf069 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift @@ -104,13 +104,14 @@ public struct ClusterConfiguration: Codable, Sendable, Equatable { /// run different Darkbloom builds); the onboarding says it in plain words (`ClusterSetupPlanning.differentBuilds`). static let peerBuildDiffers = "Peer native build differs from the capability" - /// The refusal of a tensor assistant beside `nativeMember`. Its speculative decoding has no parity qualification, - /// so it serves local clusters only; the guided setup plans a cluster served through Darkbloom without it under - /// `auto` (`ClusterPlacementTensorAssistantSelection.discoveryMode`). The leader's check of a coordinator's - /// approval runs this rule before any part stops (`ClusterApprovalAttachment.attachment`). Short enough to reach - /// the leader whole through the other Mac's refusal (`ClusterSetupFailure` keeps 240 characters). - static let tensorAssistantServesLocally = "Qwen's speculative assistant serves local clusters only (not qualified for " - + "public traffic); with mtp_mode \"auto\", press m in `darkbloom cluster` to plan without it" + /// The refusal of a tensor assistant beside `nativeMember` that this build does not declare public for the + /// artifact (`ClusterPublicModels.tensorAssistant`, the exact policy: depth, inventory and singleton verification). + /// Under `auto` the guided setup plans a cluster served through Darkbloom with the declared assistant or without + /// one (`ClusterPlacementTensorAssistantSelection.readAutomatic`). The leader's check of a coordinator's approval + /// runs this rule before any part stops (`ClusterApprovalAttachment.attachment`). Short enough to reach the leader + /// whole through the other Mac's refusal (`ClusterSetupFailure` keeps 240 characters). + static let tensorAssistantServesLocally = "Qwen's speculative assistant serves local clusters only unless this build " + + "declares it public; with mtp_mode \"auto\", press m in `darkbloom cluster` to plan without it" func validate(capability: ClusterRuntimeCapability, rawCapabilitySHA256: String) throws { func require(_ value: Bool, _ message: String) throws { @@ -171,7 +172,8 @@ public struct ClusterConfiguration: Codable, Sendable, Equatable { && selectedGenerationMode == .tensorParallel && selectedPrefillSchedule == .serial && !capability.hasPrivateImages, "A tensor assistant requires Qwen TP on a row with an inline head and serial prefill") - try require(nativeMember == nil, Self.tensorAssistantServesLocally) + try require(nativeMember == nil || ClusterPublicModels.tensorAssistant(for: capability)?.policy == tensorAssistant, + Self.tensorAssistantServesLocally) } try require(ClusterConfigurationSyntax.ipv4(coordinator.address) && (1...65535).contains(coordinator.port), "Invalid JACCL coordinator address") if let linkControl { diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts+Release.swift b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts+Release.swift index 8e43fc4489..135dede7cd 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts+Release.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts+Release.swift @@ -51,7 +51,7 @@ extension ClusterRuntimeApprovalFacts { /// at all, and when no model is left (naming what was left out). public static func release(installation: Installation, candidates: [ModelFiles], models: [ReleaseModel] = ClusterRuntimeApprovalFacts.releaseModels, - publicModels: [ClusterPublicModel] = ClusterPublicModels.declared, + publicModels: [ClusterPublicModel] = ClusterPublicModels.current, decisions: ClusterPairServingDecisions = ClusterPairServingGrants.decisions, note: (String) -> Void = { _ in }) throws -> Self { let installed = try HashedInstallation(installation) diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift index dc8dcd80d5..ae17d9db82 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift @@ -257,9 +257,10 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { /// The facts of `installation` for exactly `models`: a model `publicModels` /// declare (this build's declaration by default) has the declared grant and /// parity qualifications, any other the grant of `decisions` (this build's - /// bundled records by default). + /// bundled records by default). A resident assistant `publicModels` declare + /// for a model's artifact is part of its resource policy. public static func compute(installation: Installation, models: [ModelFiles], - publicModels: [ClusterPublicModel] = ClusterPublicModels.declared, + publicModels: [ClusterPublicModel] = ClusterPublicModels.current, decisions: ClusterPairServingDecisions = ClusterPairServingGrants.decisions) throws -> Self { let installed = try HashedInstallation(installation) return try installed.facts(models.map { try installed.describe($0, publicModels: publicModels, decisions: decisions).entry }) @@ -292,9 +293,13 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { grant = try (try? ClusterPairServingGrants.grant(runtimeModelID: capability.runtimeModelID, publicModelID: artifact.modelID, artifactSHA256: capability.artifactSHA256, decisions: decisions)).map(PairServingGrant.init) } + // The member's own start computes the same digest from the same declaration (`DistributedInstalledNativeStart`). + let assistant = ClusterPublicModels.tensorAssistant(runtimeModelID: capability.runtimeModelID, + artifactSHA256: capability.artifactSHA256, in: publicModels) return Described(entry: Model(model: artifact.modelID, artifactSHA256: capability.artifactSHA256, capabilitySHA256: ClusterConfigurationCodec.sha256(bytes), profileSHA256: capability.profileFingerprint, - resourcePolicySHA256: NativePairMemberPolicy.hex(DistributedInstalledNativeStart.resourcePolicySHA256(capability)), + resourcePolicySHA256: NativePairMemberPolicy.hex(DistributedInstalledNativeStart.resourcePolicySHA256(capability, + assistant: assistant)), pairServingGrant: grant, parityQualifications: declared.map { parityQualifications($0, metallibSHA256: metallibSHA256, inputModalities: inputModalities, layers: layerCount(configuration), diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift index be47f2ab48..01ed848bc0 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift @@ -560,9 +560,9 @@ final class LiveContext: @unchecked Sendable { let mtpMode: MTPMode do { mtpMode = try ConfigManager.loadOrDefaults(from: settings.providerConfiguration).backend.mtpMode } catch { return .failed("The provider configuration could not be read: \(clean(ClusterConsoleText.bounded(error)))") } - // A setup that serves through the coordinator carries no speculative assistant: under `auto` its plan quotes - // the ordinary target only. - let discovery = ClusterPlacementTensorAssistantSelection.discoveryMode(mtpMode, coordinator: coordinator) + // A setup that serves through the coordinator carries only the speculative assistant this build declares + // public for the artifact: under `auto` its plan quotes that one, or the ordinary target only + // (`ClusterPlacementTensorAssistantSelection.discoveryMode`). let readings = models.filter { settings.privateGLMImageQualification ? ClusterGLMOnboardingSelection.accepts($0) : ClusterMiMoOnboardingSelection.accepts($0, qualifying: settings.privateMiMoImageQualification) @@ -615,14 +615,14 @@ final class LiveContext: @unchecked Sendable { } else { let discovered = try ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool, modelDirectory: directory, publicModelID: model.modelID, capability: admitted, - mode: discovery, chunkTokens: chunk, deadline: deadline()) + mode: mtpMode, chunkTokens: chunk, deadline: deadline(), coordinator: coordinator) assistantQuote = discovered.map { .success($0) } // Capacity changes keep the shares, so the first widening's complete // quote steers the initial split; without it the choice is speed-only. if discovered != nil { discoveredWidening = try? ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool, modelDirectory: directory, publicModelID: model.modelID, capability: admitted, - mode: discovery, chunkTokens: chunk, deadline: deadline(), lanes: 2) + mode: mtpMode, chunkTokens: chunk, deadline: deadline(), lanes: 2, coordinator: coordinator) } // Only a discovered assistant may give way to the ordinary target (`assistantOrTarget`). if discovered?.assistant != nil { diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift index bbc2914c27..9a07533cde 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift @@ -18,6 +18,10 @@ public struct ClusterPublicModel: Sendable, Equatable { public let schedules: [UInt8] /// The ranks of the evidence placement. public let ranks: Ranks + /// The resident assistant the owner declared public for this artifact's + /// tensor-parallel placement; nil (every model today) keeps a setup saved + /// for coordinator pairing without one. + public var tensorAssistant: ClusterPublicTensorAssistant? = nil /// The evidence placement's ranks: how many, each on one GPU architecture /// and macOS version. @@ -30,6 +34,35 @@ public struct ClusterPublicModel: Sendable, Equatable { } } +/// A resident assistant the owner declared public for one model's tensor +/// parallel placement: the exact policy a coordinator-paired setup must save +/// (depth, the inline head's inventory, singleton verification) and the +/// evidence document it rests on, whose SHA-256 is `evidenceSHA256` (a test +/// holds them equal). +public struct ClusterPublicTensorAssistant: Sendable, Equatable { + public let policy: ClusterQwenTensorAssistantPolicy + public let evidenceDocument: String + public let evidenceSHA256: String + + public init(policy: ClusterQwenTensorAssistantPolicy, evidenceDocument: String, evidenceSHA256: String) throws { + try policy.validate() + guard policy.verification == .singleton, ClusterConfigurationSyntax.hash(evidenceSHA256), + evidenceDocument.hasPrefix("docs/reports/"), evidenceDocument.hasSuffix(".md") else { + throw ClusterConfigurationError.invalid("A public tensor assistant declares singleton verification and its evidence report") + } + self.policy = policy; self.evidenceDocument = evidenceDocument; self.evidenceSHA256 = evidenceSHA256 + } + + /// What the declaration adds to the resource policy a native start and a + /// release's facts carry (`DistributedInstalledNativeStart.resourcePolicySHA256`): + /// the arguments both workers are launched with. + var resourcePolicyFields: [String] { + [ClusterQwenTensorAssistantPolicy.schemaName, "depth=\(policy.depth)", + "\(ClusterQwenTensorAssistantPolicy.inventoryArgument)=\(policy.inventorySHA256)", + "verification=\(policy.verification.rawValue)", "evidence=\(evidenceSHA256)"] + } +} + /// The models whose clusters serve public traffic: the owner's declaration /// (jonathan308, 2026-10-31: "public traffic should not be manual"; "only glm /// 5.3 flash should be serving public & qwen 3.8 27b they are both good to go @@ -103,6 +136,31 @@ public enum ClusterPublicModels { == model.artifactSHA256 }) ?? true else { return [] } return model.families } + + /// A test's own declaration (nil: `declared`). Never set by a product + /// path: a build's public models and assistants change only with + /// `declared` and their evidence reports. + @TaskLocal static var declarationOverride: [ClusterPublicModel]? + /// `declared`, or a test's own declaration. + public static var current: [ClusterPublicModel] { declarationOverride ?? declared } + + /// The resident assistant `models` declare public for a runtime model's + /// installed artifact (mapped as grants map it), with tensor parallel + /// among its declared families; nil for any other model, artifact or a + /// model declared without one. + static func tensorAssistant(runtimeModelID: String, artifactSHA256: String, + in models: [ClusterPublicModel] = current) -> ClusterPublicTensorAssistant? { + guard let model = models.first(where: { $0.runtimeModelID == runtimeModelID }), + model.families.contains(.tensorParallel), + ClusterPairServingGrants.qualifyingArtifact(for: artifactSHA256, runtimeModelID: runtimeModelID) + == model.artifactSHA256 else { return nil } + return model.tensorAssistant + } + + /// `tensorAssistant` of a capability record's model and artifact. + static func tensorAssistant(for capability: ClusterRuntimeCapability) -> ClusterPublicTensorAssistant? { + tensorAssistant(runtimeModelID: capability.runtimeModelID, artifactSHA256: capability.artifactSHA256) + } } /// The request shape a qualified placement serves to the public, as a parity diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledNativeStart.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledNativeStart.swift index e3ae3dc016..cd6d51fc96 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledNativeStart.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledNativeStart.swift @@ -23,10 +23,21 @@ enum DistributedInstalledNativeStart { /// The resource policy a native start carries for a capability. The one /// formula: the native start below and the release's cluster runtime - /// facts (`ClusterRuntimeApprovalFacts`) both call it. + /// facts (`ClusterRuntimeApprovalFacts`) both call it. A resident assistant + /// this build declares public for the artifact (`ClusterPublicModels.tensorAssistant`) + /// adds its launch arguments (depth, `--tp-mtp-inventory-sha256`, + /// verification) and evidence, so a coordinator's approval, and every + /// start under it, names the declared assistant; without one the digest + /// is unchanged. static func resourcePolicySHA256(_ capability: ClusterRuntimeCapability) -> Data { + resourcePolicySHA256(capability, assistant: ClusterPublicModels.tensorAssistant(for: capability)) + } + + /// `resourcePolicySHA256` with the public assistant a given declaration names. + static func resourcePolicySHA256(_ capability: ClusterRuntimeCapability, assistant: ClusterPublicTensorAssistant?) -> Data { digest(["darkbloom/installed-resource-policy/v1", capability.arithmeticPolicyID, - capability.arithmeticPolicySHA256, capability.stateSemantics, capability.schedulingPolicy]) + capability.arithmeticPolicySHA256, capability.stateSemantics, capability.schedulingPolicy] + + (assistant?.resourcePolicyFields ?? [])) } /// The runtime block a member registers in its plan for a model diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift index 5fba413b74..236cea50ba 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift @@ -661,16 +661,21 @@ public enum ClusterPairServingGrants { /// The one line a plan or the onboarding shows about public traffic for a /// model served in `mode`: qualified in the families its records grant or /// the owner declared public (`ClusterPublicModels`), unless the placement - /// decodes with Qwen's speculative assistant (`tensorAssistant`), which no - /// qualification covers. + /// decodes with Qwen's speculative assistant (`tensorAssistant`) and the + /// owner declared none public for the artifact + /// (`ClusterPublicModels.tensorAssistant`; a setup saved for coordinator + /// pairing carries exactly the declared one, `ClusterConfiguration.validate`). public static func publicTrafficLine(runtimeModelID: String, artifactSHA256: String? = nil, mode: ClusterGenerationMode?, tensorAssistant: Bool = false, decisions: ClusterPairServingDecisions = decisions, - publicModels: [ClusterPublicModel] = ClusterPublicModels.declared) -> String { + publicModels: [ClusterPublicModel] = ClusterPublicModels.current) -> String { let grant = try? grant(runtimeModelID: runtimeModelID, publicModelID: runtimeModelID, artifactSHA256: artifactSHA256, decisions: decisions) + let declaredAssistant = artifactSHA256.flatMap { + ClusterPublicModels.tensorAssistant(runtimeModelID: runtimeModelID, artifactSHA256: $0, in: publicModels) + } return ClusterPairOwnerServing.publicTrafficLine(grant: grant, declared: ClusterPublicModels.families( runtimeModelID: runtimeModelID, artifactSHA256: artifactSHA256, in: publicModels), mode: mode, - tensorAssistant: tensorAssistant) + tensorAssistant: tensorAssistant && declaredAssistant == nil) } /// One rank of a placement, checked on the Mac that runs it with that @@ -786,8 +791,8 @@ public struct ClusterPairOwnerServing: Sendable, Equatable { /// The one line shown for a model or placement with no public grant. public static let notYetQualified = "not yet qualified for public traffic" /// The one line shown for a placement of a qualified model and mode that decodes with Qwen's speculative - /// assistant: the assistant serves local clusters only, so the setup is never offered to the coordinator - /// (`ClusterConfiguration.tensorAssistantServesLocally`). + /// assistant this build does not declare public: such an assistant serves local clusters only, so the setup is + /// never offered to the coordinator (`ClusterConfiguration.tensorAssistantServesLocally`). public static let tensorAssistantNotOffered = "not offered for public traffic: it decodes with Qwen's speculative " + "assistant, which serves local clusters only (with [backend] mtp_mode \"auto\", a cluster served through Darkbloom is planned without it)" 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 76dd399aba..5b270fcf9e 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift @@ -132,9 +132,10 @@ enum ClusterApprovalAttachment { resourceLibraryPath: tools.resourceLibrary.path, clusterApproval: approval, roster: paired.roster, memberPins: paired.pins, edges: edge.map { [$0] }) // Every check the save runs on the setup with the attachment, as at every load: the approval names this setup's - // model, artifact and schedule (and a build-pinned one its runtime, capability and profile), the roster's pins - // are its members in rank order, and nothing the setup carries is refused beside an approval (a tensor - // assistant serves local clusters only). So no part stops for an approval either Mac must refuse at the save. + // model, artifact and schedule (and a build-pinned one its runtime, capability, profile and resource policy, + // which carries any resident assistant this build declares public), the roster's pins are its members in rank + // order, and nothing the setup carries is refused beside an approval (a tensor assistant only as this build + // declares it public). So no part stops for an approval either Mac must refuse at the save. try configuration.replacingNativeMember(attachment).validate(capability: saved.capability, rawCapabilitySHA256: configuration.capabilitySHA256) return attachment diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift index 1b2ad56cee..67c317fa33 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift @@ -38,13 +38,14 @@ enum ClusterPlacementTensorAssistantSelection { static let automaticDepth = 3 /// The `backend.mtp_mode` discovery runs under for a plan whose setup serves through the coordinator - /// (`coordinator`) or on a local cluster. The assistant's speculative decoding has no parity qualification, so a - /// setup saved for coordinator pairing carries none (`ClusterConfiguration.tensorAssistantServesLocally`): under - /// `auto` such a plan quotes the ordinary target only. `on` is the operator's explicit choice and is kept; the - /// plan then says it is not offered for public traffic, and the leader refuses the coordinator's approval before - /// any part stops. - static func discoveryMode(_ configured: MTPMode, coordinator: Bool) -> MTPMode { - coordinator && configured == .auto ? .off : configured + /// (`coordinator`) or on a local cluster. A setup saved for coordinator pairing carries only the assistant this + /// build declares public for the artifact (`declared`, `ClusterPublicModels.tensorAssistant`; + /// `ClusterConfiguration.tensorAssistantServesLocally`): under `auto` such a plan quotes the declared assistant, + /// or the ordinary target only when none is declared. `on` is the operator's explicit choice and is kept; without + /// a declaration the plan then says it is not offered for public traffic, and the leader refuses the + /// coordinator's approval before any part stops. + static func discoveryMode(_ configured: MTPMode, coordinator: Bool, declared: Bool = false) -> MTPMode { + coordinator && configured == .auto && !declared ? .off : configured } static func automaticCandidate(mode: MTPMode, runtimeModelID: String, @@ -69,24 +70,30 @@ enum ClusterPlacementTensorAssistantSelection { } } + /// `declared`: the public assistant a coordinator-paired setup plans (its depth, singleton verification); nil + /// plans a local cluster's automatic assistant (`automaticDepth`, admitted target cohorts). static func discoveryArguments(modelDirectory: String, promptTokens: Int, outputTokens: Int, - chunkTokens: Int, assistant: Bool = true, lanes: Int = 1) throws -> [String] { + chunkTokens: Int, assistant: Bool = true, lanes: Int = 1, + declared: ClusterQwenTensorAssistantPolicy? = nil) throws -> [String] { guard promptTokens > 0, outputTokens > 0, (1...512).contains(chunkTokens), lanes == 1 || ClusterPlacementBatchScope.tensorParallelWidths.contains(lanes) else { throw ClusterConfigurationError.invalid("Invalid automatic tensor assistant quotation scope") } + let planned = declared.map { ["--mtp-depth", String($0.depth)] + $0.verificationArguments } + ?? ["--mtp-depth", String(automaticDepth), ClusterQwenTensorAssistantPolicy.verificationArgument, + ClusterQwenTensorAssistantPolicy.Verification.admittedCohort.rawValue] return ["tensor-batch-scope", "--model-dir", modelDirectory, "--prompt-tokens", String(promptTokens), "--output-tokens", String(outputTokens), - "--batch-lanes", String(lanes), "--chunk-size", String(chunkTokens)] + (assistant ? ["--mtp-depth", String(automaticDepth), - ClusterQwenTensorAssistantPolicy.verificationArgument, - ClusterQwenTensorAssistantPolicy.Verification.admittedCohort.rawValue] : []) + "--batch-lanes", String(lanes), "--chunk-size", String(chunkTokens)] + (assistant ? planned : []) } /// The quote prices the memory plan's whole request (`ClusterWorkerProfile.memoryScope`): - /// the profile's, or the standard request for a row that serves its native context. + /// the profile's, or the standard request for a row that serves its native context. A `declared` public + /// assistant must come back exactly as declared: the native helper's inventory of the installed head is the + /// one the owner's evidence ran. static func requireDiscoveredQuote(_ quote: ClusterPlacementTensorBatchQuote, capability: ClusterRuntimeCapability, chunkTokens: Int, assistant: Bool = true, - lanes: Int = 1) throws { + lanes: Int = 1, declared: ClusterQwenTensorAssistantPolicy? = nil) throws { try quote.validate() let memory = capability.profile.memoryScope try quote.requireRequest(promptTokens: memory.maximumPromptTokens, @@ -100,31 +107,46 @@ enum ClusterPlacementTensorAssistantSelection { throw ClusterConfigurationError.invalid("Native discovery changed the tensor owner's artifact or complete request scope") } if assistant { - guard let policy = quote.assistant?.policy, policy.depth == automaticDepth, - policy.verification == .admittedCohort else { + guard let policy = quote.assistant?.policy else { throw ClusterConfigurationError.invalid("Native discovery changed the embedded assistant's verification policy") } + if let declared { + guard policy == declared else { + throw ClusterConfigurationError.invalid("The embedded assistant differs from this build's public declaration") + } + } else { + guard policy.depth == automaticDepth, policy.verification == .admittedCohort else { + throw ClusterConfigurationError.invalid("Native discovery changed the embedded assistant's verification policy") + } + } } else { try quote.requireAssistant(nil) } } /// Every Qwen TP row's request-owned owner reserves its quote at LOAD, /// so each row is quoted (its target alone where it has no assistant). + /// `coordinator`: the setup serves through the coordinator, so only the + /// assistant this build declares public for the artifact is planned, with + /// its declared depth and singleton verification (`discoveryMode`). static func readAutomatic(tool: URL, modelDirectory: URL, publicModelID: String, capability: ClusterRuntimeCapability, mode: MTPMode, - chunkTokens: Int, deadline: UInt64, lanes: Int = 1, + chunkTokens: Int, deadline: UInt64, lanes: Int = 1, coordinator: Bool = false, environment: [String: String] = ProcessInfo.processInfo.environment) throws -> ClusterPlacementTensorBatchQuote? { guard ClusterPlacementTensorBatchQuote.runtimeModelIDs.contains(capability.runtimeModelID), capability.supportedGenerationModes.contains(.tensorParallel), !capability.hasPrivateImages else { return nil } - let assistant = try automaticCandidate(mode: mode, runtimeModelID: capability.runtimeModelID, + let declared = coordinator ? ClusterPublicModels.tensorAssistant(for: capability)?.policy : nil + let assistant = try automaticCandidate(mode: discoveryMode(mode, coordinator: coordinator, declared: declared != nil), + runtimeModelID: capability.runtimeModelID, modelDirectory: modelDirectory, publicModelID: publicModelID, artifactSHA256: capability.artifactSHA256, manifestSHA256: capability.manifestSHA256, environment: environment) let memory = capability.profile.memoryScope let quote = try ClusterPlacementTensorBatchQuote.decode(DistributedCapabilityProbe.run(executable: tool, arguments: discoveryArguments(modelDirectory: modelDirectory.path, promptTokens: memory.maximumPromptTokens, outputTokens: memory.maximumOutputTokens, - chunkTokens: chunkTokens, assistant: assistant, lanes: lanes), deadline: deadline, maximumOutputBytes: ClusterPlacementTensorBatchQuote.maximumEncodedBytes)) - try requireDiscoveredQuote(quote, capability: capability, chunkTokens: chunkTokens, assistant: assistant, lanes: lanes) + chunkTokens: chunkTokens, assistant: assistant, lanes: lanes, declared: declared), deadline: deadline, + maximumOutputBytes: ClusterPlacementTensorBatchQuote.maximumEncodedBytes)) + try requireDiscoveredQuote(quote, capability: capability, chunkTokens: chunkTokens, assistant: assistant, lanes: lanes, + declared: declared) return quote } diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+MTP.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+MTP.swift index 740a265d6f..0eed3d6446 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+MTP.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+MTP.swift @@ -69,6 +69,11 @@ extension EngineV2Bridge { /// takes the engine's metrics lock; this adapter never reaches controller /// mutation or the inference loop. public func mtpStatusSnapshot() -> ProviderMTPStatusSnapshot { + // A cluster pair published with its resident assistant (`publishClusterPairSlot`): the counts rank 0's + // runtime reported request by request (`DistributedCBv2Engine.mtpTotalsSnapshot`). + if mtpActivationStatus.configured, let pair = ownedEngine as? DistributedCBv2Engine { + return ProviderMTPStatusSnapshot(pair: pair.mtpTotalsSnapshot(), placementDecodesWithHead: true) + } let metrics = (ownedEngine as? EngineV2)?.mtpMetricsSnapshot() return ProviderMTPStatusSnapshot(status: mtpActivationStatus, metrics: metrics) } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift index 75ffa88bee..e01facb6e2 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift @@ -193,6 +193,12 @@ extension ProviderLoop { modelDirectory: specification.modelDirectory, pairTelemetry: specification.pairTelemetry) } catch { throw ClusterPairSlotError.ownerUnavailable } guard let bridge = entry.engineV2Bridge else { throw ClusterPairSlotError.ownerUnavailable } + // The pair's MTP posture (heartbeats, `darkbloom status`): ranks whose readiness names the resident assistant + // they loaded (`ClusterQwenTensorAssistantReady`) decode with it; any other pair keeps the disabled posture. + if ready.tensorAssistant != nil { + await bridge.configureMTPStatus(.init(configured: true, active: true, reason: nil, source: nil, revision: nil, + artifactBytes: 0, assistantBytes: 0)) + } let profile = specification.profile let sizing = SlotSizingSnapshot(weightsBytes: specification.artifactBytes, fp16KVBytesPerToken: 0, maxContextLength: profile.maxContextTokens, diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterPublicTensorAssistantTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterPublicTensorAssistantTests.swift new file mode 100644 index 0000000000..6775122438 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterPublicTensorAssistantTests.swift @@ -0,0 +1,202 @@ +import CryptoKit +import Foundation +import Testing +import DarkbloomClusterProtocol +import DarkbloomClusterSecurity +@testable import ProviderCore + +/// Qwen3.8 27B's resident assistant on a coordinator-formed pair, once a build declares it public +/// (`ClusterPublicModels.tensorAssistant`): the declaration, the setup's own checks beside a cluster approval, the +/// resource policy that release facts, the approval and each committed start carry, and the guided setup's planning +/// under `auto`. This build declares no assistant; each test declares one for the fixture's artifact +/// (`ClusterPublicModels.declarationOverride`), never a product path. +@Suite("Public Qwen tensor assistant", .serialized) +struct ClusterPublicTensorAssistantTests { + static let report = "docs/reports/2026-11-01-qwen27-public-assistant.md" + + static func policy(depth: Int = 3, inventory: Character = "8", + verification: ClusterQwenTensorAssistantPolicy.Verification = .singleton) throws -> ClusterQwenTensorAssistantPolicy { + try ClusterQwenTensorAssistantPolicy(depth: depth, inventorySHA256: ClusterApprovalMacs.hash(inventory), verification: verification) + } + + /// This build's declaration with the fixture's Qwen3.8 27B artifact (`ClusterApprovalMacs.capability`) declared + /// in both families, carrying `assistant`. + static func declaration(_ assistant: ClusterQwenTensorAssistantPolicy?, artifact: Character = "b") throws -> [ClusterPublicModel] { + var model = ClusterPublicModel(runtimeModelID: ClusterQwenTensorAssistantPolicy.runtimeModelID, catalogModelID: ClusterApprovalMacs.model, + artifactSHA256: ClusterApprovalMacs.hash(artifact), families: [.pipeline, .tensorParallel], schedules: [1, 2], + ranks: ClusterPublicModels.twoM5Ultras) + model.tensorAssistant = try assistant.map { + try ClusterPublicTensorAssistant(policy: $0, evidenceDocument: report, evidenceSHA256: ClusterApprovalMacs.hash("d")) + } + return [model] + } + + /// The facts both installations have and the approval a coordinator derives from them, with the resource policy + /// of the fixture's capability as this build computes it under the current declaration. + static func factsAndApproval(_ macs: ClusterApprovalMacs) throws -> (ClusterRuntimeApprovalFacts, ClusterRuntimeApproval) { + let policy = NativePairMemberPolicy.hex(DistributedInstalledNativeStart.resourcePolicySHA256(macs.capability)) + let base = try macs.facts(), entry = base.models[0], template = macs.approval() + let facts = try ClusterRuntimeApprovalFacts(nativeRuntimeSHA256: base.nativeRuntimeSHA256, metallibSHA256: base.metallibSHA256, + resourceLibrarySHA256: base.resourceLibrarySHA256, placementPolicySHA256: base.placementPolicySHA256, + models: [.init(model: entry.model, artifactSHA256: entry.artifactSHA256, capabilitySHA256: entry.capabilitySHA256, + profileSHA256: entry.profileSHA256, resourcePolicySHA256: policy)]) + let approval = ClusterRuntimeApproval(id: template.id, model: template.model, generation: template.generation, + placementPolicySHA256: template.placementPolicySHA256, artifactSHA256: template.artifactSHA256, + nativeRuntimeSHA256: template.nativeRuntimeSHA256, metallibSHA256: template.metallibSHA256, + resourceLibrarySHA256: template.resourceLibrarySHA256, capabilitySHA256: template.capabilitySHA256, + resourcePolicySHA256: policy, profileSHA256: template.profileSHA256, schedule: template.schedule, + maximumTransportFrame: template.maximumTransportFrame, maximumPlaintext: template.maximumPlaintext, + maximumRecords: template.maximumRecords, maximumCumulativePlaintext: template.maximumCumulativePlaintext, + allowedNumericsClasses: template.allowedNumericsClasses, minimumMembers: template.minimumMembers, + maximumMembers: template.maximumMembers, minimumMemberUsableBytes: template.minimumMemberUsableBytes, + notAfter: template.notAfter) + return (facts, approval) + } + + @Test func aDeclarationNamesOnlySingletonVerificationAndAReport() throws { + let singleton = try Self.policy() + let declared = try ClusterPublicTensorAssistant(policy: singleton, evidenceDocument: Self.report, evidenceSHA256: ClusterApprovalMacs.hash("d")) + #expect(declared.resourcePolicyFields == ["qwen27_tensor_assistant_v1", "depth=3", + "--tp-mtp-inventory-sha256=" + ClusterApprovalMacs.hash("8"), "verification=singleton_ready_set_v1", + "evidence=" + ClusterApprovalMacs.hash("d")]) + #expect(throws: (any Error).self) { + try ClusterPublicTensorAssistant(policy: try Self.policy(verification: .admittedCohort), evidenceDocument: Self.report, + evidenceSHA256: ClusterApprovalMacs.hash("d")) + } + for (document, digest) in [("mainnet/qwen27.md", ClusterApprovalMacs.hash("d")), ("docs/reports/a.txt", ClusterApprovalMacs.hash("d")), + (Self.report, "not-a-digest")] { + #expect(throws: (any Error).self) { + try ClusterPublicTensorAssistant(policy: singleton, evidenceDocument: document, evidenceSHA256: digest) + } + } + } + + /// The lookup a setup's checks, its planning and every resource policy use: the declared model's artifact, in + /// tensor parallel, else nothing. This build declares none. + @Test func theDeclaredAssistantBelongsToItsArtifactAndTensorParallel() throws { + let declared = try Self.declaration(try Self.policy()) + let model = ClusterQwenTensorAssistantPolicy.runtimeModelID + #expect(ClusterPublicModels.tensorAssistant(runtimeModelID: model, artifactSHA256: ClusterApprovalMacs.hash("b"), in: declared)?.policy + == (try Self.policy())) + #expect(ClusterPublicModels.tensorAssistant(runtimeModelID: model, artifactSHA256: ClusterApprovalMacs.hash("c"), in: declared) == nil) + #expect(ClusterPublicModels.tensorAssistant(runtimeModelID: "registered_qwen35_9b", artifactSHA256: ClusterApprovalMacs.hash("b"), + in: declared) == nil) + var pipelineOnly = declared + pipelineOnly[0] = ClusterPublicModel(runtimeModelID: model, catalogModelID: ClusterApprovalMacs.model, + artifactSHA256: ClusterApprovalMacs.hash("b"), families: [.pipeline], schedules: [1, 2], ranks: ClusterPublicModels.twoM5Ultras, + tensorAssistant: declared[0].tensorAssistant) + #expect(ClusterPublicModels.tensorAssistant(runtimeModelID: model, artifactSHA256: ClusterApprovalMacs.hash("b"), in: pipelineOnly) == nil) + #expect(ClusterPublicModels.declared.allSatisfy { $0.tensorAssistant == nil }, "the owner declares an assistant with its evidence") + #expect(ClusterPublicModels.current == ClusterPublicModels.declared) + } + + /// The plan's public-traffic line: a tensor-parallel placement that decodes with the assistant is offered only + /// for an artifact whose assistant this build declares. + @Test func aPlanWithTheDeclaredAssistantSaysItIsQualifiedForPublicTraffic() throws { + func line(_ models: [ClusterPublicModel], assistant: Bool) -> String { + ClusterPairServingGrants.publicTrafficLine(runtimeModelID: ClusterQwenTensorAssistantPolicy.runtimeModelID, + artifactSHA256: ClusterApprovalMacs.hash("b"), mode: .tensorParallel, tensorAssistant: assistant, publicModels: models) + } + let declared = try Self.declaration(try Self.policy()), undeclared = try Self.declaration(nil) + #expect(line(declared, assistant: true).hasPrefix("qualified for public traffic in tensor parallel mode"), "\(line(declared, assistant: true))") + #expect(line(undeclared, assistant: true) == ClusterPairOwnerServing.tensorAssistantNotOffered) + #expect(line(undeclared, assistant: false) == line(declared, assistant: false)) + } + + /// Every assistant this build declares rests on a report whose SHA-256 the declaration names, as the model + /// declaration's own does. + @Test func everyDeclaredAssistantNamesItsReportsDigest() throws { + var repository = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + while repository.lastPathComponent != "provider-swift", repository.path != "/" { repository.deleteLastPathComponent() } + repository.deleteLastPathComponent() + for assistant in ClusterPublicModels.declared.compactMap(\.tensorAssistant) { + let report = try Data(contentsOf: repository.appendingPathComponent(assistant.evidenceDocument)) + #expect(assistant.evidenceSHA256 == SHA256.hash(data: report).map { String(format: "%02x", $0) }.joined(), + "\(assistant.evidenceDocument)") + } + } + + /// The resource policy is unchanged without a declaration (so every existing approval keeps its digest) and + /// carries the declared assistant's launch arguments with one: each of depth, inventory and verification changes it. + @Test func theResourcePolicyCarriesTheDeclaredAssistant() throws { + let capability = try ClusterApprovalMacs.capability(runtime: ClusterApprovalMacs.hash("a"), + shape: .qwen27TensorParallel(assistant: nil)) + func digest(_ fields: [String]) -> Data { Data(SHA256.hash(data: Data(fields.joined(separator: "\u{1F}").utf8))) } + let legacy = digest(["darkbloom/installed-resource-policy/v1", capability.arithmeticPolicyID, + capability.arithmeticPolicySHA256, capability.stateSemantics, capability.schedulingPolicy]) + #expect(DistributedInstalledNativeStart.resourcePolicySHA256(capability) == legacy) + let declared = try ClusterPublicTensorAssistant(policy: try Self.policy(), evidenceDocument: Self.report, + evidenceSHA256: ClusterApprovalMacs.hash("d")) + let assisted = DistributedInstalledNativeStart.resourcePolicySHA256(capability, assistant: declared) + #expect(assisted == digest(["darkbloom/installed-resource-policy/v1", capability.arithmeticPolicyID, + capability.arithmeticPolicySHA256, capability.stateSemantics, capability.schedulingPolicy] + declared.resourcePolicyFields)) + #expect(assisted != legacy) + try ClusterPublicModels.$declarationOverride.withValue(try Self.declaration(try Self.policy())) { + #expect(DistributedInstalledNativeStart.resourcePolicySHA256(capability) == assisted) + } + var variants: Set = [legacy, assisted] + for other in [try Self.policy(depth: 2), try Self.policy(inventory: "9")] { + variants.insert(DistributedInstalledNativeStart.resourcePolicySHA256(capability, assistant: + try ClusterPublicTensorAssistant(policy: other, evidenceDocument: Self.report, evidenceSHA256: ClusterApprovalMacs.hash("d")))) + } + variants.insert(DistributedInstalledNativeStart.resourcePolicySHA256(capability, assistant: + try ClusterPublicTensorAssistant(policy: try Self.policy(), evidenceDocument: Self.report, evidenceSHA256: ClusterApprovalMacs.hash("e")))) + #expect(variants.count == 5) + } + + /// With the declaration, the whole coordinator path admits the declared assistant: both Macs save the approval + /// beside it (each Mac's own check), and the plan's committed start and its runtime block (a model approval's) + /// carry the resource policy the release facts name. An assistant other than the declared one is refused. + @Test func onceDeclaredTheApprovalIsSavedBesideTheAssistantOnBothMacs() throws { + let declared = try Self.policy() + try ClusterPublicModels.$declarationOverride.withValue(try Self.declaration(declared)) { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider", + shape: .qwen27TensorParallel(assistant: declared)) + let (facts, approval) = try Self.factsAndApproval(macs) + let result = macs.sync(.approvals([approval]), leaderFacts: facts, followerFacts: facts) + #expect(result == .init(changed: true, line: ClusterApprovalLifetime.offeredLine(approval), note: .some(nil))) + for mac in macs.macs { + let saved = try macs.saved(mac) + #expect(saved.configuration.nativeMember?.clusterApproval == approval, "rank \(mac.rank) saved no approval") + #expect(saved.configuration.tensorAssistant == declared, "rank \(mac.rank)") + let plan = try DistributedInstalledPlan(saved: saved, paths: mac.paths) + let start = try DistributedInstalledNativeStart.common(plan: plan, epoch: UUID()) + guard case .servingV1(let serving) = start.permission else { Issue.record("not a serving start"); continue } + #expect(NativePairMemberPolicy.hex(serving.resourcePolicySHA256) == approval.resourcePolicySHA256) + #expect(DistributedInstalledNativeStart.runtimeBlock(plan: plan).resourcePolicySHA256 == approval.resourcePolicySHA256) + // The workers are launched with the declared assistant's arguments. + let arguments = try DistributedInstalledGenerationSelection.workerArguments(configuration: saved.configuration, + capability: saved.capability) + #expect(arguments.suffix(4) == ["--mtp-depth", "3", ClusterQwenTensorAssistantPolicy.inventoryArgument, + ClusterApprovalMacs.hash("8")]) + #expect(DistributedInstalledSpeculation(configuration: saved.configuration, capability: saved.capability) + == .init(enabled: true, offReason: DistributedInstalledSpeculation.enabledReason)) + } + // The release facts of the build that declared nothing name another resource policy: refused unchanged. + let undeclared = try ClusterPublicModels.$declarationOverride.withValue(try Self.declaration(nil)) { + try Self.factsAndApproval(macs) + } + #expect(undeclared.1.resourcePolicySHA256 != approval.resourcePolicySHA256) + } + } + + @Test func anAssistantOtherThanTheDeclaredOneIsRefusedBesideAnApproval() throws { + for (setup, declaredAssistant, artifact) in [ + (try Self.policy(depth: 2), try Self.policy(), Character("b")), + (try Self.policy(inventory: "9"), try Self.policy(), Character("b")), + (try Self.policy(verification: .admittedCohort), try Self.policy(), Character("b")), + (try Self.policy(), try Self.policy(), Character("c")), + ] { + try ClusterPublicModels.$declarationOverride.withValue(try Self.declaration(declaredAssistant, artifact: artifact)) { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider", + shape: .qwen27TensorParallel(assistant: setup)) + let (facts, approval) = try Self.factsAndApproval(macs) + let before = try macs.macs.map(macs.bytes) + let result = macs.sync(.approvals([approval]), leaderFacts: facts, followerFacts: facts) + #expect(!result.changed && result.line?.hasPrefix(ClusterApprovalTensorAssistantTests.refusedHere) == true + && result.line?.hasSuffix(ClusterConfiguration.tensorAssistantServesLocally) == true, "\(result.line ?? "")") + #expect(try macs.macs.map(macs.bytes) == before) + } + } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift index f4f253479c..d6e33f5947 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift @@ -769,25 +769,71 @@ final class DistributedAutomaticBatchPlannerTests { } /// Which plans ask for Qwen's speculative assistant (`discoveryMode`): under the default `auto`, a cluster that - /// serves locally only, as before, and never one served through the coordinator, whose setup may not carry it; - /// an explicit `on` in either case; never `off`. - @Test func aClusterServedThroughTheCoordinatorAsksForTheAssistantOnlyUnderAnExplicitOn() throws { + /// serves locally only, as before, and one served through the coordinator only when this build declares the + /// assistant public for the artifact (`declared`); an explicit `on` in either case; never `off`. + @Test func aClusterServedThroughTheCoordinatorAsksForTheAssistantUnderAutoOnlyWhenDeclared() throws { let artifact = try inlineAssistantArtifact() - func asks(_ configured: MTPMode, coordinator: Bool) throws -> Bool { + func asks(_ configured: MTPMode, coordinator: Bool, declared: Bool = false) throws -> Bool { try ClusterPlacementTensorAssistantSelection.automaticCandidate( - mode: ClusterPlacementTensorAssistantSelection.discoveryMode(configured, coordinator: coordinator), + mode: ClusterPlacementTensorAssistantSelection.discoveryMode(configured, coordinator: coordinator, declared: declared), runtimeModelID: ClusterQwenTensorAssistantPolicy.runtimeModelID, modelDirectory: artifact.directory, publicModelID: artifact.modelID, artifactSHA256: artifact.aggregate, manifestSHA256: ClusterConfigurationCodec.sha256(artifact.manifest), environment: [:]) } #expect(try asks(.auto, coordinator: false)) #expect(try !asks(.auto, coordinator: true)) + #expect(try asks(.auto, coordinator: true, declared: true)) #expect(try asks(.on, coordinator: false) && asks(.on, coordinator: true)) - #expect(try !asks(.off, coordinator: false) && !asks(.off, coordinator: true)) + #expect(try !asks(.off, coordinator: false) && !asks(.off, coordinator: true) && !asks(.off, coordinator: true, declared: true)) #expect(ClusterPlacementTensorAssistantSelection.discoveryMode(.auto, coordinator: true) == .off) + #expect(ClusterPlacementTensorAssistantSelection.discoveryMode(.auto, coordinator: true, declared: true) == .auto) #expect(ClusterPlacementTensorAssistantSelection.discoveryMode(.auto, coordinator: false) == .auto) } + /// A coordinator-paired setup plans the declared public assistant (`ClusterPublicModels.tensorAssistant`): its + /// depth with singleton verification (no cohort argument), and the native helper's quote must return exactly the + /// declared policy, inventory included; a local cluster's automatic cohort quote is refused there. + @Test func aCoordinatorPlanQuotesExactlyTheDeclaredSingletonAssistant() throws { + let (_, cap, _, _) = try fixture() + let declared = try ClusterQwenTensorAssistantPolicy(depth: 3, inventorySHA256: hash("8")) + let arguments = try ClusterPlacementTensorAssistantSelection.discoveryArguments(modelDirectory: "/fixture/model", + promptTokens: 32768, outputTokens: 32768, chunkTokens: 128, declared: declared) + #expect(arguments.suffix(2) == ["--mtp-depth", "3"]) + #expect(!arguments.contains(ClusterQwenTensorAssistantPolicy.verificationArgument)) + #expect(!arguments.contains(ClusterQwenTensorAssistantPolicy.inventoryArgument)) + // The native helper's quote of the memory plan's whole request (as `automaticQuotePinsNativeInventory...`). + func quote(_ verification: ClusterQwenTensorAssistantPolicy.Verification = .singleton, depth: Int = 3, + assistant: Bool = true) throws -> ClusterPlacementTensorBatchQuote { + let original = try assistantQuote(1, depth: depth, verification: verification) + let request = try ClusterPlacementRequestScope(runtimeModelID: cap.runtimeModelID, + artifactSHA256: cap.artifactSHA256, configurationSHA256: cap.configurationSHA256, + promptTokens: cap.profile.maximumPromptTokens, outputTokens: cap.profile.maximumOutputTokens, + maximumPromptTokens: cap.profile.maximumPromptTokens, maximumOutputTokens: cap.profile.maximumOutputTokens, + maximumContextTokens: cap.profile.maximumContextTokens, requestChargeEveryRankBytes: gib) + return try .init(request: request, lanes: 1, chunkTokens: original.chunkTokens, + perLaneStateBytes: original.perLaneStateBytes, sharedBytesExcludingCollectives: original.sharedBytesExcludingCollectives, + allowance: original.allowance, assistant: assistant ? original.assistant : nil) + } + let singleton = try quote() + try ClusterPlacementTensorAssistantSelection.requireDiscoveredQuote(singleton, capability: cap, chunkTokens: 128, + declared: declared) + for other in [try quote(.admittedCohort), try quote(depth: 2), try quote(assistant: false)] { + #expect(throws: (any Error).self) { + try ClusterPlacementTensorAssistantSelection.requireDiscoveredQuote(other, capability: cap, chunkTokens: 128, + declared: declared) + } + } + let otherInventory = try ClusterQwenTensorAssistantPolicy(depth: 3, inventorySHA256: hash("9")) + #expect(throws: (any Error).self) { + try ClusterPlacementTensorAssistantSelection.requireDiscoveredQuote(singleton, capability: cap, chunkTokens: 128, + declared: otherInventory) + } + // A local cluster keeps its automatic cohort policy. + #expect(throws: (any Error).self) { + try ClusterPlacementTensorAssistantSelection.requireDiscoveredQuote(singleton, capability: cap, chunkTokens: 128) + } + } + @Test func automaticQuotePinsNativeInventoryAndCompleteWidthOneScope() throws { let (_, cap, _, _) = try fixture() func quote(_ verification: ClusterQwenTensorAssistantPolicy.Verification = .admittedCohort, diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairSlotTests.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairSlotTests.swift index 2e60a22ffc..3f31fb8916 100644 --- a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairSlotTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairSlotTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import MLXLMCommon +import DarkbloomClusterProtocol @testable import ProviderCore // The cluster pair as an ordinary provider slot (S09), on a member loop. The @@ -63,6 +64,8 @@ final class ScriptedPairOwner: DistributedResidentExecutionOwner, @unchecked Sen var leasesAcceptCleanStop = true /// The first this many reservations fail (the warmup canary is the first). var failFirstReservations = 0 + /// The resident assistant both "ranks" report loaded (nil: none). + var tensorAssistant: ClusterQwenTensorAssistantReady? init(model: String = clusterPairFixtureModel) { identity = .init(membershipEpoch: UUID(), modelID: model, @@ -76,7 +79,9 @@ final class ScriptedPairOwner: DistributedResidentExecutionOwner, @unchecked Sen var lastLease: ScriptedPairLease? { lock.withLock { leases.last } } func readiness() -> DistributedResidentReadiness? { - lock.withLock { available ? .init(identity: identity, profileID: profileID, requestCapacityBytes: 1 << 20) : nil } + lock.withLock { + available ? .init(identity: identity, profileID: profileID, requestCapacityBytes: 1 << 20, tensorAssistant: tensorAssistant) : nil + } } func setReadinessInvalidationHandler(_ handler: @escaping @Sendable () -> Void) { lock.withLock { invalidation = handler } @@ -174,6 +179,24 @@ struct ClusterPairSlotTests { #expect(await loop.retireClusterPairSlot(reason: "test")) } + /// The slot's MTP posture follows the pair's readiness: ranks that loaded the resident assistant report it + /// configured, with the pair runtime's own counts (none yet); any other pair keeps the disabled posture. + @Test func aPairWithTheResidentAssistantReportsItsMTPPosture() async throws { + for assisted in [false, true] { + let loop = try await clusterPairMemberLoop() + let owner = ScriptedPairOwner() + if assisted { + owner.tensorAssistant = try ClusterQwenTensorAssistantReady(policy: try ClusterQwenTensorAssistantPolicy(depth: 3, + inventorySHA256: String(repeating: "8", count: 64)), capacity: 1) + } + _ = try await loop.publishClusterPairSlot(clusterPairSpecification(owner), owner: owner) + let bridge = try #require(await loop.slotBridgeForTesting(modelId: clusterPairFixtureModel)) + let snapshot = await bridge.mtpStatusSnapshot() + #expect(snapshot.configured == assisted && !snapshot.active && snapshot.rounds == 0, "assisted \(assisted)") + #expect(await loop.retireClusterPairSlot(reason: "test")) + } + } + /// S18 warmup canary: one throwaway generation through the pair before /// admission opens (the owner's m3_warmup.py). @Test func theWarmupCanaryGeneratesOnceBeforeAdmissionOpens() async throws { From 5be6e8f0a21862e0ec25df30c9e255663fd3e358 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:43:38 -0800 Subject: [PATCH 0116/1441] Say which clusters the automatic cohort quote is for The resident-assistant section said readAutomatic asks for a depth-three cohort quote; that is a local cluster's plan. A cluster served through Darkbloom quotes the declared assistant (singleton) or none, as the numbered rules below it say. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c1bc133fe2..95c0df9aa4 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -5376,7 +5376,7 @@ does not establish an installed distributed-model pass. The Qwen3.5 9B's artifact ships the same dense one-layer inline head, so its tensor owner runs the same resident assistant (`QwenTensorParallelMTPPolicy.models`, `ClusterQwenTensorAssistantPolicy.runtimeModelIDs`): `QwenTensorParallelMTPInventory.Head` derives every expected head tensor from the row's configuration and `QwenTensorParallelMTPBudget` prices the row's own widths (the 27B's inventory fingerprint and quotes are unchanged). The 9B's READY carries the assistant without the 27B's media contract. The routed-expert rows' heads are expert layers this assistant does not load; those rows serve their request-owned lanes without speculation, and planning never asks them for an assistant. -For the exact registered Qwen3.8 27B artifact, normal cluster planning discovers the embedded assistant from the catalog manifest, capability identity and bounded inline header inspection. With `backend.mtp_mode` set to `auto` or `on`, `ClusterPlacementTensorAssistantSelection.readAutomatic` asks the native metadata helper for a complete depth-three cohort quote. The returned inventory fingerprint becomes the saved bilateral policy; the provider does not infer it from a model name. Explicit `off`, the existing MTP kill switch, or an absent head retains the completely quoted ordinary TP owner. A malformed declared assistant refuses planning. This policy does not create a hand-off or phase-split deployment. +For the exact registered Qwen3.8 27B artifact, normal cluster planning discovers the embedded assistant from the catalog manifest, capability identity and bounded inline header inspection. With `backend.mtp_mode` set to `auto` or `on`, `ClusterPlacementTensorAssistantSelection.readAutomatic` asks the native metadata helper for a complete depth-three cohort quote for a local cluster (a cluster served through Darkbloom: below). The returned inventory fingerprint becomes the saved bilateral policy; the provider does not infer it from a model name. Explicit `off`, the existing MTP kill switch, or an absent head retains the completely quoted ordinary TP owner. A malformed declared assistant refuses planning. This policy does not create a hand-off or phase-split deployment. On a coordinator-formed pair the assistant serves only as the build declares it. Its verify windows are a computation the coordinator does not see: it qualifies `tensor_parallel_v1` placements by classes, cuts and mode, a pair's registration carries no speculation field, and the bundled tensor-parallel records of the 27B predate the assistant. The owner therefore declares a public assistant per artifact beside the public model declaration (`ClusterPublicModel.tensorAssistant`, a `ClusterPublicTensorAssistant`: depth, the inline head's inventory fingerprint, singleton verification and the SHA-256 of its evidence report under `docs/reports/`). This build declares none. From f4d7edad42b14fa8a20d1c8baa9464463b613de4 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:10:20 -0800 Subject: [PATCH 0117/1441] cluster: keep Gemma 4 tensor-parallel prompt prefixes, resident and on SSD Gemma 4 tensor parallel kept no prompt prefix, so the feature-parity gate holds it back against the pipeline, which keeps them in memory and on the owner's encrypted SSD tier. Each rank now keeps its own heads' state (4 sliding, 1 full on the 26B) as the pipeline keeps a stage's: in the pipeline's memory tier (QwenStagePrefixCache) and SSD tier (QwenStagePrefixDiskTier), at the pipeline's chunk-grid boundaries, in the Gemma stage's record shape (Gemma4TensorParallelPrefix, Gemma4TensorParallelPrefixCapture). - Agreement, never assumption: one sealed sum votes every stride-grid boundary (1 in memory, 3 only on SSD); each rank restores the deepest both offer from its own tiers, then a second sealed sum confirms both restored, else both prefill from zero. Solo requests and batch lanes. - Bitwise: a restore continues on the same chunk grid. CBv2OwnedRequestState now adopts sliding windows into rows reserved for their first tokens, so a restored request's pages grow as a cold one's (additive; existing callers pass no reservation with windows). - Kept only after both ranks ended the request; a failed request drops every entry; entries, then the request's own capture, give way under memory pressure; an idle rank drops them under host pressure. - Memory: Gemma4TensorParallelRequestBudget charges each request its capture at its deepest boundary and each rank two such captures for the memory tier, in the LOAD gate and the planner's allowance (+1.32 GB a rank at the profile). Two 24 GB M4 Pro no longer fit tensor parallel. - Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes is true; Gemma4TensorParallelLoadAgreement binds it (a rank whose diagnosis switch turned prefixes off is refused). The worker passes its SSD key. Tests: Gemma4TensorParallelPrefixTests (10, GPU, synthetic, two in-process ranks): restore against cold bit for bit and the state at and after the boundary, hits and misses agreed on both ranks, the request loop and lanes, budget and eviction, the SSD round trip, refused records and the cache rules. The load-agreement test and GemmaTensorParallelChecks follow. Co-Authored-By: Claude Opus 5.5 --- .../Execution/NativeWorkerRuntime.swift | 14 +- .../Gemma4ResidentAdapterDefinition.swift | 3 + .../Gemma4TensorParallelRequestBudget.swift | 65 +- .../Gemma4TensorParallelLanes.swift | 65 +- .../Gemma4TensorParallelLoadAgreement.swift | 6 +- .../Gemma4TensorParallelPagedSession.swift | 59 +- .../Gemma4TensorParallelPrefix.swift | 403 ++++++++++++ .../Gemma4TensorParallelRequestLoop.swift | 8 +- .../Gemma4TensorParallelResidentRuntime.swift | 187 +++++- .../Placement/QwenDensePlacementFamily.swift | 5 +- .../State/CBv2OwnedRequestState.swift | 22 +- .../Gemma4TensorParallelPrefixTests.swift | 584 ++++++++++++++++++ .../Gemma4TensorParallelRuntimeTests.swift | 4 +- .../GemmaTensorParallelChecks.swift | 34 +- 14 files changed, 1371 insertions(+), 88 deletions(-) create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelPrefixTests.swift diff --git a/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift b/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift index 46c5b62fe3..8dbefc024e 100644 --- a/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift +++ b/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift @@ -36,11 +36,13 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { switch family { case .qwenDense where generationMode == .tensorParallel && Gemma4TensorParallelResidentRuntime.serves(runtimeModelID: configuration.identity.modelID): - // Gemma 4 shares the layer-stage family; its tensor-parallel rank is its own runtime. + // Gemma 4 shares the layer-stage family; its tensor-parallel rank is its own runtime, + // whose prompt-prefix cache keeps an SSD tier with the owner's key. guard speculativeTerms == nil, tensorAssistantPolicy == nil, tensorShares == [1, 1], let dataPlane else { throw WorkerFailure.invalid("Gemma tensor parallel runs equal shares over a keyed data plane without speculation") } - owner = .gemma4TensorParallel(try .load(configuration, qualification: qualification, dataPlane: dataPlane)) + owner = .gemma4TensorParallel(try .load(configuration, qualification: qualification, dataPlane: dataPlane, + prefixSSDKey: prefixSSDKey)) case .qwenDense where generationMode == .tensorParallel: owner = .qwenTensorParallel(try .load(configuration, shares: tensorShares, qualification: qualification, dataPlane: dataPlane, prefixSSDKey: prefixSSDKey, speculativeTerms: speculativeTerms, @@ -131,12 +133,14 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .glm5Next(let runtime): try runtime.releaseReservation(requestID: id) } } - /// GLM tensor parallel also drops its prompt-prefix entries under host - /// pressure; every other family gives back its freed-buffer cache only. + /// GLM and Gemma tensor parallel also drop their prompt-prefix entries + /// under host pressure; every other family gives back its freed-buffer + /// cache only. func releaseIdleMemory(underPressure: Bool) -> Int? { switch owner { case .glm5NextTensorParallel(let runtime): return try? runtime.releaseIdleMemory(underPressure: underPressure) - case .qwenDense, .qwenTensorParallel, .mimoV26, .glm5Next, .gemma4TensorParallel: + case .gemma4TensorParallel(let runtime): return try? runtime.releaseIdleMemory(underPressure: underPressure) + case .qwenDense, .qwenTensorParallel, .mimoV26, .glm5Next: return ClusterIdleMemory.releaseFreedBuffers() } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentAdapterDefinition.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentAdapterDefinition.swift index 58232ba543..7fc84c60a3 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentAdapterDefinition.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentAdapterDefinition.swift @@ -13,6 +13,9 @@ enum Gemma4ResidentAdapterDefinition { /// parallel only where it predicts it faster than the pipeline /// (`Gemma4PlacementFamily.tensorParallelPlan`, `ClusterTensorParallelChoice.fastest`). static let supportedGenerationModes: [ClusterGenerationMode] = [.pipeline, .tensorParallel] + /// Tensor parallel keeps prompt prefixes as the pipeline does, resident and on the owner's SSD tier + /// (`Gemma4TensorParallelPrefix`); its load agreement binds this (`Gemma4TensorParallelLoadAgreement.prefixCache`). + static let tensorParallelKeepsPromptPrefixes = true static func profileID(_ model: Gemma4RegisteredModel) -> String { model.rawValue + "_greedy_generation_v1" } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4TensorParallelRequestBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4TensorParallelRequestBudget.swift index 6f922cdd2a..1da5e12b98 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4TensorParallelRequestBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4TensorParallelRequestBudget.swift @@ -11,18 +11,23 @@ import Foundation /// at two ranks), one prompt chunk's attention transient over its own 8 query /// heads (`Gemma4PrefillTransient`), the chunk's FP32 partials (the attention /// row; the dense row and the 8 selected experts' rows, and the packed copy -/// of them the collective carries) and three float32 rows of the whole +/// of them the collective carries), three float32 rows of the whole /// vocabulary (the row a sampled step gathers, the split head's half, the -/// top-k). +/// top-k) and its prompt-prefix capture at its deepest boundary +/// (`prefixCaptureBytes`: its own heads' full rows for the longest prompt of +/// that context and one sliding window of every sliding layer). /// /// Once per rank (`rankBytes`): the conservative activation floor until /// hardware measures one for a Gemma tensor-parallel rank (5.5 GiB, the /// provider's default reserve, as `GLM5NextServingResources` charges GLM's), -/// the freed-buffer cache the ready rank keeps, and eight sealed frames of the -/// largest collective (`ClusterTensorParallelRequestAllowance`). The decode -/// steps' 100-operation command buffers (`Gemma4TensorParallelModel.decodeCommandBuffers`) -/// bound only how a step is submitted, and no prefill is micro-batched: neither -/// adds a buffer beyond these. +/// the freed-buffer cache the ready rank keeps, eight sealed frames of the +/// largest collective (`ClusterTensorParallelRequestAllowance`), and the +/// prompt-prefix memory tier's charged budget (`prefixResidentBytes`: two +/// captures of the longest request, as Qwen tensor parallel keeps two banks). +/// The decode steps' 100-operation command buffers +/// (`Gemma4TensorParallelModel.decodeCommandBuffers`) bound only how a step +/// is submitted, and no prefill is micro-batched: neither adds a buffer +/// beyond these. struct Gemma4TensorParallelRequestBudget: Equatable { static let ranks = 2 /// `UnifiedMemoryCap.defaultActivationReserveBytes`: 5.5 GiB. A measured @@ -42,14 +47,44 @@ struct Gemma4TensorParallelRequestBudget: Equatable { let transientBytes: Int let partialBytes: Int let logitsBytes: Int + /// The request's prompt-prefix capture at its deepest boundary. + let prefixCaptureBytes: Int + /// The prompt-prefix memory tier's charged budget on a rank. + let prefixResidentBytes: Int let allowance: ClusterTensorParallelRequestAllowance /// What one request of `contextTokens` reserves on a rank. - var requestBytes: Int { stateBytes + transientBytes + partialBytes + logitsBytes } + var requestBytes: Int { stateBytes + transientBytes + partialBytes + logitsBytes + prefixCaptureBytes } /// What a rank holds once beside every request it serves. - var rankBytes: Int { Self.activationFloorBytes + Self.freedBufferCacheBytes + allowance.collectiveScratchBytes } + var rankBytes: Int { + Self.activationFloorBytes + Self.freedBufferCacheBytes + allowance.collectiveScratchBytes + prefixResidentBytes + } + + /// One prefix capture of a prompt of `promptTokens` at the allocator's + /// bound: this rank's full-attention rows (keys and values, every token) + /// and one window of every sliding layer, its own heads. + static func prefixCaptureBytes(promptTokens: Int, allocationBound: (Int) throws -> Int) throws -> Int { + typealias G = Gemma4StageGeometry + let product = QwenLongPrefillCheckedBytes.product + guard promptTokens > 0 else { return 0 } + let layers = (0 ..< G.layerCount).map(G.isFullAttention(globalLayerIndex:)) + let full = layers.filter { $0 }.count, sliding = layers.count - full + func bound(_ logical: Int, count: Int) throws -> Int { + let allocated = try allocationBound(logical) + guard logical > 0, allocated >= logical else { throw ProbeError("Gemma tensor-parallel prefix allocator bound is invalid") } + return try product([allocated, count]) + } + let rows = try product([promptTokens, G.fullKVHeads / ranks, G.fullHeadDimension, 2]) + let window = try product([min(promptTokens, G.slidingWindow), G.slidingKVHeads / ranks, G.slidingHeadDimension, 2]) + return try QwenLongPrefillCheckedBytes.sum([bound(rows, count: 2 * full), bound(window, count: 2 * sliding)]) + } - static func derive(contextTokens: Int, chunkTokens: Int, allocationBound: (Int) throws -> Int) throws -> Self { + /// `promptTokens`: the longest prompt a request of this context holds + /// (the profile's, at most `contextTokens - 1`); nil: `contextTokens - 1`. + /// `keepsPrefixes` false charges no prefix capture or tier (the load's + /// cache off). + static func derive(contextTokens: Int, chunkTokens: Int, promptTokens: Int? = nil, keepsPrefixes: Bool = true, + allocationBound: (Int) throws -> Int) throws -> Self { typealias G = Gemma4StageGeometry let sum = QwenLongPrefillCheckedBytes.sum, product = QwenLongPrefillCheckedBytes.product let chunk = min(contextTokens, chunkTokens) @@ -60,6 +95,9 @@ struct Gemma4TensorParallelRequestBudget: Equatable { } return try product([allocated, count]) } + let prompt = min(promptTokens ?? contextTokens - 1, contextTokens - 1) + let capture = keepsPrefixes ? try prefixCaptureBytes(promptTokens: max(1, prompt), allocationBound: allocationBound) : 0 + let resident = try product([capture, 2]) let b = try Gemma4StateBudget.estimate(maximumTokens: contextTokens, chunkSize: chunk, ranks: ranks) let layers = b.fullLayers + b.slidingLayers let state = try sum([bound(b.fullKVBytes, count: 2 * b.fullLayers), bound(b.ringKVBytes, count: 2 * b.slidingLayers), @@ -75,12 +113,13 @@ struct Gemma4TensorParallelRequestBudget: Equatable { let logits = try bound(product([G.vocabularySize, 4]), count: 3) let payload = try product([chunk, maximumPartialBytesPerToken]) let frame = try sum([payload, QwenTensorParallelSealCodec.frameOverhead]) - let request = try sum([state, bound(transientLogical), partials, logits]) + let request = try sum([state, bound(transientLogical), partials, logits, capture]) let allowance = try ClusterTensorParallelRequestAllowance(maximumContextTokens: contextTokens, maximumChunkTokens: chunk, - requestBytesExcludingCollectives: sum([request, activationFloorBytes, freedBufferCacheBytes]), + requestBytesExcludingCollectives: sum([request, activationFloorBytes, freedBufferCacheBytes, resident]), maximumCollectivePayloadBytes: payload, maximumCollectiveFrameBytes: frame, allocationBound: allocationBound) return .init(contextTokens: contextTokens, chunkTokens: chunk, stateBytes: state, - transientBytes: try bound(transientLogical), partialBytes: partials, logitsBytes: logits, allowance: allowance) + transientBytes: try bound(transientLogical), partialBytes: partials, logitsBytes: logits, + prefixCaptureBytes: capture, prefixResidentBytes: resident, allowance: allowance) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLanes.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLanes.swift index 83be20ba4e..a3092bc5ba 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLanes.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLanes.swift @@ -8,20 +8,28 @@ struct Gemma4TensorParallelLaneReservation: QwenTensorParallelBatchReservation { /// The lane's own charge at its context /// (`Gemma4TensorParallelResidentRuntime.requestChargeBytes`). let laneStateBytes: Int + /// What its prefix capture may hold (0: none). + var prefixCaptureLimit = 0 var joinable: Bool { true } } /// One batch lane: a request's paged session and the frames it has run, -/// on the request's own chunk grid (the solo path's). +/// on the request's own chunk grid (the solo path's), from a restored +/// prefix's boundary when both ranks restored one. final class Gemma4TensorParallelLane: QwenTensorParallelBatchLane { let session: Gemma4TensorParallelPagedSession let request: QwenLayerStageGenerationRequest private var schedule: QwenLayerStageGenerationSchedule var pendingLogprobs: ClusterWorkerTokenLogprobs? + var reusedPrefixTokens: Int { session.reusedPrefixTokens } + /// The boundaries its capture kept, once both ranks retired it cleanly. + var storedPrefixFrontiers: [Int] = [] - init(session: Gemma4TensorParallelPagedSession, request: QwenLayerStageGenerationRequest) { - self.session = session; self.request = request - schedule = QwenLayerStageGenerationSchedule(request: request) + init(session: Gemma4TensorParallelPagedSession, request: QwenLayerStageGenerationRequest) throws { + self.session = session + self.request = session.reusedPrefixTokens > 0 + ? try request.planned(reusedPrefix: session.reusedPrefixTokens, splitFinalToken: false) : request + schedule = QwenLayerStageGenerationSchedule(request: self.request) } var nextFrame: QwenLayerStageFrame? { @@ -70,8 +78,11 @@ final class Gemma4TensorParallelBatchExecutor Void) throws -> Void private let completedDecode: (Int) -> Void + /// This rank's prompt prefixes; nil keeps none (oracles). + private let prefix: Gemma4TensorParallelPrefix? init(model: Gemma4TensorParallelModel, host: CBv2StageKVHost, reduction: any QwenTensorParallelReduction, + prefix: Gemma4TensorParallelPrefix? = nil, agree: @escaping (QwenLayerStageGenerationRequest, () throws -> Void) throws -> Void, completedDecode: @escaping (Int) -> Void = { _ in }) throws { guard case .shard(let rank) = model.role, rank == reduction.rank, reduction.size == model.plan.size, @@ -79,7 +90,7 @@ final class Gemma4TensorParallelBatchExecutor Void) throws -> [Float] { @@ -96,12 +107,30 @@ final class Gemma4TensorParallelBatchExecutor Void) throws -> Lane { let request = reservation.request try agree(request, check) try check() - return Lane(session: try .init(model: model, host: host, promptCount: request.promptCount, - outputCount: request.outputCount), request: request) + guard let prefix else { + return try Lane(session: try .init(model: model, host: host, promptCount: request.promptCount, + outputCount: request.outputCount), request: request) + } + let limit = (reservation as? Gemma4TensorParallelLaneReservation)?.prefixCaptureLimit ?? 0 + let session = try prefix.open(request, model: model, host: host, group: reduction, captureLimit: limit) + do { return try Lane(session: session, request: request) } catch { + try? session.retire(failed: true) + throw error + } + } + + /// Both ranks retired the lane: a clean one's capture becomes reusable. + func confirmedRetirement(_ lane: Lane, clean: Bool) throws { + guard let capture = lane.session.prefixCapture else { return } + lane.session.prefixCapture = nil + guard clean, let prefix, let scopes = prefix.scopes(lane.request) else { capture.discard(); return } + lane.storedPrefixFrontiers = prefix.store(capture, request: lane.request, scopes: scopes, rank: rank) } func prefill(_ lane: Lane, frame: QwenLayerStageFrame, check: () throws -> Void) throws -> Int? { @@ -270,18 +299,18 @@ extension Gemma4TensorParallelResidentRuntime { } let request = try admission.request(value, id: requestID, now: DispatchTime.now().uptimeNanoseconds) try control.check(deadline: value.deadlineUptimeNanoseconds) - let charge = try Self.requestChargeBytes(contextTokens: request.maximumTokens, admission: admission, - chunkTokens: request.chunkSize) + let priced = try prefixCharge(request) + let charge = priced.charge guard charge <= value.capacityLimitBytes else { throw ProbeError("Gemma tensor-parallel lane exceeds its owner or readiness capacity") } - // Every held lane at its whole charge, this one, and the rank's own reserve once. + // Every held lane at its whole charge, this one, and the rank's own reserve once + // (kept prefixes give way first; a capture beyond its charged part may be cut). _ = ClusterIdleMemory.releaseFreedBuffers() - try Self.requireLiveMemory(bytes: try QwenLongPrefillCheckedBytes.sum([try laneBook.stateBytes(), charge, - rankReserveBytes])) + let captureLimit = try admitCapture(priced, held: [try laneBook.stateBytes(), charge, rankReserveBytes]) try control.check(deadline: value.deadlineUptimeNanoseconds) try laneBook.reserve(requestID, .init(request: request, deadline: value.deadlineUptimeNanoseconds, - laneStateBytes: charge), lanes: lanes) + laneStateBytes: charge, prefixCaptureLimit: captureLimit), lanes: lanes) return charge } } @@ -300,7 +329,7 @@ extension Gemma4TensorParallelResidentRuntime { let records = try QwenBatchRecordBinding(epoch: admission.configuration.identity.membershipEpoch, planFingerprint: admission.plan.fingerprint, ordinal: batchOrdinal, lanes: lanes) let executor = try Gemma4TensorParallelBatchExecutor(model: model, host: host, - reduction: group, agree: { [self] request, check in try agreeRequest(request, check: check) }) + reduction: group, prefix: prefix, agree: { [self] request, check in try agreeRequest(request, check: check) }) let driver = try QwenTensorParallelBatchDriver(executor: executor, book: laneBook, capacity: lanes, vocabulary: admission.profile.vocabularySize) do { @@ -312,7 +341,9 @@ extension Gemma4TensorParallelResidentRuntime { try error.check(); try self.control.check() let now = DispatchTime.now().uptimeNanoseconds if lastResourceCheck == 0 || now - lastResourceCheck >= 250_000_000 { - try Self.requireLiveMemory(bytes: 0); lastResourceCheck = now + // Kept prefixes give way before the batch fails for memory. + try prefix.cache.yieldingMemory { try Self.requireLiveMemory(bytes: 0) } + lastResourceCheck = now } try error.check() }) @@ -321,7 +352,9 @@ extension Gemma4TensorParallelResidentRuntime { guard host.isDrained else { throw ProbeError("Gemma tensor-parallel batch retained native history") } collective.logDataPlaneStatus() } catch { - // Its native state stays reachable until shutdown's checked drain. + // Its native state stays reachable until shutdown's checked drain; + // the peer may hold other prefixes now. + prefix.cache.sweep() failedLaneDriver = driver; control.fail() throw error } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLoadAgreement.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLoadAgreement.swift index ca5a196f31..10dab6b54a 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLoadAgreement.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLoadAgreement.swift @@ -16,8 +16,10 @@ struct Gemma4TensorParallelLoadAgreement: Equatable { var lanes = 1 var kv = ClusterStageKVBackendKind.paged var kvQuantization = PagedKVQuantizationSelection.native - /// Prompt prefixes are not kept yet: both ranks say so. - var prefixCache = false + /// Prompt prefixes kept, resident and on the SSD tier (`Gemma4TensorParallelPrefix`): + /// this build's `tensorParallelKeepsPromptPrefixes`, unless the diagnosis switch + /// turns them off on a rank, which its peer then refuses. + var prefixCache = Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes /// The mode's terms (FP32 partials, rounded once after the sum; the /// sealed all-sum) and the plan's: where each layer's two sums are taken diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPagedSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPagedSession.swift index c0f171f3fb..b19c02d43a 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPagedSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPagedSession.swift @@ -51,17 +51,49 @@ final class Gemma4TensorParallelPagedSession { let state: CBv2OwnedRequestState let promptCount: Int private(set) var retired = false + /// Prompt tokens restored from a kept prefix (0 for a cold request). + let reusedPrefixTokens: Int + /// This request's prefix capture, taken after the prompt chunks that end + /// at its boundaries (`Gemma4TensorParallelPrefixCapture`); nil keeps none. + var prefixCapture: Gemma4TensorParallelPrefixCapture? - init(model: Gemma4TensorParallelModel, host: CBv2StageKVHost, promptCount: Int, outputCount: Int) throws { + /// `restoring`: this rank's state at an agreed prefix boundary (its own + /// heads' full rows and sliding windows, `Gemma4TensorParallelPrefix`), + /// written into fresh pages of the request; the prompt then continues + /// from that boundary on the same chunk grid. + init(model: Gemma4TensorParallelModel, host: CBv2StageKVHost, promptCount: Int, outputCount: Int, + restoring prefix: QwenStagePrefixState? = nil) throws { let maximum = promptCount + outputCount - guard promptCount > 0, outputCount > 0, maximum <= host.maximumTokensPerRequest else { + guard promptCount > 0, outputCount > 0, maximum <= host.maximumTokensPerRequest, + (prefix?.committedTokens ?? 0) < promptCount else { throw ProbeError("Gemma tensor-parallel request does not fit its KV host") } - let geometry = try CBv2RequestGeometry(gemma4Stage: model.requestGeometry(maximumTokens: maximum), host: host, - maximumTokens: maximum) + let geometry = try Self.geometry(model: model, host: host, maximumTokens: maximum) self.model = model; self.promptCount = promptCount - state = try CBv2OwnedRequestState(geometry: geometry, promptCount: promptCount, outputCount: outputCount, - reservedTokens: host.kind == .paged ? min(maximum, promptCount + QwenTensorParallelBatchSession.pageGrowthTokens) : nil) + let reserved = host.kind == .paged ? min(maximum, promptCount + QwenTensorParallelBatchSession.pageGrowthTokens) : nil + if let prefix { + guard Gemma4TensorParallelPrefix.adopts(prefix, into: geometry) else { + throw ProbeError("Gemma tensor-parallel prefix differs from this rank's request geometry") + } + let sliding = Set(geometry.kinds.compactMap { kind -> Int? in + if case .slidingWindow = kind.attention { return kind.modelLayerIndex } + return nil + }) + state = try CBv2OwnedRequestState(geometry: geometry, promptCount: promptCount, outputCount: outputCount, + adoptingCommittedTokens: prefix.committedTokens, attention: prefix.attention, + slidingTails: prefix.recurrent.filter { sliding.contains($0.key) }.mapValues { (keys: $0.conv, values: $0.ssm) }, + recurrent: [:], reservedTokens: reserved) + } else { + state = try CBv2OwnedRequestState(geometry: geometry, promptCount: promptCount, outputCount: outputCount, + reservedTokens: reserved) + } + reusedPrefixTokens = prefix?.committedTokens ?? 0 + } + + /// The request geometry a session of `maximumTokens` takes on `host`. + static func geometry(model: Gemma4TensorParallelModel, host: CBv2StageKVHost, maximumTokens: Int) throws -> CBv2RequestGeometry { + try CBv2RequestGeometry(gemma4Stage: model.requestGeometry(maximumTokens: maximumTokens), host: host, + maximumTokens: maximumTokens) } var committedTokens: Int { state.committedTokens } @@ -101,6 +133,10 @@ final class Gemma4TensorParallelPagedSession { logits = row return select(row) }, validateOutput: { _ in }) + if let prefixCapture, prefixCapture.frontiers.contains(range.upperBound) { + try prefixCapture.capture(state, at: range.upperBound) + try check() + } guard final else { return nil } guard let logits else { throw ProbeError("Gemma tensor-parallel prompt produced no logits") } try Self.validate(logits, rows: 1, model: model) @@ -212,6 +248,15 @@ extension Gemma4TensorParallelModel { let host = try pagedHost(lanes: 1, maximumTokens: prompt.count + outputCount, chunkTokens: chunk) let session = try Gemma4TensorParallelPagedSession(model: self, host: host, promptCount: prompt.count, outputCount: outputCount) + return try generatePaged(session: session, host: host, prompt: prompt, outputCount: outputCount, chunk: chunk, + recordTop: recordTop) + } + + /// The same greedy generation on `session` (cold, or restored from a + /// prefix: its prompt continues from its committed boundary), retired + /// at the end; `host` must drain. + func generatePaged(session: Gemma4TensorParallelPagedSession, host: CBv2StageKVHost, prompt: [Int], outputCount: Int, + chunk: Int, recordTop: Int) throws -> Generation { let rank: Int if case .shard(let r) = role { rank = r } else { rank = 0 } let choice = Gemma4TensorParallelChoice(selection: selection, sampler: nil, rank: rank) @@ -220,7 +265,7 @@ extension Gemma4TensorParallelModel { try MLX.withError { error in func checked() throws { try error.check() } let started = Self.now() - var offset = 0 + var offset = session.committedTokens var step: (logits: MLXArray, selected: MLXArray)? while offset < prompt.count { let end = min(prompt.count, offset + chunk) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift new file mode 100644 index 0000000000..6b5d0deb08 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift @@ -0,0 +1,403 @@ +import DarkbloomClusterProtocol +import Foundation +import MLX +import MLXLMCommon + +/// One Gemma 4 tensor-parallel rank's prompt prefixes: the Gemma pipeline's +/// memory tier (`QwenStagePrefixCache`) and, when the owner configured one, +/// its encrypted SSD tier (`QwenStagePrefixDiskTier`, `cache.disk`), holding +/// only this rank's own KV heads of every layer (26B: 4 sliding, 1 full). +/// +/// The pipeline's frontiers and record shape: a request keeps its state at +/// chunk-grid boundaries strictly before the prompt end, on the cache's +/// stride (`QwenLayerStageGenerationRequest.prefixCaptureFrontiers`), the +/// deepest first and then the deepest grid boundaries its capture limit +/// holds; full-attention rows are copied once, at the deepest boundary, and +/// each sliding layer's window at every kept boundary, in the recurrent +/// slots (`QwenLayerStageSession.capturePrefix`). Entries are inserted only +/// after the request retired cleanly on both ranks, and written to the SSD +/// tier behind serving. +/// +/// Both ranks key a boundary identically: the load agreement and the +/// request's chunk grid (and on SSD the persistent plan scope), in the +/// request's tenant partition (`ClusterWorkerPrefixCache.scope`). Nothing is +/// assumed: the ranks vote every capture-grid boundary of the prompt in one +/// sealed sum (`QwenTensorParallelPrefixCache.offer`: 1 in memory, 3 only on +/// SSD), take the deepest both offer, read it from their own tiers, and a +/// second sealed sum (`QwenTensorParallelPrefixCache.confirm`) shows both +/// read it before either writes a page; otherwise both prefill from zero. +final class Gemma4TensorParallelPrefix { + let cache: QwenStagePrefixCache + /// The resident scope's base: the pair's load agreement. + let load: String + /// The SSD tier's persistent scope (`planScope`); nil without the tier. + let diskPlanScope: String? + + init(cache: QwenStagePrefixCache, load: String, diskPlanScope: String?) { + self.cache = cache; self.load = load; self.diskPlanScope = cache.disk == nil ? nil : diskPlanScope + } + + var disk: QwenStagePrefixDiskTier? { cache.disk } + + /// Everything a restored state's bytes depend on that each rank knows at + /// load, never the membership epoch, so a restarted pair finds what the + /// last one kept: the plan and its arithmetic terms, the prompt policy, + /// the arithmetic receipt and profile, the verified artifact and storage, + /// and both ranks' builds. + static func planScope(admission: Gemma4ResidentAdmission, aggregateSHA256: String, + storageCommitmentSHA256: String) -> String { + QwenStagePrefixDiskTier.planScope( + planFingerprint: ([Gemma4TensorParallelPlan.name, "shares=1:1", "arithmetic=" + admission.arithmeticSHA256, + "profile=" + admission.profile.fingerprint] + + Gemma4TensorParallelLoadAgreement.termsFields + Gemma4TensorParallelLoadAgreement.promptPolicyFields) + .joined(separator: "|"), + artifactAggregateSHA256: aggregateSHA256, storageCommitmentSHA256: storageCommitmentSHA256, + rankBuildSHA256: admission.configuration.identity.peers.map(\.buildSHA256), + generationMode: ClusterGenerationMode.tensorParallel.rawValue, prefillSchedule: "serial|gemma4-tp-prefix-v1") + } + + /// A request's partition of each tier; nil when it keeps no prefix (the + /// cache off on this rank or for the request). Both ranks derive the + /// same value from the request and load they agreed. + struct Scopes: Equatable { + let resident: String + let disk: String? + } + + func scopes(_ request: QwenLayerStageGenerationRequest) -> Scopes? { + guard cache.enabled, + let resident = ClusterWorkerPrefixCache.scope(load + "|gemma4-tp-prefix-v1|chunk=\(request.chunkSize)", + request.prefixCache) else { return nil } + let disk = diskPlanScope.flatMap { + ClusterWorkerPrefixCache.scope($0 + "|chunk=\(request.chunkSize)|kv=paged", request.prefixCache) + } + return Scopes(resident: resident, disk: disk) + } + + /// The boundaries a state of `request` may be kept at and is voted on: + /// every multiple of the cache's stride (whole chunks) before the + /// prompt's final token. + func candidates(_ request: QwenLayerStageGenerationRequest) -> [Int] { + let step = cache.stride(chunkSize: request.chunkSize) + guard request.promptCount > step else { return [] } + return Array(Swift.stride(from: step, through: request.promptCount - 1, by: step)) + } + + /// Both ranks: one sealed sum of this rank's offer for every candidate. + /// The deepest boundary both offer, and whether either offers it only + /// from SSD; nil when none (both then prefill from zero). + func vote(_ request: QwenLayerStageGenerationRequest, scopes: Scopes, candidates: [Int], + group: any QwenTensorParallelReduction) throws -> (boundary: Int, ssd: Bool)? { + guard group.size == 2, !candidates.isEmpty else { throw ProbeError("The Gemma tensor-parallel prefix vote takes two ranks") } + let prompt = request.promptTokenIDs + let held = Set(cache.frontiers(scope: scopes.resident, tokens: prompt, maximumFrontier: request.promptCount - 1)) + let onDisk = scopes.disk.flatMap { scope in + disk.map { Set($0.frontiers(scope: scope, tokens: prompt, maximumFrontier: request.promptCount - 1)) } + } ?? [] + let offers = candidates.map { QwenTensorParallelPrefixCache.offer(inMemory: held.contains($0), onDisk: onDisk.contains($0)) } + let summed = group.allSum(MLXArray(offers)) + try MLX.withError { error in eval(summed); try error.check() } + let sums = summed.asArray(Float.self) + guard sums.count == candidates.count else { throw ProbeError("The Gemma tensor-parallel prefix vote changed shape") } + return QwenTensorParallelPrefixCache.agreed(sums: sums, candidates: candidates) + } + + /// This rank's state at the agreed `boundary`: from memory when it holds + /// it there (the record of the same boundary is touched), else read from + /// its SSD record and checked to adopt (`adopts`) before anything is + /// written; nil when this rank cannot restore it (an unreadable record is + /// deleted by the tier, one that does not adopt here). Only a failed + /// `check` throws. + func read(_ boundary: Int, request: QwenLayerStageGenerationRequest, scopes: Scopes, + geometry: CBv2RequestGeometry, check: () throws -> Void) throws -> (state: QwenStagePrefixState, tier: String)? { + let prompt = request.promptTokenIDs + if let state = cache.state(scope: scopes.resident, tokens: prompt, frontier: boundary) { + if let diskScope = scopes.disk { disk?.touch(scope: diskScope, tokens: prompt, frontier: boundary) } + return Self.adopts(state, into: geometry) ? (state, "resident") : nil + } + guard let disk, let diskScope = scopes.disk, + let state = try disk.restore(scope: diskScope, tokens: prompt, frontier: boundary, check: check) else { + return nil + } + guard Self.adopts(state, into: geometry) else { + log("darkbloom-prefix-ssd-v1 rank=\(disk.rank) event=restore-rejected frontier=\(boundary) reason=not_adoptable") + disk.forget(scope: diskScope, tokens: prompt, frontier: boundary) + return nil + } + return (state, "ssd") + } + + /// Whether `state` adopts into a request of `geometry` exactly as + /// `CBv2OwnedRequestState` adopts it: every full-attention layer's rows + /// at the boundary and every sliding layer's window, with this rank's + /// head counts, widths and element type, nothing else. + static func adopts(_ state: QwenStagePrefixState, into geometry: CBv2RequestGeometry) -> Bool { + let committed = state.committedTokens + guard committed > 0, state.speculativeHistory == nil, geometry.recurrent.layers.isEmpty, + state.attention.count + state.recurrent.count == geometry.kinds.count else { return false } + for kind in geometry.kinds { + guard let layer = kind.modelLayerIndex else { return false } + let shape = [1, kind.kvHeads, kind.retainedTokens(atFrontier: committed), kind.headDim] + let pair: (keys: MLXArray, values: MLXArray)? + if case .slidingWindow = kind.attention { + pair = state.recurrent[layer].map { (keys: $0.conv, values: $0.ssm) } + } else { + pair = state.attention[layer] + } + guard let pair, pair.keys.shape == shape, pair.values.shape == shape, + pair.keys.dtype == geometry.kvDType, pair.values.dtype == geometry.kvDType else { return false } + } + return true + } + + /// Opens `request`'s session on this rank, both ranks alike: with the + /// cache on and a prompt longer than one stride, one sealed vote and, on + /// an agreed boundary, each rank reads it from its own tiers (`read`) and + /// restores it into a new session, then one sealed confirmation: unless + /// both restored, both discard what they restored and prefill from zero. + /// A state read from SSD becomes resident here, confirmed or not (it is + /// this rank's valid state there), so the next offer finds it in memory. + /// `captureLimit`: what this request's capture may hold (0 keeps none). + /// `stop`: a cancel or deadline while a record is read declines it. + func open(_ request: QwenLayerStageGenerationRequest, model: Gemma4TensorParallelModel, host: CBv2StageKVHost, + group: any QwenTensorParallelReduction, captureLimit: Int, stop: @escaping () -> Bool = { false }) + throws -> Gemma4TensorParallelPagedSession { + let rank = group.rank, prompt = request.promptTokenIDs + var restored: Gemma4TensorParallelPagedSession?, tier: String?, agreed = 0 + let scopes = scopes(request) + if let scopes, case let candidates = candidates(request), !candidates.isEmpty, + let vote = try vote(request, scopes: scopes, candidates: candidates, group: group) { + agreed = vote.boundary + struct Stopped: Error {} + var local: (state: QwenStagePrefixState, tier: String)? + do { + let geometry = try Gemma4TensorParallelPagedSession.geometry(model: model, host: host, + maximumTokens: request.maximumTokens) + local = try read(vote.boundary, request: request, scopes: scopes, geometry: geometry, + check: { if stop() { throw Stopped() } }) + } catch is Stopped { + local = nil + } + if let local { + do { + restored = try Gemma4TensorParallelPagedSession(model: model, host: host, + promptCount: request.promptCount, outputCount: request.outputCount, restoring: local.state) + tier = local.tier + } catch { + // This rank could not restore; the confirmation says so. + log("darkbloom-prefix-v1 rank=\(rank) family=gemma4 restore-failed frontier=\(vote.boundary): \(error)") + if local.tier == "ssd", let diskScope = scopes.disk { + disk?.forget(scope: diskScope, tokens: prompt, frontier: vote.boundary) + } + } + } + let both: Bool + do { both = try QwenTensorParallelPrefixCache.confirm(restored != nil, group: group) } catch { + try? restored?.retire(failed: true) + throw error + } + if let local, local.tier == "ssd", restored != nil { + cache.insert(scope: scopes.resident, tokens: prompt, states: [local.state], sharedBytes: local.state.sharedBytes) + } + if !both { + log("darkbloom-prefix-ssd-v1 rank=\(rank) event=restore-declined frontier=\(vote.boundary)" + + " tier=\(tier ?? "none") local=\(restored != nil ? 1 : 0) kept=\(tier == "ssd" ? 1 : 0)") + try restored?.retire() + restored = nil; tier = nil + } + } + let session = try restored ?? Gemma4TensorParallelPagedSession(model: model, host: host, + promptCount: request.promptCount, outputCount: request.outputCount) + if scopes != nil, captureLimit > 0 { + // The pipeline's rule for chunk-grid families: existing grid ends after + // the restored prefix, strictly before the prompt end. + let step = cache.stride(chunkSize: request.chunkSize) + let frontiers = Set(Swift.stride(from: (session.reusedPrefixTokens / step + 1) * step, + to: request.promptCount, by: step)) + if !frontiers.isEmpty { + session.prefixCapture = .init(frontiers: frontiers, limitBytes: captureLimit, + maximumFrontiers: cache.frontiersPerPrompt) + } + } + if agreed > 0 { + log("darkbloom-prefix-v1 rank=\(rank) family=gemma4 mode=tensor_parallel agreed=\(agreed)" + + " reused=\(session.reusedPrefixTokens) prompt=\(request.promptCount) tier=\(tier ?? "none")") + } + return session + } + + /// What `request`'s capture may hold on this rank: the pipeline's limit + /// (`QwenStagePrefixCache.captureLimit`: after the deepest prefix this + /// rank holds for it, at the measured cost, within the budget); 0 when it + /// keeps no prefix. + func captureLimit(_ request: QwenLayerStageGenerationRequest) -> Int { + guard let scopes = scopes(request) else { return 0 } + return cache.captureLimit(scope: scopes.resident, tokens: request.promptTokenIDs, chunkSize: request.chunkSize) + } + + /// After a request retired cleanly on both ranks: its capture becomes + /// reusable in memory and is written to the SSD tier behind serving. + /// Returns the boundaries kept. + @discardableResult + func store(_ capture: Gemma4TensorParallelPrefixCapture, request: QwenLayerStageGenerationRequest, scopes: Scopes, + rank: Int) -> [Int] { + defer { capture.discard() } + let states = capture.states() + guard !states.isEmpty else { return [] } + let prompt = request.promptTokenIDs + cache.insert(scope: scopes.resident, tokens: prompt, states: states, sharedBytes: capture.sharedBytes) + if let diskScope = scopes.disk { + disk?.persist(scope: diskScope, tokens: prompt, states: states, blockTokens: cache.stride(chunkSize: request.chunkSize)) + } + if let cost = capture.cost { cache.record(cost) } + log("darkbloom-prefix-v1 rank=\(rank) family=gemma4 mode=tensor_parallel held_bytes=\(cache.bytesInUse)" + + " budget_bytes=\(cache.budgetBytes) capture_limit=\(capture.limitBytes) captured_shared=\(capture.sharedBytes)" + + " stored=\(states.map { String($0.committedTokens) }.joined(separator: ","))") + return states.map(\.committedTokens) + } +} + +extension Gemma4TensorParallelModel { + /// Oracles and tests: what a rank's prompt-prefix memory tier gives a + /// repeated prompt, on this shard's own paged host. `prompt` is served + /// cold and keeps its boundaries (every `chunk`), then `repeated` (by + /// default the same prompt) votes, restores the deepest boundary both + /// ranks hold and continues from it, as the resident runtime serves it. + /// Both ranks call it with the same values. + public func generatePagedRepeatingPrefix(prompt: [Int], repeated: [Int]? = nil, outputCount: Int, chunk: Int, + recordTop: Int = 0) + throws -> (cold: Generation, restored: Generation, reusedPromptTokens: Int, storedFrontiers: [Int]) { + let second = repeated ?? prompt + guard case .shard = role, let reduction, !prompt.isEmpty, !second.isEmpty, outputCount >= 1, chunk >= 1, + (prompt + second).allSatisfy({ (0 ..< plan.vocabularySize).contains($0) }), (0 ... 64).contains(recordTop) else { + throw ProbeError("Gemma tensor-parallel prefix oracle: a shard, two prompts in the vocabulary, bounded options") + } + let longest = max(prompt.count, second.count) + let activation = String(describing: activationDType) + let profile = try QwenLayerStageGenerationProfile(identifier: "gemma4-tensor-parallel-prefix", + vocabularySize: plan.vocabularySize, hiddenSize: plan.hiddenSize, activationDType: activation, + maximumPromptTokens: longest, maximumChunkTokens: chunk, maximumOutputTokens: outputCount, + maximumContextTokens: longest + outputCount, logitsDType: activation == "float32" ? nil : "float32") + let prefix = Gemma4TensorParallelPrefix(cache: QwenStagePrefixCache(strideTokens: chunk), + load: "gemma4-tensor-parallel-prefix-oracle|" + Gemma4TensorParallelPlan.name, diskPlanScope: nil) + let host = try pagedHost(lanes: 1, maximumTokens: longest + outputCount, chunkTokens: chunk) + func serve(_ tokens: [Int], index: Int) throws -> (generation: Generation, reused: Int, stored: [Int]) { + let request = try QwenLayerStageGenerationRequest(profile: profile, + requestID: UUID(uuidString: String(format: "00000000-0000-4000-8000-%012d", index))!, + promptTokenIDs: tokens, chunkSize: chunk, outputCount: outputCount, stopTokenIDs: []) + let session = try MLX.withError { error -> Gemma4TensorParallelPagedSession in + let value = try prefix.open(request, model: self, host: host, group: reduction, + captureLimit: prefix.captureLimit(request)) + try error.check() + return value + } + let generation = try generatePaged(session: session, host: host, prompt: tokens, outputCount: outputCount, + chunk: chunk, recordTop: recordTop) + var stored: [Int] = [] + if let capture = session.prefixCapture, let scopes = prefix.scopes(request) { + stored = prefix.store(capture, request: request, scopes: scopes, rank: reduction.rank) + } + return (generation, session.reusedPrefixTokens, stored) + } + let cold = try serve(prompt, index: 0) + let restored = try serve(second, index: 1) + return (cold.generation, restored.generation, restored.reused, cold.stored) + } +} + +/// One request's prefix capture on a Gemma 4 tensor-parallel rank: the +/// boundaries it was asked to keep, what it keeps within its limit (measured +/// at its first boundary, `QwenStagePrefixCaptureCost.kept`), and the copies, +/// as the pipeline's stage session keeps them (`QwenLayerStageSession.capturePrefix`). +final class Gemma4TensorParallelPrefixCapture { + let frontiers: Set + let limitBytes: Int + let maximumFrontiers: Int + private(set) var cost: QwenStagePrefixCaptureCost? + private var kept: Set? + private(set) var withdrawn = false + /// Each kept boundary's sliding windows, keyed by layer. + private var windows: [Int: [Int: (conv: MLXArray, ssm: MLXArray)]] = [:] + /// Full-attention rows copied once, at the deepest boundary. + private var deepest: (committed: Int, layers: [Int: (keys: MLXArray, values: MLXArray)])? + + init(frontiers: Set, limitBytes: Int, maximumFrontiers: Int) { + self.frontiers = frontiers; self.limitBytes = max(0, limitBytes); self.maximumFrontiers = maximumFrontiers + } + + /// After the prompt chunk that committed `frontier` (`state` is the + /// request's). A sliding row holds only its window, oldest first: its + /// state at a boundary is its own and is copied now (the ring takes + /// later tokens in place); full rows are copied at the deepest boundary. + func capture(_ state: CBv2OwnedRequestState, at frontier: Int) throws { + guard frontiers.contains(frontier), !withdrawn else { return } + guard state.committedTokens == frontier else { throw ProbeError("Gemma tensor-parallel prefix capture differs from the committed frontier") } + var rows: [Int: (keys: MLXArray, values: MLXArray)] = [:] + var tails: [Int: (keys: MLXArray, values: MLXArray)] = [:], windowBytes = 0 + for (position, optionalRow) in state.rows.enumerated() { + let kind = state.geometry.kinds[position] + guard let row = optionalRow, let layer = kind.modelLayerIndex else { + throw ProbeError("Gemma tensor-parallel prefix capture lacks an attention row") + } + let snapshot = row.snapshot() + let retained = kind.retainedTokens(atFrontier: frontier) + guard snapshot.offset == frontier, snapshot.keys.dim(2) == retained, retained > 0 else { + throw ProbeError("Gemma tensor-parallel prefix capture frontier differs from a row's") + } + if case .slidingWindow(let window) = kind.attention { + tails[layer] = (snapshot.keys, snapshot.values) + // Every boundary is charged a full window: one taken before the + // prompt filled it is shorter than every later one. + let perPosition = (snapshot.keys.nbytes + snapshot.values.nbytes + retained - 1) / retained + windowBytes = try QwenLongPrefillCheckedBytes.sum([windowBytes, + try QwenLongPrefillCheckedBytes.product([perPosition, window])]) + } else { + rows[layer] = (snapshot.keys, snapshot.values) + } + } + let planned = frontiers.sorted() + if kept == nil { + let attention = rows.values.reduce(0) { $0 + $1.keys.nbytes + $1.values.nbytes } + let measured = QwenStagePrefixCaptureCost(attentionBytesPerToken: (attention + frontier - 1) / frontier, + recurrentBytesPerFrontier: windowBytes, historyBytesPerToken: 0) + cost = measured + kept = measured.kept(planned, limit: limitBytes, maximum: maximumFrontiers) + } + guard kept?.contains(frontier) == true else { return } + func copy(_ value: MLXArray) -> MLXArray { value * MLXArray(1).asType(value.dtype) } + let own = tails.mapValues { (conv: copy($0.keys), ssm: copy($0.values)) } + eval(own.values.flatMap { [$0.conv, $0.ssm] }) + windows[frontier] = own + guard frontier == planned.last else { return } + let copies = rows.mapValues { (keys: copy($0.keys), values: copy($0.values)) } + eval(copies.values.flatMap { [$0.keys, $0.values] }) + deepest = (frontier, copies) + } + + /// The kept boundaries' states, ascending, each viewing the one copy of + /// the full rows; empty unless the deepest was reached. + func states() -> [QwenStagePrefixState] { + guard let deepest, !withdrawn else { return [] } + return windows.keys.sorted().compactMap { frontier in + guard frontier <= deepest.committed, let own = windows[frontier] else { return nil } + let rows = deepest.layers.mapValues { pair -> (keys: MLXArray, values: MLXArray) in + frontier == deepest.committed ? pair + : (keys: pair.keys[0..., 0..., 0 ..< frontier, 0...], values: pair.values[0..., 0..., 0 ..< frontier, 0...]) + } + return QwenStagePrefixState(committedTokens: frontier, attention: rows, recurrent: own) + } + } + + /// Bytes of the full-row copy the kept states view together. + var sharedBytes: Int { deepest?.layers.values.reduce(0) { $0 + $1.keys.nbytes + $1.values.nbytes } ?? 0 } + + /// Bytes this capture holds now. + var heldBytes: Int { + sharedBytes + windows.values.reduce(0) { total, own in total + own.values.reduce(0) { $0 + $1.conv.nbytes + $1.ssm.nbytes } } + } + + /// The running check withdrew it: let go of what it holds, capture no more. + func withdraw() { withdrawn = true; windows.removeAll(); deepest = nil } + + func discard() { windows.removeAll(); deepest = nil; kept = nil } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelRequestLoop.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelRequestLoop.swift index cf57d14b24..b3fa291709 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelRequestLoop.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelRequestLoop.swift @@ -3,8 +3,9 @@ import Foundation import MLX /// One request on one rank of a Gemma 4 tensor-parallel pair, as the resident -/// runtime serves it alone: the prompt in chunks of the request's own size, -/// then one decode step a token. Each step's token and both ranks' stop flags +/// runtime serves it alone: the prompt in chunks of the request's own size +/// (from a restored prefix's boundary, when both ranks restored one), then +/// one decode step a token. Each step's token and both ranks' stop flags /// are agreed in the step's own evaluation (`Gemma4TensorParallelChoice`); /// both ranks submit the same collectives in the same order whatever either /// decides, and end after the same step. @@ -39,7 +40,8 @@ struct Gemma4TensorParallelRequestLoop { func run(channel: ClusterCommittedTokenChannel, check: () throws -> Void) throws -> Outcome { let rank = choice.rank, prompt = request.promptTokenIDs let sampler = choice.sampler - var offset = 0 + // A restored prefix ends on the chunk grid: the rest runs the chunks a cold request runs there. + var offset = session.committedTokens var current: (logits: MLXArray, selected: MLXArray)? while offset < prompt.count { let end = min(prompt.count, offset + request.chunkSize) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift index 3b0e8fa8da..f8adf9ffe2 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift @@ -29,7 +29,12 @@ import MLXLMCommon /// request's from the vocabulary-split top-k gather, a sampled one's from the /// product's sampler on rank 0. /// -/// Not yet: prompt prefixes, speculative decoding and media. +/// Prompt prefixes are kept as the Gemma pipeline keeps them, resident and on +/// the owner's encrypted SSD tier, each rank its own heads; a request +/// restores the deepest boundary both ranks hold after a sealed vote and +/// confirmation, or neither does (`Gemma4TensorParallelPrefix`). +/// +/// Not yet: speculative decoding and media. public final class Gemma4TensorParallelResidentRuntime { static let planName = Gemma4TensorParallelPlan.name /// Bytes the worker keeps for MLX's freed-buffer cache once ready under @@ -66,10 +71,14 @@ public final class Gemma4TensorParallelResidentRuntime { var failedLaneDriver: QwenTensorParallelBatchDriver>? /// Raw-token logprobs are published for every request that asks for them. public var capturesLogprobs: Bool { true } + /// This rank's prompt prefixes, in memory and on its SSD tier. + let prefix: Gemma4TensorParallelPrefix struct Reserved { let request: QwenLayerStageGenerationRequest let deadline: UInt64 + /// What this request's prefix capture may hold (0: none). + var prefixCaptureLimit = 0 } // MARK: - Load @@ -80,15 +89,24 @@ public final class Gemma4TensorParallelResidentRuntime { (try? Gemma4RegisteredSpecification.registered(runtimeModelID: runtimeModelID)) != nil } + /// `prefixSSDKey`: the 32-byte key of this rank's prompt-prefix SSD tier, + /// as the owner sent it on the worker's input; nil keeps the tier off. public static func load(_ configuration: QwenResidentLoadConfiguration, qualification: QwenResidentQualificationSwitches = .refused, - dataPlane credential: ClusterDataPlaneCredential) throws -> Gemma4TensorParallelResidentRuntime { + dataPlane credential: ClusterDataPlaneCredential, + prefixSSDKey: Data? = nil) throws -> Gemma4TensorParallelResidentRuntime { let environment = ProcessInfo.processInfo.environment try qualification.admit(environment: environment) let kvQuantization = try PagedKVQuantizationSelection.clusterLive(environment) try kvQuantization.requireNative("Gemma tensor parallel, whose paged KV stays native until it is qualified") let kv = try ClusterStageKVBackendKind.fromEnvironment(environment) let lanes = try QwenBatchSettings.fromEnvironment(environment).lanes + // Prompt prefixes, unless the diagnosis switch turns them off on this + // rank (`DARKBLOOM_CLUSTER_PREFIX_CACHE=off`): bound into the agreement, + // so both ranks keep them or neither does. Gemma records stay native. + let prefixCache = QwenStagePrefixCache.fromEnvironment(environment) + let keepsPrefixes = Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes && prefixCache.enabled + let prefixRecords = try QwenStagePrefixDiskEncoding.fromEnvironment(environment, family: .native) let directory = configuration.modelDirectory let any = try LayerStageResidentFamily.admission(configuration: configuration, configBytes: BoundedProbeInput.data(directory.appendingPathComponent("config.json"), maximumBytes: 1_048_576), @@ -115,7 +133,8 @@ public final class Gemma4TensorParallelResidentRuntime { try admission.jaccl.requireUnchanged(environment: ProcessInfo.processInfo.environment, read: read) try admission.jaccl.requireInitialized(rank: collective.rank, worldSize: collective.size, transport: collective.transport) - let terms = Gemma4TensorParallelLoadAgreement(lanes: lanes, kv: kv, kvQuantization: kvQuantization, prefixCache: false) + let terms = Gemma4TensorParallelLoadAgreement(lanes: lanes, kv: kv, kvQuantization: kvQuantization, + prefixCache: keepsPrefixes) let loadAgreement = try terms.fingerprint(admission: try admission.loadAgreementFingerprint()) try ClusterDataPlaneAgreement.establish(collective: collective, credential: credential, loadAgreement: loadAgreement, tamper: nil, tensorParallelSeal: true, check: { try control.check() }) @@ -131,6 +150,7 @@ public final class Gemma4TensorParallelResidentRuntime { let profile = admission.profile var probe: ClusterWorkerLinkProbe? var receipt: Gemma4TensorParallelShardReceipt? + var prefixCharges = (resident: 0, capture: 0, room: 0) let capacity = try MLX.withError { nativeError -> Int in func checked() throws { try nativeError.check(); try control.check(); try nativeError.check() } try configuration.allocatorPolicy.configure(setCacheLimit: { Memory.cacheLimit = $0 }, check: checked) @@ -144,8 +164,10 @@ public final class Gemma4TensorParallelResidentRuntime { probe = measured log(QwenTensorParallelLinkProbe.line(measured, rank: collective.rank)) // The load gate admits the shard with the profile's longest request and the rank's own - // reserve (activation floor, freed-buffer cache, sealed frames) beside it: the planner's quote. - let budget = try requestBudget(contextTokens: profile.maximumContextTokens, admission: admission) + // reserve (activation floor, freed-buffer cache, sealed frames, the prefix tier's + // charged budget) beside it: the planner's quote. + let budget = try requestBudget(contextTokens: profile.maximumContextTokens, admission: admission, + keepsPrefixes: keepsPrefixes) let request = budget.requestBytes let value = try autoreleasepool { try Gemma4TensorParallelVerifiedLoad.load(admission, rank: collective.rank, reduction: reduction, @@ -177,6 +199,16 @@ public final class Gemma4TensorParallelResidentRuntime { Memory.cacheLimit = bufferCacheBytes try checked() } + // The prefix memory tier: its charged budget at least, else the + // pipeline's (half the admissible room beside the longest + // request and this rank's reserve, at most `maximumBudgetBytes`), + // whose entries beyond the charged part give way first. + if keepsPrefixes { + let room = try ClusterStagePrefixBudget.roomBytes(chargeBytes: try QwenLongPrefillCheckedBytes.sum([ + budget.requestBytes, budget.rankBytes])) + prefixCache.setBudget(max(budget.prefixResidentBytes, QwenStagePrefixCache.budget(roomBytes: room))) + prefixCharges = (budget.prefixResidentBytes, budget.prefixCaptureBytes, room) + } log("darkbloom-tensor-parallel-load-v1 rank=\(collective.rank) plan=\(planName) shares=1-1" + " shard_bytes=\(value.receipt.shardBytes) source_bytes=\(value.receipt.sourceBytes)" + " tensors=\(value.receipt.sourceTensors) load_ns=\(value.receipt.loadNanoseconds) sealed=1" @@ -184,20 +216,37 @@ public final class Gemma4TensorParallelResidentRuntime { + " kv_heads=\(value.model.plan.kvHeadsPerRank.map(String.init).joined(separator: "-"))") return request } - guard let model = loadedModel, let host = loadedHost, receipt != nil else { + guard let model = loadedModel, let host = loadedHost, let receipt else { throw ProbeError("Gemma tensor-parallel load returned no shard") } // This rank's own share, timed alone before its ready record. let shareProbe = try Gemma4TensorParallelShareProbe.measure(model: model, reduction: reduction, profile: profile, deadline: control.deadline, admit: { tokens, chunk in try QwenTensorParallelShareProbe.memoryAdmits(bytes: requestChargeBytes(contextTokens: tokens, - admission: admission, chunkTokens: chunk)) + admission: admission, chunkTokens: chunk, keepsPrefixes: false)) }, check: { try control.check() }) if let shareProbe { log(QwenTensorParallelShareProbe.line(shareProbe, rank: collective.rank)) } try control.loaded() + // The prefix cache's SSD tier, when the owner configured one: this + // rank's records of this artifact, plan and both builds, which a + // restarted pair finds again. Opening it sweeps the directories of + // other plans under the root that hold no live record. + let identity = admission.configuration.identity + let diskPlanScope = Gemma4TensorParallelPrefix.planScope(admission: admission, + aggregateSHA256: receipt.verifiedAggregateSHA256, storageCommitmentSHA256: receipt.storageCommitmentSHA256) + if keepsPrefixes { + prefixCache.disk = QwenStagePrefixDiskTier.open(configuration: .fromEnvironment(environment, key: prefixSSDKey), + planScope: diskPlanScope, rank: collective.rank, encoding: prefixRecords, + stagingEpoch: identity.membershipEpoch.uuidString.lowercased()) + } + log("darkbloom-prefix-v1 rank=\(collective.rank) family=gemma4 mode=tensor_parallel enabled=\(keepsPrefixes)" + + " budget_bytes=\(keepsPrefixes ? prefixCache.budgetBytes : 0) charged_bytes=\(prefixCharges.resident)" + + " capture_charge=\(prefixCharges.capture) room_bytes=\(prefixCharges.room) ssd=\(prefixCache.disk != nil)") + let prefix = Gemma4TensorParallelPrefix(cache: keepsPrefixes ? prefixCache : QwenStagePrefixCache(enabled: false), + load: loadAgreement, diskPlanScope: diskPlanScope) return Gemma4TensorParallelResidentRuntime(admission: admission, control: control, collective: collective, group: group, codec: codec, model: model, host: host, loadAgreement: loadAgreement, capacity: capacity, - linkProbe: probe, shareProbe: shareProbe, lanes: lanes) + linkProbe: probe, shareProbe: shareProbe, lanes: lanes, prefix: prefix) } catch { let primary = error control.fail(); loadedHost = nil; loadedModel = nil @@ -214,30 +263,48 @@ public final class Gemma4TensorParallelResidentRuntime { } /// This rank's reserve for requests of `contextTokens` (`Gemma4TensorParallelRequestBudget`) - /// at the allocator's own bound. - static func requestBudget(contextTokens: Int, admission: Gemma4ResidentAdmission, - chunkTokens: Int? = nil) throws -> Gemma4TensorParallelRequestBudget { + /// at the allocator's own bound; `keepsPrefixes` charges the prompt-prefix + /// capture and memory tier. + static func requestBudget(contextTokens: Int, admission: Gemma4ResidentAdmission, chunkTokens: Int? = nil, + keepsPrefixes: Bool = true) throws -> Gemma4TensorParallelRequestBudget { try Gemma4TensorParallelRequestBudget.derive(contextTokens: contextTokens, chunkTokens: chunkTokens ?? admission.profile.maximumChunkTokens, + promptTokens: admission.profile.maximumPromptTokens, keepsPrefixes: keepsPrefixes, allocationBound: QwenResidentResourceEnvironment.allocationBound) } /// What one request of `contextTokens` reserves on a rank: its own KV /// heads, its own query heads' prompt transient, the chunk's FP32 - /// partials and the vocabulary rows (`Gemma4TensorParallelRequestBudget.requestBytes`). + /// partials, the vocabulary rows and its prefix capture at its deepest + /// boundary (`Gemma4TensorParallelRequestBudget.requestBytes`). static func requestChargeBytes(contextTokens: Int, admission: Gemma4ResidentAdmission, - chunkTokens: Int? = nil) throws -> Int { - try requestBudget(contextTokens: contextTokens, admission: admission, chunkTokens: chunkTokens).requestBytes + chunkTokens: Int? = nil, keepsPrefixes: Bool = true) throws -> Int { + try requestBudget(contextTokens: contextTokens, admission: admission, chunkTokens: chunkTokens, + keepsPrefixes: keepsPrefixes).requestBytes } /// What the live gate asks for beside every held request: the rank's - /// activation floor, freed-buffer cache and sealed frames. + /// activation floor, freed-buffer cache, sealed frames and the prefix + /// memory tier's charged budget. var rankReserveBytes: Int { get throws { - try Self.requestBudget(contextTokens: admission.profile.maximumContextTokens, admission: admission).rankBytes + try Self.requestBudget(contextTokens: admission.profile.maximumContextTokens, admission: admission, + keepsPrefixes: prefix.cache.enabled).rankBytes } } + /// A request's charge on this rank and what its prefix capture may hold + /// beyond the part that charge covers (`Gemma4TensorParallelPrefix.captureLimit` + /// less the capture at its deepest boundary): kept entries give way before + /// the live gate refuses it, and a capture the gate still refuses is cut + /// to its charged part. + func prefixCharge(_ request: QwenLayerStageGenerationRequest) throws -> (charge: Int, captureLimit: Int, beyond: Int) { + let budget = try Self.requestBudget(contextTokens: request.maximumTokens, admission: admission, + chunkTokens: request.chunkSize, keepsPrefixes: prefix.cache.enabled) + let limit = prefix.captureLimit(request) + return (budget.requestBytes, limit, max(0, limit - budget.prefixCaptureBytes)) + } + /// The host memory gate's decision for `bytes` more, as the resident families take it. static func requireLiveMemory(bytes: Int) throws { try QwenResidentResourceEnvironment.require() @@ -253,10 +320,10 @@ public final class Gemma4TensorParallelResidentRuntime { private init(admission: Gemma4ResidentAdmission, control: QwenResidentControl, collective: Collective, group: QwenTensorParallelGroup, codec: QwenTensorParallelSealCodec, model: Gemma4TensorParallelModel, host: CBv2StageKVHost, loadAgreement: String, capacity: Int, linkProbe: ClusterWorkerLinkProbe?, - shareProbe: ClusterWorkerShareProbe?, lanes: Int) { + shareProbe: ClusterWorkerShareProbe?, lanes: Int, prefix: Gemma4TensorParallelPrefix) { self.admission = admission; self.control = control; self.collective = collective; self.group = group self.codec = codec; self.model = model; self.host = host; self.loadAgreement = loadAgreement - self.linkProbe = linkProbe; self.shareProbe = shareProbe; self.lanes = lanes + self.linkProbe = linkProbe; self.shareProbe = shareProbe; self.lanes = lanes; self.prefix = prefix baseReady = .init(identity: admission.configuration.identity, rank: collective.rank, profile: admission.wireProfile, executionPlanSHA256: admission.plan.fingerprint, requestCapacityBytes: capacity, dataPlane: collective.workerDataPlane, linkProbe: linkProbe, @@ -294,8 +361,8 @@ public final class Gemma4TensorParallelResidentRuntime { } let request = try admission.request(value, id: requestID, now: now) // Charged at its own context: the live gate alone decides whether it fits. - let charge = try Self.requestChargeBytes(contextTokens: request.maximumTokens, admission: admission, - chunkTokens: request.chunkSize) + let priced = try prefixCharge(request) + let charge = priced.charge try control.check(); try control.reserve(requestID) return try control.reserving(requestID, rank: collective.rank, deadline: value.deadlineUptimeNanoseconds) { guard model != nil, host != nil else { throw ProbeError("Resident model already released") } @@ -303,13 +370,33 @@ public final class Gemma4TensorParallelResidentRuntime { throw ProbeError("Gemma tensor-parallel reservation exceeds its owner or readiness capacity") } ClusterIdleMemory.releaseFreedBuffers() - try Self.requireLiveMemory(bytes: try QwenLongPrefillCheckedBytes.sum([charge, rankReserveBytes])) + let captureLimit = try admitCapture(priced, held: [charge, rankReserveBytes]) try control.check(deadline: value.deadlineUptimeNanoseconds) - reservation = .init(request: request, deadline: value.deadlineUptimeNanoseconds) + reservation = .init(request: request, deadline: value.deadlineUptimeNanoseconds, prefixCaptureLimit: captureLimit) return charge } } + /// The live gate for a request priced as `prefixCharge` beside `held` + /// bytes: kept prefix entries give way first; a capture beyond its + /// charged part that still does not fit is cut to that part. Returns the + /// capture limit admitted. + func admitCapture(_ priced: (charge: Int, captureLimit: Int, beyond: Int), held: [Int]) throws -> Int { + let base = try QwenLongPrefillCheckedBytes.sum(held) + if priced.beyond > 0 { + do { + try prefix.cache.yieldingMemory { + try Self.requireLiveMemory(bytes: try QwenLongPrefillCheckedBytes.sum([base, priced.beyond])) + } + return priced.captureLimit + } catch { + log("darkbloom-prefix-v1 rank=\(collective.rank) family=gemma4 capture-cut bytes=\(priced.beyond): \(error)") + } + } + try prefix.cache.yieldingMemory { try Self.requireLiveMemory(bytes: base) } + return priced.captureLimit - priced.beyond + } + public func releaseReservation(requestID: UUID) throws { guard operation.try() else { throw ProbeError("Resident native operation is already active") } defer { operation.unlock() } @@ -345,12 +432,33 @@ public final class Gemma4TensorParallelResidentRuntime { reservation = nil return value } catch { + // The peer may hold something else now. + prefix.cache.sweep() control.fail(); throw error } } public func cancel(requestID: UUID) { control.cancel(requestID) } + /// Gives back what this idle rank holds beyond its weights + /// (`ClusterIdleMemory`): MLX's freed-buffer cache, and the prompt-prefix + /// entries too while the host is `underPressure` (the vote then restores + /// nothing until both ranks hold a boundary again). Nothing while a + /// request or any batch lane is reserved, started or running. + public func releaseIdleMemory(underPressure: Bool) throws -> Int { + guard operation.try() else { throw ProbeError("Resident native operation is already active") } + defer { operation.unlock() } + guard control.available, reservation == nil, laneBook.isEmpty, model != nil else { return 0 } + let held = prefix.cache.bytesInUse, entries = prefix.cache.count + if underPressure { prefix.cache.sweep() } + let released = ClusterIdleMemory.releaseFreedBuffers() + if underPressure, entries > 0 { + log("darkbloom-idle-release-v1 rank=\(collective.rank) family=gemma4 prefix_entries_dropped=\(entries)" + + " prefix_bytes_dropped=\(held) freed_buffer_bytes=\(released)") + } + return released + } + public func shutdown() throws { guard operation.try() else { throw ProbeError("Cannot release a running native request") } defer { operation.unlock() } @@ -362,6 +470,10 @@ public final class Gemma4TensorParallelResidentRuntime { Stream.gpu.synchronize(); Stream.cpu.synchronize(); try error.check() try failedLaneDriver?.retireAll() guard host?.isDrained ?? true else { throw ProbeError("Gemma tensor-parallel request state remains owned") } + // Records already queued for the SSD are finished first + // (bounded): they are what a restarted pair restores. + prefix.disk?.close() + prefix.cache.sweep() reservation = nil; laneBook.clear(); failedLaneDriver = nil; host = nil weak var released: Gemma4TensorParallelModel? released = model; model = nil @@ -385,19 +497,33 @@ public final class Gemma4TensorParallelResidentRuntime { guard try group.digestsEqual(QwenTensorParallelResidentRuntime.digest64(request.fingerprint + "|" + loadAgreement)) else { throw ProbeError("Gemma tensor-parallel ranks were given different requests") } - let session = try Gemma4TensorParallelPagedSession(model: model, host: host, - promptCount: request.promptTokenIDs.count, outputCount: request.outputCount) + // Prompt prefix: the deepest boundary both ranks hold, voted and confirmed (or none). + let session = try MLX.withError { error -> Gemma4TensorParallelPagedSession in + let value = try prefix.open(request, model: model, host: host, group: group, + captureLimit: reserved.prefixCaptureLimit, stop: { [control] in + (try? control.check(deadline: reserved.deadline)) == nil + }) + try error.check() + return value + } do { // A step checks native errors only: a cancel or deadline must not // end one rank between two collectives (its peer would wait in the // next one), so it rides in the next step's flags (`localStop`). - let completion = try MLX.withError { error in + var completion = try MLX.withError { error in try serve(request, session: session, deadline: reserved.deadline, channel: channel, checked: { try error.check() }) } try session.retire() + // Both ranks ended after the same step and agreed how: the prompt's + // capture becomes reusable now, in memory and behind serving on SSD. + if let capture = session.prefixCapture, let scopes = prefix.scopes(request) { + completion.storedPromptFrontiers = prefix.store(capture, request: request, scopes: scopes, rank: collective.rank) + } + completion.reusedPromptTokens = session.reusedPrefixTokens return completion } catch { + session.prefixCapture?.withdraw() try? session.retire(failed: true) throw error } @@ -412,12 +538,17 @@ public final class Gemma4TensorParallelResidentRuntime { let choice = Gemma4TensorParallelChoice(selection: session.model.selection, sampler: request.sampler, rank: rank) var lastCheck: UInt64 = 0 let loop = Gemma4TensorParallelRequestLoop(session: session, request: request, choice: choice, - exchange: { [group] in try group.exchangeIntegers($0) }, localStop: { [control] in + exchange: { [group] in try group.exchangeIntegers($0) }, localStop: { [control, prefix] in if (try? control.check(deadline: deadline)) == nil { return true } let now = DispatchTime.now().uptimeNanoseconds if now - lastCheck >= 250_000_000 { lastCheck = now - if (try? Self.requireLiveMemory(bytes: 0)) == nil { return true } + // Kept prefixes give way first, then the request's own capture. + if (try? prefix.cache.yieldingMemory({ try Self.requireLiveMemory(bytes: 0) })) == nil { + guard let capture = session.prefixCapture, !capture.withdrawn else { return true } + capture.withdraw(); Memory.clearCache() + return (try? Self.requireLiveMemory(bytes: 0)) == nil + } } return false }) @@ -431,7 +562,7 @@ public final class Gemma4TensorParallelResidentRuntime { + " prompt=\(prompt.count) output=\(tokens.count) finish=\(finish.rawValue) sampled=\(choice.gathersRow ? 1 : 0)" + " logprobs=\(request.sampler?.wire.capturedLogprobs ?? 0) frames=\(codec.sealedFrames)" + " key_generation=\(codec.keyGeneration) kv_tokens=\(session.state.reservedTokens)" - + " kv_refused=\(ended.pagesRefused ? 1 : 0)") + + " kv_refused=\(ended.pagesRefused ? 1 : 0) reused=\(session.reusedPrefixTokens)") return QwenResidentGenerationCompletion(requestID: request.requestID, finishReason: finish, selectedTokenIDs: tokens, completedFrames: tokens.count, committedTokens: prompt.count + tokens.count, tokenChainSHA256: sha256(try canonicalJSONData(tokens.map { String($0) })), bothRequestStatesRetired: true) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift index 391dc32a6f..66815f56ad 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift @@ -387,9 +387,12 @@ public enum ClusterPlacementLayouts { let bound = allocationBound #endif if family.tensorParallel != nil, let bound { - // What a rank's LOAD gate reserves beside its shard: one request at the profile's longest context. + // What a rank's LOAD gate reserves beside its shard: one request at the profile's longest + // context, with its prompt-prefix capture and the prefix tier's charged budget. family.tensorParallelRequestAllowance = try Gemma4TensorParallelRequestBudget.derive( contextTokens: family.profile.maximumContextTokens, chunkTokens: family.profile.maximumChunkTokens, + promptTokens: family.profile.maximumPromptTokens, + keepsPrefixes: Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes, allocationBound: bound).allowance } return try ClusterModelLayoutBuilder.build(family: family, tensors: tensors, diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/State/CBv2OwnedRequestState.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/State/CBv2OwnedRequestState.swift index a8ed2b5589..0ffbbbd4a8 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/State/CBv2OwnedRequestState.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/State/CBv2OwnedRequestState.swift @@ -87,7 +87,8 @@ final class CBv2OwnedRequestState { /// `slidingTails`: each sliding-window layer's retained window at the /// frontier (its last `min(committed, window)` positions, oldest first), /// in place of a whole-history row. `reservedTokens` as for a fresh - /// request (full attention only), at least the adopted frontier. + /// request, at least the adopted frontier: the rows' pages then grow + /// from there as a fresh request's do. init(geometry: CBv2RequestGeometry, promptCount: Int, outputCount: Int, adoptingCommittedTokens committed: Int, attention: [Int: (keys: MLXArray, values: MLXArray)], @@ -100,7 +101,7 @@ final class CBv2OwnedRequestState { (1...(promptCount + outputCount)).contains(committed), attention.count + slidingTails.count == geometry.kinds.count, adopted.count == geometry.recurrent.layers.count, - reservedTokens == nil || slidingTails.isEmpty else { + reservedTokens.map({ $0 >= committed }) ?? true else { throw ProbeError("CBv2 adopted state exceeds the bounded request context or its layer coverage differs") } var prefix: [(keys: MLXArray, values: MLXArray, offset: Int)?] = [] @@ -127,7 +128,7 @@ final class CBv2OwnedRequestState { let backend: any CBv2KVBackend = geometry.host?.backend ?? CBv2ContiguousKVBackend(config: .init( bytesCapacity: geometry.kvCapacityBytes, kvDType: geometry.kvDType)) let rows: [CBv2SequenceKV?] - if let reservedTokens { + if let reservedTokens, slidingTails.isEmpty { // Full attention only, into rows reserved for their first tokens. guard let paged = backend as? PagedKVBackend else { throw ProbeError("A growing CBv2 reservation needs the stage's paged pool") @@ -144,9 +145,18 @@ final class CBv2OwnedRequestState { // A sliding row keeps only its window: fresh rows, each full row // written whole, each sliding row moved to its tail's first position // and written there, so ring slots, offset and oldest retained - // position are what the original frames left. - rows = try backend.makeSequenceState(layerKinds: geometry.kinds, promptLength: promptCount, - maxLength: promptCount + outputCount) + // position are what the original frames left. With `reservedTokens` + // the rows are reserved for their first tokens, as a fresh request's. + if let reservedTokens { + guard let paged = backend as? PagedKVBackend else { + throw ProbeError("A growing CBv2 reservation needs the stage's paged pool") + } + rows = try paged.makeSequenceState(layerKinds: geometry.kinds, promptLength: promptCount, + maxLength: promptCount + outputCount, reservedTokens: reservedTokens) + } else { + rows = try backend.makeSequenceState(layerKinds: geometry.kinds, promptLength: promptCount, + maxLength: promptCount + outputCount) + } guard rows.count == geometry.kinds.count, rows.allSatisfy({ $0 != nil }) else { backend.release(rows) throw ProbeError("CBv2 adopted sliding state lacks a row per layer") diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelPrefixTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelPrefixTests.swift new file mode 100644 index 0000000000..de6fb685ec --- /dev/null +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelPrefixTests.swift @@ -0,0 +1,584 @@ +import DarkbloomClusterProtocol +import Darwin +import Foundation +import MLX +import MLXLMCommon +import Testing +@testable import DarkbloomClusterRuntime + +/// Gemma 4 tensor parallel's prompt prefixes (`Gemma4TensorParallelPrefix`) +/// on synthetic checkpoints and two in-process ranks: a restore equals the +/// cold prefill bit for bit (logits, every row of state, the sliding +/// windows), both ranks agree on every hit or miss through the sealed vote +/// and its confirmation, the memory tier evicts within its budget, and the +/// encrypted SSD tier keeps the cluster tier's rules. Never a model pass. +@Suite("Gemma 4 tensor-parallel prompt prefixes", .serialized) +struct Gemma4TensorParallelPrefixTests { + private typealias Pair = Gemma4TensorParallelLocalPair + private final class Box: @unchecked Sendable { var value: T; init(_ value: T) { self.value = value } } + + private static let prompt = (0 ..< 40).map { ($0 * 37 + 11) % 512 } + private static let longer = prompt + (0 ..< 13).map { ($0 * 53 + 5) % 512 } + private static let other = (0 ..< 40).map { ($0 * 29 + 300) % 512 } + private static let chunk = 16, outputs = 6, recordTop = 4 + + private static func synthetic() throws -> URL { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("gemma4-tp-prefix-\(UUID().uuidString)") + try Device.withDefaultDevice(.cpu) { + try Gemma4TensorParallelModel.writeSyntheticCheckpoint(directory: directory, bits: 4, experts: 16, topK: 4) + } + return directory + } + + private static func bits(_ rows: [[Float]]) -> [[UInt32]] { rows.map { $0.map(\.bitPattern) } } + + private static func same(_ a: Gemma4TensorParallelModel.Generation, _ b: Gemma4TensorParallelModel.Generation) -> Bool { + a.tokenIDs == b.tokenIDs && a.topTokenIDs == b.topTokenIDs && bits(a.topLogits) == bits(b.topLogits) + && bits(a.topLogprobs) == bits(b.topLogprobs) + && a.finalLogits.map { $0.map(\.bitPattern) } == b.finalLogits.map { $0.map(\.bitPattern) } && a.finalLogits != nil + } + + private static func models(_ directory: URL, _ pair: Pair) throws -> Box<[Gemma4TensorParallelModel]> { + Box(try (0 ..< 2).map { + try Gemma4TensorParallelModel.load(modelDirectory: directory, role: .shard(rank: $0), reduction: pair.reduction(rank: $0)) + }) + } + + /// One rank's prefix tiers, paged host and requests, served as the + /// resident runtime serves them (`Gemma4TensorParallelPrefix.open`, + /// then the kept boundaries stored after a clean end). + private final class Rank: @unchecked Sendable { + let model: Gemma4TensorParallelModel + let host: CBv2StageKVHost + var prefix: Gemma4TensorParallelPrefix + let profile: QwenLayerStageGenerationProfile + var captureLimit: Int? + + init(_ model: Gemma4TensorParallelModel, cache: QwenStagePrefixCache = QwenStagePrefixCache(strideTokens: chunk), + disk: QwenStagePrefixDiskTier? = nil) throws { + self.model = model + host = try model.pagedHost(lanes: 1, maximumTokens: 128, chunkTokens: chunk) + cache.disk = disk + prefix = Gemma4TensorParallelPrefix(cache: cache, load: "gemma4-tp-prefix-tests", diskPlanScope: "gemma4-tp-prefix-tests-disk") + profile = try QwenLayerStageGenerationProfile(identifier: "synthetic-gemma4-tp-prefix", vocabularySize: 512, + hiddenSize: 256, activationDType: "bfloat16", maximumPromptTokens: 64, maximumChunkTokens: chunk, + maximumOutputTokens: 32, maximumContextTokens: 128, logitsDType: "float32") + } + + func request(_ tokens: [Int], chunk: Int = Gemma4TensorParallelPrefixTests.chunk, + cache: ClusterWorkerPrefixCache? = nil) throws -> QwenLayerStageGenerationRequest { + try QwenLayerStageGenerationRequest(profile: profile, requestID: UUID(uuidString: "00000000-0000-4000-8000-000000000001")!, + promptTokenIDs: tokens, chunkSize: chunk, outputCount: outputs, stopTokenIDs: [], prefixCache: cache) + } + + struct Served { let generation: Gemma4TensorParallelModel.Generation; let reused: Int; let stored: [Int] } + + func serve(_ request: QwenLayerStageGenerationRequest) throws -> Served { + let session = try MLX.withError { error -> Gemma4TensorParallelPagedSession in + let value = try prefix.open(request, model: model, host: host, group: model.reduction!, + captureLimit: captureLimit ?? prefix.captureLimit(request)) + try error.check() + return value + } + let generation = try model.generatePaged(session: session, host: host, prompt: request.promptTokenIDs, + outputCount: request.outputCount, chunk: request.chunkSize, recordTop: recordTop) + var stored: [Int] = [] + if let capture = session.prefixCapture, let scopes = prefix.scopes(request) { + stored = prefix.store(capture, request: request, scopes: scopes, rank: model.reduction!.rank) + } + return Served(generation: generation, reused: session.reusedPrefixTokens, stored: stored) + } + } + + // MARK: - Restore equals cold + + /// A repeated prompt restores the deepest boundary both ranks hold (32 of + /// 40 tokens on 16-token chunks) and continues on the same chunk grid: + /// its tokens, every recorded top logit and log probability and the final + /// row equal the cold request's bit for bit, on both ranks; a longer + /// prompt sharing the prefix restores the same boundary and equals that + /// prompt prefilled cold. The same ranks agree with each other bit for bit. + @Test func aRestoredPrefixEqualsTheColdPrefillBitwiseOnBothRanks() throws { + let directory = try Self.synthetic() + defer { try? FileManager.default.removeItem(at: directory) } + let pair = Pair(), models = try Self.models(directory, pair) + let ranks = try Pair.run(device: .gpu) { rank in + let model = models.value[rank] + let repeated = try model.generatePagedRepeatingPrefix(prompt: Self.prompt, outputCount: Self.outputs, + chunk: Self.chunk, recordTop: Self.recordTop) + let extended = try model.generatePagedRepeatingPrefix(prompt: Self.prompt, repeated: Self.longer, + outputCount: Self.outputs, chunk: Self.chunk, recordTop: Self.recordTop) + let coldLonger = try model.generatePaged(prompt: Self.longer, outputCount: Self.outputs, chunk: Self.chunk, + recordTop: Self.recordTop) + return (repeated, extended, coldLonger) + } + for (rank, value) in ranks.enumerated() { + #expect(value.0.reusedPromptTokens == 32 && value.0.storedFrontiers == [16, 32], "rank \(rank)") + #expect(Self.same(value.0.restored, value.0.cold), "rank \(rank): restored \(value.0.restored.tokenIDs), cold \(value.0.cold.tokenIDs)") + #expect(value.1.reusedPromptTokens == 32 && Self.same(value.1.restored, value.2), "rank \(rank): the longer prompt") + } + #expect(Self.same(ranks[0].0.restored, ranks[1].0.restored) && Self.same(ranks[0].1.restored, ranks[1].1.restored)) + } + + /// The state a restore writes is the cold request's at the boundary, + /// every layer's rows and position offsets and each sliding layer's + /// window (`CBv2OwnedStateSnapshot`), and after the next prompt chunk the + /// logits and every row (the windows having taken that chunk in place) + /// still are. Both ranks, their own heads. + @Test func aRestoredStateEqualsTheColdStateAtTheBoundaryAndAfterTheNextChunk() throws { + let directory = try Self.synthetic() + defer { try? FileManager.default.removeItem(at: directory) } + let pair = Pair(), models = try Self.models(directory, pair) + let results = try Pair.run(device: .gpu) { rank -> [Bool] in + let model = models.value[rank] + let host = try model.pagedHost(lanes: 1, maximumTokens: 128, chunkTokens: Self.chunk) + let layers = Array(0 ..< model.plan.layerCount) + func fingerprint(_ session: Gemma4TensorParallelPagedSession) throws -> String { + try session.state.snapshot(globalLayerIndices: layers, includeBytes: false, check: {}).fingerprint + } + return try MLX.withError { error -> [Bool] in + let check: () throws -> Void = { try error.check() } + let cold = try Gemma4TensorParallelPagedSession(model: model, host: host, promptCount: Self.prompt.count, + outputCount: Self.outputs) + cold.prefixCapture = .init(frontiers: [16, 32], limitBytes: Int.max, maximumFrontiers: 32) + _ = try cold.prefill(Self.prompt, range: 0 ..< 16, check: check) { $0 } + _ = try cold.prefill(Self.prompt, range: 16 ..< 32, check: check) { $0 } + let coldAt32 = try fingerprint(cold) + let coldLogits = try #require(try cold.prefill(Self.prompt, range: 32 ..< 40, check: check) { $0 }).logits + let coldAt40 = try fingerprint(cold) + let states = try #require(cold.prefixCapture).states() + try cold.retire() + let restored = try Gemma4TensorParallelPagedSession(model: model, host: host, + promptCount: Self.prompt.count, outputCount: Self.outputs, restoring: try #require(states.last)) + let restoredAt32 = try fingerprint(restored) + let restoredLogits = try #require(try restored.prefill(Self.prompt, range: 32 ..< 40, check: check) { $0 }).logits + let restoredAt40 = try fingerprint(restored) + let logitsEqual = coldLogits.asArray(Float.self).map(\.bitPattern) == restoredLogits.asArray(Float.self).map(\.bitPattern) + try restored.retire() + return [states.map(\.committedTokens) == [16, 32], restored.reusedPrefixTokens == 32, + coldAt32 == restoredAt32, logitsEqual, coldAt40 == restoredAt40, host.isDrained] + } + } + for (rank, checks) in results.enumerated() { + #expect(checks == [true, true, true, true, true, true], "rank \(rank): kept, reused, state@32, logits, state@40, drained") + } + } + + /// The resident runtime's own request loop (`Gemma4TensorParallelRequestLoop`) + /// on a restored session continues from the boundary: a greedy and a + /// sampled request (keyed draws, so a differing logit would move a token) + /// publish exactly the tokens their cold runs published, on both ranks. + @Test func theRequestLoopContinuesARestoredPrefixWithTheColdTokens() throws { + let directory = try Self.synthetic() + defer { try? FileManager.default.removeItem(at: directory) } + let pair = Pair(), models = try Self.models(directory, pair) + let sampling = ClusterWorkerSampling(temperature: 1.0, topP: 1, topK: 0, minP: 0, repetitionPenalty: 1, + repetitionContextSize: 0, frequencyPenalty: 0, presencePenalty: 0, seed: 0x5eed, stream: 0xab, logitBias: [], + topLogprobs: 0) + let results = try Pair.run(device: .gpu) { rank -> [[Int]] in + let fixture = try Rank(models.value[rank]) + var runs: [[Int]] = [] + for sampled in [false, true] { + // A prompt's state does not depend on its sampler: start each pair cold. + fixture.prefix.cache.sweep() + for _ in 0 ..< 2 { + let request = try QwenLayerStageGenerationRequest(profile: fixture.profile, + requestID: UUID(uuidString: "00000000-0000-4000-8000-00000000000\(sampled ? 2 : 1)")!, + promptTokenIDs: Self.prompt, chunkSize: Self.chunk, outputCount: 8, stopTokenIDs: [], + sampling: sampled ? sampling : nil) + let reduction = fixture.model.reduction! + let session = try fixture.prefix.open(request, model: fixture.model, host: fixture.host, group: reduction, + captureLimit: fixture.prefix.captureLimit(request)) + var published: [Int] = [] + let channel = ClusterCommittedTokenChannel(publishToken: { _, token, _, _ in published.append(token) }, + answer: { true }) + let outcome = try MLX.withError { error in + try Gemma4TensorParallelRequestLoop(session: session, request: request, + choice: Gemma4TensorParallelChoice(selection: fixture.model.selection, sampler: request.sampler, rank: rank), + exchange: { values in + let summed = reduction.allSum(MLXArray(values.map(Float.init))) + eval(summed) + return summed.asArray(Float.self).map { Int32($0) } + }, localStop: { false }).run(channel: channel, check: { try error.check() }) + } + try session.retire() + if let capture = session.prefixCapture, let scopes = fixture.prefix.scopes(request) { + fixture.prefix.store(capture, request: request, scopes: scopes, rank: rank) + } + runs.append([session.reusedPrefixTokens] + outcome.tokens + (rank == 0 ? published : outcome.tokens)) + } + } + return runs + } + for (rank, runs) in results.enumerated() { + #expect(runs.map { $0[0] } == [0, 32, 0, 32], "rank \(rank): cold, restored, cold, restored") + #expect(runs[0].dropFirst() == runs[1].dropFirst() && runs[2].dropFirst() == runs[3].dropFirst(), + "rank \(rank): a restored request publishes its cold tokens, greedy and sampled") + } + #expect(results[0] == results[1]) + } + + /// The batch driver's lanes vote, restore and keep prefixes as a request + /// served alone does: a repeated request restores in its lane, takes its + /// cold tokens, and both report what each lane reused and stored. + @Test func lanesRestoreAndKeepPrefixesThroughTheBatchDriver() throws { + let directory = try Self.synthetic() + defer { try? FileManager.default.removeItem(at: directory) } + let pair = Pair(), models = try Self.models(directory, pair) + final class Host: QwenBatchServingHost, @unchecked Sendable { + var tokens: [UUID: [Int]] = [:], cache: [UUID: (reused: Int, stored: [Int])] = [:] + func serviceControl() throws {} + func publishToken(requestID: UUID, ordinal: Int, tokenID: Int, committedTokens: Int) throws { + tokens[requestID, default: []].append(tokenID) + } + func awaitDecisions(_ requestIDs: [UUID]) throws -> [UUID: Bool] { Dictionary(uniqueKeysWithValues: requestIDs.map { ($0, true) }) } + func pollDecision(_ requestID: UUID) throws -> Bool? { true } + func publishFinished(requestID: UUID, reason: ClusterWorkerFinishReason) throws {} + func publishLeft(requestID: UUID) throws {} + func publishPromptCache(requestID: UUID, reusedTokens: Int, storedFrontiers: [Int]) throws { + cache[requestID] = (reusedTokens, storedFrontiers) + } + } + let results = try Pair.run(device: .gpu) { rank -> [String] in + let fixture = try Rank(models.value[rank]) + let lanesHost = try fixture.model.pagedHost(lanes: 2, maximumTokens: 128, chunkTokens: Self.chunk) + var lines: [String] = [] + for round in 0 ..< 2 { + let requests = try [Self.prompt, Self.other].enumerated().map { index, prompt in + try QwenLayerStageGenerationRequest(profile: fixture.profile, + requestID: UUID(uuidString: "00000000-0000-4000-8000-0000000001\(round)\(index)")!, + promptTokenIDs: prompt, chunkSize: Self.chunk, outputCount: Self.outputs, stopTokenIDs: []) + } + let book = ClusterBatchLaneBook() + for request in requests { + try book.reserve(request.requestID, .init(request: request, deadline: .max, laneStateBytes: 1, + prefixCaptureLimit: fixture.prefix.captureLimit(request)), lanes: 2) + try book.start(request.requestID) + } + let executor = try Gemma4TensorParallelBatchExecutor(model: fixture.model, + host: lanesHost, reduction: fixture.model.reduction!, prefix: fixture.prefix, agree: { _, check in try check() }) + let driver = try QwenTensorParallelBatchDriver(executor: executor, book: book, capacity: 2, vocabulary: 512) + let host = Host() + var selected: [UUID: [Int]] = [:] + try MLX.withError { error in + try driver.serve(host: host, retiredSelection: { id, tokens, _ in selected[id] = tokens }, + check: { try error.check() }) + } + for request in requests { + let cache = host.cache[request.requestID] + lines.append("\(round) reused=\(cache?.reused ?? 0) stored=\(cache?.stored ?? []) tokens=\(selected[request.requestID] ?? [])") + } + lines.append("drained=\(lanesHost.isDrained)") + } + return lines + } + for (rank, lines) in results.enumerated() { + #expect(lines[0].hasPrefix("0 reused=0 stored=[16, 32]") && lines[1].hasPrefix("0 reused=0 stored=[16, 32]"), "rank \(rank): \(lines)") + #expect(lines[3].hasPrefix("1 reused=32 stored=[]") && lines[4].hasPrefix("1 reused=32 stored=[]"), "rank \(rank): \(lines)") + let tokens = lines.map { $0.components(separatedBy: " tokens=").last ?? "" } + #expect(tokens[0] == tokens[3] && tokens[1] == tokens[4] && lines[2] == "drained=true" && lines[5] == "drained=true", + "rank \(rank): each restored lane takes its cold tokens") + } + #expect(results[0] == results[1]) + } + + // MARK: - Hit or miss, agreed + + /// Both ranks agree on every hit or miss before using it: a boundary only + /// one rank holds is a miss on both (the vote sums 1); a boundary both + /// offer whose state one rank cannot restore (it does not adopt into that + /// rank's geometry) is declined by the confirmation on both; another + /// chunk grid is another key; a request whose cache is off votes nothing + /// and keeps nothing. Every case prefills from zero on both ranks with + /// the cold request's every bit. + @Test func bothRanksAgreeOnEveryHitOrMiss() throws { + let directory = try Self.synthetic() + defer { try? FileManager.default.removeItem(at: directory) } + let pair = Pair(), models = try Self.models(directory, pair) + let results = try Pair.run(device: .gpu) { rank -> [String: (reused: Int, same: Bool, stored: [Int])] in + let fixture = try Rank(models.value[rank]) + let request = try fixture.request(Self.prompt) + let cold = try fixture.serve(request) + var outcomes: [String: (reused: Int, same: Bool, stored: [Int])] = [:] + func record(_ name: String, _ served: Rank.Served) { + outcomes[name] = (served.reused, Self.same(served.generation, cold.generation), served.stored) + } + // Rank 1 lost what it kept; rank 0 still holds both boundaries. + if rank == 1 { fixture.prefix.cache.sweep() } + record("one-rank", try fixture.serve(request)) + // Both hold the boundary again (the miss kept it on rank 1); rank 1's + // entry at 32 is replaced by one of another geometry. + if rank == 1 { + let scope = try #require(fixture.prefix.scopes(request)).resident + let held = try #require(fixture.prefix.cache.state(scope: scope, tokens: Self.prompt, frontier: 32)) + let truncated = held.attention.mapValues { pair -> (keys: MLXArray, values: MLXArray) in + (keys: pair.keys[0..., 0..., 0 ..< 31, 0...], values: pair.values[0..., 0..., 0 ..< 31, 0...]) + } + fixture.prefix.cache.insert(scope: scope, tokens: Self.prompt, states: [QwenStagePrefixState(committedTokens: 32, + attention: truncated, recurrent: held.recurrent)], sharedBytes: 0) + } + record("not-adoptable", try fixture.serve(request)) + record("other-grid", try fixture.serve(try fixture.request(Self.prompt, chunk: 8))) + record("cache-off", try fixture.serve(try fixture.request(Self.prompt, + cache: ClusterWorkerPrefixCache.partition(prefixCacheEnabled: false, cacheSalt: nil)))) + record("both", try fixture.serve(request)) + return outcomes + } + for (rank, outcomes) in results.enumerated() { + #expect(outcomes["one-rank"]?.reused == 0 && outcomes["one-rank"]?.same == true, "rank \(rank): one rank held it") + #expect(outcomes["not-adoptable"]?.reused == 0 && outcomes["not-adoptable"]?.same == true, "rank \(rank): one rank could not restore it") + #expect(outcomes["other-grid"]?.reused == 0, "rank \(rank): another chunk grid") + #expect(outcomes["cache-off"]?.reused == 0 && outcomes["cache-off"]?.stored == [] && outcomes["cache-off"]?.same == true, + "rank \(rank): a request whose cache is off") + #expect(outcomes["both"]?.reused == 32 && outcomes["both"]?.same == true, "rank \(rank): both hold it") + } + } + + // MARK: - Budget and eviction + + /// The memory tier keeps what its budget holds and evicts the least + /// recently used prompt alike on both ranks (a repeat then misses on + /// both); a capture keeps the deepest boundary first and grid boundaries + /// only within its limit, and nothing when even the deepest does not fit. + @Test func theMemoryTierEvictsWithinItsBudgetAndCapturesWithinTheLimit() throws { + let directory = try Self.synthetic() + defer { try? FileManager.default.removeItem(at: directory) } + let pair = Pair(), models = try Self.models(directory, pair) + let results = try Pair.run(device: .gpu) { rank -> [Int] in + // Measure one capture's bytes, then hold one prompt's at most. + let probe = try Rank(models.value[rank]) + _ = try probe.serve(try probe.request(Self.prompt)) + let one = probe.prefix.cache.bytesInUse + // A budget of one prompt: a second prompt's entries evict the first's grid + // boundaries, then its own, then the least recently used deepest one. + let fixture = try Rank(models.value[rank], cache: QwenStagePrefixCache(strideTokens: Self.chunk, budgetBytes: one)) + let first = try fixture.serve(try fixture.request(Self.prompt)) + _ = try fixture.serve(try fixture.request(Self.other)) + let kept = try fixture.serve(try fixture.request(Self.other)) + let evicted = try fixture.serve(try fixture.request(Self.prompt)) + // The deepest boundary alone: its rows and one window. + let cost = try #require(fixture.prefix.cache.captureCost) + let tight = try Rank(models.value[rank]) + tight.captureLimit = cost.bytes(deepest: 32, frontiers: 1) + let deepestOnly = try tight.serve(try tight.request(Self.prompt)) + let none = try Rank(models.value[rank]) + none.captureLimit = cost.bytes(deepest: 32, frontiers: 1) - 1 + let nothing = try none.serve(try none.request(Self.prompt)) + return [one > 0 ? 1 : 0, first.stored.count, kept.reused, evicted.reused, deepestOnly.stored.last ?? 0, + deepestOnly.stored.count, nothing.stored.count, fixture.prefix.cache.bytesInUse <= one ? 1 : 0] + } + for (rank, value) in results.enumerated() { + #expect(value == [1, 2, 32, 0, 32, 1, 0, 1], "rank \(rank): measured, kept, kept hit, evicted miss, deepest only, none, budget") + } + } + + /// What one request and a rank charge for prompt prefixes + /// (`Gemma4TensorParallelRequestBudget`): the request its capture at its + /// deepest boundary (its own full rows and one window of every sliding + /// layer), the rank two of them for its memory tier, both in the LOAD + /// quote; nothing when the load keeps no prefixes. + @Test func prefixMemoryIsChargedInTheRequestBudgetAndTheLoadQuote() throws { + let bound: (Int) throws -> Int = { $0 + 16_384 } + let on = try Gemma4TensorParallelRequestBudget.derive(contextTokens: 65_536, chunkTokens: 512, promptTokens: 32_768, + allocationBound: bound) + let off = try Gemma4TensorParallelRequestBudget.derive(contextTokens: 65_536, chunkTokens: 512, promptTokens: 32_768, + keepsPrefixes: false, allocationBound: bound) + let capture = 10 * (32_768 * 512 * 2 + 16_384) + 50 * (1_024 * 4 * 256 * 2 + 16_384) + #expect(on.prefixCaptureBytes == capture && on.prefixResidentBytes == 2 * capture) + #expect(on.requestBytes == off.requestBytes + capture && on.rankBytes == off.rankBytes + 2 * capture) + #expect(on.allowance.reservedBytes == on.requestBytes + on.rankBytes) + #expect(on.allowance.reservedBytes == off.allowance.reservedBytes + 3 * capture) + #expect(off.prefixCaptureBytes == 0 && off.prefixResidentBytes == 0) + // A short request's capture: its own rows and a short window. + #expect(try Gemma4TensorParallelRequestBudget.prefixCaptureBytes(promptTokens: 100, allocationBound: bound) + == 10 * (100 * 512 * 2 + 16_384) + 50 * (100 * 4 * 256 * 2 + 16_384)) + } + + // MARK: - SSD tier + + /// A root the tier makes itself (as on a Mac whose owner never kept one). + private static func root(create: Bool = false) throws -> URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("gemma4-tp-prefix-ssd-\(UUID().uuidString)", + isDirectory: true) + if create { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) } + return url + } + + private static func configuration(_ root: URL, key: UInt8 = 0x5a, + _ change: (inout QwenStagePrefixDiskConfiguration) -> Void = { _ in }) + -> QwenStagePrefixDiskConfiguration { + var value = QwenStagePrefixDiskConfiguration(mode: .on(root: root, key: Data(repeating: key, count: 32))) + value.minimumTokens = 1; value.minimumFreeBytes = 1 + change(&value) + return value + } + + private static func tier(_ root: URL, rank: Int, key: UInt8 = 0x5a, + _ change: (inout QwenStagePrefixDiskConfiguration) -> Void = { _ in }) throws -> QwenStagePrefixDiskTier { + try #require(QwenStagePrefixDiskTier.open(configuration: configuration(root, key: key, change), + planScope: "gemma4-tp-prefix-tests-plan", rank: rank)) + } + + private static func records(_ root: URL, rank: Int) -> [URL] { + let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil) + return (enumerator?.allObjects as? [URL] ?? []).filter { + $0.pathExtension == "dbpx" && $0.deletingLastPathComponent().lastPathComponent == "rank\(rank)" + } + } + + private static func mode(_ url: URL) -> mode_t { + var info = stat() + return lstat(url.path, &info) == 0 ? info.st_mode & 0o777 : 0o777 + } + + /// Each rank writes its own heads' state at the deepest boundary to its + /// encrypted SSD tier behind serving, in owner-only directories and + /// files that hold none of the state's bytes in the clear. After both + /// tiers reopen with empty memory (a restarted pair), the vote offers the + /// records (3 a rank), both ranks read and restore them, the confirmation + /// passes, and the request equals its cold prefill bit for bit; the state + /// read is resident afterwards, so the next repeat restores from memory. + @Test func ssdRecordsRestoreBitwiseAfterTheTiersReopenEncryptedAndOwnerOnly() throws { + let directory = try Self.synthetic() + let root = try Self.root() + defer { try? FileManager.default.removeItem(at: directory); try? FileManager.default.removeItem(at: root) } + let pair = Pair(), models = try Self.models(directory, pair) + let results = try Pair.run(device: .gpu) { rank -> [String: Bool] in + var checks: [String: Bool] = [:] + let first = try Rank(models.value[rank], disk: try Self.tier(root, rank: rank)) + let request = try first.request(Self.prompt) + let cold = try first.serve(request) + let disk = try #require(first.prefix.disk) + checks["drained"] = disk.drain(timeoutSeconds: 60) + checks["persisted"] = disk.stats.persisted == 1 && disk.recordCount == 1 + let files = Self.records(root, rank: rank) + let rankDirectory = try #require(files.first).deletingLastPathComponent() + checks["owner-only"] = files.count == 1 && files.allSatisfy { Self.mode($0) == 0o600 } + && [root, rankDirectory.deletingLastPathComponent(), rankDirectory].allSatisfy { Self.mode($0) == 0o700 } + // No 64-byte run of the kept rows appears in the record. + let scope = try #require(first.prefix.scopes(request)).resident + let kept = try #require(first.prefix.cache.state(scope: scope, tokens: Self.prompt, frontier: 32)) + let plain = kept.attention.values.map { $0.keys.asData(access: .copy).data } + + kept.recurrent.values.map { $0.conv.asData(access: .copy).data } + let sealed = try Data(contentsOf: files[0]) + checks["encrypted"] = !plain.isEmpty && plain.allSatisfy { data in + Swift.stride(from: 0, to: data.count - 64, by: 64).allSatisfy { sealed.range(of: data[$0 ..< $0 + 64]) == nil } + } + disk.close(timeoutSeconds: 5) + checks["closed"] = disk.stats.closeDrained + // A restarted pair: empty memory, the same root and key. + let second = try Rank(models.value[rank], disk: try Self.tier(root, rank: rank)) + let restored = try second.serve(request) + checks["restored"] = restored.reused == 32 && Self.same(restored.generation, cold.generation) + checks["read"] = try #require(second.prefix.disk).stats.restores == 1 + let again = try second.serve(request) + checks["memory"] = again.reused == 32 && Self.same(again.generation, cold.generation) + && second.prefix.disk!.stats.restores == 1 + second.prefix.disk?.close(timeoutSeconds: 5) + return checks + } + for (rank, checks) in results.enumerated() { + for name in ["drained", "persisted", "owner-only", "encrypted", "closed", "restored", "read", "memory"] { + #expect(checks[name] == true, "rank \(rank): \(name)") + } + } + } + + /// A record a rank cannot use is refused on both ranks, never assumed: + /// a record past its TTL is not offered (the vote misses); a record + /// corrupted on one rank fails to authenticate there and is deleted, + /// and the confirmation makes both ranks prefill from zero (the other + /// rank keeps what it read, resident); a rank whose key changed deletes + /// what it cannot read and offers nothing. Every case equals the cold + /// request bit for bit. + @Test func staleCorruptedAndForeignRecordsAreRefusedOnBothRanks() throws { + let directory = try Self.synthetic() + let root = try Self.root() + defer { try? FileManager.default.removeItem(at: directory); try? FileManager.default.removeItem(at: root) } + let pair = Pair(), models = try Self.models(directory, pair) + let results = try Pair.run(device: .gpu) { rank -> [String: (reused: Int, same: Bool)] in + var outcomes: [String: (reused: Int, same: Bool)] = [:] + let writer = try Rank(models.value[rank], disk: try Self.tier(root, rank: rank)) + let request = try writer.request(Self.prompt) + let cold = try writer.serve(request) + writer.prefix.disk?.close(timeoutSeconds: 30) + func reopen(key: UInt8 = 0x5a, now: TimeInterval? = nil) throws -> Rank { + let tier = try Self.tier(root, rank: rank, key: key) + if let now { tier.now = { now } } + return try Rank(models.value[rank], disk: tier) + } + let stale = try reopen(now: Date().timeIntervalSince1970 + 2 * Double(QwenStagePrefixDiskConfiguration.maximumTTLSeconds)) + let expired = try stale.serve(request) + outcomes["stale"] = (expired.reused, Self.same(expired.generation, cold.generation)) + stale.prefix.disk?.close(timeoutSeconds: 5) + if rank == 1, let file = Self.records(root, rank: 1).first { + // The last unit's sealed bytes: the header still opens, the rows do not. + var bytes = try Data(contentsOf: file) + for index in max(0, bytes.count - 64) ..< bytes.count { bytes[index] ^= 0xff } + try bytes.write(to: file) + } + let corrupted = try reopen() + let declined = try corrupted.serve(request) + outcomes["corrupted"] = (declined.reused, Self.same(declined.generation, cold.generation)) + let stats = try #require(corrupted.prefix.disk).stats + // Rank 1 refused its record (unreadable, deleted); rank 0 read its own and let it go. + outcomes["refused"] = (rank == 1 ? stats.failedRestores + stats.sweptFiles : stats.restores, true) + corrupted.prefix.disk?.close(timeoutSeconds: 5) + let foreign = try reopen(key: rank == 0 ? 0x5a : 0x11) + let unread = try foreign.serve(request) + outcomes["foreign"] = (unread.reused, Self.same(unread.generation, cold.generation)) + foreign.prefix.disk?.close(timeoutSeconds: 5) + return outcomes + } + for (rank, outcomes) in results.enumerated() { + for name in ["stale", "corrupted", "foreign"] { + #expect(outcomes[name]?.reused == 0 && outcomes[name]?.same == true, "rank \(rank): \(name)") + } + } + #expect(results[0]["refused"]?.reused == 1 && (results[1]["refused"]?.reused ?? 0) >= 1, + "the corrupted record is refused and deleted on its rank; the other rank read its own") + } + + /// The SSD tier keeps the cluster tier's rules for Gemma tensor parallel + /// as for every family: no directory or no key is no tier (nothing is + /// ever written unencrypted); a root that cannot be made private is no + /// tier; writes stop at the daily write cap and below the free-space + /// floor, dropped rather than waited for; and closing finishes what was + /// queued within its bound. + @Test func theSSDTierKeepsTheCacheRules() throws { + let directory = try Self.synthetic() + let root = try Self.root(create: true) + defer { try? FileManager.default.removeItem(at: directory); try? FileManager.default.removeItem(at: root) } + let key = Data(repeating: 0x5a, count: 32) + #expect(!QwenStagePrefixDiskConfiguration.fromEnvironment([:], key: key).enabled) + #expect(!QwenStagePrefixDiskConfiguration.fromEnvironment([QwenStagePrefixDiskConfiguration.directoryEnvironmentName: root.path], + key: nil).enabled) + #expect(!QwenStagePrefixDiskConfiguration.fromEnvironment([QwenStagePrefixDiskConfiguration.directoryEnvironmentName: "relative"], + key: key).enabled) + let file = root.appendingPathComponent("not-a-directory") + try Data("x".utf8).write(to: file) + #expect(QwenStagePrefixDiskTier.open(configuration: Self.configuration(file.appendingPathComponent("cache")), + planScope: "gemma4-tp-prefix-tests-plan", rank: 0) == nil, "a root that cannot be made is no tier") + let pair = Pair(), models = try Self.models(directory, pair) + let results = try Pair.run(device: .gpu) { rank -> [Int] in + let capped = try Rank(models.value[rank], disk: try Self.tier(root.appendingPathComponent("capped"), rank: rank) { + $0.maximumWriteBytesPerDay = 1 + }) + _ = try capped.serve(try capped.request(Self.prompt)) + let cap = try #require(capped.prefix.disk) + _ = cap.drain(timeoutSeconds: 60) + let full = try Rank(models.value[rank], disk: try Self.tier(root.appendingPathComponent("full"), rank: rank) { + $0.minimumFreeBytes = Int.max / 4 + }) + _ = try full.serve(try full.request(Self.prompt)) + let floor = try #require(full.prefix.disk) + _ = floor.drain(timeoutSeconds: 60) + cap.close(timeoutSeconds: 5); floor.close(timeoutSeconds: 5) + return [cap.recordCount, cap.stats.droppedPersists, floor.recordCount, floor.stats.droppedPersists, + cap.stats.closeDrained && floor.stats.closeDrained ? 1 : 0] + } + for (rank, value) in results.enumerated() { + #expect(value == [0, 1, 0, 1, 1], "rank \(rank): daily cap, free-space floor, bounded close") + } + } +} diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift index 0edaf5372d..79cec40cd1 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift @@ -660,8 +660,10 @@ struct Gemma4TensorParallelRuntimeTests { } let fingerprint = try base.fingerprint(admission: "row") #expect(try Gemma4TensorParallelLoadAgreement().fingerprint(admission: "row") == fingerprint) + // This build keeps prompt prefixes; a rank whose diagnosis switch turned them off refuses its peer. + #expect(base.prefixCache && base.prefixCache == Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes) var lanes = base; lanes.lanes = 2 - var prefix = base; prefix.prefixCache = true + var prefix = base; prefix.prefixCache = false var packed = base; packed.kvQuantization = .k8v8 let others = try [lanes, prefix, packed].map { try $0.fingerprint(admission: "row") } + [try base.fingerprint(admission: "other row")] diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift index c0f46082ae..f2fe97127f 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift @@ -101,16 +101,30 @@ private func checkGemmaLayouts(_ layout: ClusterModelLayout, configuration: Data } /// A product layout carries the rank's native reserve (`Gemma4TensorParallelRequestBudget`): -/// its own heads' state, the activation floor, the freed-buffer cache and eight sealed frames. +/// its own heads' state and prompt-prefix capture, the activation floor, the freed-buffer cache, +/// eight sealed frames and the prompt-prefix memory tier's charged budget. private func checkGemmaRequestAllowance(_ priced: ClusterModelLayout, _ checks: PlacementChecks) throws { let allowance = priced.tensorParallel?.family.requestAllowance - let budget = try Gemma4TensorParallelRequestBudget.derive(contextTokens: 65_536, chunkTokens: 512, allocationBound: { $0 + 16_384 }) + let budget = try Gemma4TensorParallelRequestBudget.derive(contextTokens: 65_536, chunkTokens: 512, promptTokens: 32_768, + allocationBound: { $0 + 16_384 }) checks.require("Gemma TP allowance: the layout quotes the rank's budget at the profile's longest request (65,536 tokens, 512-token chunks)", allowance == budget.allowance && allowance?.maximumContextTokens == 65_536 && allowance?.maximumChunkTokens == 512) - checks.require("Gemma TP allowance: the conservative 5.5 GiB activation floor and the freed-buffer cache are charged once beside the request", + checks.require("Gemma TP allowance: the conservative 5.5 GiB activation floor, the freed-buffer cache and the prefix tier are charged once beside the request", budget.rankBytes == Gemma4TensorParallelRequestBudget.activationFloorBytes + Gemma4TensorParallelRequestBudget.freedBufferCacheBytes - + budget.allowance.collectiveScratchBytes && Gemma4TensorParallelRequestBudget.activationFloorBytes == 5_905_580_032 + + budget.allowance.collectiveScratchBytes + budget.prefixResidentBytes + && Gemma4TensorParallelRequestBudget.activationFloorBytes == 5_905_580_032 && budget.allowance.reservedBytes == budget.requestBytes + budget.rankBytes) + // A 32,768-token prompt's own full rows (5 layers x 1 head x 512 x K and V, bf16) and a 1,024-token window + // of each of the 25 sliding layers (4 heads x 256 x K and V), each array at the allocator's bound. + let capture = 10 * (32_768 * 512 * 2 + 16_384) + 50 * (1_024 * 4 * 256 * 2 + 16_384) + checks.require("Gemma TP allowance: a request's prompt-prefix capture (\(budget.prefixCaptureBytes) bytes) and two of them for the memory tier", + budget.prefixCaptureBytes == capture && budget.prefixResidentBytes == 2 * capture + && budget.requestBytes == budget.stateBytes + budget.transientBytes + budget.partialBytes + budget.logitsBytes + capture) + let off = try Gemma4TensorParallelRequestBudget.derive(contextTokens: 65_536, chunkTokens: 512, promptTokens: 32_768, + keepsPrefixes: false, allocationBound: { $0 + 16_384 }) + checks.require("Gemma TP allowance: a rank whose prefix cache is off charges neither", + off.prefixCaptureBytes == 0 && off.prefixResidentBytes == 0 + && budget.allowance.reservedBytes - off.allowance.reservedBytes == 3 * capture) checks.require("Gemma TP allowance: eight sealed frames of the packed feed-forward collective (512 x 101,376 bytes and the seal)", budget.allowance.maximumCollectivePayloadBytes == 512 * 101_376 && budget.allowance.collectiveScratchBytes == 8 * (budget.allowance.maximumCollectiveFrameBytes + 16_384)) @@ -187,8 +201,8 @@ private func checkGemmaFastestPlan(_ layout: ClusterModelLayout, _ checks: Place checks.require("Gemma fastest plan: without its choice the same layout, Macs and policy put tensor parallel first", ruled.chosen?.mode == .tensorParallel) - // 2. Two small Macs (24 and 32 GB M4 Pro), default link costs: tensor parallel where the plan predicts it faster. - for gib in [24.0, 32.0] { + // 2. Two small Macs (32 GB M4 Pro), default link costs: tensor parallel where the plan predicts it faster. + for gib in [32.0] { let small = try pros(gib) let decodeHeavy = try plan(small, first(128, 128), .unmeasured), times = predicted(decodeHeavy) checks.require("Gemma fastest plan: 2x M4 Pro \(Int(gib)) GB, default link costs, 128 + 128: tensor parallel, predicted faster by the margin (\(times.tensor) s vs \(times.other) s)", @@ -196,6 +210,14 @@ private func checkGemmaFastestPlan(_ layout: ClusterModelLayout, _ checks: Place checks.require("Gemma fastest plan: 2x M4 Pro \(Int(gib)) GB, default link costs, 8,192 + 128: a pipeline (the prompt's sums dominate)", pipeline(try plan(small, first(8_192, 128), .unmeasured))) } + // Two 24 GB M4 Pro: a rank's share and reserve with its prompt-prefix capture and memory tier charged + // (`Gemma4TensorParallelRequestBudget`) exceed what the Mac gives a model, so the pipeline, which keeps + // prefixes too, is placed for every request. + for (prompt, outputs) in [(128, 128), (8_192, 128)] { + let result = try plan(try pros(24), first(prompt, outputs), .unmeasured) + checks.require("Gemma fastest plan: 2x M4 Pro 24 GB, \(prompt) + \(outputs): a pipeline, tensor parallel does not fit with its prefix memory charged", + result.chosen?.mode == .pipeline && result.tensorParallel?.verdict == .doesNotFit) + } // 3. A measured link flips the choice as predicted, both ways. let ultraDefault = try plan(ultras, first(1_024, 128), .unmeasured), ultraMeasured = try plan(ultras, first(1_024, 128), measuredLink) From f2d1dfa1e4ef839ec62dd15465552f9f06ac1781 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:10:20 -0800 Subject: [PATCH 0118/1441] cluster: Gemma 4 tensor-parallel repeated-prefix oracle over the ring `darkbloom-cluster-tp-check gemma run --path paged --prefix repeat` serves the request twice through each rank's prompt-prefix memory tier (Gemma4TensorParallelModel.generatePagedRepeatingPrefix): the repeat restores the deepest boundary both ranks hold after their sealed vote and confirmation, and must equal its cold run bit for bit. The paged oracle matrix runs it in simulated and on both tp ranks over the sealed local ring, and requires each rank's repeat to equal simulated's bit for bit. Co-Authored-By: Claude Opus 5.5 --- .../TensorParallelCheck/GemmaCheck.swift | 57 +++++++++++++++++-- .../Tests/GemmaTensorParallelOracles/run.sh | 31 ++++++++++ 2 files changed, 82 insertions(+), 6 deletions(-) diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift index fa20ab3617..c175f5d889 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift @@ -11,7 +11,7 @@ import MLX // a tiny random Gemma 4 MoE checkpoint with the 26B's structure and request.json (never a model pass) // darkbloom-cluster-tp-check gemma run --mode full|split-sum|simulated|shard|tp --model-dir DIR --request FILE --report FILE // [--record-top K] [--backend ring|socket|jaccl] [--reduction native|sealed-bench] [--shard-rank R] -// [--pack yes|no] [--path legacy|paged] [--deadline-seconds S] +// [--pack yes|no] [--path legacy|paged] [--prefix none|repeat] [--deadline-seconds S] // darkbloom-cluster-tp-check gemma compare --reference FILE --candidate FILE [--bitwise yes|no] [--near-tie-ulps U] // darkbloom-cluster-tp-check gemma allsum [--backend ring|socket|jaccl] [--count N] // darkbloom-cluster-tp-check gemma lanes --mode simulated|tp --model-dir DIR --report FILE [--lanes N] [--outputs N] @@ -38,6 +38,12 @@ import MLX // each rank's own heads, the product's CBv2 prompt entry under the registered // prompt policy, and each step's token and stop flags agreed in the step's // evaluation; `legacy` (the default) keeps the SDK's legacy caches. +// `--prefix repeat` (paged; simulated or tp) serves the request twice through +// each rank's prompt-prefix memory tier (`generatePagedRepeatingPrefix`): +// cold, keeping its chunk boundaries, then again restoring the deepest +// boundary both ranks hold after their sealed vote and confirmation. The +// report is the repeat's, which must have restored a prefix and equal the +// cold request bit for bit. // `lanes` serves N greedy requests of different lengths through the batch // driver on each rank's paged host (`Gemma4TensorParallelModel.generateLanes`), // after each alone (`generatePaged`): every lane must take its solo tokens, @@ -84,6 +90,11 @@ enum GemmaCheck { var decodeSeconds: Double var ranksAgree: Bool? var passed: Bool + /// `--prefix repeat`: the prompt tokens the repeat restored, and + /// whether it equals the cold request bit for bit. + var prefix: String? + var reusedPromptTokens: Int? + var restoredEqualsCold: Bool? } static func run(_ arguments: [String]) throws { @@ -135,11 +146,16 @@ enum GemmaCheck { let deadline = Int(fields["--deadline-seconds"] ?? "900"), (30 ... 7200).contains(deadline), ["native", "sealed-bench"].contains(fields["--reduction"] ?? "native"), ["yes", "no"].contains(fields["--pack"] ?? "yes"), - ["legacy", "paged"].contains(fields["--path"] ?? "legacy") else { + ["legacy", "paged"].contains(fields["--path"] ?? "legacy"), + ["none", "repeat"].contains(fields["--prefix"] ?? "none") else { throw Failure("gemma run needs --mode full|split-sum|simulated|shard|tp, --model-dir, --request, a new --report and bounded options") } let paged = (fields["--path"] ?? "legacy") == "paged" guard !paged || mode != "split-sum" else { throw Failure("--path paged does not run the split-sum oracle") } + let repeatPrefix = fields["--prefix"] == "repeat" + guard !repeatPrefix || (paged && ["simulated", "tp"].contains(mode)) else { + throw Failure("--prefix repeat runs on the paged path of simulated or tp ranks") + } let sealed = (fields["--reduction"] ?? "native") == "sealed-bench" guard !sealed || mode == "tp" else { throw Failure("--reduction sealed-bench applies to a tp rank only") } let pack = (fields["--pack"] ?? "yes") == "yes" @@ -182,7 +198,7 @@ enum GemmaCheck { reduction = g note("rank \(g.rank) of \(g.size) over \(backend.rawValue)\(backend.correctnessOnly ? " (correctness only, not a pair timing)" : "")") // Everything that changes the collectives is agreed before loading. - let workload = "\(configurationSHA)|\(request.promptTokenIDsSHA256)|\(request.outputCount)|\(request.chunkSize)|top=\(recordTop)|pack=\(pack)|sealed=\(sealed)|paged=\(paged)|\(Gemma4TensorParallelPlan.arithmeticAgreementFields.joined(separator: ","))" + let workload = "\(configurationSHA)|\(request.promptTokenIDsSHA256)|\(request.outputCount)|\(request.chunkSize)|top=\(recordTop)|pack=\(pack)|sealed=\(sealed)|paged=\(paged)|prefix=\(repeatPrefix)|\(Gemma4TensorParallelPlan.arithmeticAgreementFields.joined(separator: ","))" guard try g.digestsEqual(fnv(workload)) else { throw Failure("the ranks disagree on the workload, the model configuration or the arithmetic contract") } @@ -202,7 +218,34 @@ enum GemmaCheck { if let group { guard try group.agree([7]) else { throw Failure("load barrier failed") } } let generation: Gemma4TensorParallelModel.Generation var pairAgrees: Bool? - if let pair { + var prefixOutcome: (reused: Int, equalsCold: Bool)? + func bitsEqual(_ a: Gemma4TensorParallelModel.Generation, _ b: Gemma4TensorParallelModel.Generation) -> Bool { + func bits(_ rows: [[Float]]) -> [[UInt32]] { rows.map { $0.map(\.bitPattern) } } + return a.tokenIDs == b.tokenIDs && a.topTokenIDs == b.topTokenIDs && bits(a.topLogits) == bits(b.topLogits) + && bits(a.topLogprobs) == bits(b.topLogprobs) + && a.finalLogits.map { $0.map(\.bitPattern) } == b.finalLogits.map { $0.map(\.bitPattern) } + } + if repeatPrefix { + let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize + let runs: [(cold: Gemma4TensorParallelModel.Generation, restored: Gemma4TensorParallelModel.Generation, reused: Int)] + if let pair { + let ranks = Ranks([model, try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory, + role: .shard(rank: 1), reduction: pair.reduction(rank: 1), packFeedForward: pack)]) + runs = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in + let value = try ranks.models[rank].generatePagedRepeatingPrefix(prompt: prompt, outputCount: count, + chunk: chunk, recordTop: recordTop) + return (value.cold, value.restored, value.reusedPromptTokens) + } + pairAgrees = bitsEqual(runs[0].restored, runs[1].restored) + } else { + let value = try model.generatePagedRepeatingPrefix(prompt: prompt, outputCount: count, chunk: chunk, + recordTop: recordTop) + runs = [(value.cold, value.restored, value.reusedPromptTokens)] + } + generation = runs[0].restored + prefixOutcome = (runs[0].reused, runs.allSatisfy { $0.reused > 0 && bitsEqual($0.restored, $0.cold) }) + note("prefix repeat: reused \(runs[0].reused) prompt tokens; restored equals cold bit for bit: \(prefixOutcome!.equalsCold)") + } else if let pair { let ranks = Ranks([model, try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory, role: .shard(rank: 1), reduction: pair.reduction(rank: 1), packFeedForward: pack)]) let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize @@ -238,12 +281,14 @@ enum GemmaCheck { topTokenIDs: recordTop > 0 ? generation.topTokenIDs : nil, topLogits: recordTop > 0 ? generation.topLogits : nil, topLogprobs: recordTop > 0 ? generation.topLogprobs : nil, finalLogits: generation.finalLogits, firstTokenSeconds: generation.firstTokenSeconds, decodeSeconds: generation.decodeSeconds, - ranksAgree: pairAgrees, passed: pairAgrees ?? true) + ranksAgree: pairAgrees, passed: (pairAgrees ?? true) && (prefixOutcome?.equalsCold ?? true), + prefix: repeatPrefix ? "repeat" : nil, reusedPromptTokens: prefixOutcome?.reused, + restoredEqualsCold: prefixOutcome?.equalsCold) if let group { let evidence = report.tokenIDsSHA256 + "|" + sha256Hex(Data((generation.finalLogits ?? []).flatMap { withUnsafeBytes(of: $0.bitPattern.littleEndian) { Array($0) } })) report.ranksAgree = try group.digestsEqual(fnv(evidence)) - report.passed = try group.agree([report.ranksAgree == true ? 1 : 0]) + report.passed = try group.agree([report.ranksAgree == true && report.restoredEqualsCold != false ? 1 : 0]) } note("tokens \(String(report.tokenIDsSHA256.prefix(16))): \(generation.tokenIDs.prefix(12).map(String.init).joined(separator: " "))…" + (report.ranksAgree.map { " ranks agree: \($0)" } ?? "")) diff --git a/libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh b/libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh index 85c459e0b8..3ed6ab673a 100755 --- a/libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh +++ b/libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh @@ -15,6 +15,9 @@ # comparator's verdict of each rank against `full`, and `split-sum` against tp. # The paged path also serves three requests as batch lanes (`gemma lanes`, # simulated and over the ring). Required: every lane takes its solo tokens. +# And it serves the request twice through each rank's prompt-prefix tier +# (`--prefix repeat`). Required: the repeat restored a prefix, equals its cold +# run bit for bit, and each tp rank's repeat equals simulated's bit for bit. set -euo pipefail tp_check="$1" scratch="$2" @@ -63,6 +66,34 @@ run_variant() { echo "$name ($path): split-sum against tp: $(grep -E '^bitwise' "$dir/split-sum-vs-tp.txt")" return fi + # A repeated prompt through each rank's prefix tier: the repeat restores the + # deepest boundary both ranks hold and must equal its cold run bit for bit + # (in each report), and each tp rank's repeat must equal simulated's. + env $environment nice -n 19 "$tp_check" gemma run --mode simulated --path paged --prefix repeat --model-dir "$dir" \ + --request "$dir/request.json" --report "$dir/prefix-simulated.json" >"$dir/prefix-simulated.log" 2>&1 || true + env $environment MLX_RANK=0 MLX_HOSTFILE="$scratch/hosts.json" nice -n 19 "$tp_check" gemma run --mode tp \ + --path paged --prefix repeat --backend ring --reduction sealed-bench --model-dir "$dir" --request "$dir/request.json" \ + --report "$dir/prefix-tp-rank0.json" --deadline-seconds 300 >"$dir/prefix-tp-rank0.log" 2>&1 & + rank0=$! + env $environment MLX_RANK=1 MLX_HOSTFILE="$scratch/hosts.json" nice -n 19 "$tp_check" gemma run --mode tp \ + --path paged --prefix repeat --backend ring --reduction sealed-bench --model-dir "$dir" --request "$dir/request.json" \ + --report "$dir/prefix-tp-rank1.json" --deadline-seconds 300 >"$dir/prefix-tp-rank1.log" 2>&1 || true + wait "$rank0" || true + for rank in 0 1; do + if "$tp_check" gemma compare --reference "$dir/prefix-simulated.json" --candidate "$dir/prefix-tp-rank$rank.json" \ + --bitwise yes >"$dir/prefix-tp-rank$rank-vs-simulated.txt" 2>&1 \ + && /usr/bin/python3 - "$dir" "$rank" <<'PY' +import json, sys +d, rank = sys.argv[1], sys.argv[2] +reports = [json.load(open(f"{d}/{name}.json")) for name in ("prefix-simulated", f"prefix-tp-rank{rank}")] +sys.exit(0 if all(r["passed"] and r["restoredEqualsCold"] and r["reusedPromptTokens"] > 0 for r in reports) else 1) +PY + then + echo "$name ($path): repeated prefix restored $(/usr/bin/python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["reusedPromptTokens"])' "$dir/prefix-tp-rank$rank.json") tokens; tp rank $rank == simulated and == cold, bitwise" + else + echo "$name ($path): repeated prefix on tp rank $rank DIFFERS"; failures=$((failures + 1)) + fi + done # Batch lanes: three requests through the batch driver, each against itself alone. env $environment nice -n 19 "$tp_check" gemma lanes --mode simulated --model-dir "$dir" \ --report "$dir/lanes-simulated.json" >"$dir/lanes-simulated.log" 2>&1 || true From 992d690826b7e02e599864133ee804bf25ca5115 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:10:20 -0800 Subject: [PATCH 0119/1441] docs: Gemma 4 tensor-parallel prompt prefixes and their memory prefix-cache.md gains "Gemma TP prompt prefixes" (capture, keep, scope, vote, restore, memory, logs, tests) and the tenant-partition scope; inference.md's resident runtime says what is kept and charged; hardware-support.md's rank-memory table gains the capture and the tier; two-mac-cluster.md and test.md follow, including two 24 GB M4 Pro now keeping the pipeline. The changelog fragment is updated in place. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-tensor-parallel.md | 3 +- docs/architecture/hardware-support.md | 6 +++ docs/architecture/inference.md | 30 ++++++++++----- docs/architecture/prefix-cache.md | 53 ++++++++++++++++++++++++++- docs/developer/test.md | 29 +++++++++++++-- docs/provider/two-mac-cluster.md | 11 ++++-- 6 files changed, 114 insertions(+), 18 deletions(-) diff --git a/changelog.d/gemma-tensor-parallel.md b/changelog.d/gemma-tensor-parallel.md index 418252bb51..d8f078e231 100644 --- a/changelog.d/gemma-tensor-parallel.md +++ b/changelog.d/gemma-tensor-parallel.md @@ -1,6 +1,7 @@ ### Gemma 4 tensor parallel on two-Mac clusters - Gemma 4 26B (QAT 4-bit and 8-bit) can run tensor parallel on a pair: each Mac holds half of every layer's heads and expert channels, both share every token over the encrypted link, and the pair returns the same tokens a single Mac would on the synthetic checks. Text only. -- The planner chooses tensor parallel for Gemma 4 only where it predicts it faster than the pipeline: short prompts with longer answers, on smaller Macs (for example two 24 or 32 GB M4 Pro) from the first setup, and on two big Macs (for example two M5 Ultra) only after a load has measured the link. Prompt-heavy requests keep the pipeline. Qwen and GLM still choose tensor parallel wherever it fits. +- The planner chooses tensor parallel for Gemma 4 only where it predicts it faster than the pipeline: short prompts with longer answers, on smaller Macs (for example two 32 GB M4 Pro) from the first setup, and on two big Macs (for example two M5 Ultra) only after a load has measured the link. Prompt-heavy requests keep the pipeline. Qwen and GLM still choose tensor parallel wherever it fits. - In tensor parallel, Gemma 4 returns logprobs (`logprobs` / `top_logprobs`), and each Mac reserves memory for its own half of the model: about 8.0 GB of weights at QAT 4-bit (14.9 GB at 8-bit) plus its own KV, with a conservative 5.5 GiB activation reserve until a pair measures one. +- Gemma 4 tensor parallel keeps prompt prefixes as the pipeline does, in memory and in the encrypted SSD tier: a repeated or shared prompt prefix is restored only when both Macs hold it, with exactly the tokens of a request that prefilled the whole prompt, and it survives a restart of both Macs. Each Mac reserves about 1.3 GB more for it, so two 24 GB Macs now keep the pipeline for Gemma 4. - Gemma 4 tensor-parallel pairs serve one request at a time unless `DARKBLOOM_CLUSTER_BATCH_LANES` names more. Speed on a real pair is not measured yet. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 456506b072..8c520b4367 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1133,15 +1133,21 @@ A Gemma 4 tensor-parallel rank is charged its own share, not the whole model | Its own KV heads of every layer (4 sliding, 1 full), residual rows | per request | about 364 MB (the whole model's: 719,380,600) | | One prompt chunk's attention transient over its 8 query heads | per request | about 145 MB | | FP32 partials (attention row, dense row, 8 expert rows and their packed copy) and 3 vocabulary rows | per request | about 113 MB | +| Prompt-prefix capture at its deepest boundary: its own full-attention rows and one window of every sliding layer (`prefixCaptureBytes`) | per request | about 191 MB (441,384,960 for the profile's 32,768-token prompt) | | Activation floor: `UnifiedMemoryCap`'s conservative default, 5.5 GiB, until a pair measures one | per rank | 5,905,580,032 | | Freed-buffer cache (half the allocator headroom) | per rank | 1,073,741,824 | | Eight sealed frames of the packed collective (512 x 101,376 bytes and the seal) | per rank | about 415 MB | +| Prompt-prefix memory tier: two captures of the profile's longest prompt (`prefixResidentBytes`) | per rank | 882,769,920 | The layout's `requestAllowance` quotes one request at the profile's longest context (65,536 tokens) plus the per-rank charges, and the worker's LOAD gate reserves exactly that beside the shard. A reservation or lane asks the live gate for every held request, the new one and the per-rank charges. The planner still charges at least the pipeline's whole-model `requestChargeEveryRankBytes`. +The memory tier's budget is its charge, or the pipeline's room-derived budget +where it is larger; entries beyond the charge give way before any refusal +([Gemma TP prompt prefixes](prefix-cache.md#gemma-tp-prompt-prefixes)). A rank +whose prefix cache is off charges neither prefix term. Nothing here is measured on a pair; see [inference](inference.md#gemma-tensor-parallel-placement). diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index d733544343..db50ebd9f3 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4105,8 +4105,10 @@ stops, cancellations and retirements. rank's part and materialized at once. - Agreement. `Gemma4TensorParallelLoadAgreement` binds the registered row's fingerprint, the mode's and the plan's terms, the prompt policy, the - selection, the lanes, the KV storage and the prefix-cache switch. A rank - started with any other value refuses its peer before reading weights. + selection, the lanes, the KV storage and the prefix cache (on in this build, + `Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes`; off only + by the diagnosis switch `DARKBLOOM_CLUSTER_PREFIX_CACHE=off`). A rank started + with any other value refuses its peer before reading weights. - Probes. The load measures the link (`QwenTensorParallelLinkProbe`) and this rank's own decode step with every sum local (`Gemma4TensorParallelShareProbe`). The ready record carries both. @@ -4140,14 +4142,23 @@ stops, cancellations and retirements. that could not grow) ends both after the same step (`Gemma4TensorParallelRequestLoop`). A rank that stopped commits nothing more, but still ends at a stop token its peer commits. +- Prompt prefixes. Each rank keeps its own heads' state at a prompt's chunk + boundaries as the Gemma pipeline keeps a stage's, in the pipeline's memory + tier and the owner's encrypted SSD tier (`Gemma4TensorParallelPrefix`). A + request restores the deepest boundary both ranks hold after one sealed vote + and one sealed confirmation, or neither restores it, and then runs the rest + of the prompt on the same chunk grid: a restore equals the cold prefill bit + for bit. Solo requests and lanes alike + ([Gemma TP prompt prefixes](prefix-cache.md#gemma-tp-prompt-prefixes)). Memory is charged per rank (`Gemma4TensorParallelRequestBudget`; see [hardware support](hardware-support.md#gemma-4-tensor-parallel-rank-memory)): -each request its own KV heads, prompt transient, FP32 partials and vocabulary -rows; each rank once the conservative activation floor, the freed-buffer cache -and eight sealed frames. A lane is gated with every held lane's charge, the new -one and the rank's reserve. Prefix caching, speculative decoding, media and a -measured activation floor are not built yet. +each request its own KV heads, prompt transient, FP32 partials, vocabulary +rows and its prompt-prefix capture; each rank once the conservative activation +floor, the freed-buffer cache, eight sealed frames and the prefix memory tier's +charged budget. A lane is gated with every held lane's charge, the new one and +the rank's reserve. Speculative decoding, media and a measured activation floor +are not built yet. ### Gemma tensor-parallel placement @@ -4198,8 +4209,9 @@ sums cross the link: about 0.67-0.93x one M5 Ultra's decode, unmeasured | 2x M5 Ultra 256 GB | measured 29 us sums | 1,024 + 128 | pipeline | | 2x M5 Ultra 256 GB | measured 29 us sums, no share probe | 128 + 128 | tensor parallel (device-index prior) | | 2x M5 Ultra 256 GB | measured 5 us sums | 1,024 + 128 | tensor parallel | -| 2x M4 Pro 24 or 32 GB | default | 128 + 128 | tensor parallel | -| 2x M4 Pro 24 or 32 GB | default | 8,192 + 128 | pipeline | +| 2x M4 Pro 32 GB | default | 128 + 128 | tensor parallel | +| 2x M4 Pro 32 GB | default | 8,192 + 128 | pipeline | +| 2x M4 Pro 24 GB | any | any | pipeline: a rank's share and reserve, prompt-prefix memory included, do not fit | | 2x M4 Pro 32 GB | measured 29 us / 109 us sums | 1,024 + 128 | tensor parallel / pipeline | Before a share probe, the comparison takes a Mac's weight time from its device diff --git a/docs/architecture/prefix-cache.md b/docs/architecture/prefix-cache.md index 04293c9c21..64c49bca96 100644 --- a/docs/architecture/prefix-cache.md +++ b/docs/architecture/prefix-cache.md @@ -1,6 +1,6 @@ # KV cache layouts and prefix caching -> Last updated: 2026-10-28 +> Last updated: 2026-11-01 How the provider lays out a request's KV cache, how it decides whether a previously computed prefix can be reused, and where reusable state lives: @@ -1040,7 +1040,8 @@ reach both ranks in its reservation: `ClusterWorkerReservation.prefixCache` stage families through `qwenStagePrefixScope` (resident cache, SSD tier, speculative history), GLM tensor parallel through `GLM5NextTensorParallelResidentRuntime.prefixScope` (vote, restore and kept - boundary) and `prefixDiskScope` (its SSD records), and the Qwen + boundary) and `prefixDiskScope` (its SSD records), Gemma tensor parallel + through `Gemma4TensorParallelPrefix.scopes` (both tiers), and the Qwen tensor-parallel batch owner through `QwenTensorParallelResidentRuntime.batchPrefixScope` (both tiers and the assistant's donors). @@ -1260,3 +1261,51 @@ native records; `GLM53_PREFIX_SSD=1` on the serving-width synthetic stage, also through a balanced record) and `GLM5NextTensorParallelPrefixRecordEncodingTests` (a balanced record encodes only the DSA latents and adopts). + +### Gemma TP prompt prefixes + +Both ranks of Gemma 4 tensor parallel keep their prompt prefixes as the Gemma +pipeline keeps a stage's: in the same memory tier (`QwenStagePrefixCache`) and +the same encrypted SSD tier (`QwenStagePrefixDiskTier`), each rank only its own +KV heads of every layer (4 sliding, 1 full on the 26B). Code: +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift` +(`Gemma4TensorParallelPrefix`, `Gemma4TensorParallelPrefixCapture`). + +| Step | What happens | +|---|---| +| Capture | During the prompt, after each chunk that ends on the cache's stride grid strictly before the prompt end (the [chunk-grid rule](#gemma-chunk-grid-reuse)), the rank copies each sliding layer's window, and at the deepest such boundary its full-attention rows; a capture keeps the deepest boundary first, then the deepest grid boundaries its limit holds (`QwenStagePrefixCaptureCost.kept`). The record shape is the pipeline stage's: full rows as attention entries, each window in the recurrent slots. | +| Keep | Only after the request ended on both ranks: a solo request after the end-of-request exchange and its pages' release, a lane after the batch driver's bilateral retirement (`confirmedRetirement`). Its boundaries become resident and are written to the SSD tier behind serving. A failed request keeps nothing, and the rank drops every entry (its peer may hold others). | +| Scope | Resident: the load agreement and the request's chunk grid; on SSD: `Gemma4TensorParallelPrefix.planScope` (the plan and its arithmetic terms, the prompt policy, the arithmetic receipt and profile, the verified artifact and storage commitment, both builds; never the membership epoch) and the request's chunk grid; both in the request's [tenant partition](#cluster-prefix-tenant-partitions) (`Gemma4TensorParallelPrefix.scopes`). | +| Vote | One sealed sum of every stride-grid boundary before the prompt's final token: each rank offers 1 for a boundary in memory and 3 for one held only as a complete SSD record (`QwenTensorParallelPrefixCache.offer`); the deepest boundary both offer (a sum of 2, 4 or 6) is agreed. A request whose cache is off, or whose prompt is shorter than one stride, votes on neither rank. | +| Restore | Each rank reads the agreed boundary from its own tiers, memory first, checks it adopts into its geometry (`Gemma4TensorParallelPrefix.adopts`), and writes it into fresh pages of a new request, reserved for its first tokens as a cold request's are (`CBv2OwnedRequestState` sliding adoption). Then a second sealed sum (`QwenTensorParallelPrefixCache.confirm`) shows both ranks restored; otherwise both discard what they restored and prefill from zero. An unreadable record is deleted by the tier, one that does not adopt by the rank; a state read from SSD stays resident either way. | + +A restore continues the prompt from the boundary on the same chunk grid, so its +frames are the cold request's frames from there: the restored rows, windows and +position offsets equal the cold request's at the boundary, and its logits and +tokens equal the cold request's bit for bit. Gemma records are native +(`QwenStagePrefixDiskFamily.native`), so an SSD restore is exact too. The load +agreement carries `gemma4-tensor-parallel-prefix-v1` `on`; a rank whose +`DARKBLOOM_CLUSTER_PREFIX_CACHE=off` loads `off` and its peer refuses it. + +Memory: each request's charge includes its capture at its deepest boundary, +and each rank's reserve two such captures of the longest request for the +memory tier, both in the LOAD quote +([rank memory](hardware-support.md#gemma-4-tensor-parallel-rank-memory)). The +tier's budget is that charge, or the pipeline's budget when the room beside +the rank's reserve allows more; a request's capture beyond its charged part is +asked of the live gate and cut to that part when refused. Kept entries give way +before a reservation, a lane or a running request is refused for memory, then +the request's own capture, as in the pipeline; under host pressure an idle rank +drops them (`releaseIdleMemory`). The SSD tier's configuration, key, owner-only +directories, TTL, daily write cap, free-space floor and bounded close are every +cluster family's (`QwenStagePrefixDiskConfiguration`). + +Logs: `darkbloom-prefix-v1 … family=gemma4 mode=tensor_parallel` at load +(`budget_bytes=`, `charged_bytes=`, `ssd=`), at each agreed boundary +(`agreed=`, `reused=`, `tier=`) and at each keep (`stored=`); the tier's +`darkbloom-prefix-ssd-v1` lines and `restore-declined`. Tests: +`Gemma4TensorParallelPrefixTests` (restore against cold bit for bit, the +state at and after the boundary, hits and misses on both ranks, the request +loop and lanes, budget and eviction, the SSD round trip, refused records and +the cache rules) and the paged oracle matrix's `--prefix repeat` runs +([focused checks](../developer/test.md#focused-gemma-4-tensor-parallel-checks)). diff --git a/docs/developer/test.md b/docs/developer/test.md index 9be9110e7f..5a0707eebe 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1267,6 +1267,24 @@ neither real-weight numerics, a pair qualification nor speed. the pipeline on default link costs, a measured fast link takes tensor parallel, the forced mode places it, and each rank is charged its own heads. + `swift test --package-path libs/darkbloom-cluster --filter Gemma4TensorParallelPrefixTests` + (GPU, as above) covers the prompt-prefix tiers on two in-process ranks: + + - a repeated prompt, and a longer one sharing it, restores the deepest + boundary both ranks hold and equals the cold request bit for bit; + - the restored rows, windows and position offsets equal the cold request's + at the boundary and after the next chunk; + - a boundary only one rank holds, or one rank cannot restore, another chunk + grid and a request whose cache is off all prefill from zero on both ranks; + - the request loop (greedy and sampled) and batch lanes through the driver + continue a restored prefix with the cold tokens; + - the memory tier's budget and eviction, and a capture within its limit; + - the prefix charges in the request budget and the LOAD quote; + - the SSD tier: records restore bit for bit after both tiers reopen, + encrypted and owner-only; stale, corrupted and other-key records are + refused on both ranks; no directory or key is no tier, and the daily write + cap, the free-space floor and the bounded close hold. + `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh` also runs `GemmaTensorParallelChecks.swift` (model-free). It builds the QAT 4-bit layout from the retained real headers and the 8-bit layouts from their @@ -1275,8 +1293,9 @@ neither real-weight numerics, a pair qualification nor speed. 14,915,635,260 bytes), and the rank's reserve (`Gemma4TensorParallelRequestBudget`) must be quoted. Under the provider's tensor-parallel-first policy it checks the fastest-plan rule on constructed pairs: 2x M5 Ultra 256 GB keeps the pipeline on - default link costs; 2x M4 Pro 24 or 32 GB takes tensor parallel where predicted - faster; measured links flip the choice both ways. It also pins the device-index + default link costs; 2x M4 Pro 32 GB takes tensor parallel where predicted + faster, and 2x M4 Pro 24 GB keeps the pipeline (tensor parallel does not fit + with its prompt-prefix memory charged); measured links flip the choice both ways. It also pins the device-index prior's choice for 2x M5 Ultra on the measured link: tensor parallel for a 128 + 128 request. @@ -1310,9 +1329,13 @@ neither real-weight numerics, a pair qualification nor speed. entry, and each step's choice in its own evaluation. The paged path also runs `gemma lanes`: three requests served together through the batch driver, in one process and over the ring, each of which must take its solo - tokens. + tokens. And it runs `gemma run --prefix repeat` in `simulated` and on both + `tp` ranks: the request served twice through each rank's prompt-prefix tier, + the repeat restoring the deepest boundary both ranks hold. 3. Verify. Each `tp` rank must equal `simulated` bit for bit (exit status 0). + Each repeated-prefix run must have restored a prefix and equal its cold run + bit for bit, and each `tp` rank's repeat must equal `simulated`'s. The script also prints QualificationComparator's verdict for each rank against `full`. diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 870ffc55f6..5af9d719bb 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -347,8 +347,10 @@ measured the link the plan prices tensor parallel on a slow assumed link. Once the link is measured, short prompts with longer answers can be predicted faster in tensor parallel, an estimate from each Mac's device index that a tensor-parallel load's own measurement then corrects. Two smaller Macs whose -decode is limited by memory bandwidth (for example 24 or 32 GB M4 Pro) get -tensor parallel for short prompts with longer answers. The plan's "Tensor +decode is limited by memory bandwidth (for example 32 GB M4 Pro) get tensor +parallel for short prompts with longer answers; two 24 GB Macs keep the +pipeline, because tensor parallel's share with its prompt-prefix memory does +not fit them. The plan's "Tensor parallel or pipeline" lines say which and why ([Gemma tensor-parallel placement](../architecture/inference.md#gemma-tensor-parallel-placement)). See the [placement planner](../../libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift) @@ -484,7 +486,10 @@ memory holds its share. Both Macs keep the prompt prefixes of every model family, in memory and in the encrypted SSD tier: a repeated long prompt starts with its prefix restored, and after both Macs restart the SSD tier gives it back. Gemma 4 keeps each -sliding-window layer's window at every kept frontier; GLM-5.3-Flash in pipeline +sliding-window layer's window at every kept frontier, in pipeline and in tensor +parallel, where each Mac keeps its own half of every layer's heads and a prefix +is restored only when both Macs hold it, with exactly the tokens of a request +that prefilled the whole prompt; GLM-5.3-Flash in pipeline keeps its attention history once per prompt and its linear-attention state per frontier. GLM-5.3-Flash in tensor parallel keeps one boundary per prompt, the last whole 4,096-token chunk before its final token: each Mac writes its own From 43eb054f5d5d01206de159c3111d5ecedd8f301f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:37:08 -0800 Subject: [PATCH 0120/1441] Say exactly what a Qwen27 assistant declaration changes, and that none exists yet Refactor pass on the public assistant declaration. Docs, changelog and one comment; no behavior change. - inference.md, Qwen27 resident assistant: explicit `on` plans the declared assistant the same way as `auto` (without a declaration it plans a local cluster's depth-three cohort assistant); the resource policy digest follows the build's declaration for the artifact, not the setup, so a pair planned with mtp_mode "off" carries the same value; the pair's MTP posture reaches `darkbloom status` and the engine_v2_slot_posture telemetry event, not the coordinator heartbeat. - changelog: lead with "nothing changes in serving until a build declares the assistant public" and name the one change visible now, the wording of the refusal beside a cluster approval. - ProviderLoop+ClusterPairSlot: the same posture correction in the comment. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-public-assistant.md | 38 ++++++++++--------- docs/architecture/inference.md | 6 +-- .../ProviderLoop+ClusterPairSlot.swift | 5 ++- 3 files changed, 26 insertions(+), 23 deletions(-) diff --git a/changelog.d/qwen27-public-assistant.md b/changelog.d/qwen27-public-assistant.md index de5dd9aea0..f798e98147 100644 --- a/changelog.d/qwen27-public-assistant.md +++ b/changelog.d/qwen27-public-assistant.md @@ -1,19 +1,21 @@ -### Qwen3.8-27B pairs can keep their speculative assistant on public traffic once declared +### Qwen3.8-27B pairs can keep their speculative assistant on public traffic once a build declares it -- A build can now declare Qwen3.8-27B's resident speculative assistant public - for its tensor-parallel pairs, the way the public model declaration names a - model's mode families: the exact depth, head inventory and singleton - verification, with the SHA-256 of its evidence report. This build declares - none, so coordinator-paired setups still carry no assistant and nothing - changes until the owner signs a declaration after the real-pair evidence. -- With a declaration, the guided setup plans a cluster served through - Darkbloom with the declared assistant under `mtp_mode = "auto"`, each Mac - admits a cluster approval beside exactly that assistant (any other is - refused before any part stops), and the release's cluster runtime facts, the - coordinator's approval and every committed start name it in their resource - policy digest. Without a declaration that digest is unchanged. -- A pair whose ranks report the resident assistant ready now shows MTP as - configured in its slot posture and heartbeats, with the counts its runtime - reports, instead of disabled. -- The refusal of an undeclared assistant beside an approval now says it serves - local clusters only unless the build declares it public. +- Nothing changes in serving until a build declares the assistant public. This + build declares none: coordinator-paired Qwen3.8-27B setups still carry no + speculative assistant, and every release fact, approval and committed start + keeps its resource policy digest. The owner declares one only after the + real-pair evidence. +- A declaration names the exact depth, head inventory and singleton + verification, with the SHA-256 of its evidence report, beside the public + model declaration. Once a build carries one: + - the guided setup plans a cluster served through Darkbloom with that + assistant under `mtp_mode = "auto"`; + - each Mac admits a cluster approval beside exactly that assistant, and any + other is refused before any part stops; + - the release's cluster runtime facts, the coordinator's approval and every + committed start name it in their resource policy digest; + - the pair's slot posture shows MTP as configured, with the counts its + runtime reports. +- The only change visible now is the wording of one refusal: an assistant + beside a cluster approval is refused as serving local clusters only "unless + this build declares it public". diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 95c0df9aa4..7e62aa1c1b 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -5381,10 +5381,10 @@ For the exact registered Qwen3.8 27B artifact, normal cluster planning discovers On a coordinator-formed pair the assistant serves only as the build declares it. Its verify windows are a computation the coordinator does not see: it qualifies `tensor_parallel_v1` placements by classes, cuts and mode, a pair's registration carries no speculation field, and the bundled tensor-parallel records of the 27B predate the assistant. The owner therefore declares a public assistant per artifact beside the public model declaration (`ClusterPublicModel.tensorAssistant`, a `ClusterPublicTensorAssistant`: depth, the inline head's inventory fingerprint, singleton verification and the SHA-256 of its evidence report under `docs/reports/`). This build declares none. 1. A setup saved for coordinator pairing carries no assistant, or exactly the declared one (`ClusterConfiguration.validate`, refusal `ClusterConfiguration.tensorAssistantServesLocally`). The leader checks a coordinator's approval against this rule before any part stops (`ClusterApprovalAttachment.attachment` runs the setup's full validation), and the other Mac checks it again before it saves. -2. Under `auto` the guided setup plans a cluster served through Darkbloom with the declared assistant, or without one when none is declared (`ClusterPlacementTensorAssistantSelection.discoveryMode`, from the serving scope in `OnboardingLive.localPlanModels`). The quote is asked at the declared depth with singleton verification (no cohort argument), and the native helper must return exactly the declared policy, inventory included (`requireDiscoveredQuote`). Explicit `on` is kept; without a declaration the plan's public-traffic line says the pair is not offered (`ClusterPairOwnerServing.tensorAssistantNotOffered`), and the approval is refused as above. -3. The declared assistant's launch arguments (`--mtp-depth`, `--tp-mtp-inventory-sha256`, the verification) and its evidence digest are part of the model's resource policy (`DistributedInstalledNativeStart.resourcePolicySHA256`, see [cluster runtime facts](#cluster-runtime-facts-of-an-installed-app)). A release's facts, the coordinator's approval and every committed start under it therefore name the declared assistant; without a declaration the digest is unchanged. +2. Under `auto` the guided setup plans a cluster served through Darkbloom with the declared assistant, or without one when none is declared (`ClusterPlacementTensorAssistantSelection.discoveryMode`, from the serving scope in `OnboardingLive.localPlanModels`). The quote is asked at the declared depth with singleton verification (no cohort argument), and the native helper must return exactly the declared policy, inventory included (`requireDiscoveredQuote`). Explicit `on` plans the declared assistant the same way. Without a declaration, `on` plans a local cluster's assistant (depth three, admitted cohorts), the plan's public-traffic line says the pair is not offered (`ClusterPairOwnerServing.tensorAssistantNotOffered`), and the approval is refused as above. +3. The declared assistant's launch arguments (`--mtp-depth`, `--tp-mtp-inventory-sha256`, the verification) and its evidence digest are part of the model's resource policy (`DistributedInstalledNativeStart.resourcePolicySHA256`, see [cluster runtime facts](#cluster-runtime-facts-of-an-installed-app)). A release's facts, the coordinator's approval and every committed start under it therefore name the declared assistant; without a declaration the digest is unchanged. The digest follows the build's declaration for the artifact, not the setup: a pair planned without the assistant (`mtp_mode = "off"`) carries the same value. The assistant a pair loads is bound by both workers at LOAD, as on a local cluster. 4. Singleton verification (`singleton_ready_set_v1`) speculates only for a step whose ready set is one request; wider steps decode as one plain rectangle with the assistant observing each row (`QwenTensorParallelNativeBatchExecutor.decodeRound`). Media rows, samplers that do not admit speculative verification and requested logprobs keep their target paths, as on a local cluster. -5. A pair slot whose ranks report the assistant in READY (`ClusterQwenTensorAssistantReady`) reports MTP as configured in its slot posture and heartbeats, with the counts rank zero's runtime returned request by request (`ProviderLoop.publishClusterPairSlot`, `EngineV2Bridge.mtpStatusSnapshot`, `DistributedCBv2Engine.mtpTotalsSnapshot`). Any other pair keeps the disabled posture. +5. A pair slot whose ranks report the assistant in READY (`ClusterQwenTensorAssistantReady`) reports MTP as configured in its slot posture (`darkbloom status`, the `engine_v2_slot_posture` telemetry event), with the counts rank zero's runtime returned request by request (`ProviderLoop.publishClusterPairSlot`, `EngineV2Bridge.mtpStatusSnapshot`, `DistributedCBv2Engine.mtpTotalsSnapshot`). Any other pair keeps the disabled posture. The evidence a declaration needs (the fixed greedy answers byte-identical with and without the assistant, concurrent answers equal to solo, sampled and logprob requests against plain tensor parallel) is recorded on a non-production pair; tiny paired-shard fixtures and the checks above do not establish it. diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift index e01facb6e2..2dcbf3a5c6 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift @@ -193,8 +193,9 @@ extension ProviderLoop { modelDirectory: specification.modelDirectory, pairTelemetry: specification.pairTelemetry) } catch { throw ClusterPairSlotError.ownerUnavailable } guard let bridge = entry.engineV2Bridge else { throw ClusterPairSlotError.ownerUnavailable } - // The pair's MTP posture (heartbeats, `darkbloom status`): ranks whose readiness names the resident assistant - // they loaded (`ClusterQwenTensorAssistantReady`) decode with it; any other pair keeps the disabled posture. + // The pair's MTP posture (`darkbloom status`, the slot posture telemetry): ranks whose readiness names the + // resident assistant they loaded (`ClusterQwenTensorAssistantReady`) decode with it; any other pair keeps the + // disabled posture. if ready.tensorAssistant != nil { await bridge.configureMTPStatus(.init(configured: true, active: true, reason: nil, source: nil, revision: nil, artifactBytes: 0, assistantBytes: 0)) From 3e00abf34f0783638ddfa23cf32b1ec3ba95fbc3 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:57:20 -0800 Subject: [PATCH 0121/1441] cluster: charge each Gemma 4 TP request its own prefix capture, no tier floor Owner decision on the refactor pass: a Gemma 4 tensor-parallel rank no longer charges its prompt-prefix memory tier a fixed floor (two captures, 882,769,920 B at the profile) in the LOAD quote and the planner's allowance. That floor pushed two 24 GB M4 Pro Macs off tensor parallel. - Gemma4TensorParallelRequestBudget: requestBytes keeps the request's capture at its deepest boundary; rankBytes and the allowance drop the tier (prefixResidentBytes is gone). The LOAD quote charges the capture of the profile's longest prompt (441,384,960 B at 32,768 tokens). - Each reservation and lane is charged its own prompt's capture, none when its cache is off (prefixCharge), not the profile's longest. - The memory tier's budget is the pipeline's alone: half the room the load measures beside the shard and that quote (QwenStagePrefixCache .budget), so it never exceeds that room; entries still give way before a reservation, a lane or a running request is refused for memory. The load line drops charged_bytes=. - A request captures what its charge covers whatever the tier's budget (Gemma4TensorParallelPrefix.captureLimit(_:chargedBytes:)). On two idle 24 GB Macs the planner leaves about 145 MiB a rank beside the quote, so the room-derived tier budget is zero; without this the charged capture went unused and no SSD record was written. The pipeline's limit beyond the charge is still asked of the live gate and cut when refused. - Tests: aRequestsCaptureIsChargedAndTheTierStaysWithinItsRoom, aRequestCapturesWithinItsChargeWhenTheTierHasNoBudget (zero budget: nothing resident, the deepest boundary on SSD, a repeat restored from it bit for bit on both ranks); PlacementChecks quote the capture once and two 24 GB Macs fit a rank each again (151,758,668 bytes to spare); the fastest-plan rows return to their base text (2x M4 Pro 24 or 32 GB: tensor parallel where predicted faster). - Review: docs say lanes do not withdraw their own captures under pressure (as the pipeline's and GLM's batch paths), the sliding adoption section names the growing reservation, the rank-memory table, placement rows and changelog follow; a redundant #require is removed. Co-Authored-By: Claude Opus 5.5 --- changelog.d/gemma-tensor-parallel.md | 4 +- docs/architecture/hardware-support.md | 19 ++--- docs/architecture/inference.md | 15 ++-- docs/architecture/prefix-cache.md | 41 ++++++---- docs/developer/test.md | 11 ++- docs/provider/two-mac-cluster.md | 6 +- .../Gemma4TensorParallelRequestBudget.swift | 37 +++++---- .../Gemma4TensorParallelLanes.swift | 4 +- .../Gemma4TensorParallelPrefix.swift | 12 ++- .../Gemma4TensorParallelResidentRuntime.swift | 53 ++++++------- .../Placement/QwenDensePlacementFamily.swift | 2 +- .../Gemma4TensorParallelPrefixTests.swift | 76 +++++++++++++++---- .../GemmaTensorParallelChecks.swift | 37 +++++---- 13 files changed, 186 insertions(+), 131 deletions(-) diff --git a/changelog.d/gemma-tensor-parallel.md b/changelog.d/gemma-tensor-parallel.md index d8f078e231..11acf264f5 100644 --- a/changelog.d/gemma-tensor-parallel.md +++ b/changelog.d/gemma-tensor-parallel.md @@ -1,7 +1,7 @@ ### Gemma 4 tensor parallel on two-Mac clusters - Gemma 4 26B (QAT 4-bit and 8-bit) can run tensor parallel on a pair: each Mac holds half of every layer's heads and expert channels, both share every token over the encrypted link, and the pair returns the same tokens a single Mac would on the synthetic checks. Text only. -- The planner chooses tensor parallel for Gemma 4 only where it predicts it faster than the pipeline: short prompts with longer answers, on smaller Macs (for example two 32 GB M4 Pro) from the first setup, and on two big Macs (for example two M5 Ultra) only after a load has measured the link. Prompt-heavy requests keep the pipeline. Qwen and GLM still choose tensor parallel wherever it fits. +- The planner chooses tensor parallel for Gemma 4 only where it predicts it faster than the pipeline: short prompts with longer answers, on smaller Macs (for example two 24 or 32 GB M4 Pro) from the first setup, and on two big Macs (for example two M5 Ultra) only after a load has measured the link. Prompt-heavy requests keep the pipeline. Qwen and GLM still choose tensor parallel wherever it fits. - In tensor parallel, Gemma 4 returns logprobs (`logprobs` / `top_logprobs`), and each Mac reserves memory for its own half of the model: about 8.0 GB of weights at QAT 4-bit (14.9 GB at 8-bit) plus its own KV, with a conservative 5.5 GiB activation reserve until a pair measures one. -- Gemma 4 tensor parallel keeps prompt prefixes as the pipeline does, in memory and in the encrypted SSD tier: a repeated or shared prompt prefix is restored only when both Macs hold it, with exactly the tokens of a request that prefilled the whole prompt, and it survives a restart of both Macs. Each Mac reserves about 1.3 GB more for it, so two 24 GB Macs now keep the pipeline for Gemma 4. +- Gemma 4 tensor parallel keeps prompt prefixes as the pipeline does, in memory and in the encrypted SSD tier: a repeated or shared prompt prefix is restored only when both Macs hold it, with exactly the tokens of a request that prefilled the whole prompt, and it survives a restart of both Macs. Each request reserves room for its own prompt's prefix (about 0.44 GB a Mac for a 32K-token prompt); kept prefixes use free memory only and are dropped first when memory runs short. - Gemma 4 tensor-parallel pairs serve one request at a time unless `DARKBLOOM_CLUSTER_BATCH_LANES` names more. Speed on a real pair is not measured yet. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 8c520b4367..c4c5b42396 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1133,21 +1133,22 @@ A Gemma 4 tensor-parallel rank is charged its own share, not the whole model | Its own KV heads of every layer (4 sliding, 1 full), residual rows | per request | about 364 MB (the whole model's: 719,380,600) | | One prompt chunk's attention transient over its 8 query heads | per request | about 145 MB | | FP32 partials (attention row, dense row, 8 expert rows and their packed copy) and 3 vocabulary rows | per request | about 113 MB | -| Prompt-prefix capture at its deepest boundary: its own full-attention rows and one window of every sliding layer (`prefixCaptureBytes`) | per request | about 191 MB (441,384,960 for the profile's 32,768-token prompt) | +| Prompt-prefix capture at its deepest boundary: its own full-attention rows for its prompt and one window of every sliding layer (`prefixCaptureBytes`); none when its cache is off | per request | 191,027,200 for an 8,319-token prompt (the LOAD quote's, for the profile's 32,768-token prompt: 441,384,960) | | Activation floor: `UnifiedMemoryCap`'s conservative default, 5.5 GiB, until a pair measures one | per rank | 5,905,580,032 | | Freed-buffer cache (half the allocator headroom) | per rank | 1,073,741,824 | | Eight sealed frames of the packed collective (512 x 101,376 bytes and the seal) | per rank | about 415 MB | -| Prompt-prefix memory tier: two captures of the profile's longest prompt (`prefixResidentBytes`) | per rank | 882,769,920 | The layout's `requestAllowance` quotes one request at the profile's longest -context (65,536 tokens) plus the per-rank charges, and the worker's LOAD gate -reserves exactly that beside the shard. A reservation or lane asks the live -gate for every held request, the new one and the per-rank charges. The planner -still charges at least the pipeline's whole-model `requestChargeEveryRankBytes`. -The memory tier's budget is its charge, or the pipeline's room-derived budget -where it is larger; entries beyond the charge give way before any refusal +context (65,536 tokens) and prompt plus the per-rank charges, and the worker's +LOAD gate reserves exactly that beside the shard. A reservation or lane asks +the live gate for every held request, the new one and the per-rank charges. The +planner still charges at least the pipeline's whole-model +`requestChargeEveryRankBytes`. The prompt-prefix memory tier is charged +nowhere: its budget is half the room the load measures beside the shard and +that quote (`QwenStagePrefixCache.budget(roomBytes:)`), and its entries give +way before any refusal ([Gemma TP prompt prefixes](prefix-cache.md#gemma-tp-prompt-prefixes)). A rank -whose prefix cache is off charges neither prefix term. +whose prefix cache is off charges no capture. Nothing here is measured on a pair; see [inference](inference.md#gemma-tensor-parallel-placement). diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index db50ebd9f3..8fb249c84d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4154,11 +4154,11 @@ stops, cancellations and retirements. Memory is charged per rank (`Gemma4TensorParallelRequestBudget`; see [hardware support](hardware-support.md#gemma-4-tensor-parallel-rank-memory)): each request its own KV heads, prompt transient, FP32 partials, vocabulary -rows and its prompt-prefix capture; each rank once the conservative activation -floor, the freed-buffer cache, eight sealed frames and the prefix memory tier's -charged budget. A lane is gated with every held lane's charge, the new one and -the rank's reserve. Speculative decoding, media and a measured activation floor -are not built yet. +rows and its own prompt's prefix capture; each rank once the conservative +activation floor, the freed-buffer cache and eight sealed frames. The prefix +memory tier lives in measured free room and is not charged. A lane is gated +with every held lane's charge, the new one and the rank's reserve. Speculative +decoding, media and a measured activation floor are not built yet. ### Gemma tensor-parallel placement @@ -4209,9 +4209,8 @@ sums cross the link: about 0.67-0.93x one M5 Ultra's decode, unmeasured | 2x M5 Ultra 256 GB | measured 29 us sums | 1,024 + 128 | pipeline | | 2x M5 Ultra 256 GB | measured 29 us sums, no share probe | 128 + 128 | tensor parallel (device-index prior) | | 2x M5 Ultra 256 GB | measured 5 us sums | 1,024 + 128 | tensor parallel | -| 2x M4 Pro 32 GB | default | 128 + 128 | tensor parallel | -| 2x M4 Pro 32 GB | default | 8,192 + 128 | pipeline | -| 2x M4 Pro 24 GB | any | any | pipeline: a rank's share and reserve, prompt-prefix memory included, do not fit | +| 2x M4 Pro 24 or 32 GB | default | 128 + 128 | tensor parallel | +| 2x M4 Pro 24 or 32 GB | default | 8,192 + 128 | pipeline | | 2x M4 Pro 32 GB | measured 29 us / 109 us sums | 1,024 + 128 | tensor parallel / pipeline | Before a share probe, the comparison takes a Mac's weight time from its device diff --git a/docs/architecture/prefix-cache.md b/docs/architecture/prefix-cache.md index 64c49bca96..28f6eec60c 100644 --- a/docs/architecture/prefix-cache.md +++ b/docs/architecture/prefix-cache.md @@ -1075,10 +1075,13 @@ restored in chronological writes no larger than `PagedKVBackend.pool.config.maxPrefillChunk` by `CBv2PagedPrefixRestore.write` in `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/State/CBv2PagedPrefixRestore.swift`. This permits a retained window larger than a legal individual write without -changing its absolute position or dropping tail tokens. Adoption releases its -new rows when restoration throws. Contiguous rows keep their existing update -path. This is resident stage restoration; it adds no SSD format, persistent -cache identity or cross-host KV-transfer contract. +changing its absolute position or dropping tail tokens. With `reservedTokens` +(Gemma tensor parallel), the new rows are reserved for the request's first +tokens and grow as a fresh request's do; without it, as before, for its whole +length. Adoption releases its new rows when restoration throws. Contiguous +rows keep their existing update path. This is resident stage restoration; it +adds no SSD format, persistent cache identity or cross-host KV-transfer +contract. ## Nemotron chunk-grid reuse @@ -1287,21 +1290,27 @@ tokens equal the cold request's bit for bit. Gemma records are native agreement carries `gemma4-tensor-parallel-prefix-v1` `on`; a rank whose `DARKBLOOM_CLUSTER_PREFIX_CACHE=off` loads `off` and its peer refuses it. -Memory: each request's charge includes its capture at its deepest boundary, -and each rank's reserve two such captures of the longest request for the -memory tier, both in the LOAD quote +Memory: each request's charge includes its own prompt's capture at its deepest +boundary (none when its cache is off), and the LOAD quote the capture of the +profile's longest prompt ([rank memory](hardware-support.md#gemma-4-tensor-parallel-rank-memory)). The -tier's budget is that charge, or the pipeline's budget when the room beside -the rank's reserve allows more; a request's capture beyond its charged part is -asked of the live gate and cut to that part when refused. Kept entries give way -before a reservation, a lane or a running request is refused for memory, then -the request's own capture, as in the pipeline; under host pressure an idle rank -drops them (`releaseIdleMemory`). The SSD tier's configuration, key, owner-only -directories, TTL, daily write cap, free-space floor and bounded close are every -cluster family's (`QwenStagePrefixDiskConfiguration`). +memory tier is charged nowhere: as the pipeline's, its budget is half the room +the load measures beside the shard and that quote +(`QwenStagePrefixCache.budget(roomBytes:)`), so it never exceeds that room. A +request captures what its charge covers whatever the tier's budget +(`Gemma4TensorParallelPrefix.captureLimit`): a tier the measured room leaves +without budget keeps nothing resident, and the capture still reaches the SSD +tier. A capture beyond its charged part (the pipeline's limit) is asked of the +live gate and cut to that part when refused. Kept entries give way before a +reservation, a lane or a running request is refused for memory, and a request +served alone then lets its own capture go, as the pipeline's does; under host +pressure an idle rank drops them (`releaseIdleMemory`). The SSD tier's +configuration, key, owner-only directories, TTL, daily write cap, free-space +floor and bounded close are every cluster family's +(`QwenStagePrefixDiskConfiguration`). Logs: `darkbloom-prefix-v1 … family=gemma4 mode=tensor_parallel` at load -(`budget_bytes=`, `charged_bytes=`, `ssd=`), at each agreed boundary +(`budget_bytes=`, `capture_charge=`, `room_bytes=`, `ssd=`), at each agreed boundary (`agreed=`, `reused=`, `tier=`) and at each keep (`stored=`); the tier's `darkbloom-prefix-ssd-v1` lines and `restore-declined`. Tests: `Gemma4TensorParallelPrefixTests` (restore against cold bit for bit, the diff --git a/docs/developer/test.md b/docs/developer/test.md index 5a0707eebe..698398bf1c 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1279,7 +1279,10 @@ neither real-weight numerics, a pair qualification nor speed. - the request loop (greedy and sampled) and batch lanes through the driver continue a restored prefix with the cold tokens; - the memory tier's budget and eviction, and a capture within its limit; - - the prefix charges in the request budget and the LOAD quote; + - a request's own capture charged in its budget and the LOAD quote, no + charge for the memory tier, whose budget stays within the measured room; + with no tier budget a request still captures within its charge and a + repeat restores from the SSD tier; - the SSD tier: records restore bit for bit after both tiers reopen, encrypted and owner-only; stale, corrupted and other-key records are refused on both ranks; no directory or key is no tier, and the daily write @@ -1293,9 +1296,9 @@ neither real-weight numerics, a pair qualification nor speed. 14,915,635,260 bytes), and the rank's reserve (`Gemma4TensorParallelRequestBudget`) must be quoted. Under the provider's tensor-parallel-first policy it checks the fastest-plan rule on constructed pairs: 2x M5 Ultra 256 GB keeps the pipeline on - default link costs; 2x M4 Pro 32 GB takes tensor parallel where predicted - faster, and 2x M4 Pro 24 GB keeps the pipeline (tensor parallel does not fit - with its prompt-prefix memory charged); measured links flip the choice both ways. It also pins the device-index + default link costs; 2x M4 Pro 24 or 32 GB takes tensor parallel where predicted + faster, each rank quoted with its request's prompt-prefix capture; measured + links flip the choice both ways. It also pins the device-index prior's choice for 2x M5 Ultra on the measured link: tensor parallel for a 128 + 128 request. diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 5af9d719bb..afaa6b2c1a 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -347,10 +347,8 @@ measured the link the plan prices tensor parallel on a slow assumed link. Once the link is measured, short prompts with longer answers can be predicted faster in tensor parallel, an estimate from each Mac's device index that a tensor-parallel load's own measurement then corrects. Two smaller Macs whose -decode is limited by memory bandwidth (for example 32 GB M4 Pro) get tensor -parallel for short prompts with longer answers; two 24 GB Macs keep the -pipeline, because tensor parallel's share with its prompt-prefix memory does -not fit them. The plan's "Tensor +decode is limited by memory bandwidth (for example 24 or 32 GB M4 Pro) get +tensor parallel for short prompts with longer answers. The plan's "Tensor parallel or pipeline" lines say which and why ([Gemma tensor-parallel placement](../architecture/inference.md#gemma-tensor-parallel-placement)). See the [placement planner](../../libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4TensorParallelRequestBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4TensorParallelRequestBudget.swift index 1da5e12b98..69f82b6b5b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4TensorParallelRequestBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4TensorParallelRequestBudget.swift @@ -14,20 +14,24 @@ import Foundation /// of them the collective carries), three float32 rows of the whole /// vocabulary (the row a sampled step gathers, the split head's half, the /// top-k) and its prompt-prefix capture at its deepest boundary -/// (`prefixCaptureBytes`: its own heads' full rows for the longest prompt of -/// that context and one sliding window of every sliding layer). +/// (`prefixCaptureBytes`: its own heads' full rows for its prompt, the +/// profile's longest in the LOAD quote, and one sliding window of every +/// sliding layer). /// /// Once per rank (`rankBytes`): the conservative activation floor until /// hardware measures one for a Gemma tensor-parallel rank (5.5 GiB, the /// provider's default reserve, as `GLM5NextServingResources` charges GLM's), -/// the freed-buffer cache the ready rank keeps, eight sealed frames of the -/// largest collective (`ClusterTensorParallelRequestAllowance`), and the -/// prompt-prefix memory tier's charged budget (`prefixResidentBytes`: two -/// captures of the longest request, as Qwen tensor parallel keeps two banks). -/// The decode steps' 100-operation command buffers +/// the freed-buffer cache the ready rank keeps and eight sealed frames of the +/// largest collective (`ClusterTensorParallelRequestAllowance`). The decode +/// steps' 100-operation command buffers /// (`Gemma4TensorParallelModel.decodeCommandBuffers`) bound only how a step /// is submitted, and no prefill is micro-batched: neither adds a buffer /// beyond these. +/// +/// The prompt-prefix memory tier is not charged: as the pipeline's, its +/// budget is half the room the load measures beside this charge +/// (`QwenStagePrefixCache.budget(roomBytes:)`), and its entries give way +/// before a reservation, a lane or a running request is refused for memory. struct Gemma4TensorParallelRequestBudget: Equatable { static let ranks = 2 /// `UnifiedMemoryCap.defaultActivationReserveBytes`: 5.5 GiB. A measured @@ -49,16 +53,12 @@ struct Gemma4TensorParallelRequestBudget: Equatable { let logitsBytes: Int /// The request's prompt-prefix capture at its deepest boundary. let prefixCaptureBytes: Int - /// The prompt-prefix memory tier's charged budget on a rank. - let prefixResidentBytes: Int let allowance: ClusterTensorParallelRequestAllowance /// What one request of `contextTokens` reserves on a rank. var requestBytes: Int { stateBytes + transientBytes + partialBytes + logitsBytes + prefixCaptureBytes } /// What a rank holds once beside every request it serves. - var rankBytes: Int { - Self.activationFloorBytes + Self.freedBufferCacheBytes + allowance.collectiveScratchBytes + prefixResidentBytes - } + var rankBytes: Int { Self.activationFloorBytes + Self.freedBufferCacheBytes + allowance.collectiveScratchBytes } /// One prefix capture of a prompt of `promptTokens` at the allocator's /// bound: this rank's full-attention rows (keys and values, every token) @@ -79,10 +79,10 @@ struct Gemma4TensorParallelRequestBudget: Equatable { return try QwenLongPrefillCheckedBytes.sum([bound(rows, count: 2 * full), bound(window, count: 2 * sliding)]) } - /// `promptTokens`: the longest prompt a request of this context holds - /// (the profile's, at most `contextTokens - 1`); nil: `contextTokens - 1`. - /// `keepsPrefixes` false charges no prefix capture or tier (the load's - /// cache off). + /// `promptTokens`: the prompt whose capture is charged (a request's own, + /// or the profile's longest in the LOAD quote), at most `contextTokens - 1`; + /// nil: `contextTokens - 1`. `keepsPrefixes` false charges no prefix + /// capture (the load's cache off, or the request's). static func derive(contextTokens: Int, chunkTokens: Int, promptTokens: Int? = nil, keepsPrefixes: Bool = true, allocationBound: (Int) throws -> Int) throws -> Self { typealias G = Gemma4StageGeometry @@ -97,7 +97,6 @@ struct Gemma4TensorParallelRequestBudget: Equatable { } let prompt = min(promptTokens ?? contextTokens - 1, contextTokens - 1) let capture = keepsPrefixes ? try prefixCaptureBytes(promptTokens: max(1, prompt), allocationBound: allocationBound) : 0 - let resident = try product([capture, 2]) let b = try Gemma4StateBudget.estimate(maximumTokens: contextTokens, chunkSize: chunk, ranks: ranks) let layers = b.fullLayers + b.slidingLayers let state = try sum([bound(b.fullKVBytes, count: 2 * b.fullLayers), bound(b.ringKVBytes, count: 2 * b.slidingLayers), @@ -116,10 +115,10 @@ struct Gemma4TensorParallelRequestBudget: Equatable { let request = try sum([state, bound(transientLogical), partials, logits, capture]) let allowance = try ClusterTensorParallelRequestAllowance(maximumContextTokens: contextTokens, maximumChunkTokens: chunk, - requestBytesExcludingCollectives: sum([request, activationFloorBytes, freedBufferCacheBytes, resident]), + requestBytesExcludingCollectives: sum([request, activationFloorBytes, freedBufferCacheBytes]), maximumCollectivePayloadBytes: payload, maximumCollectiveFrameBytes: frame, allocationBound: allocationBound) return .init(contextTokens: contextTokens, chunkTokens: chunk, stateBytes: state, transientBytes: try bound(transientLogical), partialBytes: partials, logitsBytes: logits, - prefixCaptureBytes: capture, prefixResidentBytes: resident, allowance: allowance) + prefixCaptureBytes: capture, allowance: allowance) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLanes.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLanes.swift index a3092bc5ba..5101cbe23d 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLanes.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLanes.swift @@ -5,8 +5,8 @@ import MLX struct Gemma4TensorParallelLaneReservation: QwenTensorParallelBatchReservation { let request: QwenLayerStageGenerationRequest let deadline: UInt64 - /// The lane's own charge at its context - /// (`Gemma4TensorParallelResidentRuntime.requestChargeBytes`). + /// The lane's own charge at its context, with its own prompt's prefix + /// capture (`Gemma4TensorParallelResidentRuntime.prefixCharge`). let laneStateBytes: Int /// What its prefix capture may hold (0: none). var prefixCaptureLimit = 0 diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift index 6b5d0deb08..4992c26f1b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift @@ -226,13 +226,17 @@ final class Gemma4TensorParallelPrefix { return session } - /// What `request`'s capture may hold on this rank: the pipeline's limit + /// What `request`'s capture may hold on this rank: what its own charge + /// covers (`chargedBytes`, its capture at its deepest boundary) whatever + /// the tier's budget, or the pipeline's limit where larger /// (`QwenStagePrefixCache.captureLimit`: after the deepest prefix this /// rank holds for it, at the measured cost, within the budget); 0 when it - /// keeps no prefix. - func captureLimit(_ request: QwenLayerStageGenerationRequest) -> Int { + /// keeps no prefix. A tier the measured room leaves without budget keeps + /// nothing resident, but the charged capture still reaches the SSD tier. + func captureLimit(_ request: QwenLayerStageGenerationRequest, chargedBytes: Int = 0) -> Int { guard let scopes = scopes(request) else { return 0 } - return cache.captureLimit(scope: scopes.resident, tokens: request.promptTokenIDs, chunkSize: request.chunkSize) + return max(chargedBytes, + cache.captureLimit(scope: scopes.resident, tokens: request.promptTokenIDs, chunkSize: request.chunkSize)) } /// After a request retired cleanly on both ranks: its capture becomes diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift index f8adf9ffe2..7637bdb5b6 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift @@ -150,7 +150,7 @@ public final class Gemma4TensorParallelResidentRuntime { let profile = admission.profile var probe: ClusterWorkerLinkProbe? var receipt: Gemma4TensorParallelShardReceipt? - var prefixCharges = (resident: 0, capture: 0, room: 0) + var prefixCharges = (capture: 0, room: 0) let capacity = try MLX.withError { nativeError -> Int in func checked() throws { try nativeError.check(); try control.check(); try nativeError.check() } try configuration.allocatorPolicy.configure(setCacheLimit: { Memory.cacheLimit = $0 }, check: checked) @@ -163,9 +163,9 @@ public final class Gemma4TensorParallelResidentRuntime { hiddenSize: profile.hiddenSize, chunkTokens: profile.maximumChunkTokens, check: checked) probe = measured log(QwenTensorParallelLinkProbe.line(measured, rank: collective.rank)) - // The load gate admits the shard with the profile's longest request and the rank's own - // reserve (activation floor, freed-buffer cache, sealed frames, the prefix tier's - // charged budget) beside it: the planner's quote. + // The load gate admits the shard with the profile's longest request (its prompt-prefix + // capture included) and the rank's own reserve (activation floor, freed-buffer cache, + // sealed frames) beside it: the planner's quote. let budget = try requestBudget(contextTokens: profile.maximumContextTokens, admission: admission, keepsPrefixes: keepsPrefixes) let request = budget.requestBytes @@ -199,15 +199,14 @@ public final class Gemma4TensorParallelResidentRuntime { Memory.cacheLimit = bufferCacheBytes try checked() } - // The prefix memory tier: its charged budget at least, else the - // pipeline's (half the admissible room beside the longest - // request and this rank's reserve, at most `maximumBudgetBytes`), - // whose entries beyond the charged part give way first. + // The prefix memory tier, charged nowhere: the pipeline's budget, + // half the admissible room measured beside the longest request + // and this rank's reserve (at most `maximumBudgetBytes`). if keepsPrefixes { let room = try ClusterStagePrefixBudget.roomBytes(chargeBytes: try QwenLongPrefillCheckedBytes.sum([ budget.requestBytes, budget.rankBytes])) - prefixCache.setBudget(max(budget.prefixResidentBytes, QwenStagePrefixCache.budget(roomBytes: room))) - prefixCharges = (budget.prefixResidentBytes, budget.prefixCaptureBytes, room) + prefixCache.setBudget(QwenStagePrefixCache.budget(roomBytes: room)) + prefixCharges = (budget.prefixCaptureBytes, room) } log("darkbloom-tensor-parallel-load-v1 rank=\(collective.rank) plan=\(planName) shares=1-1" + " shard_bytes=\(value.receipt.shardBytes) source_bytes=\(value.receipt.sourceBytes)" @@ -240,8 +239,8 @@ public final class Gemma4TensorParallelResidentRuntime { stagingEpoch: identity.membershipEpoch.uuidString.lowercased()) } log("darkbloom-prefix-v1 rank=\(collective.rank) family=gemma4 mode=tensor_parallel enabled=\(keepsPrefixes)" - + " budget_bytes=\(keepsPrefixes ? prefixCache.budgetBytes : 0) charged_bytes=\(prefixCharges.resident)" - + " capture_charge=\(prefixCharges.capture) room_bytes=\(prefixCharges.room) ssd=\(prefixCache.disk != nil)") + + " budget_bytes=\(keepsPrefixes ? prefixCache.budgetBytes : 0) capture_charge=\(prefixCharges.capture)" + + " room_bytes=\(prefixCharges.room) ssd=\(prefixCache.disk != nil)") let prefix = Gemma4TensorParallelPrefix(cache: keepsPrefixes ? prefixCache : QwenStagePrefixCache(enabled: false), load: loadAgreement, diskPlanScope: diskPlanScope) return Gemma4TensorParallelResidentRuntime(admission: admission, control: control, collective: collective, @@ -264,12 +263,12 @@ public final class Gemma4TensorParallelResidentRuntime { /// This rank's reserve for requests of `contextTokens` (`Gemma4TensorParallelRequestBudget`) /// at the allocator's own bound; `keepsPrefixes` charges the prompt-prefix - /// capture and memory tier. + /// capture of a prompt of `promptTokens` (the profile's longest by default). static func requestBudget(contextTokens: Int, admission: Gemma4ResidentAdmission, chunkTokens: Int? = nil, - keepsPrefixes: Bool = true) throws -> Gemma4TensorParallelRequestBudget { + promptTokens: Int? = nil, keepsPrefixes: Bool = true) throws -> Gemma4TensorParallelRequestBudget { try Gemma4TensorParallelRequestBudget.derive(contextTokens: contextTokens, chunkTokens: chunkTokens ?? admission.profile.maximumChunkTokens, - promptTokens: admission.profile.maximumPromptTokens, keepsPrefixes: keepsPrefixes, + promptTokens: promptTokens ?? admission.profile.maximumPromptTokens, keepsPrefixes: keepsPrefixes, allocationBound: QwenResidentResourceEnvironment.allocationBound) } @@ -284,24 +283,22 @@ public final class Gemma4TensorParallelResidentRuntime { } /// What the live gate asks for beside every held request: the rank's - /// activation floor, freed-buffer cache, sealed frames and the prefix - /// memory tier's charged budget. + /// activation floor, freed-buffer cache and sealed frames. var rankReserveBytes: Int { - get throws { - try Self.requestBudget(contextTokens: admission.profile.maximumContextTokens, admission: admission, - keepsPrefixes: prefix.cache.enabled).rankBytes - } + get throws { try Self.requestBudget(contextTokens: admission.profile.maximumContextTokens, admission: admission).rankBytes } } - /// A request's charge on this rank and what its prefix capture may hold - /// beyond the part that charge covers (`Gemma4TensorParallelPrefix.captureLimit` - /// less the capture at its deepest boundary): kept entries give way before - /// the live gate refuses it, and a capture the gate still refuses is cut - /// to its charged part. + /// A request's charge on this rank, at its own context with its own + /// prompt's prefix capture (none when its cache is off: it neither + /// restores nor captures), what that capture may hold + /// (`Gemma4TensorParallelPrefix.captureLimit`, at least the charged part) + /// and the part beyond the charge: kept entries give way before the live + /// gate refuses that part, and a capture the gate still refuses is cut to + /// its charged part. func prefixCharge(_ request: QwenLayerStageGenerationRequest) throws -> (charge: Int, captureLimit: Int, beyond: Int) { let budget = try Self.requestBudget(contextTokens: request.maximumTokens, admission: admission, - chunkTokens: request.chunkSize, keepsPrefixes: prefix.cache.enabled) - let limit = prefix.captureLimit(request) + chunkTokens: request.chunkSize, promptTokens: request.promptCount, keepsPrefixes: prefix.scopes(request) != nil) + let limit = prefix.captureLimit(request, chargedBytes: budget.prefixCaptureBytes) return (budget.requestBytes, limit, max(0, limit - budget.prefixCaptureBytes)) } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift index 66815f56ad..ea65058401 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift @@ -388,7 +388,7 @@ public enum ClusterPlacementLayouts { #endif if family.tensorParallel != nil, let bound { // What a rank's LOAD gate reserves beside its shard: one request at the profile's longest - // context, with its prompt-prefix capture and the prefix tier's charged budget. + // context, with its prompt-prefix capture. family.tensorParallelRequestAllowance = try Gemma4TensorParallelRequestBudget.derive( contextTokens: family.profile.maximumContextTokens, chunkTokens: family.profile.maximumChunkTokens, promptTokens: family.profile.maximumPromptTokens, diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelPrefixTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelPrefixTests.swift index de6fb685ec..46ee9c9ded 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelPrefixTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelPrefixTests.swift @@ -147,9 +147,10 @@ struct Gemma4TensorParallelPrefixTests { let coldLogits = try #require(try cold.prefill(Self.prompt, range: 32 ..< 40, check: check) { $0 }).logits let coldAt40 = try fingerprint(cold) let states = try #require(cold.prefixCapture).states() + let deepest: QwenStagePrefixState = try #require(states.last) try cold.retire() let restored = try Gemma4TensorParallelPagedSession(model: model, host: host, - promptCount: Self.prompt.count, outputCount: Self.outputs, restoring: try #require(states.last)) + promptCount: Self.prompt.count, outputCount: Self.outputs, restoring: deepest) let restoredAt32 = try fingerprint(restored) let restoredLogits = try #require(try restored.prefill(Self.prompt, range: 32 ..< 40, check: check) { $0 }).logits let restoredAt40 = try fingerprint(restored) @@ -372,26 +373,73 @@ struct Gemma4TensorParallelPrefixTests { } } - /// What one request and a rank charge for prompt prefixes - /// (`Gemma4TensorParallelRequestBudget`): the request its capture at its - /// deepest boundary (its own full rows and one window of every sliding - /// layer), the rank two of them for its memory tier, both in the LOAD - /// quote; nothing when the load keeps no prefixes. - @Test func prefixMemoryIsChargedInTheRequestBudgetAndTheLoadQuote() throws { + /// A tier the measured room leaves without budget (as on two 24 GB Macs) + /// keeps nothing resident, but a request still captures what its own + /// charge covers (`captureLimit(_:chargedBytes:)`): its deepest boundary + /// reaches the SSD tier, and a repeat restores it from there on both + /// ranks, bit for bit. + @Test func aRequestCapturesWithinItsChargeWhenTheTierHasNoBudget() throws { + let directory = try Self.synthetic() + let root = try Self.root() + defer { try? FileManager.default.removeItem(at: directory); try? FileManager.default.removeItem(at: root) } + let pair = Pair(), models = try Self.models(directory, pair) + let results = try Pair.run(device: .gpu) { rank -> [String: Bool] in + // The deepest boundary's cost, measured as a load's first capture measures it. + let probe = try Rank(models.value[rank]) + let request = try probe.request(Self.prompt) + let cold = try probe.serve(request) + let charged = try #require(probe.prefix.cache.captureCost).bytes(deepest: 32, frontiers: 1) + let tier = QwenStagePrefixCache(strideTokens: Self.chunk, budgetBytes: 0) + let fixture = try Rank(models.value[rank], cache: tier, disk: try Self.tier(root, rank: rank)) + let limit = fixture.prefix.captureLimit(request, chargedBytes: charged) + let withoutCharge = fixture.prefix.captureLimit(request) + fixture.captureLimit = limit + let first = try fixture.serve(request) + let disk = try #require(fixture.prefix.disk) + let written = disk.drain(timeoutSeconds: 60) && disk.recordCount == 1 + let repeated = try fixture.serve(request) + disk.close(timeoutSeconds: 5) + return ["limit": limit == charged && withoutCharge == 0, "stored": first.stored == [32], + "resident": tier.bytesInUse == 0 && tier.count == 0, "written": written, + "restored": repeated.reused == 32 && Self.same(repeated.generation, cold.generation) + && disk.stats.restores == 1] + } + for (rank, checks) in results.enumerated() { + for name in ["limit", "stored", "resident", "written", "restored"] { + #expect(checks[name] == true, "rank \(rank): \(name)") + } + } + } + + /// What prompt prefixes charge (`Gemma4TensorParallelRequestBudget`): a + /// request its own capture at its deepest boundary (its own full rows and + /// one window of every sliding layer), in its reservation and, at the + /// profile's longest prompt, in the LOAD quote; a rank nothing for its + /// memory tier, whose budget is half the room the load measures + /// (`QwenStagePrefixCache.budget(roomBytes:)`), never more than that room; + /// nothing when the load keeps no prefixes. + @Test func aRequestsCaptureIsChargedAndTheTierStaysWithinItsRoom() throws { let bound: (Int) throws -> Int = { $0 + 16_384 } let on = try Gemma4TensorParallelRequestBudget.derive(contextTokens: 65_536, chunkTokens: 512, promptTokens: 32_768, allocationBound: bound) let off = try Gemma4TensorParallelRequestBudget.derive(contextTokens: 65_536, chunkTokens: 512, promptTokens: 32_768, keepsPrefixes: false, allocationBound: bound) let capture = 10 * (32_768 * 512 * 2 + 16_384) + 50 * (1_024 * 4 * 256 * 2 + 16_384) - #expect(on.prefixCaptureBytes == capture && on.prefixResidentBytes == 2 * capture) - #expect(on.requestBytes == off.requestBytes + capture && on.rankBytes == off.rankBytes + 2 * capture) + #expect(on.prefixCaptureBytes == capture && off.prefixCaptureBytes == 0) + #expect(on.requestBytes == off.requestBytes + capture && on.rankBytes == off.rankBytes) #expect(on.allowance.reservedBytes == on.requestBytes + on.rankBytes) - #expect(on.allowance.reservedBytes == off.allowance.reservedBytes + 3 * capture) - #expect(off.prefixCaptureBytes == 0 && off.prefixResidentBytes == 0) - // A short request's capture: its own rows and a short window. - #expect(try Gemma4TensorParallelRequestBudget.prefixCaptureBytes(promptTokens: 100, allocationBound: bound) - == 10 * (100 * 512 * 2 + 16_384) + 50 * (100 * 4 * 256 * 2 + 16_384)) + #expect(on.allowance.reservedBytes == off.allowance.reservedBytes + capture) + // A short request is charged its own prompt's capture: its own rows and a short window. + let short = try Gemma4TensorParallelRequestBudget.derive(contextTokens: 8_320, chunkTokens: 512, promptTokens: 100, + allocationBound: bound) + #expect(short.prefixCaptureBytes == 10 * (100 * 512 * 2 + 16_384) + 50 * (100 * 4 * 256 * 2 + 16_384)) + // The tier's budget from the measured room: half of it in 256 MiB steps, at most the ceiling. + let mib = 1 << 20 + for room in [0, 1, 511 * mib, 512 * mib, 1_000 * mib, 3 << 30, 1 << 40] { + let tier = QwenStagePrefixCache.budget(roomBytes: room) + #expect(tier <= room / 2 && tier <= QwenStagePrefixCache.maximumBudgetBytes && tier % (256 * mib) == 0, "room \(room)") + } + #expect(QwenStagePrefixCache.budget(roomBytes: 511 * mib) == 0 && QwenStagePrefixCache.budget(roomBytes: 1_000 * mib) == 256 * mib) } // MARK: - SSD tier diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift index f2fe97127f..f56091bdc2 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift @@ -101,30 +101,29 @@ private func checkGemmaLayouts(_ layout: ClusterModelLayout, configuration: Data } /// A product layout carries the rank's native reserve (`Gemma4TensorParallelRequestBudget`): -/// its own heads' state and prompt-prefix capture, the activation floor, the freed-buffer cache, -/// eight sealed frames and the prompt-prefix memory tier's charged budget. +/// its own heads' state and prompt-prefix capture, the activation floor, the freed-buffer cache +/// and eight sealed frames. The prefix memory tier is not charged (its budget is measured room). private func checkGemmaRequestAllowance(_ priced: ClusterModelLayout, _ checks: PlacementChecks) throws { let allowance = priced.tensorParallel?.family.requestAllowance let budget = try Gemma4TensorParallelRequestBudget.derive(contextTokens: 65_536, chunkTokens: 512, promptTokens: 32_768, allocationBound: { $0 + 16_384 }) checks.require("Gemma TP allowance: the layout quotes the rank's budget at the profile's longest request (65,536 tokens, 512-token chunks)", allowance == budget.allowance && allowance?.maximumContextTokens == 65_536 && allowance?.maximumChunkTokens == 512) - checks.require("Gemma TP allowance: the conservative 5.5 GiB activation floor, the freed-buffer cache and the prefix tier are charged once beside the request", + checks.require("Gemma TP allowance: the conservative 5.5 GiB activation floor and the freed-buffer cache are charged once beside the request", budget.rankBytes == Gemma4TensorParallelRequestBudget.activationFloorBytes + Gemma4TensorParallelRequestBudget.freedBufferCacheBytes - + budget.allowance.collectiveScratchBytes + budget.prefixResidentBytes - && Gemma4TensorParallelRequestBudget.activationFloorBytes == 5_905_580_032 + + budget.allowance.collectiveScratchBytes && Gemma4TensorParallelRequestBudget.activationFloorBytes == 5_905_580_032 && budget.allowance.reservedBytes == budget.requestBytes + budget.rankBytes) // A 32,768-token prompt's own full rows (5 layers x 1 head x 512 x K and V, bf16) and a 1,024-token window // of each of the 25 sliding layers (4 heads x 256 x K and V), each array at the allocator's bound. let capture = 10 * (32_768 * 512 * 2 + 16_384) + 50 * (1_024 * 4 * 256 * 2 + 16_384) - checks.require("Gemma TP allowance: a request's prompt-prefix capture (\(budget.prefixCaptureBytes) bytes) and two of them for the memory tier", - budget.prefixCaptureBytes == capture && budget.prefixResidentBytes == 2 * capture + checks.require("Gemma TP allowance: the request's own prompt-prefix capture (\(budget.prefixCaptureBytes) bytes), and nothing for the memory tier", + budget.prefixCaptureBytes == capture && budget.requestBytes == budget.stateBytes + budget.transientBytes + budget.partialBytes + budget.logitsBytes + capture) let off = try Gemma4TensorParallelRequestBudget.derive(contextTokens: 65_536, chunkTokens: 512, promptTokens: 32_768, keepsPrefixes: false, allocationBound: { $0 + 16_384 }) - checks.require("Gemma TP allowance: a rank whose prefix cache is off charges neither", - off.prefixCaptureBytes == 0 && off.prefixResidentBytes == 0 - && budget.allowance.reservedBytes - off.allowance.reservedBytes == 3 * capture) + checks.require("Gemma TP allowance: a rank whose prefix cache is off charges no capture; the capture is the quote's only prefix term", + off.prefixCaptureBytes == 0 && off.rankBytes == budget.rankBytes + && budget.allowance.reservedBytes - off.allowance.reservedBytes == capture) checks.require("Gemma TP allowance: eight sealed frames of the packed feed-forward collective (512 x 101,376 bytes and the seal)", budget.allowance.maximumCollectivePayloadBytes == 512 * 101_376 && budget.allowance.collectiveScratchBytes == 8 * (budget.allowance.maximumCollectiveFrameBytes + 16_384)) @@ -140,6 +139,12 @@ private func checkGemmaRequestAllowance(_ priced: ClusterModelLayout, _ checks: let pages = (priced.layers.reduce(0) { $0 + $1.weights.tensorCount } + priced.ingress.tensorCount + priced.egress.tensorCount) * SyntheticMac.page checks.require("Gemma TP quote: a rank's weights are its exact 8,040,450,108-byte shard in whole pages, and its request need covers the reserve", rank?.weightsBytes == 8_040_450_108 + pages && (rank?.requestNeedBytes ?? 0) >= budget.allowance.reservedBytes) + // Two idle 24 GB Macs (the fastest-plan checks' M4 Pro) hold a rank each with that quote, the request's capture in it. + let small = try [SyntheticMac.idle(24).device("a"), SyntheticMac.idle(24).device("b")] + let fitted = try ClusterPlacementPlanner.plan(devices: small, layout: priced, policy: forced).chosen?.ranks ?? [] + let spare = fitted.map { $0.admissibleNowBytes - $0.needBytes }.min() ?? -1 + checks.require("Gemma TP quote: two 24 GB Macs each fit a rank now, its request's prompt-prefix capture charged (\(spare) bytes to spare)", + fitted.count == 2 && fitted.allSatisfy { $0.fit == .now && $0.requestNeedBytes >= budget.allowance.reservedBytes } && spare >= 0) } /// The fastest-plan rule on constructed pairs, under the provider's own @@ -201,8 +206,8 @@ private func checkGemmaFastestPlan(_ layout: ClusterModelLayout, _ checks: Place checks.require("Gemma fastest plan: without its choice the same layout, Macs and policy put tensor parallel first", ruled.chosen?.mode == .tensorParallel) - // 2. Two small Macs (32 GB M4 Pro), default link costs: tensor parallel where the plan predicts it faster. - for gib in [32.0] { + // 2. Two small Macs (24 and 32 GB M4 Pro), default link costs: tensor parallel where the plan predicts it faster. + for gib in [24.0, 32.0] { let small = try pros(gib) let decodeHeavy = try plan(small, first(128, 128), .unmeasured), times = predicted(decodeHeavy) checks.require("Gemma fastest plan: 2x M4 Pro \(Int(gib)) GB, default link costs, 128 + 128: tensor parallel, predicted faster by the margin (\(times.tensor) s vs \(times.other) s)", @@ -210,14 +215,6 @@ private func checkGemmaFastestPlan(_ layout: ClusterModelLayout, _ checks: Place checks.require("Gemma fastest plan: 2x M4 Pro \(Int(gib)) GB, default link costs, 8,192 + 128: a pipeline (the prompt's sums dominate)", pipeline(try plan(small, first(8_192, 128), .unmeasured))) } - // Two 24 GB M4 Pro: a rank's share and reserve with its prompt-prefix capture and memory tier charged - // (`Gemma4TensorParallelRequestBudget`) exceed what the Mac gives a model, so the pipeline, which keeps - // prefixes too, is placed for every request. - for (prompt, outputs) in [(128, 128), (8_192, 128)] { - let result = try plan(try pros(24), first(prompt, outputs), .unmeasured) - checks.require("Gemma fastest plan: 2x M4 Pro 24 GB, \(prompt) + \(outputs): a pipeline, tensor parallel does not fit with its prefix memory charged", - result.chosen?.mode == .pipeline && result.tensorParallel?.verdict == .doesNotFit) - } // 3. A measured link flips the choice as predicted, both ways. let ultraDefault = try plan(ultras, first(1_024, 128), .unmeasured), ultraMeasured = try plan(ultras, first(1_024, 128), measuredLink) From f20d8f6f89c2c7abdfeb125267fa931ae6953ed4 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:01:00 -0800 Subject: [PATCH 0122/1441] cluster: MiMo TP verify windows hand each sum the one-token FP32 partials Under contract v2 (#1707) a rank's row-parallel partials stay FP32 until the cross-rank sum. The SDK merge (0a1e228d) makes the verify window follow it: o_proj is one FP32 product per row (the one-token step's M=1 product; the BF16/F16 row-exact kernel no longer serves a rank), the dense down_proj runs row by row, and the routed layer combines each row's FP32 expert rows (float32ExpertRows) as its one-row step does. - MiMoTensorParallelFloat32PartialTests.windowPartialsAreTheOneTokenStepsFloat32Partials (GPU, the kernel variant): after a 12-token prompt that wraps the 8-row sliding ring, a 4-row window hands every sum, on both ranks, the one-token steps' own partials row for row and bit for bit; every window partial is FP32 and holds values BF16 cannot; the logits are the steps'. - The speculative load agreement names the window's contract: windows=row-exact-one-token-float32-partials-v2 (was windows=row-exact-one-token-bits), pinned by its test. Co-Authored-By: Claude Opus 5.5 --- .../MiMoTensorParallelResidentRuntime.swift | 6 +- ...iMoTensorParallelFloat32PartialTests.swift | 55 +++++++++++++++++++ .../MiMoTensorParallelSpeculativeTests.swift | 3 +- 3 files changed, 61 insertions(+), 3 deletions(-) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift index 3c9d6f840c..46001dd266 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift @@ -65,10 +65,12 @@ public final class MiMoTensorParallelResidentRuntime { + ClusterDataPlaneAgreement.loadAgreementFields + (speculative.map(speculativeAgreementFields) ?? []) } - /// Rounds of `terms.depth` proposals from heads replicated whole, verified in row-exact windows. + /// Rounds of `terms.depth` proposals from heads replicated whole, verified in row-exact windows whose + /// partials are each row's one-token FP32 partials (contract v2: `o_proj` one FP32 product a row, the dense + /// layer row by row, the routed layer's FP32 expert rows combined row by row). static func speculativeAgreementFields(_ terms: MiMoMTPTerms) -> [String] { ["mimo-v26-tensor-parallel-speculative-v1"] + terms.loadAgreementFields - + ["heads=replicated-whole", "draft=split-argmax-sum", "windows=row-exact-one-token-bits"] + + ["heads=replicated-whole", "draft=split-argmax-sum", "windows=row-exact-one-token-float32-partials-v2"] } let admission: MiMoResidentAdmission diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift index 4fdb1c6472..abb425c52a 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift @@ -205,4 +205,59 @@ struct MiMoTensorParallelFloat32PartialTests { #expect(error <= scale * 0x1p-16, "FP32 reassociation only: \(error) of \(scale)") #expect(perHalfError > 16 * error, "per-half BF16 rows (v1) err \(perHalfError), FP32 rows \(error)") } + + /// A speculative round's verify window (`forwardVerifyWindow`, 4 rows after a prompt that + /// wrapped the sliding ring) hands each sum the one-token steps' own partials, row for row and + /// bit for bit: `o_proj` (one FP32 product per row; the row-exact BF16 kernel serves no rank), + /// the dense feed-forward row by row, and the routed one's per-row combine of FP32 expert rows. + /// Every window partial is FP32 and holds values BF16 cannot, and the logits are the steps'. + @Test func windowPartialsAreTheOneTokenStepsFloat32Partials() throws { + let (_, ranks, directory) = try Self.models() + defer { try? FileManager.default.removeItem(at: directory) } + final class Recorder: @unchecked Sendable { var summed: [MLXArray] = [] } + func bits(_ value: MLXArray) -> [UInt32] { + Device.withDefaultDevice(.cpu) { value.asType(.float32).asArray(Float.self).map(\.bitPattern) } + } + let prompt = MLXArray((0 ..< 12).map { Int32(($0 * 37 + 11) % 512) }).reshaped([1, 12]) + let tokens: [Int32] = [7, 301, 45, 129] + for (rankIndex, rank) in ranks.enumerated() { + // Each rank alone: the sum hands its partial back, so the window and the steps see one function. + let recorder = Recorder() + let context = MiMoV26TensorParallelContext( + reduce: { recorder.summed.append($0); return $0 }, vocabularyRows: rank.vocabularyRange) + let layers = rank.model.model.layers + let installed = layers.map(\.tensorParallel) + for layer in layers { layer.tensorParallel = context } + defer { for (layer, value) in zip(layers, installed) { layer.tensorParallel = value } } + let windowCaches = try rank.model.makeIndependentHistoryCaches() + let stepCaches = try rank.model.makeIndependentHistoryCaches() + for caches in [windowCaches, stepCaches] { + eval(try rank.model.forwardIndependentHistory(inputIDs: prompt, caches: caches).logits) + } + recorder.summed = [] + let window = try rank.model.forwardVerifyWindow( + inputIDs: MLXArray(tokens).reshaped([1, tokens.count]), caches: windowCaches) + eval([window.logits] + recorder.summed) + let windowPartials = recorder.summed + #expect(windowPartials.count == 2 * layers.count, "rank \(rankIndex): an attention and a feed-forward sum a layer") + for (index, partial) in windowPartials.enumerated() { + #expect(partial.dtype == .float32 && partial.shape == [1, tokens.count, Self.hidden]) + let widenedBF16 = partial.asType(.bfloat16).asType(.float32) + #expect(any(partial .!= widenedBF16).item(Bool.self), "rank \(rankIndex): window partial \(index) holds only BF16 values") + } + for (row, token) in tokens.enumerated() { + recorder.summed = [] + let step = try rank.model.forwardIndependentHistory( + inputIDs: MLXArray([token]).reshaped([1, 1]), caches: stepCaches) + eval([step.logits] + recorder.summed) + #expect(recorder.summed.count == windowPartials.count) + for (index, partial) in zip(windowPartials, recorder.summed).enumerated() { + #expect(bits(partial.0[0..., row ..< (row + 1), 0...]) == bits(partial.1), + "rank \(rankIndex), row \(row): window partial \(index) is not the step's") + } + #expect(bits(window.logits[0..., row ..< (row + 1), 0...]) == bits(step.logits), + "rank \(rankIndex), row \(row): window logits are not the step's") + } + } + } } diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift index 8e601342a6..e885d72ab5 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift @@ -276,7 +276,8 @@ struct MiMoTensorParallelSpeculativeTests { let two = Runtime.loadAgreementFields(plan: plan, chunkTokens: 512, speculative: try MiMoMTPTerms(depth: 2)) let three = Runtime.loadAgreementFields(plan: plan, chunkTokens: 512, speculative: try MiMoMTPTerms(depth: 3)) #expect(Array(two.prefix(plain.count)) == plain && two.count > plain.count && two != three) - #expect(two.contains("depth=2") && two.contains("windows=row-exact-one-token-bits")) + #expect(two.contains("depth=2") && two.contains("windows=row-exact-one-token-float32-partials-v2")) + #expect(!two.contains("windows=row-exact-one-token-bits"), "the BF16-partial window contract is gone") } /// A window's settle at the registered sliding window (a 128-row ring over two 64-token From baf274b27efb2e2da51f8d0970bcd66407468a90 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:01:23 -0800 Subject: [PATCH 0123/1441] cluster: MiMo tensor parallel decodes in speculative rounds by default The owner said everything ships, and feature parity (#1715) holds MiMo tensor parallel back against pipeline_mtp_v1 until it keeps the rounds. - ClusterMiMoTensorParallel (protocol): the installed depth, 2 (the depth MiMo's pipeline measured fastest, MiMoMTPTerms.standard), and the worker arguments that turn the rounds on for tensor parallel of the registered MiMo text row. - The provider passes both ranks --mtp-depth 2 after the mode wherever the pinned capability record declares tensor parallel's rounds (DistributedInstalledGenerationSelection.mimoTensorParallelRounds), and the cluster status then reports the head as decoding (DistributedInstalledSpeculation). - The worker declares them: MiMoTensorParallelResidentRuntime.servingFeatures .speculativeRounds follows the installed depth, so the capability record says MiMo tensor parallel keeps every feature of the speculative and the compact-decode pipelines and drops only the plain pipeline's 8 lanes. A worker launched by hand without the depth still decodes one token a step. - Checks: the capability test pins the declaration and what each mode drops; the installed-session check launches MiMo tensor parallel with and without the declaration (depth exactly when declared); the provider setup check plans MiMo with this build's declarations (the evidence rule decides against the speculative pipeline: prior only keeps it, this build's records at 95 tok/s choose tensor parallel), keeps a record without rounds held back, and holds tensor parallel back for the plain pipeline's lanes where that pipeline is the mode it would replace. Co-Authored-By: Claude Opus 5.5 --- .../Execution/NativeWorkerRuntime.swift | 3 +- .../ClusterMiMoTensorParallel.swift | 25 ++++++++++++ .../MiMoTensorParallelResidentRuntime.swift | 17 +++++--- .../MiMoTensorParallelResidentTests.swift | 19 +++++++-- ...tributedInstalledGenerationSelection.swift | 20 +++++++++- .../InstalledFixture.swift | 8 ++-- .../InstalledSessionCheck.swift | 23 +++++++++++ .../PlacementSetupCheck.swift | 39 +++++++++++++------ 8 files changed, 126 insertions(+), 28 deletions(-) create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterMiMoTensorParallel.swift diff --git a/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift b/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift index 14dabbcff9..c868c7f35a 100644 --- a/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift +++ b/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift @@ -52,7 +52,8 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { prefixSSDKey: prefixSSDKey)) case .mimoV26 where generationMode == .tensorParallel: // Every layer on both ranks, half of each split weight, sealed sums; text only. `--mtp-depth` - // (1...3, MiMo's own terms) adds speculative rounds on heads replicated whole; none by default. + // (1...3, MiMo's own terms) adds speculative rounds on heads replicated whole; the installed owner + // passes `ClusterMiMoTensorParallel.speculativeDepth`, and a hand launch without it runs none. guard tensorAssistantPolicy == nil, tensorShares == [1, 1], let dataPlane else { throw WorkerFailure.invalid("MiMo tensor parallel runs equal shares over a keyed data plane") } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterMiMoTensorParallel.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterMiMoTensorParallel.swift new file mode 100644 index 0000000000..5455d17757 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterMiMoTensorParallel.swift @@ -0,0 +1,25 @@ +import Foundation + +/// How MiMo V2.6 Flash's tensor parallel decodes, for the owner that launches +/// it and the worker that declares it: every rank holds the artifact's three +/// trained next-N heads whole and decodes in speculative rounds +/// (`MiMoTensorParallelResidentRuntime`, `--mtp-depth`). No generation mode +/// names those heads, so the owner passes the depth to both ranks, and both +/// bind it into their load agreement. +public enum ClusterMiMoTensorParallel { + /// Drafts each round verifies: the depth MiMo's speculative pipeline + /// measured fastest (`MiMoMTPTerms.standard`), which the tensor-parallel + /// plan recommends too. + public static let speculativeDepth = 2 + + /// Whether a placement of `runtimeModelID` in `mode` decodes with the + /// heads: tensor parallel of the registered MiMo text row. + public static func decodesWithHead(runtimeModelID: String, mode: ClusterGenerationMode) -> Bool { + runtimeModelID == ClusterMiMoImageCandidate.runtimeModelID && mode == .tensorParallel && speculativeDepth > 0 + } + + /// The worker arguments that turn the rounds on; none for any other placement. + public static func workerArguments(runtimeModelID: String, mode: ClusterGenerationMode) -> [String] { + decodesWithHead(runtimeModelID: runtimeModelID, mode: mode) ? ["--mtp-depth", String(speculativeDepth)] : [] + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift index 46001dd266..5e650a6626 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift @@ -12,10 +12,13 @@ import MLXLLM /// step together, and sum each layer's attention and feed-forward partials /// with the sealed all-sum inside the lazy graph, under the session's keyed /// data plane. Text only: the private image candidate stays a pipeline -/// candidate. With a speculative depth (`--mtp-depth`, off by default) both -/// ranks also hold the three trained heads whole and decode in rounds +/// candidate. With a speculative depth (`--mtp-depth`, which the installed +/// owner passes every MiMo tensor-parallel launch: +/// `ClusterMiMoTensorParallel.speculativeDepth`) both ranks also hold the three +/// trained heads whole and decode in rounds /// (`MiMoTensorParallelDecoding.runRounds`): row-exact verify windows through -/// the same sums, so greedy tokens are the one-token path's. +/// the same sums, so every token is the one-token path's. A hand launch +/// without the depth decodes one token a step. /// /// The executor contract of `GLM5NextTensorParallelResidentRuntime`, one /// lane: one request at a time, cancel from the control thread, an enclosing @@ -39,10 +42,12 @@ import MLXLLM /// product's own gather (sampled rows). No prompt-prefix reuse yet. public final class MiMoTensorParallelResidentRuntime { /// What this owner keeps of the model's serving features, as the capability declares it - /// (`MiMoResidentCapabilityMetadata.servingFeatures`): one lane and no prompt prefix (both bound below), no - /// speculative rounds (no rank holds the trained heads), and committed-token logprobs. + /// (`MiMoResidentCapabilityMetadata.servingFeatures`): one lane and no prompt prefix (both bound below), + /// speculative rounds on the trained heads (the installed owner launches both ranks with + /// `ClusterMiMoTensorParallel.speculativeDepth`, bound by `speculativeAgreementFields`), and committed-token + /// logprobs. static let servingFeatures = ClusterServingFeatures(promptPrefixReuse: false, ssdPrefixTier: false, - speculativeRounds: false, maximumLanes: 1, logprobs: true) + speculativeRounds: ClusterMiMoTensorParallel.speculativeDepth > 0, maximumLanes: 1, logprobs: true) /// Everything about serving both ranks must have been told the same, /// beside the plan: one lane, paged KV, the chunk grid, the selection diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelResidentTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelResidentTests.swift index 2aff9d4750..5979c46784 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelResidentTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelResidentTests.swift @@ -369,8 +369,10 @@ struct MiMoTensorParallelResidentTests { /// What the text row's capability declares of each mode is what its loads run: no mode keeps prompt prefixes /// (paged or handed-off histories), only the plain pipeline takes lanes, the speculative pipeline decodes in - /// rounds, and tensor parallel serves one lane without rounds and adds logprobs. The provider's setup check plans - /// with these values (`PlacementSetupCheck.mimoFeatures`). + /// rounds, and tensor parallel serves one lane in rounds (the installed owner passes every MiMo tensor-parallel + /// launch `ClusterMiMoTensorParallel.speculativeDepth`) and adds logprobs. So tensor parallel keeps every + /// feature of the speculative pipeline and of the compact-decode pipeline, and drops only the plain pipeline's + /// lanes. The provider's setup check plans with these values (`PlacementSetupCheck.mimoFeatures`). @Test func capabilityDeclaresWhatEachTextModeKeeps() throws { let modes: [ClusterGenerationMode] = [.pipeline, .pipelineCompactDecode, .phaseSplit, .tensorParallel, .pipelineMTP] let features = try MiMoResidentCapabilityMetadata.servingFeatures(modes) @@ -378,8 +380,17 @@ struct MiMoTensorParallelResidentTests { .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: rounds, maximumLanes: lanes, logprobs: logprobs) } #expect(features == [.pipeline: entry(lanes: 8), .pipelineCompactDecode: entry(lanes: 1), .phaseSplit: entry(lanes: 1), - .tensorParallel: entry(lanes: 1, logprobs: true), .pipelineMTP: entry(lanes: 1, rounds: true)]) - #expect(features[.pipelineMTP]?.dropped(by: MiMoTensorParallelResidentRuntime.servingFeatures) == ["speculative (MTP) rounds"]) + .tensorParallel: entry(lanes: 1, rounds: true, logprobs: true), .pipelineMTP: entry(lanes: 1, rounds: true)]) + let tensorParallel = MiMoTensorParallelResidentRuntime.servingFeatures + #expect(ClusterMiMoTensorParallel.speculativeDepth == MiMoMTPTerms.standard.depth) + #expect(features[.pipelineMTP]?.dropped(by: tensorParallel) == []) + #expect(features[.pipelineCompactDecode]?.dropped(by: tensorParallel) == []) + #expect(features[.phaseSplit]?.dropped(by: tensorParallel) == []) + #expect(features[.pipeline]?.dropped(by: tensorParallel) == ["batch lanes up to 8 (it serves 1)"]) + let mimo = MiMoRegisteredModel.v26FlashMOPD.rawValue + #expect(ClusterMiMoTensorParallel.workerArguments(runtimeModelID: mimo, mode: .tensorParallel) == ["--mtp-depth", "2"]) + #expect(ClusterMiMoTensorParallel.workerArguments(runtimeModelID: mimo, mode: .pipelineMTP).isEmpty) + #expect(ClusterMiMoTensorParallel.workerArguments(runtimeModelID: "registered_glm53_flash", mode: .tensorParallel).isEmpty) } /// The registered plan's per-rank reserve: paged history (full layers grow diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledGenerationSelection.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledGenerationSelection.swift index d0d6d1ba3e..c33a6089ff 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledGenerationSelection.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledGenerationSelection.swift @@ -7,7 +7,9 @@ import DarkbloomClusterProtocol /// mode is passed to both ranks, and only when the pinned capability record /// covers each member's worker and advertises the mode; the two ranks then /// bind it into their load agreement themselves. The owner never passes a -/// qualification switch. +/// qualification switch. MiMo's tensor parallel decodes in speculative rounds +/// on its trained heads wherever the pinned record declares them +/// (`ClusterMiMoTensorParallel`), so both ranks get the same depth. enum DistributedInstalledGenerationSelection { static func workerArguments(configuration: ClusterConfiguration, capability: ClusterRuntimeCapability) throws -> [String] { @@ -15,6 +17,9 @@ enum DistributedInstalledGenerationSelection { try ClusterGenerationSelection.requireSupport(for: mode, peers: configuration.peers, capability: capability) let shares = configuration.tensorShares.map { ["--tensor-shares", $0.map(String.init).joined(separator: ":")] } ?? [] var arguments = mode == .pipeline ? [] : ["--generation-mode", mode.rawValue] + (mode == .tensorParallel ? shares : []) + if mimoTensorParallelRounds(mode: mode, capability: capability) { + arguments += ClusterMiMoTensorParallel.workerArguments(runtimeModelID: capability.runtimeModelID, mode: mode) + } if let assistant = configuration.tensorAssistant { try assistant.validate() guard mode == .tensorParallel, ClusterQwenTensorAssistantPolicy.runtimeModelIDs.contains(capability.runtimeModelID) else { @@ -25,6 +30,12 @@ enum DistributedInstalledGenerationSelection { } return arguments } + + /// MiMo tensor parallel's rounds, launched only where the worker's record declares them for the mode. + static func mimoTensorParallelRounds(mode: ClusterGenerationMode, capability: ClusterRuntimeCapability) -> Bool { + ClusterMiMoTensorParallel.decodesWithHead(runtimeModelID: capability.runtimeModelID, mode: mode) + && capability.modeFeatures?[mode]?.speculativeRounds == true + } } /// Whether an installed session decodes with the model's speculative (MTP) @@ -60,7 +71,14 @@ struct DistributedInstalledSpeculation: Equatable, Sendable { } } + /// MiMo's tensor parallel also decodes with heads no mode names, launched with them where its record declares + /// them (`DistributedInstalledGenerationSelection.mimoTensorParallelRounds`). init(configuration: ClusterConfiguration, capability: ClusterRuntimeCapability) { + if DistributedInstalledGenerationSelection.mimoTensorParallelRounds(mode: configuration.selectedGenerationMode, + capability: capability) { + self.init(enabled: true, offReason: Self.enabledReason) + return + } self.init(mode: configuration.selectedGenerationMode, runtimeModelID: capability.runtimeModelID, tensorAssistant: configuration.tensorAssistant != nil, everyMemberAdvertisesHead: configuration.peers.allSatisfy { diff --git a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift index 37e14e873a..d76bcb5e24 100644 --- a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift +++ b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledFixture.swift @@ -15,14 +15,14 @@ struct InstalledFixture: Sendable { } /// `pairing` saves the setup with a coordinator pair approval that matches its own pins. /// `generationMode` is written into the setup when given; `advertisedModes` - /// is what the fabricated worker's capability record lists. `registered` - /// selects the registered model the record describes. + /// is what the fabricated worker's capability record lists, with `modeFeatures` + /// when given. `registered` selects the registered model the record describes. static func make(root: URL, probe: URL, owner: URL, worker: URL, lifetimeSeconds: Int = 10, pairing: Bool = false, generationMode: String? = nil, advertisedModes: [ClusterGenerationMode] = [.pipeline], registered: (model: String, profile: String, publicID: String) = ("registered_qwen35_9b", "registered_qwen35_9b_greedy_generation_v1", "fixture/public-model"), adapter: ClusterRuntimeAdapter = .qwen35Dense, standsForRegisteredArtifact: Bool = true, - batchLanes: Int? = nil) throws -> Self { + batchLanes: Int? = nil, modeFeatures: [ClusterGenerationMode: ClusterServingFeatures]? = nil) throws -> Self { try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) let model = root.appendingPathComponent("model", isDirectory: true) try FileManager.default.createDirectory(at: model, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) @@ -58,7 +58,7 @@ struct InstalledFixture: Sendable { .init(rank:0,sourceLayerStart:0,sourceLayerEnd:4,stagePlanSHA256:pin("1"),constructionConfigurationSHA256:pin("2")), .init(rank:1,sourceLayerStart:4,sourceLayerEnd:32,stagePlanSHA256:pin("3"),constructionConfigurationSHA256:pin("4"))])], arithmeticPolicyID:adapter.arithmeticPolicyID,arithmeticPolicySHA256:pin("5"), - supportedGenerationModes:advertisedModes) + supportedGenerationModes:advertisedModes,modeFeatures:modeFeatures) let capBytes = try ClusterRuntimeCapabilityCodec.encode(cap), capHash = hash(capBytes) try capBytes.write(to: model.appendingPathComponent("fixture-capability.json")) let key=root.appendingPathComponent("key"),hosts=root.appendingPathComponent("known_hosts") diff --git a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift index 378c268d8b..3ce6f62870 100644 --- a/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift +++ b/provider-swift/Tests/ClusterInstalledSessionChecks/InstalledSessionCheck.swift @@ -364,6 +364,7 @@ final class EndpointBox: @unchecked Sendable { try progressGuardIsRequired(fixture,prepared,unguarded:URL(fileURLWithPath:CommandLine.arguments[4])) try ordinaryProviderExclusion(fixture) try generationModeSelection(fixture,prepared) + try mimoTensorParallelRounds(fixture) try perModelBudgets(fixture,prepared) try longPromptsFitTheInstalledSession(fixture) try pairServingGrant(fixture) @@ -822,6 +823,28 @@ final class EndpointBox: @unchecked Sendable { let foreign=try refusal{try ClusterGenerationSelection.requireSupport(for:.pipeline,peers:[other],capability:split.capability)} try require(foreign.contains("member peer-9") && foreign.contains("nothing in the saved record"),"foreign worker refusal: \(foreign)") } + /// MiMo tensor parallel decodes in speculative rounds by default: where the pinned record declares tensor + /// parallel's rounds, both ranks get `--mtp-depth 2` (`ClusterMiMoTensorParallel`) after the mode, and the status + /// says the head decodes; a record that declares none launches none. + static func mimoTensorParallelRounds(_ f: InstalledFixture) throws { + let registered = ClusterRuntimeAdapter.mimoV26LayerStage.registeredProfiles[0] + for rounds in [true, false] { + let features: [ClusterGenerationMode: ClusterServingFeatures] = [ + .pipeline: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 8, logprobs: false), + .tensorParallel: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: rounds, maximumLanes: 1, logprobs: true)] + let fixture = try InstalledFixture.make(root: f.root.appendingPathComponent("mimo-tensor-parallel-rounds-\(rounds)"), + probe: f.probe, owner: f.owner, worker: f.worker, generationMode: ClusterGenerationMode.tensorParallel.rawValue, + advertisedModes: [.pipeline, .tensorParallel], registered: (registered.runtimeModelID, registered.profileID, "fixture/mimo"), + adapter: .mimoV26LayerStage, modeFeatures: features) + let plan = try fixture.prepare().plan + let arguments = try DistributedInstalledGenerationSelection.workerArguments(configuration: plan.configuration, capability: plan.capability) + let expected = ["--generation-mode", "tensor_parallel_v1"] + (rounds ? ["--mtp-depth", "2"] : []) + try require(arguments == expected, "MiMo tensor parallel (rounds declared: \(rounds)) launched \(arguments), not \(expected)") + let speculation = DistributedInstalledSpeculation(configuration: plan.configuration, capability: plan.capability) + try require(speculation.enabled == rounds && (speculation.offReason == DistributedInstalledSpeculation.enabledReason) == rounds, + "MiMo tensor parallel's status (rounds declared: \(rounds)) says \(speculation)") + } + } /// Both installed and member serving derive their profile through the same /// selected-mode initializer; a pipeline must not inherit GLM TP capture. static func logprobModeAdmission(_ f: InstalledFixture) throws { diff --git a/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift b/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift index 585774c01c..4fae6fda54 100644 --- a/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift +++ b/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift @@ -866,12 +866,13 @@ import Foundation ] /// MiMo V2.6's text modes as its worker declares them (`MiMoResidentCapabilityMetadata.servingFeatures`, pinned /// by `MiMoTensorParallelResidentTests`): no mode keeps prompt prefixes, only the plain pipeline batches lanes, the - /// speculative pipeline decodes in rounds, and tensor parallel serves one lane without rounds and adds logprobs. + /// speculative pipeline decodes in rounds, and tensor parallel serves one lane in rounds (the owner launches it + /// with `ClusterMiMoTensorParallel.speculativeDepth`) and adds logprobs. static let mimoFeatures: [ClusterGenerationMode: ClusterServingFeatures] = [ .pipeline: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 8, logprobs: false), .pipelineCompactDecode: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 1, logprobs: false), .phaseSplit: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 1, logprobs: false), - .tensorParallel: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 1, logprobs: true), + .tensorParallel: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: true, maximumLanes: 1, logprobs: true), .pipelineMTP: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: true, maximumLanes: 1, logprobs: false), ] /// `features` with tensor parallel's entry changed, as a later worker build might declare it. @@ -964,10 +965,11 @@ import Foundation // Ultra's index, MiMo alone at 57 tok/s and the pair's measured link. On the index alone tensor parallel is // predicted faster than the credited rounds for 128 + 128, so the speculative pipeline is kept. MiMo's runtime // takes no share probe: requests this build served in tensor parallel are its only evidence. Feature parity - // comes first: tensor parallel as this build runs it has no speculative rounds, which the speculative pipeline - // it would replace keeps, so it is held back whatever the evidence; the evidence rule is checked on a record - // whose tensor parallel decodes in rounds, as a later build's may. - let (roundsOn, roundsDescription) = try capability(rowModes, features: with(mimoFeatures, tensorParallelRounds: true)) + // comes first: as this build declares it, tensor parallel decodes in speculative rounds (on by default), so it + // keeps every feature of the speculative pipeline it would replace and the evidence rule decides; a record + // without tensor parallel's rounds (an older build's) holds it back whatever the evidence, and so do the plain + // pipeline's batch lanes where that pipeline is the mode it would replace. + let (roundsOff, roundsOffDescription) = try capability(rowModes, features: with(mimoFeatures, tensorParallelRounds: false)) let ultras = try indexedUltras(), alone = try aloneSpeed(layout, prefill: 1_000, decode: 57) func served(_ decode: Double, build: String) -> [ClusterServedSpeedRecords.Entry] { let setup = ClusterServedSpeedRecords.Setup(modelID: bothDescription.publicModelID, mode: ClusterGenerationMode.tensorParallel.rawValue, @@ -976,9 +978,10 @@ import Foundation return (0..<3).map { .init(setup: setup, sample: .init(route: .pair, member: nil, promptTokens: 128, outputTokens: 128, firstTokenSeconds: 0.08, decodeTokensPerSecond: decode, finishedAt: Double($0))) } } - func decide(_ records: [ClusterServedSpeedRecords.Entry], asBuilt: Bool = false) + func decide(_ records: [ClusterServedSpeedRecords.Entry], + record: (ClusterRuntimeCapability, ClusterPairDescription)? = nil) throws -> (lines: [String], result: ClusterPlacementResult, setup: ClusterPlacementSetup?) { - try ClusterPlacementFlow.decide(description: asBuilt ? bothDescription : roundsDescription, capability: asBuilt ? both : roundsOn, + try ClusterPlacementFlow.decide(description: record?.1 ?? bothDescription, capability: record?.0 ?? both, localMemberID: "mac-one", localProfile: ultras.local, peerProfile: ultras.peer, layout: layout, measurements: [alone], promptTokens: 128, outputTokens: 128, served: records, link: ultras.link, environment: [:], benchDebugBuild: false) } @@ -988,8 +991,8 @@ import Foundation let roundsLine = heldLine("speculative (MTP) rounds that the speculative pipeline keeps") for (name, records) in [("nothing served in tensor parallel", [ClusterServedSpeedRecords.Entry]()), ("three requests this build served in tensor parallel at 95 tok/s", served(95, build: hash("a")))] { - let held = try decide(records, asBuilt: true) - require("MiMo parity: as this build declares it, tensor parallel has no speculative rounds, so with \(name) the speculative pipeline is kept and the line says what tensor parallel would drop (\(line(held, " Pipeline:")))", + let held = try decide(records, record: (roundsOff, roundsOffDescription)) + require("MiMo parity: a record whose tensor parallel has no speculative rounds holds it back; with \(name) the speculative pipeline is kept and the line says what tensor parallel would drop (\(line(held, " Pipeline:")))", held.result.chosen?.mode == .pipelineMTP && held.result.tensorParallel?.verdict == .dropsFeatures && held.lines.contains(roundsLine) && held.setup != nil && ClusterPlacementExplanation.tensorParallelNote(held.result) == .dropsFeature @@ -997,12 +1000,13 @@ import Foundation && !held.result.alternatives.contains { $0.mode.usesTensorParallelDecode }) } let priorOnly = try decide([]) - require("MiMo evidence rule: 2x 256 GB on the measured link, nothing served in tensor parallel: the speculative pipeline is kept, and the line says tensor parallel is predicted faster only from the device index (\(line(priorOnly, " Pipeline:")))", + require("MiMo parity and evidence: as this build declares it, tensor parallel keeps every feature of the speculative pipeline; 2x 256 GB on the measured link, nothing served in tensor parallel: the speculative pipeline is kept on the evidence rule alone, and the line says tensor parallel is predicted faster only from the device index (\(line(priorOnly, " Pipeline:")))", priorOnly.result.chosen?.mode == .pipelineMTP && priorOnly.result.tensorParallel?.verdict == .predictedFasterOnPriorOnly && line(priorOnly, " Pipeline:").contains(", but from the device index, not its own measured step; it can be chosen once its step is measured on both Macs") + && !priorOnly.lines.contains { $0.contains("would drop") } && priorOnly.lines.contains(fastestLine) && priorOnly.setup != nil) let fast = try decide(served(95, build: hash("a"))) - require("MiMo parity and evidence: with its rounds on, tensor parallel keeps every feature of the speculative pipeline; three requests this build served in tensor parallel at 95 tok/s: tensor parallel, chosen on its own measured step, and the line says so (\(line(fast, " Tensor parallel:")))", + require("MiMo parity and evidence: as this build declares it (rounds on), three requests this build served in tensor parallel at 95 tok/s: tensor parallel, chosen on its own measured step, and the line says so (\(line(fast, " Tensor parallel:")))", fast.result.chosen?.mode == .tensorParallel && fast.result.tensorParallel?.evidence == .measured && !fast.lines.contains { $0.contains("would drop") } && line(fast, " Tensor parallel:").hasSuffix(", on its own step as measured on both Macs.") && fast.setup != nil) @@ -1014,6 +1018,17 @@ import Foundation require("MiMo evidence rule: another worker build's tensor-parallel records are no evidence: the speculative pipeline is kept, and the plan says they were ignored", otherBuild.result.chosen?.mode == .pipelineMTP && otherBuild.result.tensorParallel?.verdict == .predictedFasterOnPriorOnly && otherBuild.lines.contains { $0.hasPrefix(" 3 record(s) from other worker builds ignored") }) + // Where the plain pipeline is the mode tensor parallel would replace (here a record without the speculative + // pipeline), its 8 lanes hold one-lane tensor parallel back, even on this build's served records. + let plainRecord = try capability(rowModes.filter { $0 != .pipelineMTP }) + let lanesLine = heldLine("batch lanes up to 8 (it serves 1) that the pipeline keeps") + for (name, records) in [("nothing served in tensor parallel", [ClusterServedSpeedRecords.Entry]()), + ("three requests this build served in tensor parallel at 95 tok/s", served(95, build: hash("a")))] { + let held = try decide(records, record: plainRecord) + require("MiMo parity: where the plain pipeline is the mode it would replace, with \(name), its batch lanes hold tensor parallel back (\(line(held, " Pipeline:")))", + held.result.chosen.map { !$0.mode.usesTensorParallelDecode } == true + && held.result.tensorParallel?.verdict == .dropsFeatures && held.lines.contains(lanesLine) && held.setup != nil) + } } /// The Gemma 4 QAT 4-bit golden layout (with the family's tensor-parallel facts and `fastest_v1`), `adjust`ed, and From 5975fd22b2c25c45ed2ceffcdf21d60096fa82b4 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:01:37 -0800 Subject: [PATCH 0124/1441] cluster: price MiMo tensor parallel's rounds in the placement quote With rounds on by default, the LOAD gate charges each rank the three heads (1,975,640,448 B) and each request's speculative charge (the drafter's bounded declaration and the window's rows). The plan now quotes the same, so the planner admits only pairs the gate admits: - MiMoPlacementFamily states ClusterTensorParallelFamilyPlan.speculativeHead (depth 2, requestBytes = the speculative charge, decodeSpeedup 1): every rank holds the layout's speculativeHead part (the 42 head tensors) whole in whole pages, and the quoted reserve carries the charge beside the plain reserve (MiMoTensorParallelRequestBudget.allowance(speculativeRequestBytes: allocationBound:)), as the LOAD gate sums them. - The product layout computes it with the SDK's drafter declaration at the allocator's bound (MiMoTensorParallelResidentRuntime.placementRounds, the same speculativeRequestBytes the LOAD gate takes); metadata-only layouts (the recorded golden one) carry neither, as they carry no allowance, so every golden digest is unchanged. - No speed-up is credited until records measure the rounds: served records correct the shard rates meanwhile (ClusterServedCalibration), and the evidence rule decides. Checks: placementQuotesWhatTheLoadGateChargesWithRounds pins the product layout's head and allowance to the LOAD gate's terms; PlacementChecks prices the rounds on the registered layout (weights + the heads' pages, request need + the charge, need = the LOAD gate + page padding, decode uncredited, 2x 128 GB M5 Max fit now at 99.9 GiB a rank) and runs the fastest-plan checks on that layout, unchanged. Co-Authored-By: Claude Opus 5.5 --- .../MiMo/Metadata/MiMoPlacementFamily.swift | 16 +++- .../MiMoTensorParallelRequestBudget.swift | 13 +++ .../MiMoTensorParallelResidentRuntime.swift | 28 +++++- .../Placement/QwenDensePlacementFamily.swift | 14 ++- .../MiMoTensorParallelSpeculativeTests.swift | 28 ++++++ .../MiMoTensorParallelChecks.swift | 92 ++++++++++++++++++- 6 files changed, 182 insertions(+), 9 deletions(-) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift index c22b1fcff1..7ed44e1dcd 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift @@ -26,6 +26,13 @@ struct MiMoPlacementFamily: ClusterPlacementFamily { /// (`MiMoTensorParallelRequestBudget`), set where the allocator's bound is /// known (`ClusterPlacementLayouts.layout`); nil in metadata-only layouts. var tensorParallelRequestAllowance: ClusterTensorParallelRequestAllowance? + /// The speculative rounds every tensor-parallel rank decodes in + /// (`ClusterMiMoTensorParallel`): the three heads whole beside its share + /// (the layout's `speculativeHead`) and each request's drafter state and + /// window rows, which the allowance above then carries too, as the rank's + /// LOAD gate charges them. Set with the allowance where the SDK's drafter + /// declaration is compiled; nil in metadata-only layouts. + var tensorParallelSpeculativeHead: ClusterTensorParallelSpeculativeHead? static func handles(configuration: Data) -> Bool { (try? MiMoRegisteredSpecification.specification(configuration: configuration)) != nil @@ -156,14 +163,17 @@ struct MiMoPlacementFamily: ClusterPlacementFamily { /// selection. Each rank keeps its own KV heads. Equal shares with no /// padding: every cut lands on whole heads, quantization groups and packed /// words. Chosen only where predicted faster than the pipeline - /// (`ClusterTensorParallelChoice.fastest`): 97 sums a step cross the link, - /// and the pipeline keeps its speculative rounds (`docs/architecture/inference.md`). + /// (`ClusterTensorParallelChoice.fastest`): 97 sums a step cross the link. + /// Both modes decode in speculative rounds; the rounds of tensor parallel + /// are priced in memory (`tensorParallelSpeculativeHead`) and credited no + /// speed-up until records measure one (`docs/architecture/inference.md`). var tensorParallelPlan: ClusterTensorParallelFamilyPlan? { tensorParallel.map { plan in ClusterTensorParallelFamilyPlan(plan: MiMoTensorParallelPlan.name, ranks: [plan.size], reductionsPerLayer: plan.reductionsPerLayer, reductionsPerStep: plan.reductionsPerStep, partialBytesPerToken: plan.partialBytesPerToken, stateDividesByHeads: true, - requestAllowance: tensorParallelRequestAllowance, choice: .fastest) + requestAllowance: tensorParallelRequestAllowance, speculativeHead: tensorParallelSpeculativeHead, + choice: .fastest) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRequestBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRequestBudget.swift index 4a550b5e67..3359bac73e 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRequestBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRequestBudget.swift @@ -56,6 +56,19 @@ struct MiMoTensorParallelRequestBudget: Equatable, Sendable { /// What a rank holds once beside every request it serves. var rankBytes: Int { Self.activationFloorBytes + Self.freedBufferCacheBytes + allowance.collectiveScratchBytes } + /// The reserve of a rank that decodes in speculative rounds: `speculativeRequestBytes` (the drafter's state + /// and the window's rows) beside the request, as its LOAD gate and every reservation add them. + func allowance(speculativeRequestBytes: Int, + allocationBound: (Int) throws -> Int) throws -> ClusterTensorParallelRequestAllowance { + guard speculativeRequestBytes >= 0 else { throw ProbeError("MiMo speculative request bytes are negative") } + return try ClusterTensorParallelRequestAllowance(maximumContextTokens: allowance.maximumContextTokens, + maximumChunkTokens: allowance.maximumChunkTokens, + requestBytesExcludingCollectives: QwenLongPrefillCheckedBytes.sum([allowance.requestBytesExcludingCollectives, + speculativeRequestBytes]), + maximumCollectivePayloadBytes: allowance.maximumCollectivePayloadBytes, + maximumCollectiveFrameBytes: allowance.maximumCollectiveFrameBytes, allocationBound: allocationBound) + } + static func derive(plan: MiMoTensorParallelPlan, slidingWindow: Int, contextTokens: Int, chunkTokens: Int, allocationBound: (Int) throws -> Int) throws -> Self { let sum = QwenLongPrefillCheckedBytes.sum, product = QwenLongPrefillCheckedBytes.product diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift index 5e650a6626..012085a7f2 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift @@ -318,15 +318,37 @@ public final class MiMoTensorParallelResidentRuntime { /// product's declaration at the allocator's bound) and the window's extra /// rows (`MiMoTensorParallelRequestBudget.speculativeWindowBytes`). static func speculativeRequestBytes(configuration: MiMoV26Configuration, terms: MiMoMTPTerms, - plan: MiMoTensorParallelPlan, slidingWindow: Int, chunkTokens: Int) throws -> Int { - let bound = QwenResidentResourceEnvironment.allocationBound - return try QwenLongPrefillCheckedBytes.sum([ + plan: MiMoTensorParallelPlan, slidingWindow: Int, chunkTokens: Int, + bound: (Int) throws -> Int = QwenResidentResourceEnvironment.allocationBound) + throws -> Int { + try QwenLongPrefillCheckedBytes.sum([ MiMoTensorParallelDraftHead.requestBytes(configuration: configuration, chunkSize: chunkTokens, depth: terms.depth, bound: bound), MiMoTensorParallelRequestBudget.speculativeWindowBytes(plan: plan, slidingWindow: slidingWindow, depth: terms.depth, allocationBound: bound)]) } + /// The rounds as the planner prices a rank (`ClusterTensorParallelSpeculativeHead`), from the configuration + /// alone: the installed depth (`ClusterMiMoTensorParallel.speculativeDepth`), each request's speculative charge + /// at the profile's chunk (what the LOAD gate adds beside `budget`, so the quoted allowance carries it too), and + /// a decode speed-up of 1. No record has measured MiMo tensor parallel's rounds against its one-token steps, so + /// the plan credits none: served records correct the shard rates instead (`ClusterServedCalibration`), and the + /// evidence rule decides. Nil when the installed depth is 0. + static func placementRounds(configuration data: Data, plan: MiMoTensorParallelPlan, chunkTokens: Int, + budget: MiMoTensorParallelRequestBudget, allocationBound: (Int) throws -> Int) throws + -> (head: ClusterTensorParallelSpeculativeHead, allowance: ClusterTensorParallelRequestAllowance)? { + let depth = ClusterMiMoTensorParallel.speculativeDepth + guard depth > 0 else { return nil } + let configuration = try JSONDecoder().decode(MiMoV26Configuration.self, from: data) + guard let window = configuration.slidingAttention.slidingWindow else { + throw ProbeError("MiMo tensor parallel needs the sliding layers' window") + } + let bytes = try speculativeRequestBytes(configuration: configuration, terms: MiMoMTPTerms(depth: depth), plan: plan, + slidingWindow: window, chunkTokens: chunkTokens, bound: allocationBound) + return (.init(depth: depth, requestBytes: bytes, decodeSpeedup: 1), + try budget.allowance(speculativeRequestBytes: bytes, allocationBound: allocationBound)) + } + /// The host memory gate's decision for `bytes` more, as the resident families take it. static func requireLiveMemory(bytes: Int) throws { try QwenResidentResourceEnvironment.require() diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift index 1c36c7edfa..9122606d55 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift @@ -363,9 +363,19 @@ public enum ClusterPlacementLayouts { #endif if let plan = family.tensorParallel, let bound { // What a rank's LOAD gate reserves beside its shard: one request at the profile's longest context. - family.tensorParallelRequestAllowance = try MiMoTensorParallelRequestBudget.derive(plan: plan, + let budget = try MiMoTensorParallelRequestBudget.derive(plan: plan, slidingWindow: family.specification.slidingWindow, contextTokens: family.profile.maximumContextTokens, - chunkTokens: family.profile.maximumChunkTokens, allocationBound: bound).allowance + chunkTokens: family.profile.maximumChunkTokens, allocationBound: bound) + family.tensorParallelRequestAllowance = budget.allowance + #if canImport(MLXLLM) + // Its speculative rounds (`ClusterMiMoTensorParallel`): the heads whole, and each request's drafter + // state (the SDK's own declaration) and window rows beside the reserve, as the LOAD gate adds them. + if let rounds = try MiMoTensorParallelResidentRuntime.placementRounds(configuration: configuration, + plan: plan, chunkTokens: family.profile.maximumChunkTokens, budget: budget, allocationBound: bound) { + family.tensorParallelSpeculativeHead = rounds.head + family.tensorParallelRequestAllowance = rounds.allowance + } + #endif } return try ClusterModelLayoutBuilder.build(family: family, tensors: tensors, artifactSHA256: family.specification.artifactSHA256, diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift index e885d72ab5..ae5594d3d6 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift @@ -1,3 +1,4 @@ +import DarkbloomClusterPlacement import DarkbloomClusterProtocol import Foundation import MLX @@ -280,6 +281,33 @@ struct MiMoTensorParallelSpeculativeTests { #expect(!two.contains("windows=row-exact-one-token-bits"), "the BF16-partial window contract is gone") } + /// Rounds are on by default (`ClusterMiMoTensorParallel`), so the product layout prices a rank as its LOAD + /// gate charges it with them: the plan holds the three heads whole beside the share (the layout's speculative + /// head, 42 tensors of 1,975,640,448 bytes), and the quoted reserve carries each request's speculative charge + /// (the drafter's declaration and the window's rows at the profile's 512-token chunk, at the allocator's + /// bound) beside the plain reserve: the LOAD gate's sum. No decode speed-up is credited until records + /// measure one. + @Test func placementQuotesWhatTheLoadGateChargesWithRounds() throws { + let configuration = try MiMoTensorParallelTests.fixture("configuration") + let tensors = try JSONDecoder().decode([MiMoCanonicalTensor].self, from: MiMoTensorParallelTests.fixture("tensor-inventory")) + .map { ClusterPlacementStoredTensor(name: $0.name, byteCount: $0.byteCount, dtype: $0.sourceDType, shape: $0.shape) } + let layout = try ClusterPlacementLayouts.layout(configuration: configuration, tensors: tensors) + let family = try #require(layout.tensorParallel?.family) + let head = try #require(layout.speculativeHead) + #expect(head.tensorCount == 42 && head.storedBytes == 1_975_640_448 && head.loadedBytes == 1_975_640_448) + typealias Runtime = MiMoTensorParallelResidentRuntime + let plan = try MiMoTensorParallelPlan(configuration: configuration) + let budget = try Runtime.requestBudget(plan: plan, slidingWindow: 128, contextTokens: 65_536, chunkTokens: 512) + let charge = try Runtime.speculativeRequestBytes(configuration: JSONDecoder().decode(MiMoV26Configuration.self, + from: configuration), terms: MiMoMTPTerms(depth: ClusterMiMoTensorParallel.speculativeDepth), plan: plan, + slidingWindow: 128, chunkTokens: 512) + #expect(charge >= 438_426_984 + 36_347_904, "at least the exact-size charge") + #expect(family.speculativeHead == ClusterTensorParallelSpeculativeHead(depth: 2, requestBytes: charge, decodeSpeedup: 1)) + #expect(family.requestAllowance?.reservedBytes == budget.allowance.reservedBytes + charge) + #expect(family.requestAllowance?.collectiveScratchBytes == budget.allowance.collectiveScratchBytes) + #expect(family.choice == .fastest) + } + /// A window's settle at the registered sliding window (a 128-row ring over two 64-token /// pages) and on a full layer leaves exactly the cache that one-token appends leave: the /// same rows in the same physical order, offset and ring index, for every window size and diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/MiMoTensorParallelChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/MiMoTensorParallelChecks.swift index c5a1281813..aaa91361a3 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/MiMoTensorParallelChecks.swift +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/MiMoTensorParallelChecks.swift @@ -25,7 +25,97 @@ func checkMiMoTensorParallel(golden: URL, _ checks: PlacementChecks) throws { let priced = try ClusterPlacementLayouts.layout(configuration: configuration, tensors: tensors, tensorParallelAllocationBound: { $0 + 16_384 }) try checkMiMoRequestAllowance(priced, configuration: configuration, checks) - try checkMiMoFastestPlan(priced, checks) + let rounds = try mimoWithRounds(priced, configuration: configuration, allocationBound: { $0 + 16_384 }) + try checkMiMoRounds(priced, rounds: rounds, checks) + try checkMiMoFastestPlan(rounds, checks) +} + +/// One request's speculative charge at the registered geometry, at exact sizes: the drafter's bounded state at +/// depth 2 and 512-token chunks (438,426,984 bytes) and the window's rows (36,347,904), both pinned by +/// `MiMoTensorParallelSpeculativeTests`. The product prices it at the allocator's bound, a few pages more +/// (`placementQuotesWhatTheLoadGateChargesWithRounds`); its drafter half needs the SDK these checks do not compile. +private let mimoSpeculativeRequestBytes = 438_426_984 + 36_347_904 + +/// The layout as the product prices it (`MiMoTensorParallelResidentRuntime.placementRounds`): MiMo tensor +/// parallel decodes in speculative rounds by default (`ClusterMiMoTensorParallel`), so its plan holds the three +/// heads whole on every rank and its reserve carries each request's speculative charge, with no speed-up credited. +private func mimoWithRounds(_ layout: ClusterModelLayout, configuration: Data, + allocationBound: @escaping (Int) throws -> Int) throws -> ClusterModelLayout { + guard let tp = layout.tensorParallel else { throw ProbeError("the MiMo layout carries no tensor-parallel plan") } + let budget = try MiMoTensorParallelRequestBudget.derive(plan: MiMoTensorParallelPlan(configuration: configuration), + slidingWindow: 128, contextTokens: 65_536, chunkTokens: 512, allocationBound: allocationBound) + let f = tp.family + let family = ClusterTensorParallelFamilyPlan(plan: f.plan, ranks: f.ranks, reductionsPerLayer: f.reductionsPerLayer, + reductionsPerStep: f.reductionsPerStep, partialBytesPerToken: f.partialBytesPerToken, + layerPartialBytesPerToken: f.layerPartialBytesPerToken, stateDividesByHeads: f.stateDividesByHeads, + shareOptions: f.shareOptions, shareUnits: f.shareUnits, + requestAllowance: try budget.allowance(speculativeRequestBytes: mimoSpeculativeRequestBytes, allocationBound: allocationBound), + additionalResidentBytes: f.additionalResidentBytes, + speculativeHead: .init(depth: ClusterMiMoTensorParallel.speculativeDepth, requestBytes: mimoSpeculativeRequestBytes, + decodeSpeedup: 1), + choice: f.choice) + return try layout.with(tensorParallel: .init(family: family, terms: tp.terms, layerDividedBytes: tp.layerDividedBytes, + layerReplicatedBytes: tp.layerReplicatedBytes, ingressDividedBytes: tp.ingressDividedBytes, + ingressReplicatedBytes: tp.ingressReplicatedBytes, egressDividedBytes: tp.egressDividedBytes, + egressReplicatedBytes: tp.egressReplicatedBytes)) +} + +/// Rounds in the quote (2026-11-01, on by default): every rank holds the three heads whole beside its share, in +/// whole pages, and each request's speculative charge beside its reserve, so the plan admits only pairs the rank's +/// LOAD gate (shard + heads + reserve + charge, then the loading headroom) admits. Decode is credited nothing until +/// records measure the rounds. Two 128 GB M5 Max, which cannot hold MiMo alone, still fit now. +private func checkMiMoRounds(_ priced: ClusterModelLayout, rounds: ClusterModelLayout, _ checks: PlacementChecks) throws { + guard let head = rounds.speculativeHead, let plan = rounds.tensorParallel?.family.speculativeHead, + let allowance = rounds.tensorParallel?.family.requestAllowance, + let plain = priced.tensorParallel?.family.requestAllowance else { + checks.require("mimo rounds: the layout carries the three heads and the plan prices them", false) + return + } + checks.require("mimo rounds: the heads are the artifact's three next-N layers (42 tensors, 1,975,640,448 bytes), in no range; depth 2, no speed-up credited", + head.tensorCount == 42 && head.storedBytes == 1_975_640_448 && head.loadedBytes == 1_975_640_448 + && plan.depth == 2 && plan.decodeSpeedup == 1 && plan.requestBytes == mimoSpeculativeRequestBytes) + checks.require("mimo rounds: the quoted reserve carries each request's speculative charge beside the plain reserve (+\(mimoSpeculativeRequestBytes) bytes), its collectives unchanged", + allowance.reservedBytes == plain.reservedBytes + mimoSpeculativeRequestBytes + && allowance.collectiveScratchBytes == plain.collectiveScratchBytes + && allowance.maximumContextTokens == 65_536 && allowance.maximumChunkTokens == 512) + func mac(_ label: String, _ gib: Double) throws -> ClusterPlacementDevice { + .init(label: label, profile: try SyntheticMac.idle(gib).profile(chip: "Apple M5 Max"), speed: measured(prefill: 400, decode: 40)) + } + let maxes = try [mac("a", 128), mac("b", 128)] + // The pair's own probe (two M5 Ultra, keyed JACCL, 2026-10-31): sealed all-sum 29 us at 16 KB, 3,919 us at 32 MiB. + let link = ClusterLinkCosts(probe: ClusterWorkerLinkProbe(transport: "jaccl", keyed: true, pointToPointSmallBytes: 64, + pointToPointSmallMicroseconds: 180, pointToPointLargeBytes: 4 << 20, pointToPointLargeMicroseconds: 2_502, + allSumSmallBytes: 16_384, allSumSmallMicroseconds: 29, allSumLargeBytes: 32 << 20, allSumLargeMicroseconds: 3_919), + measuredUTC: "2026-10-31T00:00:00Z")! + func tensor(_ layout: ClusterModelLayout, _ devices: [ClusterPlacementDevice]) throws -> ClusterPlacementCandidate { + try ClusterPlacementPlanner.evaluate(devices: devices, cuts: [], mode: .tensorParallel, prefillSchedule: .serial, + layout: layout, policy: ClusterPlacementPolicy(), link: link) + } + let before = try tensor(priced, maxes), after = try tensor(rounds, maxes) + let pages = head.loadedBytes + head.tensorCount * SyntheticMac.page + checks.require("mimo rounds: each rank holds the heads whole beside its share, each tensor in whole pages (+\(pages) bytes)", + before.ranks.count == 2 && zip(before.ranks, after.ranks).allSatisfy { $1.weightsBytes == $0.weightsBytes + pages }) + checks.require("mimo rounds: each rank's request need carries the speculative charge", + zip(before.ranks, after.ranks).allSatisfy { $1.requestNeedBytes == $0.requestNeedBytes + mimoSpeculativeRequestBytes }) + checks.require("mimo rounds: so each rank needs both more before it loads", + zip(before.ranks, after.ranks).allSatisfy { $1.needBytes == $0.needBytes + pages + mimoSpeculativeRequestBytes }) + // The rank's LOAD gate with rounds: its exact shard, the heads, the reserve with the charge, then the headroom. + let loadGate = 84_013_770_176 + 1_975_640_448 + allowance.reservedBytes + maxes[0].profile.memory.loadingHeadroomBytes + checks.require("mimo rounds: the plan's need is the rank's LOAD gate (\(loadGate) bytes on a 128 GB Mac) plus its tensors' page padding", + after.ranks.allSatisfy { $0.needBytes == loadGate + ($0.weightsBytes - 84_013_770_176 - 1_975_640_448) }) + checks.require("mimo rounds: decode and the first token are predicted as before (no credit for unmeasured rounds)", + after.rested.decodeTokensPerSecond == before.rested.decodeTokensPerSecond + && after.rested.firstTokenSeconds == before.rested.firstTokenSeconds) + checks.require(String(format: "mimo rounds: two 128 GB M5 Max still fit now with the heads (each rank needs %.1f GiB of 128)", + Double(after.ranks[0].needBytes) / Double(gib)), + after.ranks.allSatisfy { $0.fit == .now }) + checks.require("mimo rounds: a pipeline holds no tensor-parallel heads and keeps its prediction", + try ClusterPlacementPlanner.evaluate(devices: maxes, cuts: [41], mode: .pipeline, prefillSchedule: .serial, layout: rounds, + policy: ClusterPlacementPolicy(), link: link) == ClusterPlacementPlanner.evaluate(devices: maxes, cuts: [41], + mode: .pipeline, prefillSchedule: .serial, layout: priced, policy: ClusterPlacementPolicy(), link: link)) + checks.require("mimo rounds: the layout's description says the rounds and their charge", + ClusterPlacementExplanation.layout(rounds).contains { $0.contains("speculative rounds of up to 2 proposals") } + && !ClusterPlacementExplanation.layout(priced).contains { $0.contains("speculative rounds of up to") }) } /// What one rank holds of a layout's tensor-parallel facts: every part's From 822e2a25608c619be02b16da70d650ab15fb4894 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:01:49 -0800 Subject: [PATCH 0125/1441] docs: MiMo tensor parallel decodes in speculative rounds by default - inference.md: the rounds are on by default (the installed depth, the capability declaration, the status); verify windows under contract v2 (o_proj one FP32 product a row, dense row by row, FP32 expert rows combined per row) and the window agreement string; the plan's speculativeHead and the rounds in the quoted reserve, with how measured records credit the rounds later; feature parity now admits MiMo tensor parallel against the speculative pipeline and holds it back only where the plain pipeline's lanes are replaced (106 and 118 GB in the checks' device model). - hardware-support.md: the planner's quote counts the heads and the per-request terms; two 128 GB Macs still fit. - two-mac-cluster.md: what users see (speculative decoding in tensor parallel; the plain pipeline's lanes). - test.md: the window-partials test, the placement-quote test, the PlacementChecks rounds checks, the setup and installed-session checks. - changelog.d/mimo-tp-speculative.md: on by default, priced in the plan, no longer held back by feature parity against the speculative pipeline; one sentence each in the parent fragments (mimo-tensor-parallel, cluster-feature-parity) so the merged notes agree. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-feature-parity.md | 2 +- changelog.d/mimo-tensor-parallel.md | 2 +- changelog.d/mimo-tp-speculative.md | 9 +- docs/architecture/hardware-support.md | 15 ++-- docs/architecture/inference.md | 121 +++++++++++++++++--------- docs/developer/test.md | 55 ++++++++---- docs/provider/two-mac-cluster.md | 28 +++--- 7 files changed, 156 insertions(+), 76 deletions(-) diff --git a/changelog.d/cluster-feature-parity.md b/changelog.d/cluster-feature-parity.md index 0b23fb5a34..6f9da289fb 100644 --- a/changelog.d/cluster-feature-parity.md +++ b/changelog.d/cluster-feature-parity.md @@ -1,6 +1,6 @@ ### Tensor parallel only where it keeps every feature - On a two-Mac pair, Gemma 4 and MiMo V2.6 Flash use tensor parallel only where it keeps every feature and caching behavior of the mode it would replace: prompt-prefix and SSD cache reuse, speculative (MTP) rounds, batch lanes, media, penalties and logit bias, stop handling and logprobs. What tensor parallel adds, such as logprobs where the pipeline has none, never counts against it. Each mode's features come from the installed cluster worker's capability record. -- Today Gemma 4's tensor parallel keeps no prompt prefixes and MiMo's has no speculative rounds, so these pairs keep the pipeline, whatever tensor parallel's measured speed. The plan's "Tensor parallel or pipeline" line says what tensor parallel would drop ("Pipeline: tensor parallel would drop prompt-prefix reuse and the SSD prefix tier that the pipeline keeps; held back until it keeps them."), and the model list says "tensor parallel: drops a feature". +- Today Gemma 4's tensor parallel keeps no prompt prefixes, so Gemma pairs keep the pipeline, whatever tensor parallel's measured speed. MiMo's tensor parallel decodes in speculative rounds, so it keeps every feature of the speculative pipeline and its measured speed decides; only where the plain pipeline is the mode it would replace do that pipeline's batch lanes keep it. The plan's "Tensor parallel or pipeline" line says what tensor parallel would drop ("Pipeline: tensor parallel would drop prompt-prefix reuse and the SSD prefix tier that the pipeline keeps; held back until it keeps them."), and the model list says "tensor parallel: drops a feature". - Where only tensor parallel fits the two Macs, the plan refuses with that reason and saves no setup, instead of saving one with fewer features. The developer's forced mode (debug builds) still places tensor parallel, and the plan says exactly what it drops. - Qwen and GLM plans are unchanged. diff --git a/changelog.d/mimo-tensor-parallel.md b/changelog.d/mimo-tensor-parallel.md index 4cd59a06e8..8dfb8e22aa 100644 --- a/changelog.d/mimo-tensor-parallel.md +++ b/changelog.d/mimo-tensor-parallel.md @@ -3,5 +3,5 @@ - MiMo V2.6 Flash text can run tensor parallel on a pair: each Mac holds half of every layer's heads and expert channels and half of the output head, both share every token over the encrypted link, and on the synthetic checks the two Macs agree bit for bit with a one-process simulation of both halves. The image candidate stays a pipeline. - Each Mac's half of a layer's attention output and feed-forward is kept at full 32-bit precision until both halves are added, then rounded once, so a pair never rounds more than one Mac does. On the synthetic checks, the two halves of an expert's output add up bit for bit to the full output that one Mac rounds once. - The planner chooses tensor parallel for MiMo only where it predicts it faster than the pipeline with speculative decoding, which MiMo's qualification records credit 1.37x, from tensor parallel's own speed measured on both Macs (see "Tensor parallel for Gemma 4 and MiMo only on measured speed"). Two 128 GB Macs, which cannot hold MiMo alone, can serve it this way. Qwen and GLM still choose tensor parallel wherever it fits. -- In tensor parallel, MiMo returns logprobs (`logprobs` / `top_logprobs`), serves one request at a time (without speculative decoding unless the launch asks for it), and each Mac reserves memory for its own half: 84.0 GB of weights plus its own KV, work and buffers, with a conservative 5.5 GiB activation reserve until a pair measures one (about 98 GiB per Mac at the longest request). +- In tensor parallel, MiMo returns logprobs (`logprobs` / `top_logprobs`), serves one request at a time with speculative decoding (see "MiMo V2.6 Flash tensor parallel with speculative decoding"), and each Mac reserves memory for its own half: 84.0 GB of weights plus its own KV, work and buffers, with a conservative 5.5 GiB activation reserve until a pair measures one (about 98 GiB per Mac at the longest request, about 100 GiB with the draft heads). - No MiMo tensor-parallel qualification record exists yet, and speed on a real pair is not measured. diff --git a/changelog.d/mimo-tp-speculative.md b/changelog.d/mimo-tp-speculative.md index 49ae266648..00dd5d7dfb 100644 --- a/changelog.d/mimo-tp-speculative.md +++ b/changelog.d/mimo-tp-speculative.md @@ -1,7 +1,8 @@ ### MiMo V2.6 Flash tensor parallel with speculative decoding -- A MiMo V2.6 Flash tensor-parallel pair can decode with MiMo's three trained draft heads: each round checks up to three drafted tokens in one pass through the pair, so every token a round keeps shares that pass's link and weight costs. -- It is off by default. Only a worker launched by hand with `--mtp-depth` uses it: the installed provider never passes that flag to a MiMo tensor-parallel worker, and the planner does not count it. -- Output is identical to tensor parallel without drafting, token for token and bit for bit on the synthetic checks: greedy (with or without logprobs) and sampled. Every kind of stop works inside a round. Requests with penalties or a logit bias, and sampled requests that ask for logprobs, decode one token at a time, as in the speculative pipeline. -- Each Mac holds the draft heads whole (about 2 GB more, still within two 128 GB Macs) and reserves their per-request state. +- A MiMo V2.6 Flash tensor-parallel pair decodes with MiMo's three trained draft heads: each round checks up to two drafted tokens in one pass through the pair, so every token a round keeps shares that pass's link and weight costs. +- It is on by default: the installed provider starts both Macs' tensor-parallel workers with two drafts a round. +- Output is identical to tensor parallel without drafting, token for token and bit for bit on the synthetic checks: greedy (with or without logprobs) and sampled. Each Mac's halves stay at full 32-bit precision inside a round too, exactly as in a one-token step. Every kind of stop works inside a round. Requests with penalties or a logit bias, and sampled requests that ask for logprobs, decode one token at a time, as in the speculative pipeline. +- Each Mac holds the draft heads whole (about 2 GB more) and reserves their per-request state, and the plan counts both before it chooses tensor parallel. Two 128 GB Macs still fit, at about 100 GiB a Mac. +- Because MiMo's tensor parallel now keeps the speculative pipeline's rounds, feature parity no longer holds it back where that pipeline is the mode it would replace; its measured speed decides, and the plan credits the rounds no speed-up until they are measured. Where the plain pipeline is the mode it would replace, that pipeline's batch lanes still keep it. - Not yet measured on a real pair: the speed-up, the heads' acceptance rate and qualification records. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 7452c0ffb3..ecab6caaf4 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1170,11 +1170,15 @@ headroom. That fits a 128 GB Mac. A reservation asks the live gate for its own r per-rank charges. Nothing here is measured on a pair; see [inference](inference.md#mimo-tensor-parallel-placement). -A rank launched with speculative rounds (`--mtp-depth`) adds the charges below -to its own gates only; the planner's quote does not count them yet. The LOAD -gate adds all three before anything is read, with the per-request terms at the +Every installed rank decodes in speculative rounds (`--mtp-depth 2`, on by +default: `ClusterMiMoTensorParallel`) and adds the charges below. The LOAD gate +adds all three before anything is read, with the per-request terms at the profile's longest request; READY's capacity and each reservation add the two -per-request terms. +per-request terms. The planner's quote counts the same: the heads whole on +every rank (the layout's `speculativeHead`, each tensor in whole pages) and the +two per-request terms in the layout's `requestAllowance` +(`MiMoTensorParallelResidentRuntime.placementRounds`), so the plan admits only +pairs the LOAD gate admits. | Charge | Held | Bytes | |---|---|---| @@ -1183,7 +1187,8 @@ per-request terms. | The window's extra rows at depth 2: each sliding ring once more per extra row, one page per layer, the window's rows twice (`MiMoTensorParallelRequestBudget.speculativeWindowBytes`) | per request | 36,347,904 | With them a rank still fits a 128 GB Mac: 107,281,620,648 bytes (99.9 GiB) with -the loading headroom, against a 115.2 GiB ceiling. See +the loading headroom, against a 115.2 GiB ceiling; the placement checks plan two +idle 128 GB M5 Max in tensor parallel now at 99.9 GiB a rank. See [speculative rounds](inference.md#mimo-tensor-parallel-speculative-rounds). ### Additional TP resident allocations diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index b696f27cb0..c7d410e1f1 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4207,7 +4207,7 @@ from the facts its loads bind; the provider keeps no table of them: |---|---|---| | `promptPrefixReuse`, resident | yes / no | no / no / no | | `ssdPrefixTier` | yes / no | no / no / no | -| `speculativeRounds` (MTP) | no / no | no / yes / no | +| `speculativeRounds` (MTP) | no / no | no / yes / yes | | `maximumLanes` | 8 / 8 | 8 / 1 / 1 | | `requestMedia` | none / none | none | | `penaltiesAndLogitBias`, `stopHandling` | yes / yes | yes | @@ -4219,8 +4219,12 @@ Gemma's come from `Gemma4ResidentAdapterDefinition.servingFeatures`, whose `MiMoResidentCapabilityMetadata.servingFeatures`: the widest lanes and paged histories `MiMoBatchSettings` gives each mode, and `MiMoTensorParallelResidentRuntime.servingFeatures`, whose lanes and prefix -setting its serving agreement binds. A record without features -(`ClusterRuntimeCapabilityCodec` writes no `modeFeatures`) keeps its bytes. +setting its serving agreement binds and whose rounds are the depth the installed +owner launches every MiMo tensor-parallel worker with +(`ClusterMiMoTensorParallel.speculativeDepth`, bound by the speculative +agreement fields; [rounds](#mimo-tensor-parallel-speculative-rounds)). A record +without features (`ClusterRuntimeCapabilityCodec` writes no `modeFeatures`) +keeps its bytes. `ClusterModeParity`, in `ClusterPlacementFlow.decide` beside `ClusterModelFeaturePolicy.admissibleModes`, applies the rule before the planner @@ -4248,10 +4252,20 @@ ranks anything: back: nothing shows it keeps them. Today the rule holds Gemma's tensor parallel back everywhere, whatever its -evidence, and MiMo's wherever the speculative pipeline is the mode it would -replace; the evidence rule below decides once a worker declares parity. The -tensor-parallel-first families (Qwen, GLM) declare no features and are not -gated. Applied to them, the rule would leave GLM unchanged (its tensor parallel +evidence. MiMo's tensor parallel decodes in speculative rounds, so it keeps every +feature of the speculative pipeline (and of the compact-decode pipeline and the +phase split), and the evidence rule below decides wherever one of those is the +mode it would replace. It is held back only where the plain pipeline is: that +pipeline declares 8 batch lanes and tensor parallel serves one ("Pipeline: tensor +parallel would drop batch lanes up to 8 (it serves 1) that the pipeline keeps; +held back until it keeps them."). On equal idle Macs in the placement checks' +device model, with MiMo's rounds credited and the heads priced, that is 106 GB +for 128 + 128 and 118 GB for a fresh pair's 32,768 + 32,768; from 104 GB +(where tensor parallel first fits) every other size replaces the speculative +pipeline, and no size fits tensor parallel alone (2026-11-01 scan, +`mainnet/overnight/mimo-tp-speculative-v2.md`) [INFERENCE: the device model, +not real Macs]. The tensor-parallel-first families (Qwen, GLM) declare no +features and are not gated. Applied to them, the rule would leave GLM unchanged (its tensor parallel keeps prompt-prefix and SSD reuse and adds rounds, eight lanes, images, video and logprobs) but would move Qwen3.5 9B from tensor parallel to its speculative pipeline, which its records credit 1.74x: Qwen tensor parallel @@ -4371,8 +4385,8 @@ are excluded by name and refused as text, as is any unknown or misaligned name: Every equal half lands on whole quantization groups and packed words, so no rank stores padding: 84,013,770,176 B of text weights per rank. A layer issues -two collectives of one 16,384 B row per token, and a decode step 97. MTP is off -unless the launch asks for it +two collectives of one 16,384 B row per token, and a decode step 97. Decode runs +in MTP rounds by default, the three heads replicated whole beside the shard ([speculative rounds](#mimo-tensor-parallel-speculative-rounds)). The routed experts' partial is not the Qwen and Gemma one, which sums every @@ -4448,8 +4462,8 @@ tensor parallel's executor contract and one lane: whose first logprob is the greedy token's even when an exactly tied token leads it; a sampled row publishes the product sampler's own logprobs from the gathered row. -- Speculative rounds when the worker gets `--mtp-depth` (off by default; see - below). +- Speculative rounds at depth 2, on by default: the installed owner launches + every MiMo tensor-parallel worker with `--mtp-depth 2` (see below). - Not yet: lanes, prompt-prefix reuse, 2,048-token prefill frames and micro-batches, building decode steps one ahead. - Memory. One formula, `MiMoTensorParallelRequestBudget`, gives the LOAD @@ -4481,10 +4495,15 @@ the gate. A MiMo tensor-parallel worker launched with `--mtp-depth N` (1 to 3; MiMo's `MiMoMTPTerms`) decodes in `pipeline_mtp_v1`'s rounds through the -tensor-parallel sums. It is off by default: the installed provider passes no -depth to a MiMo tensor-parallel worker -(`DistributedInstalledGenerationSelection` passes one only for Qwen's tensor -assistant), and the planner credits no speed-up. +tensor-parallel sums. It is on by default: the installed owner passes both ranks +`--mtp-depth 2` (`ClusterMiMoTensorParallel.speculativeDepth`, the depth MiMo's +pipeline measured fastest) wherever the worker's capability record declares +tensor parallel's rounds (`DistributedInstalledGenerationSelection`), which this +build's record does (`MiMoTensorParallelResidentRuntime.servingFeatures`), and +the cluster status reports the head as decoding (`DistributedInstalledSpeculation`). +A worker launched by hand without the depth decodes one token a step. The +planner prices the rounds' memory and credits them no speed-up (placement, +below). - **Heads.** Both ranks hold the three trained BF16 heads whole (3 × 658,546,816 B), named by the pipeline's head inventory @@ -4499,13 +4518,19 @@ assistant), and the planner credits no speed-up. hold 0.83 GiB less, but adds new BF16 partials and two sums per proposal. - **Windows.** A round runs `[last, d1 … dk]` through every layer's two sums at once (`MiMoV26TextModel.forwardVerifyWindow`). Each row takes one-row decode's - arithmetic: the row-exact affine 8-bit projections - (`MiMoV26RowExactProjection`), per-row RoPE and router, per-row expert combine, - full-attention rows reading their own prefix and sliding layers taking one - ring update and one attention per row. So each window row is the one-token - step's bits, and greedy rounds are lossless against the one-token path, not - only close to it. NAX has no kernel for 2 to 4 rows (MLX's NAX attention needs - more than 8 queries), so windows stay on these kernels; prefill is unchanged. + arithmetic: the row-exact affine 8-bit projections for queries, keys and values + (`MiMoV26RowExactProjection`), per-row RoPE and router, full-attention rows + reading their own prefix and sliding layers taking one ring update and one + attention per row. The row-parallel partials follow contract v2 (FP32 until the + sum, [above](#mimo-v26-tensor-parallel)): `o_proj` is one FP32 product per row + (`MiMoV26RectangularDense.tensorParallelProjection`, the one-token step's M=1 + product; the row-exact kernel is BF16/F16 only), the dense layer's `down_proj` + runs row by row (`MiMoV26RectangularDense.tensorParallelPartial`), and the + routed layer combines each row's FP32 expert rows (`float32ExpertRows`) as its + one-row step does. So each window row is the one-token step's bits, partials + included, and rounds are lossless against the one-token path, not only close + to it. NAX has no kernel for 2 to 4 rows (MLX's NAX attention needs more than 8 + queries), so windows stay on these kernels; prefill is unchanged. - **Agreement and acceptance.** One sum per round carries, per rank, every column's maximum and token (or rank 0's keyed target sample over the gathered rows, `QwenStageTokenSampler.verifyRound`), the stop slot and the position. @@ -4534,18 +4559,19 @@ assistant), and the planner credits no speed-up. at the profile's longest request, the drafter's bounded request state and the window's extra rows (`MiMoTensorParallelResidentRuntime.speculativeRequestBytes`, from the configuration alone). READY's capacity and each reservation add the - same two per-request terms. The activation floor stays the conservative - default. + same two per-request terms, and the placement quote prices the same + (`MiMoTensorParallelResidentRuntime.placementRounds`, below). The activation + floor stays the conservative default. - **Agreement.** The load agreement adds the depth, the verification rule and - the head and window contracts (`speculativeAgreementFields`); a load without a - depth keeps its agreement unchanged. + the head and window contracts (`speculativeAgreementFields`; the window's is + `windows=row-exact-one-token-float32-partials-v2`); a load without a depth + keeps its agreement unchanged. Code map: `MiMoTensorParallelRounds.swift` (rounds, agreement, end reconciliation), `MiMoTensorParallelSpeculation.swift` (heads, drafter, -scripted oracle proposals), the SDK's `MiMoV26IndependentHistory.swift` and -`MiMoV26TensorParallel.swift`. Placement keeps `speculativeHead` nil until a pair -measures MiMo tensor parallel with and without rounds, as GLM's -`GLM5NextServingMetadata.measuredTensorParallelDecode` does. +scripted oracle proposals), `ClusterMiMoTensorParallel` (the installed depth), +the SDK's `MiMoV26IndependentHistory.swift`, `MiMoV26RectangularDense.swift` and +`MiMoV26TensorParallel.swift`. ### MiMo tensor-parallel placement @@ -4558,7 +4584,8 @@ layout carries `tensorParallel`; the image candidate's layout carries none: | `reductionsPerLayer`, `reductionsPerStep` | 2 (attention, feed-forward), 1 (vocabulary-split selection): 97 a decode step | `MiMoTensorParallelPlan.reductionsPerLayer` | | `partialBytesPerToken` | 16,384 (one FP32 hidden row); no `layerPartialBytesPerToken` | `MiMoTensorParallelPlan.partialBytesPerToken` | | `stateDividesByHeads` | true: each rank keeps its own KV heads | `MiMoTensorParallelPlan.kvHeadsPerRank` | -| `requestAllowance` | the rank's reserve at the profile's longest request (65,536 tokens), where the allocator's bound is known | `MiMoTensorParallelRequestBudget` | +| `requestAllowance` | the rank's reserve at the profile's longest request (65,536 tokens), with each request's speculative charge beside it, where the allocator's bound is known | `MiMoTensorParallelRequestBudget`, `allowance(speculativeRequestBytes:allocationBound:)` | +| `speculativeHead` | depth 2; `requestBytes` = one request's speculative charge (the drafter's declaration and the window's rows: 438,426,984 + 36,347,904 B at exact sizes); `decodeSpeedup` 1, credited nothing; the three heads are the layout's `speculativeHead` part (42 tensors, 1,975,640,448 B), held whole on every rank in whole pages | `MiMoTensorParallelResidentRuntime.placementRounds` | | `choice` | `fastest_v1` | `ClusterTensorParallelChoice` | Each stored tensor's cut is the plan's disposition @@ -4569,19 +4596,36 @@ routing, 8 of 256 experts (`expertRouting`, `isRoutedExpert`, the same definition as the pipeline's), so the hardware prior reads 10,767,036,288 weight bytes per token, 99.1 % of them divided. +The rounds are priced as the LOAD gate charges them, so the planner admits only +pairs the rank's gate admits: each rank's weights gain the heads in whole pages, +and its quoted reserve gains each request's speculative charge (the product +layout computes it with the SDK's drafter declaration at the allocator's bound; +`placementQuotesWhatTheLoadGateChargesWithRounds` pins it to the LOAD gate's +sum). Metadata-only layouts, such as the recorded golden one, carry neither, as +they carry no `requestAllowance`. Two 128 GB Macs still fit: a rank's LOAD gate +is 107,281,620,648 B (99.9 GiB) at exact sizes, and the planner asks 99.9 GiB of +an idle 128 GB Mac in the placement checks. No speed-up is credited until +records measure the rounds: when a pair has served MiMo tensor parallel with and +without them on the same build, a measured table (as GLM's +`GLM5NextServingMetadata.measuredTensorParallelDecode`, depth 0 against depth 2) +sets `decodeSpeedup` to their ratio. Until then served records, which run with +the rounds, correct the shard rates directly (`ClusterServedCalibration`), so the +evidence rule weighs what was served. + MiMo opts into the fastest-plan rule ([Gemma tensor-parallel placement](#gemma-tensor-parallel-placement)): 97 sealed sums a step cross the link, and the pipeline it competes with decodes in -speculative rounds (`pipeline_mtp_v1`), which tensor parallel does not yet. The -guided step credits those rounds the decode speed-up MiMo's passing +speculative rounds (`pipeline_mtp_v1`), as tensor parallel now does, uncredited. +The guided step credits the pipeline's rounds the decode speed-up MiMo's passing qualification records measured, 1.37x (59.18 against 43.05 tok/s; `ClusterPairServingGrants.recordedPipelineSpeculativeFactor`), and a fresh pair plans for the layout's longest request, 32,768 + 32,768 tokens. On the planner's own figures (`PlacementChecks`, `MiMoTensorParallelChecks.swift`; constructed Macs: M5 Ultra 57 tok/s, the M5 Max 128 GB from its stage probes at -40 tok/s), the comparison and the evidence rule place MiMo as follows; the -guided step's feature parity then keeps the speculative pipeline in the rows -that end in tensor parallel, until MiMo's tensor parallel decodes in rounds: +40 tok/s; tensor parallel priced with its rounds), the comparison and the +evidence rule place MiMo as follows. Tensor parallel keeps every feature of the +speculative pipeline, so the guided step's feature parity holds none of these +rows back: | Pair | Link | Request | Chosen | |---|---|---|---| @@ -4594,7 +4638,7 @@ that end in tensor parallel, until MiMo's tensor parallel decodes in rounds: Against the plain pipeline (a capability without `pipeline_mtp_v1`, or no passing record of the rounds), tensor parallel would also drop the plain pipeline's eight batch lanes (it serves one), so feature parity keeps the -pipeline there too. On speed alone, two M5 Max are predicted faster in tensor +pipeline there, whatever the evidence. On speed alone, two M5 Max are predicted faster in tensor parallel even on default link costs for decode-heavy requests (128 + 128: 3.17 s against 3.50 s), on the prior alone, so they keep the pipeline too, as they do inside the 5 % margin (1,024 + 128) or for long prompts; two M5 Ultra @@ -4610,8 +4654,7 @@ MiMo's runtime takes no share probe, so only requests a pair served in tensor parallel with the same worker build give it evidence (`ClusterServedCalibration`). Only the developer's forced mode, in a debug build, serves MiMo tensor parallel before that; a release build cannot force it, -so release builds keep MiMo on the pipeline until MiMo gets a share probe, and -feature parity keeps it there until MiMo's tensor parallel decodes in rounds. The +so release builds keep MiMo on the pipeline until MiMo gets a share probe. The recorded golden layout gains the facts and routed experts beside its recorded bytes; its golden plans keep their placements (pipeline, cut 41 and cut 24), and their tensor-parallel diff --git a/docs/developer/test.md b/docs/developer/test.md index 9dd94ecc99..84b502c581 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1352,7 +1352,11 @@ registered artifact for them. ranks' expert rows add up bit for bit to the exact full-width row that one Mac rounds once, through the decode-expert kernel and MLX's sorted gather; every partial a rank sums is FP32, and no `o_proj` or dense - partial was rounded to BF16 first; the contract v2 strings are pinned; + partial was rounded to BF16 first; the contract v2 strings are pinned; a + speculative round's verify window (4 rows after a prompt that wrapped the + sliding ring) hands each sum the one-token steps' own FP32 partials, row + for row and bit for bit, with logits to match + (`windowPartialsAreTheOneTokenStepsFloat32Partials`); - the vocabulary-split head against the whole head; - the resident runtime's verified load: each rank reads exactly its shard's bytes, and a tampered or foreign checkpoint is refused; @@ -1372,9 +1376,17 @@ registered artifact for them. what the loaded heads declare; a window's rollback (`MiMoV26VerifyWindow.settle`) leaves exactly the cache of one-token appends on the registered 128-row ring (two 64-token pages, across its - page boundary and wrap) and on a full layer; and exactly tied columns and - draft readouts choose the lowest token ID; - - what the text row's capability declares of each mode (`ClusterServingFeatures`). + page boundary and wrap) and on a full layer; exactly tied columns and + draft readouts choose the lowest token ID; the window contract + (`windows=row-exact-one-token-float32-partials-v2`) is in the agreement; and + the product layout quotes what the LOAD gate charges with rounds on by + default: the heads (42 tensors, 1,975,640,448 bytes) and each request's + speculative charge beside the reserve, no speed-up credited + (`placementQuotesWhatTheLoadGateChargesWithRounds`); + - what the text row's capability declares of each mode (`ClusterServingFeatures`): + tensor parallel decodes in rounds at `ClusterMiMoTensorParallel.speculativeDepth`, + so it drops nothing of the speculative or compact-decode pipeline and only + the plain pipeline's batch lanes. `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh` also runs `MiMoTensorParallelChecks.swift` (model-free). It builds the layout from the @@ -1382,7 +1394,13 @@ registered artifact for them. facts (97 sums a step, `fastest_v1`), a rank's share of exactly 84,013,770,176 bytes, the routing prior (10,767,036,288 bytes a step), no facts for the image candidate, the same facts in the golden layout, and the - rank's reserve (`MiMoTensorParallelRequestBudget`) in the quote. Under the + rank's reserve (`MiMoTensorParallelRequestBudget`) in the quote. With the + rounds on by default, it prices them as the product layout does (the SDK's + drafter declaration stands in at its registered 438,426,984 bytes plus the + window's 36,347,904): each rank holds the 42 head tensors whole in whole pages, + its request need carries the speculative charge, its need is exactly the + rank's LOAD gate plus its tensors' page padding, decode is credited nothing, + and two idle 128 GB M5 Max still fit now (99.9 GiB a rank). Under the provider's tensor-parallel-first policy it checks the fastest-plan rule on constructed pairs against the plain pipeline: 2x M5 Max 128 GB keeps the pipeline where tensor parallel is predicted faster on the device index alone, @@ -1397,15 +1415,19 @@ registered artifact for them. guided step credits MiMo's rounds from its shipped records and prints the fastest-plan and logprob lines. Through the guided step it also checks feature parity (`ClusterModeParity`) before the evidence rule: - - as this build declares them, MiMo's tensor parallel has no rounds, so the - speculative pipeline is kept even with this build's served records; Gemma's - keeps no prompt prefixes, so the pipeline is kept even with both Macs' share - probes, after an update that served tensor parallel, and with nothing - measured; each plan says what tensor parallel would drop; - - with rounds (MiMo) or prefix reuse (Gemma) declared, the evidence rule - decides: MiMo on two 256 GB Macs keeps the speculative pipeline with no - served record or another build's and follows this build's served records, - and Gemma follows both Macs' share probes; + - as this build declares them, MiMo's tensor parallel decodes in rounds, so it + keeps every feature of the speculative pipeline and the evidence rule + decides: on two 256 GB Macs the speculative pipeline is kept with no served + record (prior only) or another build's, and this build's served records + choose (95 tok/s: tensor parallel; 60: the speculative pipeline); + - a MiMo record without tensor parallel's rounds holds it back even with this + build's served records, and where the plain pipeline is the mode it would + replace (a record without `pipeline_mtp_v1`), that pipeline's 8 batch lanes + hold one-lane tensor parallel back, served records or not; + - Gemma's tensor parallel keeps no prompt prefixes, so the pipeline is kept even + with both Macs' share probes, after an update that served tensor parallel, + and with nothing measured; each plan says what tensor parallel would drop; + with prefix reuse declared, Gemma follows both Macs' share probes; - where only tensor parallel fits, the plan refuses and saves no setup; the forced mode places it and says what it drops; a record without features holds it back, and the forced mode then says what it drops is not known; @@ -2107,7 +2129,10 @@ default. Run `bash provider-swift/Tests/ClusterInstalledSessionChecks/run.sh`. The CPU runner compiles the actual local-owner launcher, installed plan/session and -member-installation code. `InstalledBatchLanesCheck.swift` launches a real child +member-installation code. Its generation-mode check also launches MiMo tensor +parallel: both ranks get `--mtp-depth 2` after the mode exactly where the pinned +record declares tensor parallel's rounds, and the status then reports the head +as decoding. `InstalledBatchLanesCheck.swift` launches a real child with the fixed owner arguments and checks its exact environment, supported lane widths, out-of-range rejection, malformed-override parity even with an eight-lane family default, admission/owner/native parity, unsupported diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index ce732bca98..4d60d8d6fd 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -341,15 +341,18 @@ Models that run tensor parallel, and when: | Qwen3.5 9B, Qwen3.8 27B, Qwen3.5/3.6 35B A3B | wherever it fits | Qwen3.8 27B keeps images, video and logprobs only in tensor parallel | | GLM-5.3-Flash | wherever it fits | Eight concurrent requests by default | | Gemma 4 26B (QAT 4-bit, 8-bit) | only where it keeps every feature of the pipeline (not yet: no prompt-prefix or SSD reuse) and the plan predicts it faster from its own measured speed on both Macs | Text only; logprobs in tensor parallel only; one request at a time unless you set `DARKBLOOM_CLUSTER_BATCH_LANES` | -| MiMo V2.6 Flash | only where it keeps every feature of the mode it would replace (not yet: no speculative rounds) and the plan predicts it faster from its own measured speed on both Macs | Text only; logprobs in tensor parallel only; one request at a time; see [MiMo V2.6 Flash on the pair](#mimo-v26-flash-on-the-pair) | +| MiMo V2.6 Flash | only where it keeps every feature of the mode it would replace (it keeps the speculative pipeline's rounds, not the plain pipeline's batch lanes) and the plan predicts it faster from its own measured speed on both Macs | Text only; speculative decoding; logprobs in tensor parallel only; one request at a time; see [MiMo V2.6 Flash on the pair](#mimo-v26-flash-on-the-pair) | For Gemma 4 and MiMo V2.6 Flash, tensor parallel must first keep every feature and caching behavior of the mode it would replace, as the installed cluster worker declares them: prompt-prefix and SSD cache reuse, speculative rounds, batch lanes, media, penalties and logit bias, stop handling and logprobs. What it adds, such as logprobs where the pipeline has none, never counts against it. -Today Gemma 4's tensor parallel keeps no prompt prefixes and MiMo's has no -speculative rounds, so these pairs serve the pipeline: +Today Gemma 4's tensor parallel keeps no prompt prefixes, so Gemma pairs serve +the pipeline. MiMo's tensor parallel decodes in speculative rounds and keeps every +feature of the speculative pipeline, so speed decides there (below); it is held +back only where the plain pipeline, with its batch lanes, is the mode it would +replace. Where tensor parallel is held back: - The plan's "Tensor parallel or pipeline" line says what tensor parallel would drop ("Pipeline: tensor parallel would drop prompt-prefix reuse and the SSD @@ -569,14 +572,16 @@ KV on the pair yet, and the pair decodes slower than the M5 Ultra alone. Its phase split (one Mac decodes alone) is kept off like every hand-off mode. MiMo V2.6 Flash text can also run tensor parallel: each Mac holds half of every -layer, about 84 GB of weights and about 98 GiB in all with its reserves +layer, about 84 GB of weights, and MiMo's three draft heads whole (about 2 GB), +about 100 GiB in all with its reserves ([rank memory](../architecture/hardware-support.md#mimo-v26-tensor-parallel-rank-memory)), -so two 128 GB Macs that cannot hold MiMo alone can serve it. The plan chooses -tensor parallel only where it keeps the speculative rounds of the pipeline it -would replace, which it does not yet, so MiMo pairs keep the pipeline with -speculative decoding (above). Speed decides only after that: tensor parallel must -be predicted faster than that pipeline, which MiMo's qualification records -credit 1.37x, from tensor parallel's own speed measured on both Macs: +so two 128 GB Macs that cannot hold MiMo alone can serve it. It decodes with +speculative decoding by default, as the pipeline does, so it keeps the speculative +pipeline's features. Where the plain pipeline is the mode it would replace, its +batch lanes keep the pipeline. Speed decides after that: tensor parallel must be +predicted faster than the speculative pipeline, which MiMo's qualification +records credit 1.37x, from tensor parallel's own speed measured on both Macs. The +plan credits tensor parallel's own rounds nothing until they are measured: - Before a load has measured the link, two 128 GB Macs and two 256 GB Macs alike keep the pipeline. @@ -589,7 +594,8 @@ credit 1.37x, from tensor parallel's own speed measured on both Macs: pairs keep the pipeline today. In tensor parallel MiMo returns logprobs, serves one request at a time and -runs without speculative decoding; the image candidate stays a pipeline. Speed +decodes with speculative decoding (up to two drafted tokens a round); its output +is the same as without drafting. The image candidate stays a pipeline. Speed on a real pair is not measured yet. No qualification record covers MiMo tensor parallel yet, so its grant names only the modes above and a tensor-parallel MiMo pair serves its owner's local endpoint. From 9cba78f2803b9e827238aaab7ba1b2a611e85236 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:03:02 -0800 Subject: [PATCH 0126/1441] docs: list Gemma 4 tensor parallel in the cluster prefix tenant partitions Gemma4TensorParallelPrefix.scopes derives both tiers' scopes through ClusterWorkerPrefixCache.scope, like the other pair families the table names. Co-Authored-By: Claude Opus 5.5 --- docs/reference/ssd-kv-cache.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/reference/ssd-kv-cache.md b/docs/reference/ssd-kv-cache.md index 728b31a595..f73a17410a 100644 --- a/docs/reference/ssd-kv-cache.md +++ b/docs/reference/ssd-kv-cache.md @@ -1,6 +1,6 @@ # SSD KV cache reference -> Last updated: 2026-10-28 +> Last updated: 2026-11-01 Exact on-disk format, paths, identity binding, environment knobs, size and eviction rules, and per-family reuse capability of the provider's encrypted SSD @@ -618,7 +618,7 @@ record format are unchanged. | Request (`ClusterWorkerReservation.prefixCache`) | SSD record behavior | Enforcement | |---|---|---| | None (cache on, no salt) | The plan's earlier scope; read and written as before | `ClusterWorkerPrefixCache.scope` in `libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterWorkerPrefixCache.swift` | -| `tenant` | Scope carries `\|tenant=` and the salt's SHA-256 digest; offered, restored and written only for that tenant | the same helper, through `qwenStagePrefixScope`, `QwenTensorParallelResidentRuntime.batchPrefixScope` and `GLM5NextTensorParallelResidentRuntime.prefixDiskScope` | +| `tenant` | Scope carries `\|tenant=` and the salt's SHA-256 digest; offered, restored and written only for that tenant | the same helper, through `qwenStagePrefixScope`, `QwenTensorParallelResidentRuntime.batchPrefixScope`, `GLM5NextTensorParallelResidentRuntime.prefixDiskScope` and `Gemma4TensorParallelPrefix.scopes` | | `disabled` | Nothing offered, restored or written | the same helper (no scope) | See [cluster prefix tenant partitions](../architecture/prefix-cache.md#cluster-prefix-tenant-partitions). From 4633e71f4b69c07ca057839621103bac92118f53 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:06:54 -0800 Subject: [PATCH 0127/1441] placement: say an uncredited speculative head is credited nothing The layout explanation said every tensor-parallel speculative head's decode is "credited N.NNx one token per step, as the rounds measured". MiMo's head is priced with a speed-up of 1 until records measure its rounds, so for a speed-up of 1 the line now says decode is "credited nothing over one token per step until the rounds are measured". GLM's line (1.21x) is byte-identical; PlacementChecks pins both. Co-Authored-By: Claude Opus 5.5 --- .../ClusterPlacementExplanation.swift | 6 ++++-- .../Tests/PlacementChecks/MiMoTensorParallelChecks.swift | 7 ++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementExplanation.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementExplanation.swift index 2f7abd5657..d9a0f8d871 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementExplanation.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementExplanation.swift @@ -108,9 +108,11 @@ public enum ClusterPlacementExplanation { lines.append(" Modes: \(layout.generationModes.map(\.rawValue).joined(separator: ", ")). " + "Largest request: \(layout.maximumPromptTokens) prompt and \(layout.maximumOutputTokens) output tokens.") if let head = layout.tensorParallel?.speculativeHead(mode: .tensorParallel, layout: layout) { + // A plan states no speed-up above 1 until the pair measured the rounds (MiMo's, 2026-11-01). lines.append(" Tensor parallel decodes in speculative rounds of up to \(head.plan.depth) proposals: every rank holds the model's head " - + "whole (\(gibText(head.part.loadedBytes))) and \(gibText(head.plan.requestBytes)) of its request state, and decode is credited " - + "\(number(head.plan.decodeSpeedup, 2))x one token per step, as the rounds measured.") + + "whole (\(gibText(head.part.loadedBytes))) and \(gibText(head.plan.requestBytes)) of its request state, and decode is " + + (head.plan.decodeSpeedup > 1 ? "credited \(number(head.plan.decodeSpeedup, 2))x one token per step, as the rounds measured." + : "credited nothing over one token per step until the rounds are measured.")) } return lines } diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/MiMoTensorParallelChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/MiMoTensorParallelChecks.swift index aaa91361a3..f1549f57cf 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/MiMoTensorParallelChecks.swift +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/MiMoTensorParallelChecks.swift @@ -113,9 +113,10 @@ private func checkMiMoRounds(_ priced: ClusterModelLayout, rounds: ClusterModelL try ClusterPlacementPlanner.evaluate(devices: maxes, cuts: [41], mode: .pipeline, prefillSchedule: .serial, layout: rounds, policy: ClusterPlacementPolicy(), link: link) == ClusterPlacementPlanner.evaluate(devices: maxes, cuts: [41], mode: .pipeline, prefillSchedule: .serial, layout: priced, policy: ClusterPlacementPolicy(), link: link)) - checks.require("mimo rounds: the layout's description says the rounds and their charge", - ClusterPlacementExplanation.layout(rounds).contains { $0.contains("speculative rounds of up to 2 proposals") } - && !ClusterPlacementExplanation.layout(priced).contains { $0.contains("speculative rounds of up to") }) + checks.require("mimo rounds: the layout's description says the rounds, their charge and that decode is credited nothing until measured", + ClusterPlacementExplanation.layout(rounds).contains { + $0.contains("speculative rounds of up to 2 proposals") && $0.hasSuffix("credited nothing over one token per step until the rounds are measured.") + } && !ClusterPlacementExplanation.layout(priced).contains { $0.contains("speculative rounds of up to") }) } /// What one rank holds of a layout's tensor-parallel facts: every part's From aa6c3b8e96b785c5d2321c37ef5fdcb27b55f38d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:10:46 -0800 Subject: [PATCH 0128/1441] docs: cite the MiMo parity scan without an out-of-repo path inference.md named a scratch note outside the repository for the scan of where the plain pipeline is the mode MiMo tensor parallel would replace. It now says what the scan was (the planner on the placement checks' device model, the measured 29 us link, 2026-11-01), still marked [INFERENCE]. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c7d410e1f1..73a31afd8a 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4262,10 +4262,10 @@ held back until it keeps them."). On equal idle Macs in the placement checks' device model, with MiMo's rounds credited and the heads priced, that is 106 GB for 128 + 128 and 118 GB for a fresh pair's 32,768 + 32,768; from 104 GB (where tensor parallel first fits) every other size replaces the speculative -pipeline, and no size fits tensor parallel alone (2026-11-01 scan, -`mainnet/overnight/mimo-tp-speculative-v2.md`) [INFERENCE: the device model, -not real Macs]. The tensor-parallel-first families (Qwen, GLM) declare no -features and are not gated. Applied to them, the rule would leave GLM unchanged (its tensor parallel +pipeline, and no size fits tensor parallel alone (a planner scan on 2026-11-01, +the measured 29 µs link) [INFERENCE: the checks' device model, not measured +Macs]. The tensor-parallel-first families (Qwen, GLM) declare no features and +are not gated. Applied to them, the rule would leave GLM unchanged (its tensor parallel keeps prompt-prefix and SSD reuse and adds rounds, eight lanes, images, video and logprobs) but would move Qwen3.5 9B from tensor parallel to its speculative pipeline, which its records credit 1.74x: Qwen tensor parallel From afec28f1102d5f94a8ebbce21d1651ab7797bd47 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:20:29 -0800 Subject: [PATCH 0129/1441] cluster: Gemma 4 tensor parallel keeps prompt prefixes, so the parity gate admits it With #1706's prompt prefixes merged, Gemma 4's capability record declares prefix reuse resident and on the SSD tier for tensor parallel, as for the pipeline. The feature-parity gate then has nothing to hold Gemma back on, and the evidence rule decides. - Gemma4TensorParallelRuntimeTests.capabilityDeclaresWhatEachModeKeeps pins the new declaration: tensor parallel drops nothing the pipeline keeps. - PlacementSetupCheck plans with what this build declares; the gate's Gemma checks (held, kept mode, forced line, only-tensor-parallel-fits refusal, codec) use a record whose tensor parallel keeps no prompt prefix, as builds before 0.10.7 declared it. - inference.md, two-mac-cluster.md, test.md and the parity changelog say only MiMo is held (no speculative rounds yet), with MiMo's line as the example. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-feature-parity.md | 2 +- docs/architecture/inference.md | 12 ++--- docs/developer/test.md | 18 ++++---- docs/provider/two-mac-cluster.md | 14 +++--- .../Gemma4TensorParallelRuntimeTests.swift | 11 ++--- .../PlacementSetupCheck.swift | 45 ++++++++++--------- 6 files changed, 57 insertions(+), 45 deletions(-) diff --git a/changelog.d/cluster-feature-parity.md b/changelog.d/cluster-feature-parity.md index 0b23fb5a34..5318357564 100644 --- a/changelog.d/cluster-feature-parity.md +++ b/changelog.d/cluster-feature-parity.md @@ -1,6 +1,6 @@ ### Tensor parallel only where it keeps every feature - On a two-Mac pair, Gemma 4 and MiMo V2.6 Flash use tensor parallel only where it keeps every feature and caching behavior of the mode it would replace: prompt-prefix and SSD cache reuse, speculative (MTP) rounds, batch lanes, media, penalties and logit bias, stop handling and logprobs. What tensor parallel adds, such as logprobs where the pipeline has none, never counts against it. Each mode's features come from the installed cluster worker's capability record. -- Today Gemma 4's tensor parallel keeps no prompt prefixes and MiMo's has no speculative rounds, so these pairs keep the pipeline, whatever tensor parallel's measured speed. The plan's "Tensor parallel or pipeline" line says what tensor parallel would drop ("Pipeline: tensor parallel would drop prompt-prefix reuse and the SSD prefix tier that the pipeline keeps; held back until it keeps them."), and the model list says "tensor parallel: drops a feature". +- Gemma 4's tensor parallel keeps every feature of its pipeline, prompt-prefix and SSD reuse included, so its measured speed decides. MiMo's tensor parallel has no speculative rounds yet, so MiMo pairs keep the speculative pipeline wherever it is the mode tensor parallel would replace, whatever tensor parallel's measured speed. The plan's "Tensor parallel or pipeline" line says what tensor parallel would drop ("Pipeline: tensor parallel would drop speculative (MTP) rounds that the speculative pipeline keeps; held back until it keeps them."), and the model list says "tensor parallel: drops a feature". - Where only tensor parallel fits the two Macs, the plan refuses with that reason and saves no setup, instead of saving one with fewer features. The developer's forced mode (debug builds) still places tensor parallel, and the plan says exactly what it drops. - Qwen and GLM plans are unchanged. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 3e751aa86c..c1bc2ba7c1 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4247,8 +4247,8 @@ ranks anything: evidence hold, a kept mode, a better hardware group) brings it back. The assessment's verdict is `dropsFeatures` (`ClusterPlacementPolicy.tensorParallelHeldForFeatures`), the plan's line says, for example, "Pipeline: tensor parallel would drop - prompt-prefix reuse and the SSD prefix tier that the pipeline keeps; held back - until it keeps them.", and the model list says `tensor parallel: drops a feature`. + speculative (MTP) rounds that the speculative pipeline keeps; held back until + it keeps them.", and the model list says `tensor parallel: drops a feature`. 4. Where tensor parallel is the only mode that places, the plan refuses rather than save a reduced setup: "Only tensor parallel fits these Macs, and it would drop ... No reduced-feature setup was saved." The result's `modesReason` @@ -4258,9 +4258,11 @@ ranks anything: 6. A `fastest` family whose record declares no features keeps tensor parallel back: nothing shows it keeps them. -Today the rule holds Gemma's tensor parallel back everywhere, whatever its -evidence, and MiMo's wherever the speculative pipeline is the mode it would -replace; the evidence rule below decides once a worker declares parity. The +Gemma's tensor parallel keeps every feature of its pipeline, prompt prefixes +included, resident and on the SSD tier (`Gemma4TensorParallelPrefix`), so the +evidence rule below decides for it. The rule holds MiMo's tensor parallel back +wherever the speculative pipeline is the mode it would replace, because it has +no speculative rounds. The tensor-parallel-first families (Qwen, GLM) declare no features and are not gated. Applied to them, the rule would leave GLM unchanged (its tensor parallel keeps prompt-prefix and SSD reuse and adds rounds, eight lanes, images, video diff --git a/docs/developer/test.md b/docs/developer/test.md index d1c5e008ac..38613cc4a2 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1411,14 +1411,16 @@ registered artifact for them. fastest-plan and logprob lines. Through the guided step it also checks feature parity (`ClusterModeParity`) before the evidence rule: - as this build declares them, MiMo's tensor parallel has no rounds, so the - speculative pipeline is kept even with this build's served records; Gemma's - keeps no prompt prefixes, so the pipeline is kept even with both Macs' share - probes, after an update that served tensor parallel, and with nothing - measured; each plan says what tensor parallel would drop; - - with rounds (MiMo) or prefix reuse (Gemma) declared, the evidence rule - decides: MiMo on two 256 GB Macs keeps the speculative pipeline with no - served record or another build's and follows this build's served records, - and Gemma follows both Macs' share probes; + speculative pipeline is kept even with this build's served records; a Gemma + record whose tensor parallel keeps no prompt prefixes (as builds before + 0.10.7 declared it) keeps the pipeline even with both Macs' share probes, + after an update that served tensor parallel, and with nothing measured; each + plan says what tensor parallel would drop; + - with rounds declared (MiMo) and with Gemma's record as this build declares + it (prefix reuse kept), the evidence rule decides: MiMo on two 256 GB Macs + keeps the speculative pipeline with no served record or another build's and + follows this build's served records, and Gemma follows both Macs' share + probes; - where only tensor parallel fits, the plan refuses and saves no setup; the forced mode places it and says what it drops; a record without features holds it back, and the forced mode then says what it drops is not known; diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 1cfe03856c..f66c759d30 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -340,7 +340,7 @@ Models that run tensor parallel, and when: |---|---|---| | Qwen3.5 9B, Qwen3.8 27B, Qwen3.5/3.6 35B A3B | wherever it fits | Qwen3.8 27B keeps images, video and logprobs only in tensor parallel | | GLM-5.3-Flash | wherever it fits | Eight concurrent requests by default | -| Gemma 4 26B (QAT 4-bit, 8-bit) | only where it keeps every feature of the pipeline (not yet: no prompt-prefix or SSD reuse) and the plan predicts it faster from its own measured speed on both Macs | Text only; logprobs in tensor parallel only; one request at a time unless you set `DARKBLOOM_CLUSTER_BATCH_LANES` | +| Gemma 4 26B (QAT 4-bit, 8-bit) | only where the plan predicts it faster from its own measured speed on both Macs (it keeps every feature of the pipeline, prompt-prefix and SSD reuse included) | Text only; logprobs in tensor parallel only; one request at a time unless you set `DARKBLOOM_CLUSTER_BATCH_LANES` | | MiMo V2.6 Flash | only where it keeps every feature of the mode it would replace (not yet: no speculative rounds) and the plan predicts it faster from its own measured speed on both Macs | Text only; logprobs in tensor parallel only; one request at a time; see [MiMo V2.6 Flash on the pair](#mimo-v26-flash-on-the-pair) | For Gemma 4 and MiMo V2.6 Flash, tensor parallel must first keep every feature @@ -348,13 +348,15 @@ and caching behavior of the mode it would replace, as the installed cluster worker declares them: prompt-prefix and SSD cache reuse, speculative rounds, batch lanes, media, penalties and logit bias, stop handling and logprobs. What it adds, such as logprobs where the pipeline has none, never counts against it. -Today Gemma 4's tensor parallel keeps no prompt prefixes and MiMo's has no -speculative rounds, so these pairs serve the pipeline: +Gemma 4's tensor parallel keeps every feature of its pipeline, prompt-prefix +and SSD reuse included. MiMo's has no speculative rounds yet, so MiMo pairs +serve the speculative pipeline wherever it is the mode tensor parallel would +replace: - The plan's "Tensor parallel or pipeline" line says what tensor parallel would - drop ("Pipeline: tensor parallel would drop prompt-prefix reuse and the SSD - prefix tier that the pipeline keeps; held back until it keeps them."), and the - model list says "tensor parallel: drops a feature". + drop ("Pipeline: tensor parallel would drop speculative (MTP) rounds that the + speculative pipeline keeps; held back until it keeps them."), and the model + list says "tensor parallel: drops a feature". - Where only tensor parallel fits the two Macs, the plan refuses and saves no setup ("Only tensor parallel fits these Macs, and it would drop ... No reduced-feature setup was saved."). diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift index 0869044c2a..a9f3524b6c 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift @@ -670,21 +670,22 @@ struct Gemma4TensorParallelRuntimeTests { #expect(Set(others + [fingerprint]).count == 5) } - /// What the capability declares of each mode is what the loads run: tensor parallel binds no prompt-prefix cache - /// into its agreement and declares none, both modes take the batch wire's lanes, and only tensor parallel captures - /// logprobs. The provider's setup check plans with these values (`PlacementSetupCheck.gemmaFeatures`). + /// What the capability declares of each mode is what the loads run: tensor parallel binds the prompt-prefix cache + /// into its agreement and declares it resident and on the SSD tier, as the pipeline does; both modes take the batch + /// wire's lanes, and only tensor parallel captures logprobs. The provider's setup check plans with these values + /// (`PlacementSetupCheck.gemmaFeatures`). @Test func capabilityDeclaresWhatEachModeKeeps() throws { let features = Gemma4ResidentAdapterDefinition.servingFeatures #expect(features == [ .pipeline: .init(promptPrefixReuse: true, ssdPrefixTier: true, speculativeRounds: false, maximumLanes: 8, logprobs: false), - .tensorParallel: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 8, logprobs: true), + .tensorParallel: .init(promptPrefixReuse: true, ssdPrefixTier: true, speculativeRounds: false, maximumLanes: 8, logprobs: true), ]) #expect(Set(features.keys) == Set(Gemma4ResidentAdapterDefinition.supportedGenerationModes)) #expect(features[.tensorParallel]?.promptPrefixReuse == Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes && Gemma4TensorParallelLoadAgreement().prefixCache == Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes && features[.pipeline]?.maximumLanes == QwenBatchWire.maximumLanes) let pipeline = try #require(features[.pipeline]), tensor = try #require(features[.tensorParallel]) - #expect(pipeline.dropped(by: tensor) == ["prompt-prefix reuse", "the SSD prefix tier"]) + #expect(pipeline.dropped(by: tensor) == []) #expect(tensor.dropped(by: pipeline) == ["committed-token logprobs"]) } diff --git a/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift b/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift index 585774c01c..b6f13bc273 100644 --- a/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift +++ b/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift @@ -859,11 +859,15 @@ import Foundation } /// Gemma 4's modes as its worker declares them (`Gemma4ResidentAdapterDefinition.servingFeatures`, pinned by - /// `Gemma4TensorParallelRuntimeTests`): tensor parallel keeps no prompt prefix yet, and adds logprobs. + /// `Gemma4TensorParallelRuntimeTests`): tensor parallel keeps prompt prefixes resident and on the SSD tier, as the + /// pipeline does, and adds logprobs. static let gemmaFeatures: [ClusterGenerationMode: ClusterServingFeatures] = [ .pipeline: .init(promptPrefixReuse: true, ssdPrefixTier: true, speculativeRounds: false, maximumLanes: 8, logprobs: false), - .tensorParallel: .init(promptPrefixReuse: false, ssdPrefixTier: false, speculativeRounds: false, maximumLanes: 8, logprobs: true), + .tensorParallel: .init(promptPrefixReuse: true, ssdPrefixTier: true, speculativeRounds: false, maximumLanes: 8, logprobs: true), ] + /// Gemma 4's modes as a worker build whose tensor parallel kept no prompt prefix declared them (before 0.10.7): + /// the record the rule must hold back. + static let gemmaFeaturesWithoutPrefixes = with(gemmaFeatures, tensorParallelPrefixes: false) /// MiMo V2.6's text modes as its worker declares them (`MiMoResidentCapabilityMetadata.servingFeatures`, pinned /// by `MiMoTensorParallelResidentTests`): no mode keeps prompt prefixes, only the plain pipeline batches lanes, the /// speculative pipeline decodes in rounds, and tensor parallel serves one lane without rounds and adds logprobs. @@ -1034,15 +1038,15 @@ import Foundation } /// Gemma 4 QAT 4-bit through the guided step, on two 256 GB Macs with the M5 Ultra's index, Gemma alone at 90 tok/s - /// and the pair's measured link, for a 128 + 128 request. Feature parity first: as this build declares it, Gemma's - /// tensor parallel keeps no prompt prefix, resident or on the SSD tier, which the pipeline it would replace keeps, - /// so it is held back whatever the evidence, a kept mode or the device index say; a developer's forced mode places - /// it and says what it drops. Once its record declares prefix reuse (as a later build's may), the evidence rule - /// decides: the device index alone keeps the pipeline, and the share probes a Gemma tensor-parallel load records + /// and the pair's measured link, for a 128 + 128 request. Feature parity first: a record whose tensor parallel keeps + /// no prompt prefix, resident or on the SSD tier, which the pipeline it would replace keeps (as builds before 0.10.7 + /// declared it), is held back whatever the evidence, a kept mode or the device index say; a developer's forced mode + /// places it and says what it drops. As this build declares it (prefix reuse kept), the evidence rule decides: the + /// device index alone keeps the pipeline, and the share probes a Gemma tensor-parallel load records /// (`Gemma4TensorParallelShareProbe`, kept by `ClusterShareProbeHistory`) decide. static func gemmaEvidenceLines(description base: [String: Any]) throws { - let asBuilt = try gemma(features: gemmaFeatures, description: base) - let (layout, capability, description) = try gemma(features: with(gemmaFeatures, tensorParallelPrefixes: true), description: base) + let withoutPrefixes = try gemma(features: gemmaFeaturesWithoutPrefixes, description: base) + let (layout, capability, description) = try gemma(features: gemmaFeatures, description: base) let ultras = try indexedUltras(), alone = try aloneSpeed(layout, prefill: 7_000, decode: 90) func probes(halfStepMicroseconds: Int) -> [String: [ClusterShareRate]] { ClusterShareProbeHistory().recording(["mac-one", "mac-two"].map { @@ -1050,9 +1054,10 @@ import Foundation }, artifactSHA256: layout.artifactSHA256, now: 1_000).shareRates(artifactSHA256: layout.artifactSHA256, members: ["mac-one", "mac-two"], now: 1_060) } - func decide(_ shareProbes: [String: [ClusterShareRate]], asBuilt built: Bool = false, incumbentMode: ClusterGenerationMode? = nil, + func decide(_ shareProbes: [String: [ClusterShareRate]], keepingNoPrefix reduced: Bool = false, incumbentMode: ClusterGenerationMode? = nil, environment: [String: String] = [:]) throws -> (lines: [String], result: ClusterPlacementResult, setup: ClusterPlacementSetup?) { - try ClusterPlacementFlow.decide(description: built ? asBuilt.description : description, capability: built ? asBuilt.capability : capability, + try ClusterPlacementFlow.decide(description: reduced ? withoutPrefixes.description : description, + capability: reduced ? withoutPrefixes.capability : capability, localMemberID: "mac-one", localProfile: ultras.local, peerProfile: ultras.peer, layout: layout, measurements: [alone], promptTokens: 128, outputTokens: 128, link: ultras.link, shareProbes: shareProbes, incumbentMode: incumbentMode, environment: environment, benchDebugBuild: !environment.isEmpty) @@ -1060,17 +1065,17 @@ import Foundation let prefixLine = heldLine("prompt-prefix reuse and the SSD prefix tier that the pipeline keeps") for (name, shareProbes) in [("no share probe", [String: [ClusterShareRate]]()), ("both Macs' share probes at 7.0 ms a half step", probes(halfStepMicroseconds: 7_000))] { - let held = try decide(shareProbes, asBuilt: true) - require("Gemma parity: as this build declares it, tensor parallel keeps no prompt prefix, so with \(name) the pipeline is kept and the line says what tensor parallel would drop (\(held.lines.first { $0.hasPrefix(" Pipeline:") } ?? "-"))", + let held = try decide(shareProbes, keepingNoPrefix: true) + require("Gemma parity: a record whose tensor parallel keeps no prompt prefix, with \(name): the pipeline is kept and the line says what tensor parallel would drop (\(held.lines.first { $0.hasPrefix(" Pipeline:") } ?? "-"))", held.result.chosen?.mode == .pipeline && held.result.tensorParallel?.verdict == .dropsFeatures && held.lines.contains(prefixLine) && held.lines.contains(" " + ClusterModeParity.ruleLine) && held.setup != nil && ClusterPlacementExplanation.tensorParallelNote(held.result) == .dropsFeature && !held.result.alternatives.contains { $0.mode == .tensorParallel }) } - let kept = try decide(probes(halfStepMicroseconds: 7_000), asBuilt: true, incumbentMode: .tensorParallel) + let kept = try decide(probes(halfStepMicroseconds: 7_000), keepingNoPrefix: true, incumbentMode: .tensorParallel) require("Gemma parity: a pair that served tensor parallel before an update is planned as the pipeline (parity before the kept mode)", kept.result.chosen?.mode == .pipeline && kept.result.tensorParallel?.verdict == .dropsFeatures && kept.lines.contains(prefixLine)) - let forced = try decide([:], asBuilt: true, environment: [ClusterForcedModeSetting.environmentName: "tensor_parallel_v1"]) + let forced = try decide([:], keepingNoPrefix: true, environment: [ClusterForcedModeSetting.environmentName: "tensor_parallel_v1"]) require("Gemma parity: the developer's forced mode places tensor parallel and the plan says exactly what it drops", forced.result.chosen?.mode == .tensorParallel && forced.setup != nil && forced.lines.contains(" Developer setting: tensor parallel is placed because it is forced; it drops " @@ -1081,7 +1086,7 @@ import Foundation && priorOnly.lines.contains { $0.hasPrefix(" Pipeline: tensor parallel is predicted") && $0.contains("from the device index") } && priorOnly.lines.contains(fastestLine)) let measured = try decide(probes(halfStepMicroseconds: 7_000)), planned = try decide(probes(halfStepMicroseconds: 10_300)) - require("Gemma parity and evidence: once its record declares prefix reuse resident and on the SSD tier, tensor parallel is admissible; both Macs' share probes at 7.0 ms a half step: tensor parallel, chosen on its measured step", + require("Gemma parity and evidence: as this build declares it, tensor parallel keeps prefix reuse resident and on the SSD tier and is admissible; both Macs' share probes at 7.0 ms a half step: tensor parallel, chosen on its measured step", measured.result.chosen?.mode == .tensorParallel && measured.result.tensorParallel?.evidence == .measured && !measured.lines.contains { $0.contains("would drop") } && measured.lines.contains { $0.hasPrefix(" Tensor parallel: predicted") && $0.hasSuffix(", on its own step as measured on both Macs.") }) @@ -1095,7 +1100,7 @@ import Foundation /// where only tensor parallel fits and it drops a feature, the plan refuses and saves nothing (owner, 2026-11-01), /// and the same Macs place it once its record keeps that feature. static func featureParity(description base: [String: Any]) throws { - let built = try gemma(features: gemmaFeatures, description: base) + let built = try gemma(features: gemmaFeaturesWithoutPrefixes, description: base) let data = try ClusterRuntimeCapabilityCodec.encode(built.capability) let decoded = try ClusterRuntimeCapabilityCodec.decode(data) require("parity record: a capability's per-mode serving features cross the codec canonically", decoded == built.capability @@ -1138,8 +1143,8 @@ import Foundation // Only tensor parallel fits: the layout admits one cut only, 1, whose last rank holds every layer but one, on two // equal Macs too small for that rank and large enough for a tensor-parallel half (found by planning each mode alone). let narrow: (inout [String: Any]) -> Void = { $0["admittedCuts"] = [1] } - let reduced = try gemma(features: gemmaFeatures, description: base, adjust: narrow) - let gained = try gemma(features: with(gemmaFeatures, tensorParallelPrefixes: true), description: base, adjust: narrow) + let reduced = try gemma(features: gemmaFeaturesWithoutPrefixes, description: base, adjust: narrow) + let gained = try gemma(features: gemmaFeatures, description: base, adjust: narrow) func macs(_ giB: Int) throws -> [ClusterPlacementDevice] { try ["mac-one", "mac-two"].map { try device($0, physicalGiB: giB, freeGiB: giB - 4, prefill: 7_000, decode: 90) } } @@ -1164,7 +1169,7 @@ import Foundation require("parity refusal: where only tensor parallel fits (two \(giB) GB Macs, cut 1 only), the plan refuses, says why and saves no setup", refused.result.chosen == nil && refused.setup == nil && refused.lines.contains(" " + refusal) && refused.result.modesReason == refusal && refused.result.tensorParallel?.verdict == .dropsFeatures) - require("parity refusal: the same Macs place tensor parallel once its record declares prefix reuse", + require("parity refusal: the same Macs place tensor parallel with the record this build declares (prefix reuse kept)", placed.result.chosen?.mode == .tensorParallel && placed.setup != nil && !placed.lines.contains { $0.contains("would drop") }) } From 0bf4dcd543a3e7059fead3c836ebc4fbf4604e72 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:29:33 -0800 Subject: [PATCH 0130/1441] cluster: check every MiMo TP verify-window width; pin the plan's heads to the LOAD gate's Refactor pass on MiMo tensor parallel's speculative rounds (contract v2 windows, on by default). Tests and docs only. - windowPartialsAreTheOneTokenStepsFloat32Partials now checks every window width (2, 3 and 4 rows), so the installed depth's 3-row window is compared with the one-token steps partial for partial; only 4 rows were before. A window mutated to v1 dense and routed partials (o_proj kept v2) fails it with 204 issues. - placementQuotesWhatTheLoadGateChargesWithRounds also requires the layout's head part to equal the LOAD gate's own head inventory (MiMoMTPHeadInventory) over the same registered headers; before, only a constant pinned it. - inference.md: against the plain pipeline tensor parallel "would drop" its lanes (no longer "also"); the rank's LOAD gate figure is linked from rank memory, not restated; a depth-2 round never runs the third head, which every rank holds and is charged for. - hardware-support.md links the placement section instead of restating the planner's 99.9 GiB. - Changelog: "MiMo's own trained draft heads" (a depth-2 round drafts with two of the three); the parent fragment gives the installed figure, about 100 GiB a Mac with the draft heads. - test.md: both tests' descriptions. Co-Authored-By: Claude Opus 5.5 --- changelog.d/mimo-tensor-parallel.md | 2 +- changelog.d/mimo-tp-speculative.md | 2 +- docs/architecture/hardware-support.md | 6 +- docs/architecture/inference.md | 27 +++---- docs/developer/test.md | 9 +-- ...iMoTensorParallelFloat32PartialTests.swift | 70 ++++++++++--------- .../MiMoTensorParallelSpeculativeTests.swift | 13 ++-- 7 files changed, 72 insertions(+), 57 deletions(-) diff --git a/changelog.d/mimo-tensor-parallel.md b/changelog.d/mimo-tensor-parallel.md index 8dfb8e22aa..6b524874ca 100644 --- a/changelog.d/mimo-tensor-parallel.md +++ b/changelog.d/mimo-tensor-parallel.md @@ -3,5 +3,5 @@ - MiMo V2.6 Flash text can run tensor parallel on a pair: each Mac holds half of every layer's heads and expert channels and half of the output head, both share every token over the encrypted link, and on the synthetic checks the two Macs agree bit for bit with a one-process simulation of both halves. The image candidate stays a pipeline. - Each Mac's half of a layer's attention output and feed-forward is kept at full 32-bit precision until both halves are added, then rounded once, so a pair never rounds more than one Mac does. On the synthetic checks, the two halves of an expert's output add up bit for bit to the full output that one Mac rounds once. - The planner chooses tensor parallel for MiMo only where it predicts it faster than the pipeline with speculative decoding, which MiMo's qualification records credit 1.37x, from tensor parallel's own speed measured on both Macs (see "Tensor parallel for Gemma 4 and MiMo only on measured speed"). Two 128 GB Macs, which cannot hold MiMo alone, can serve it this way. Qwen and GLM still choose tensor parallel wherever it fits. -- In tensor parallel, MiMo returns logprobs (`logprobs` / `top_logprobs`), serves one request at a time with speculative decoding (see "MiMo V2.6 Flash tensor parallel with speculative decoding"), and each Mac reserves memory for its own half: 84.0 GB of weights plus its own KV, work and buffers, with a conservative 5.5 GiB activation reserve until a pair measures one (about 98 GiB per Mac at the longest request, about 100 GiB with the draft heads). +- In tensor parallel, MiMo returns logprobs (`logprobs` / `top_logprobs`), serves one request at a time with speculative decoding (see "MiMo V2.6 Flash tensor parallel with speculative decoding"), and each Mac reserves memory for its own half: 84.0 GB of weights plus its own KV, work and buffers, with a conservative 5.5 GiB activation reserve until a pair measures one (about 100 GiB per Mac at the longest request, the draft heads included). - No MiMo tensor-parallel qualification record exists yet, and speed on a real pair is not measured. diff --git a/changelog.d/mimo-tp-speculative.md b/changelog.d/mimo-tp-speculative.md index 00dd5d7dfb..6641eb2cd0 100644 --- a/changelog.d/mimo-tp-speculative.md +++ b/changelog.d/mimo-tp-speculative.md @@ -1,6 +1,6 @@ ### MiMo V2.6 Flash tensor parallel with speculative decoding -- A MiMo V2.6 Flash tensor-parallel pair decodes with MiMo's three trained draft heads: each round checks up to two drafted tokens in one pass through the pair, so every token a round keeps shares that pass's link and weight costs. +- A MiMo V2.6 Flash tensor-parallel pair decodes with MiMo's own trained draft heads: each round checks up to two drafted tokens in one pass through the pair, so every token a round keeps shares that pass's link and weight costs. - It is on by default: the installed provider starts both Macs' tensor-parallel workers with two drafts a round. - Output is identical to tensor parallel without drafting, token for token and bit for bit on the synthetic checks: greedy (with or without logprobs) and sampled. Each Mac's halves stay at full 32-bit precision inside a round too, exactly as in a one-token step. Every kind of stop works inside a round. Requests with penalties or a logit bias, and sampled requests that ask for logprobs, decode one token at a time, as in the speculative pipeline. - Each Mac holds the draft heads whole (about 2 GB more) and reserves their per-request state, and the plan counts both before it chooses tensor parallel. Two 128 GB Macs still fit, at about 100 GiB a Mac. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index ecab6caaf4..d9bd8640c1 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1187,9 +1187,9 @@ pairs the LOAD gate admits. | The window's extra rows at depth 2: each sliding ring once more per extra row, one page per layer, the window's rows twice (`MiMoTensorParallelRequestBudget.speculativeWindowBytes`) | per request | 36,347,904 | With them a rank still fits a 128 GB Mac: 107,281,620,648 bytes (99.9 GiB) with -the loading headroom, against a 115.2 GiB ceiling; the placement checks plan two -idle 128 GB M5 Max in tensor parallel now at 99.9 GiB a rank. See -[speculative rounds](inference.md#mimo-tensor-parallel-speculative-rounds). +the loading headroom, against a 115.2 GiB ceiling. See +[speculative rounds](inference.md#mimo-tensor-parallel-speculative-rounds) and +[placement](inference.md#mimo-tensor-parallel-placement). ### Additional TP resident allocations diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 73a31afd8a..a3802d29ae 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4509,7 +4509,9 @@ below). (3 × 658,546,816 B), named by the pipeline's head inventory (`MiMoMTPHeadInventory`) and read through the verified checkpoint beside their shard (`MiMoTensorParallelDraftHead`); both ranks compare the inventory's - digest before either is ready. The drafter is the product's + digest before either is ready. A round's k-th draft runs the k-th head + (`MiMoV26MTP.forwardTrusted`), so at the installed depth 2 the third head is + held and charged but never runs. The drafter is the product's (`MiMoV26MTPAssistant`); its target is a one-layer shell that lends it this rank's embedding and vocabulary rows. A proposal is the whole vocabulary's argmax from one small sum (`MiMoV26TextModel.readoutArgMax`), so both ranks @@ -4602,9 +4604,10 @@ and its quoted reserve gains each request's speculative charge (the product layout computes it with the SDK's drafter declaration at the allocator's bound; `placementQuotesWhatTheLoadGateChargesWithRounds` pins it to the LOAD gate's sum). Metadata-only layouts, such as the recorded golden one, carry neither, as -they carry no `requestAllowance`. Two 128 GB Macs still fit: a rank's LOAD gate -is 107,281,620,648 B (99.9 GiB) at exact sizes, and the planner asks 99.9 GiB of -an idle 128 GB Mac in the placement checks. No speed-up is credited until +they carry no `requestAllowance`. Two 128 GB Macs still fit: in the placement +checks the planner asks 99.9 GiB of an idle 128 GB Mac, the rank's LOAD gate +([rank memory](hardware-support.md#mimo-v26-tensor-parallel-rank-memory)) plus +its tensors' page padding. No speed-up is credited until records measure the rounds: when a pair has served MiMo tensor parallel with and without them on the same build, a measured table (as GLM's `GLM5NextServingMetadata.measuredTensorParallelDecode`, depth 0 against depth 2) @@ -4636,14 +4639,14 @@ rows back: | either pair | measured 109 us sums | 32,768 + 32,768 | speculative pipeline | Against the plain pipeline (a capability without `pipeline_mtp_v1`, or no -passing record of the rounds), tensor parallel would also drop the plain -pipeline's eight batch lanes (it serves one), so feature parity keeps the -pipeline there, whatever the evidence. On speed alone, two M5 Max are predicted faster in tensor -parallel even on default link costs for decode-heavy requests (128 + 128: -3.17 s against 3.50 s), on the prior alone, so they keep the pipeline too, as -they do inside the 5 % margin (1,024 + 128) or for long prompts; two M5 Ultra -keep the pipeline on default link costs, where 97 sums cost about 10.3 ms a -step, more than the weight streaming a half saves. +passing record of the rounds), tensor parallel would drop the plain pipeline's +eight batch lanes (it serves one), so feature parity keeps the pipeline there, +whatever the evidence. On speed alone, two M5 Max are predicted faster in +tensor parallel even on default link costs for decode-heavy requests (128 + +128: 3.17 s against 3.50 s), on the prior alone, so they keep the pipeline too, +as they do inside the 5 % margin (1,024 + 128) or for long prompts; two M5 +Ultra keep the pipeline on default link costs, where 97 sums cost about 10.3 ms +a step, more than the weight streaming a half saves. Every tensor-parallel prediction here without served records rests on the hardware prior: the M5 Ultra's device index puts the whole 17.5 ms step in diff --git a/docs/developer/test.md b/docs/developer/test.md index 84b502c581..8382066de9 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1353,9 +1353,9 @@ registered artifact for them. one Mac rounds once, through the decode-expert kernel and MLX's sorted gather; every partial a rank sums is FP32, and no `o_proj` or dense partial was rounded to BF16 first; the contract v2 strings are pinned; a - speculative round's verify window (4 rows after a prompt that wrapped the - sliding ring) hands each sum the one-token steps' own FP32 partials, row - for row and bit for bit, with logits to match + speculative round's verify window (every width from 2 to 4 rows, after a + prompt that wrapped the sliding ring) hands each sum the one-token steps' + own FP32 partials, row for row and bit for bit, with logits to match (`windowPartialsAreTheOneTokenStepsFloat32Partials`); - the vocabulary-split head against the whole head; - the resident runtime's verified load: each rank reads exactly its shard's @@ -1380,7 +1380,8 @@ registered artifact for them. draft readouts choose the lowest token ID; the window contract (`windows=row-exact-one-token-float32-partials-v2`) is in the agreement; and the product layout quotes what the LOAD gate charges with rounds on by - default: the heads (42 tensors, 1,975,640,448 bytes) and each request's + default: the heads (42 tensors, 1,975,640,448 bytes, equal to the LOAD + gate's head inventory over the same headers) and each request's speculative charge beside the reserve, no speed-up credited (`placementQuotesWhatTheLoadGateChargesWithRounds`); - what the text row's capability declares of each mode (`ClusterServingFeatures`): diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift index abb425c52a..e198d4bf6e 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift @@ -1,3 +1,4 @@ +import DarkbloomClusterProtocol import Foundation import MLX @testable import MLXLLM @@ -206,11 +207,12 @@ struct MiMoTensorParallelFloat32PartialTests { #expect(perHalfError > 16 * error, "per-half BF16 rows (v1) err \(perHalfError), FP32 rows \(error)") } - /// A speculative round's verify window (`forwardVerifyWindow`, 4 rows after a prompt that - /// wrapped the sliding ring) hands each sum the one-token steps' own partials, row for row and - /// bit for bit: `o_proj` (one FP32 product per row; the row-exact BF16 kernel serves no rank), - /// the dense feed-forward row by row, and the routed one's per-row combine of FP32 expert rows. - /// Every window partial is FP32 and holds values BF16 cannot, and the logits are the steps'. + /// A speculative round's verify window (`forwardVerifyWindow`, every width from 2 to 4 rows, + /// the installed depth's 3 included, after a prompt that wrapped the sliding ring) hands each + /// sum the one-token steps' own partials, row for row and bit for bit: `o_proj` (one FP32 + /// product per row; the row-exact BF16 kernel serves no rank), the dense feed-forward row by + /// row, and the routed one's per-row combine of FP32 expert rows. Every window partial is FP32 + /// and holds values BF16 cannot, and the logits are the steps'. @Test func windowPartialsAreTheOneTokenStepsFloat32Partials() throws { let (_, ranks, directory) = try Self.models() defer { try? FileManager.default.removeItem(at: directory) } @@ -219,7 +221,8 @@ struct MiMoTensorParallelFloat32PartialTests { Device.withDefaultDevice(.cpu) { value.asType(.float32).asArray(Float.self).map(\.bitPattern) } } let prompt = MLXArray((0 ..< 12).map { Int32(($0 * 37 + 11) % 512) }).reshaped([1, 12]) - let tokens: [Int32] = [7, 301, 45, 129] + let drafted: [Int32] = [7, 301, 45, 129] + #expect(ClusterMiMoTensorParallel.speculativeDepth + 1 <= drafted.count, "the installed depth's window is checked") for (rankIndex, rank) in ranks.enumerated() { // Each rank alone: the sum hands its partial back, so the window and the steps see one function. let recorder = Recorder() @@ -229,34 +232,37 @@ struct MiMoTensorParallelFloat32PartialTests { let installed = layers.map(\.tensorParallel) for layer in layers { layer.tensorParallel = context } defer { for (layer, value) in zip(layers, installed) { layer.tensorParallel = value } } - let windowCaches = try rank.model.makeIndependentHistoryCaches() - let stepCaches = try rank.model.makeIndependentHistoryCaches() - for caches in [windowCaches, stepCaches] { - eval(try rank.model.forwardIndependentHistory(inputIDs: prompt, caches: caches).logits) - } - recorder.summed = [] - let window = try rank.model.forwardVerifyWindow( - inputIDs: MLXArray(tokens).reshaped([1, tokens.count]), caches: windowCaches) - eval([window.logits] + recorder.summed) - let windowPartials = recorder.summed - #expect(windowPartials.count == 2 * layers.count, "rank \(rankIndex): an attention and a feed-forward sum a layer") - for (index, partial) in windowPartials.enumerated() { - #expect(partial.dtype == .float32 && partial.shape == [1, tokens.count, Self.hidden]) - let widenedBF16 = partial.asType(.bfloat16).asType(.float32) - #expect(any(partial .!= widenedBF16).item(Bool.self), "rank \(rankIndex): window partial \(index) holds only BF16 values") - } - for (row, token) in tokens.enumerated() { + for rows in 2 ... drafted.count { + let tokens = Array(drafted.prefix(rows)), label = "rank \(rankIndex), \(rows)-row window" + let windowCaches = try rank.model.makeIndependentHistoryCaches() + let stepCaches = try rank.model.makeIndependentHistoryCaches() + for caches in [windowCaches, stepCaches] { + eval(try rank.model.forwardIndependentHistory(inputIDs: prompt, caches: caches).logits) + } recorder.summed = [] - let step = try rank.model.forwardIndependentHistory( - inputIDs: MLXArray([token]).reshaped([1, 1]), caches: stepCaches) - eval([step.logits] + recorder.summed) - #expect(recorder.summed.count == windowPartials.count) - for (index, partial) in zip(windowPartials, recorder.summed).enumerated() { - #expect(bits(partial.0[0..., row ..< (row + 1), 0...]) == bits(partial.1), - "rank \(rankIndex), row \(row): window partial \(index) is not the step's") + let window = try rank.model.forwardVerifyWindow( + inputIDs: MLXArray(tokens).reshaped([1, rows]), caches: windowCaches) + eval([window.logits] + recorder.summed) + let windowPartials = recorder.summed + #expect(windowPartials.count == 2 * layers.count, "\(label): an attention and a feed-forward sum a layer") + for (index, partial) in windowPartials.enumerated() { + #expect(partial.dtype == .float32 && partial.shape == [1, rows, Self.hidden]) + let widenedBF16 = partial.asType(.bfloat16).asType(.float32) + #expect(any(partial .!= widenedBF16).item(Bool.self), "\(label): partial \(index) holds only BF16 values") + } + for (row, token) in tokens.enumerated() { + recorder.summed = [] + let step = try rank.model.forwardIndependentHistory( + inputIDs: MLXArray([token]).reshaped([1, 1]), caches: stepCaches) + eval([step.logits] + recorder.summed) + #expect(recorder.summed.count == windowPartials.count) + for (index, partial) in zip(windowPartials, recorder.summed).enumerated() { + #expect(bits(partial.0[0..., row ..< (row + 1), 0...]) == bits(partial.1), + "\(label), row \(row): partial \(index) is not the step's") + } + #expect(bits(window.logits[0..., row ..< (row + 1), 0...]) == bits(step.logits), + "\(label), row \(row): logits are not the step's") } - #expect(bits(window.logits[0..., row ..< (row + 1), 0...]) == bits(step.logits), - "rank \(rankIndex), row \(row): window logits are not the step's") } } } diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift index ae5594d3d6..ae8b16266c 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift @@ -283,10 +283,10 @@ struct MiMoTensorParallelSpeculativeTests { /// Rounds are on by default (`ClusterMiMoTensorParallel`), so the product layout prices a rank as its LOAD /// gate charges it with them: the plan holds the three heads whole beside the share (the layout's speculative - /// head, 42 tensors of 1,975,640,448 bytes), and the quoted reserve carries each request's speculative charge - /// (the drafter's declaration and the window's rows at the profile's 512-token chunk, at the allocator's - /// bound) beside the plain reserve: the LOAD gate's sum. No decode speed-up is credited until records - /// measure one. + /// head, 42 tensors of 1,975,640,448 bytes, the LOAD gate's own head inventory over the same headers), and the + /// quoted reserve carries each request's speculative charge (the drafter's declaration and the window's rows + /// at the profile's 512-token chunk, at the allocator's bound) beside the plain reserve: the LOAD gate's sum. + /// No decode speed-up is credited until records measure one. @Test func placementQuotesWhatTheLoadGateChargesWithRounds() throws { let configuration = try MiMoTensorParallelTests.fixture("configuration") let tensors = try JSONDecoder().decode([MiMoCanonicalTensor].self, from: MiMoTensorParallelTests.fixture("tensor-inventory")) @@ -295,6 +295,11 @@ struct MiMoTensorParallelSpeculativeTests { let family = try #require(layout.tensorParallel?.family) let head = try #require(layout.speculativeHead) #expect(head.tensorCount == 42 && head.storedBytes == 1_975_640_448 && head.loadedBytes == 1_975_640_448) + // The LOAD gate's heads term: the head inventory over the same headers (`MiMoMTPHead.inventory`). + let heads = try MiMoMTPHeadInventory(configuration: configuration, headers: tensors.map { + .init(name: $0.name, shape: $0.shape, dtype: $0.dtype, byteCount: $0.byteCount) + }).head + #expect(heads.count == head.tensorCount && heads.reduce(0) { $0 + $1.byteCount } == head.loadedBytes) typealias Runtime = MiMoTensorParallelResidentRuntime let plan = try MiMoTensorParallelPlan(configuration: configuration) let budget = try Runtime.requestBudget(plan: plan, slidingWindow: 128, contextTokens: 65_536, chunkTokens: 512) From b18c9d7daf0c6401348c0a7cdc3c9003c63ac0af Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:46:41 -0800 Subject: [PATCH 0131/1441] provider: apply feature parity outside ClusterPlacementFlow.decide's frame CI's provider shard 2 crashed in DistributedAutomaticBatchPlannerTests (discoveredAssistantThatCannotBePlacedGivesWayToTheOrdinaryTarget): a stack overflow on a Swift Testing cooperative thread (512 KiB), in ClusterPlacementPlanner's tensorRequirement below ClusterPlacementFlow.decide. In debug builds every local keeps its own stack slot, and the parity block's planner run and temporaries grew decide's frame by about 17 KB, past the chain's limit. ClusterModeParity.apply (@inline(never)) now holds that block, with the same behaviour: tensor parallel's modes leave the policy where they drop a feature unless the mode is forced, and the only-tensor-parallel-fits refusal is recorded in modesReason. Measured with lldb on the same test, decide's frame is back to its size before the gate (98,992 B; 116,320 B with the block). Co-Authored-By: Claude Opus 5.5 --- .../Placement/ClusterModeParity.swift | 19 +++++++++++++++++++ .../Placement/ClusterPlacementFlow.swift | 18 ++---------------- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift index c4a61948cb..e748908724 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift @@ -75,6 +75,25 @@ enum ClusterModeParity { return dropped.isEmpty ? nil : Hold(modes: tensor, replaced: replaced, otherModePlaces: placed != nil, dropped: dropped) } + /// The rule applied to `policy` as `ClusterPlacementFlow.decide` plans it: tensor parallel's modes leave the policy + /// where they would drop a feature, unless a developer forced the mode; where tensor parallel is the only mode that + /// places, the plan refuses rather than save a reduced setup (owner, 2026-11-01), and `modesReason` says so. + /// Not inlined into `decide`: the planner runs below `decide` on a cooperative thread's fixed-size stack. + @inline(never) + static func apply(to policy: inout ClusterPlacementPolicy, capability: ClusterRuntimeCapability, layout: ClusterModelLayout, + forced: Bool, plan: (ClusterPlacementPolicy) throws -> ClusterPlacementResult) -> (hold: Hold?, refusal: String?) { + guard let hold = hold(capability: capability, layout: layout, policy: policy, plan: plan) else { return (nil, nil) } + guard !forced else { return (hold, nil) } + var refusal: String? + if !hold.otherModePlaces, let only = (try? plan(policy))?.chosen, hold.modes.contains(only.mode) { + refusal = hold.refusal + policy.modesReason = policy.modesReason ?? hold.refusal + } + policy.modes = (policy.modes ?? layout.generationModes).filter { !hold.modes.contains($0) } + policy.tensorParallelHeldForFeatures = hold.reason + return (hold, refusal) + } + /// The rule, as a plan of a family it applies to says it. static let ruleLine = "A mode is chosen only where it keeps every feature and caching behavior of the mode it would " + "replace, as this worker build declares them: prompt-prefix and SSD reuse, speculative rounds, batch lanes, " diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift index 8b1ee4dd09..a5cd8324de 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift @@ -278,22 +278,8 @@ public enum ClusterPlacementFlow { // Feature parity (`ClusterModeParity`): tensor parallel is planned only where it keeps every feature of the // mode it would replace, as the worker's capability record declares them, and is left out before anything is // ranked. A developer's forced mode is placed anyway, and the plan says what it drops. - let parity = ClusterModeParity.hold(capability: capability, layout: layout, policy: policy) { - try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: $0, link: link) - } - var parityRefusal: String? - if let parity, forced == nil { - // Where tensor parallel is the only mode that places, the plan refuses rather than save a reduced setup - // (owner, 2026-11-01), and says so where a refusal is read (`modesReason`). - if !parity.otherModePlaces, - let only = (try? ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: policy, link: link))?.chosen, - parity.modes.contains(only.mode) { - parityRefusal = parity.refusal - policy.modesReason = policy.modesReason ?? parity.refusal - } - policy.modes = (policy.modes ?? layout.generationModes).filter { !parity.modes.contains($0) } - policy.tensorParallelHeldForFeatures = parity.reason - } + let (parity, parityRefusal) = ClusterModeParity.apply(to: &policy, capability: capability, layout: layout, + forced: forced != nil) { try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: $0, link: link) } let result = try ClusterPlacementPlanner.plan(devices: devices, layout: layout, policy: policy, link: link) var lines = (forced.map(ClusterForcedModeSetting.lines) ?? []) + (benchCap.map(ClusterPlannerBenchCap.lines(capBytes:)) ?? []) + (benchChip.map(ClusterBenchChip.lines(chipName:)) ?? []) From 62fee42f1d7aef0feab2ee44d58126339c1ce291 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:59:29 -0800 Subject: [PATCH 0132/1441] Log Qwen TP decode routes once per load and check 27B rows at registered widths Each rank of a Qwen tensor-parallel pair now logs its decode routes once per loaded model when the native executor starts (qwen-tp-decode-census-v1): every projection's route (the batch-invariant kernel, a row-parallel FP32 partial on it, or MLX's own kernels with the reason) with each shape's layout per vector count, the residual-norm form, the paged attention geometry and partition size, the selection, and any arithmetic switch the launcher set. Host values only. QwenTensorParallelRowsCheck checks the row contract at the registered Qwen3.8-27B per-rank widths with random affine 4-bit weights (three Gated DeltaNet layers and one attention layer, the full 248,320-row vocabulary): a row's logits and history equal its run alone on a one- or eight-lane host, beside rows of 100 to 4,600 tokens that join and leave, across two KV segments, while an assistant observes the cohort, and at every position of a four-column verify window alone and in a cohort. It runs both ranks in one process (QwenTensorParallelRealGeometryRowsTests, QWEN_TP_REAL_GEOMETRY_GPU=1) and as two processes over the loopback ring (darkbloom-cluster-tp-check qwen-rows, native or sealed sums, with the worker's arithmetic environment). On an M5 Ultra every comparison is bitwise equal, so the plain c8 non-equality seen on the real pair does not reproduce synthetically; the census and the tool are for the real-pair and real-checkpoint runs that remain. No serving arithmetic changes. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-decode-loop.md | 9 + docs/architecture/inference.md | 33 +- .../TensorParallelCheck/QwenRowsCheck.swift | 72 ++++ .../TensorParallelCheck.swift | 6 + .../QwenTensorParallelBatchSession.swift | 85 +++++ ...wenTensorParallelNativeBatchExecutor.swift | 1 + .../QwenTensorParallelRowsCheck.swift | 341 ++++++++++++++++++ ...nTensorParallelRealGeometryRowsTests.swift | 97 +++++ 8 files changed, 642 insertions(+), 2 deletions(-) create mode 100644 changelog.d/qwen27-tp-decode-loop.md create mode 100644 libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRealGeometryRowsTests.swift diff --git a/changelog.d/qwen27-tp-decode-loop.md b/changelog.d/qwen27-tp-decode-loop.md new file mode 100644 index 0000000000..f4b70eb48e --- /dev/null +++ b/changelog.d/qwen27-tp-decode-loop.md @@ -0,0 +1,9 @@ +### Qwen tensor-parallel decode routes in the rank log + +- Each rank of a Qwen tensor-parallel pair logs its decode routes once per load + (`qwen-tp-decode-census-v1`): which projections take the batch-invariant + kernel and at which layout per row count, the attention and residual-norm + routes, and the arithmetic switches in force. +- `darkbloom-cluster-tp-check qwen-rows` checks, on one Mac over the loopback + ring, that a Qwen3.8-27B row decodes the same bytes alone, beside other rows + and in verify windows at the registered per-rank widths (random weights). diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..23b3c68647 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -5101,8 +5101,37 @@ the 27B, whose features keep it in tensor parallel, and an assistant quote bind placement to tensor parallel as before. Synthetic CPU and both-chip native fixtures are not full-artifact, RDMA, tower, throughput or endpoint evidence. +Each rank logs its decode routes once per loaded model when its native +executor starts (`qwen-tp-decode-census-v1`, +`QwenTensorParallelBatchSession.censusLine`): every projection's route (the +batch-invariant kernel `aqv`, a row-parallel FP32 partial on it `partial`, or +MLX's own kernels with the reason, `mlx-...`) and each projection shape's +layout per vector count (plain rows of one to eight and their four-column +windows), the residual-norm form, the paged attention geometry and partition +size, the selection, and any arithmetic switch the launcher set. A registered +27B rank reports `mlx=0`. Only host values are read; nothing is evaluated. + +`QwenTensorParallelRowsCheck` checks the row contract at the registered 27B +per-rank widths with random weights (affine 4-bit, group 64, BF16 scales, +biases and norms; three Gated DeltaNet layers and one attention layer; the +whole 248,320-row vocabulary): a row's logits and history equal its run alone, +on a one- or an eight-lane host, beside rows of 100 to 4,600 tokens that join +and leave, across two KV segments, while an assistant observes the cohort, and +at every position of a four-column verify window alone and in a cohort. Both +ranks run it in one process (`QwenTensorParallelRealGeometryRowsTests`, +`QWEN_TP_REAL_GEOMETRY_GPU=1`) or as two processes over the loopback ring +(`darkbloom-cluster-tp-check qwen-rows`, native or sealed sums, with the +worker's arithmetic environment); on an M5 Ultra every comparison is bitwise +equal. It covers neither the registered weights nor JACCL's streamed sealed +sums, the driver under live traffic or the HTTP stream; `qwen-rows run` also +loads a registered checkpoint directory on a Mac with the memory for it. + Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift` -(`QwenTensorParallelBatchSession`), +(`QwenTensorParallelBatchSession`, `censusLine`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift` +(`QwenTensorParallelRowsCheck`), +`libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift` +(`QwenRowsCheck`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift` (`serve`, `makePlan`, `join`, `leave`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Batch/QwenBatchDecodeCoalescing.swift` diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift new file mode 100644 index 0000000000..57ad341195 --- /dev/null +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift @@ -0,0 +1,72 @@ +import DarkbloomClusterRuntime +import Foundation +import MLX + +// Qwen3.8-27B rows at the registered per-rank widths on two ranks of one Mac +// (`QwenTensorParallelRowsCheck`): random weights, never a model pass. +// darkbloom-cluster-tp-check qwen-rows synthesize --output /DIR [--layers 4] +// MLX_RANK=0|1 MLX_HOSTFILE=hosts.json darkbloom-cluster-tp-check qwen-rows run --model-dir /DIR \ +// --report FILE [--backend ring|socket] [--reduction native|sealed-bench] +// Each rank compares its own digests (a row alone, in cohorts, across KV +// segments, observed, in verify windows) and both agree on the verdict. +enum QwenRowsCheck { + static func run(_ arguments: [String]) throws { + guard let command = arguments.first, ["synthesize", "run"].contains(command) else { + throw Failure("usage: darkbloom-cluster-tp-check qwen-rows synthesize|run ...") + } + var options: [String: String] = [:] + var index = 1 + while index < arguments.count { + guard arguments[index].hasPrefix("--"), index + 1 < arguments.count else { + throw Failure("qwen-rows: expected --name value pairs") + } + options[String(arguments[index].dropFirst(2))] = arguments[index + 1] + index += 2 + } + if command == "synthesize" { + guard let output = options["output"], output.hasPrefix("/") else { throw Failure("synthesize needs --output /DIR") } + let layers = Int(options["layers"] ?? "4") ?? 4 + guard (1...8).contains(layers) else { throw Failure("--layers takes 1 to 8") } + try Device.withDefaultDevice(.gpu) { + try QwenTensorParallelRowsCheck.writeCheckpoint(directory: URL(fileURLWithPath: output), layers: layers) + } + note("real-geometry checkpoint written (\(layers) layers)") + return + } + guard let directory = options["model-dir"], let reportPath = options["report"] else { + throw Failure("run needs --model-dir and --report") + } + guard let backend = QwenTensorParallelGroup.Backend(rawValue: options["backend"] ?? "ring"), backend != .jaccl else { + throw Failure("qwen-rows runs on the loopback ring or socket only") + } + let reduction = options["reduction"] ?? "native" + guard ["native", "sealed-bench"].contains(reduction) else { throw Failure("--reduction takes native or sealed-bench") } + let url = URL(fileURLWithPath: directory) + let configuration = try Data(contentsOf: url.appendingPathComponent("config.json")) + let group = try QwenTensorParallelGroup(backend: backend) + guard try group.digestsEqual(fnv(sha256Hex(configuration) + "|" + reduction)) else { + throw Failure("the ranks disagree on the checkpoint or the reduction") + } + if reduction == "sealed-bench" { + let codec = try QwenTensorParallelSealCodec.bench(group: group, + scope: Data(("darkbloom-tp-qwen-rows-v1|" + sha256Hex(configuration)).utf8)) + try codec.install() + group.sealed = codec + } + note("rank \(group.rank) of \(group.size) over \(backend.rawValue), \(reduction) sums") + let report = try Device.withDefaultDevice(.gpu) { () throws -> QwenTensorParallelRowsCheck.Report in + let model = try QwenTensorParallelModel.load(modelDirectory: url, role: .shard(rank: group.rank, size: 2), + reduction: group) + return try QwenTensorParallelRowsCheck.run(model: model, configuration: configuration, rank: group.rank) + } + let bothPassed = try group.exchangeIntegers([report.passed ? 1 : 0]) == [2] + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .prettyPrinted] + guard FileManager.default.createFile(atPath: reportPath, contents: try encoder.encode(report)) else { + throw Failure("could not write the report") + } + note("compared \(report.compared) digests, \(report.differing.count) differ\(report.differing.isEmpty ? "" : ": \(report.differing.prefix(8))");" + + " both ranks passed: \(bothPassed)") + guard bothPassed else { throw Failure("a rank found a row that differs from itself alone") } + } +} diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift index 23c7fad6aa..8fe4f9c905 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift @@ -22,6 +22,8 @@ import MLX // tensor parallel against one rank without a registered model; never a model pass) // darkbloom-cluster-tp-check record --rank0 FILE --rank1 FILE --reference FILE [--reference FILE] --model-dir DIR // --output FILE [--partials float32|bfloat16] [--near-tie-ulps U] (appends one qualification record line) +// darkbloom-cluster-tp-check qwen-rows synthesize|run ... (27B batch rows at the registered per-rank widths: +// each row against itself alone and in verify windows over the loopback ring; `QwenRowsCheck`) // // `full` is the unsharded model on one Mac (this code path's single-Mac // reference); `simulated` is the single-process tensor-parallel oracle (the @@ -521,6 +523,10 @@ enum CompareCommand { try QwenPrefillBench.run(Array(CommandLine.arguments.dropFirst(2))) return } + if CommandLine.arguments.count > 1, CommandLine.arguments[1] == "qwen-rows" { + try QwenRowsCheck.run(Array(CommandLine.arguments.dropFirst(2))) + return + } let options = try Options(Array(CommandLine.arguments.dropFirst())) let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys, .prettyPrinted] diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift index 5ff7bb411d..8f711e56f5 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift @@ -3,6 +3,7 @@ import Foundation import MLX import MLXLLM import MLXLMCommon +import MLXNN /// Input ownership is request-local. A media owner supplies its authenticated /// position slices and prompt embeddings; text keeps the cache's own offsets. @@ -291,6 +292,90 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { + " fenced_sums=\(sumsAreFencedInputs ? "on" : "off")" } + /// Vector counts the census describes: plain rows of one to eight, and + /// their four-column verify windows. + static let censusCounts = [1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 28, 32] + + /// The decode route of every projection of a loaded shard + /// (`qwen-tp-decode-census-v1`), so a pair's log shows what each row count + /// runs: the batch-invariant kernel (`aqv`), a row-parallel FP32 partial on + /// it (`partial`), or MLX's own kernels and why (`mlx-...`), with each + /// shape's layout per vector count (layouts never change a result), and + /// the attention, residual-norm and selection routes. Host only: no + /// array is evaluated. + static func censusLine(rank: Int, model: QwenTensorParallelModel) -> String { + var routes: [String: Int] = [:], layouts: [String: String] = [:], tally: [String: Int] = [:] + for (path, module) in model.model.leafModules().flattened() { + guard let linear = module as? Linear else { continue } + let name = path.split(separator: ".").last.map(String.init) ?? path + let (outputs, inputs) = linear.shape + let route: String + if let packed = linear as? QuantizedLinear { + let probe = MLXArray.zeros([1, inputs], dtype: .bfloat16) + let reason: String? + if !usesExactVectors { reason = "off" } + else if Device.defaultDevice().deviceType != .gpu { reason = "cpu" } + else if AffineQuantizedVectors.supports(input: probe, weight: packed.weight, scales: packed.scales, + biases: packed.biases, groupSize: packed.groupSize, bits: packed.bits, mode: packed.mode) { reason = nil } + else if packed.mode != .affine { reason = "mode" } + else if packed.biases == nil { reason = "biases" } + else { reason = "bits\(packed.bits)-group\(packed.groupSize)-\(packed.scales.dtype)" } + if packed is QwenTensorParallelRowLinear { + route = reason.map { "mlx-partial-\($0)" } ?? (packed.bias == nil ? "partial" : "mlx-partial-bias") + } else if type(of: packed) == QuantizedLinear.self { + route = reason.map { "mlx-\($0)" } ?? "aqv" + } else { + route = "mlx-subclass-\(type(of: packed))" + } + if !route.hasPrefix("mlx") { + var runs: [(String, Int, Int)] = [] + for count in censusCounts { + let layout = AffineQuantizedVectors.layout(vectors: count, inputs: inputs, outputs: outputs, + bits: packed.bits).description + if let last = runs.last, last.0 == layout { runs[runs.count - 1].2 = count } + else { runs.append((layout, count, count)) } + } + layouts["\(inputs)x\(outputs)"] = runs.map { "\($0.1 == $0.2 ? "\($0.1)" : "\($0.1)-\($0.2)")=\($0.0)" } + .joined(separator: "/") + } + } else { + route = "mlx-unquantized" + } + routes["\(name):\(inputs)x\(outputs):\(route)", default: 0] += 1 + tally[route.hasPrefix("mlx") ? "mlx" : route, default: 0] += 1 + } + let attention = Set(model.model.cbv2LayerKinds.map { kind -> String in + let gqa = kind.queryHeads / max(1, kind.kvHeads) + let hpt = PagedAttentionKernel.headsPerThreadgroup(headDim: kind.headDim, gqa: gqa) + return "d\(kind.headDim)-kv\(kind.kvHeads)-gqa\(gqa)-hpt\(hpt)" + }).sorted() + let environment = ProcessInfo.processInfo.environment + let switches = ["MLX_QMV_BATCH_INVARIANT", "MLX_ENABLE_TF32", "DARKBLOOM_QWEN35_FUSE_ELEMENTWISE", + "DARKBLOOM_QWEN35_DECODE_FUSIONS_V2", "DARKBLOOM_GDN_FUSED_CONV", "DARKBLOOM_GDN_FUSED_QK_NORM", + "DARKBLOOM_RESIDUAL_RMS_NORM", "DARKBLOOM_CBV2_PAGED_PTOK_TARGET", "DARKBLOOM_TTFT_GDN_BLOCKED"] + .compactMap { key in environment[key].map { "\(key)=\($0)" } } + let hidden = model.plan.hiddenSize + return "qwen-tp-decode-census-v1 rank=\(rank) exact_vectors=\(usesExactVectors ? "on" : "off")" + + " aqv=\(tally["aqv", default: 0]) partial=\(tally["partial", default: 0]) mlx=\(tally["mlx", default: 0])" + + " routes=" + routes.sorted { $0.key < $1.key }.map { "\($0.key)*\($0.value)" }.joined(separator: ",") + + " layouts=" + layouts.sorted { $0.key < $1.key }.map { "\($0.key):\($0.value)" }.joined(separator: ",") + + " swiglu_fused_vectors=" + censusCounts.filter { AffineQuantizedVectors.fusesSwiGLU(vectors: $0) } + .map(String.init).joined(separator: "/") + + " residual_rms_norm=\(ResidualRMSNorm.isEnabled && ResidualRMSNorm.verifiedFamilies.contains(AffineQuantizedVectors.family()) ? (hidden > 4096 ? "looped" : "single") : "off")" + + " attention=paged-\(attention.joined(separator: "/")) ptok=\(PagedAttentionKernel.partitionTokens)" + + " ptok_target=\(PagedAttentionKernel.partitionTargetThreadgroups)" + + " selection=greedy-rank-argmax/sampled-gather switches=" + (switches.isEmpty ? "none" : switches.joined(separator: ",")) + } + + private static let censusLock = NSLock() + nonisolated(unsafe) private static var censusModels = Set() + + /// Logs `censusLine` once per loaded model. + static func logCensusOnce(rank: Int, model: QwenTensorParallelModel) { + let first = censusLock.withLock { censusModels.insert(ObjectIdentifier(model)).inserted } + if first { log(censusLine(rank: rank, model: model)) } + } + static func decode(_ sessions: [QwenTensorParallelBatchSession], tokens: [Int], check: () throws -> Void) throws -> MLXArray { try decodeResult(sessions, tokens: tokens, capturingHidden: false, check: check).logits diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift index 2b21249f57..118de89de6 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift @@ -119,6 +119,7 @@ final class QwenTensorParallelNativeBatchExecutor Void) throws -> [Float] { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift new file mode 100644 index 0000000000..71cf13f782 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift @@ -0,0 +1,341 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +/// Qwen3.8-27B rows at the registered per-rank widths, for the row-count +/// gate before wider Qwen TP lanes: one rank's half of a check that a row's +/// logits and history are the same bytes alone (P1), beside rows of other +/// context lengths that join and leave (PB), while an assistant observes the +/// cohort, and at every position of a four-column verify window alone or in +/// a cohort (W). Both ranks run `run` in lock step (their reductions pair +/// them); each compares only its own digests. Random weights only (affine +/// 4-bit, group 64, BF16 scales, biases and norms, as the registered +/// artifact is quantized), never a model pass: the test suite runs it in one +/// process, `darkbloom-cluster-tp-check qwen-rows` over the loopback ring. +public enum QwenTensorParallelRowsCheck { + public struct Report: Codable, Sendable { + public var rank: Int + public var compared: Int + public var differing: [String] + public var reservedBytesAcrossSegments: Int + public var census: String + public var kernel: String + public var passed: Bool { differing.isEmpty && compared > 0 } + } + + /// The registered 27B text geometry at `layers` layers (three Gated + /// DeltaNet layers to one attention layer, as registered). + static func configuration(layers: Int) throws -> Data { + let text: [String: Any] = [ + "model_type": "qwen3_5_text", "hidden_size": 5120, "num_hidden_layers": layers, + "full_attention_interval": 4, "num_attention_heads": 24, "num_key_value_heads": 4, "head_dim": 256, + "linear_num_key_heads": 16, "linear_num_value_heads": 48, "linear_key_head_dim": 128, + "linear_value_head_dim": 128, "linear_conv_kernel_dim": 4, "intermediate_size": 17408, + "vocab_size": 248_320, "tie_word_embeddings": false, "attn_output_gate": true, "attention_bias": false, + "rms_norm_eps": 1e-6, "max_position_embeddings": 262_144, "partial_rotary_factor": 0.25, + "rope_parameters": ["mrope_interleaved": true, "mrope_section": [11, 11, 10], "partial_rotary_factor": 0.25, + "rope_theta": 10_000_000, "rope_type": "default"], + "layer_types": (0.. Void) throws { + let h = 5120, inter = 17408, vocabulary = 248_320, hq = 24, hkv = 4, hd = 256, nk = 16, nv = 48 + let lk = nk * 128, lv = nv * 128 + func key(_ name: String) -> MLXArray { + MLXRandom.key(name.utf8.reduce(UInt64(0xCBF2_9CE4_8422_2325)) { ($0 ^ UInt64($1)) &* 0x100_0000_01B3 }) + } + func q(_ name: String, _ out: Int, _ input: Int) throws { + let keys = MLXRandom.split(key: key(name), into: 2) + let scales = MLXRandom.uniform(low: Float(0.002), high: Float(0.02), [out, input / 64], key: keys[0]) + .asType(.bfloat16) + try keep(name + ".weight", MLXRandom.randInt(low: 0, high: Int32.max, [out, input / 8], key: keys[1]) + .asType(.uint32)) + try keep(name + ".scales", scales) + try keep(name + ".biases", (scales * -7.5).asType(.bfloat16)) + } + func norm(_ name: String, _ n: Int) throws { + try keep(name, MLXRandom.uniform(low: Float(0.9), high: Float(1.1), [n], key: key(name)).asType(.bfloat16)) + } + try q("language_model.model.embed_tokens", vocabulary, h) + try q("language_model.lm_head", vocabulary, h) + try norm("language_model.model.norm.weight", h) + for layer in 0.. [Int] { (0.. Int { (step * 15_485_863 + row * 32_452_843 + 7) % 248_320 } + + /// Context lengths across the decode kernels' partition and buffer + /// thresholds (256-token partitions; 1,024, 2,048 and 4,096 keys). + static let lengths: [Int: Int] = [0: 100, 1: 250, 2: 509, 3: 760, 4: 1020, 5: 1100, 6: 2045, 7: 4090] + /// Rows whose eight histories need more than one 64 MB segment of the + /// paged pool (2 KB a token a rank at four layers), so rows span segments. + static let longLengths: [Int: Int] = [10: 4100, 11: 4350, 12: 4600, 13: 4000, 14: 4500, 15: 4250, 16: 4096, 17: 4400] + + /// This rank's digests: logits by row and step (step -1: the prompt's + /// last logits) and history by row and decode count. + struct Trace { + var logits: [String: String] = [:] + var history: [String: String] = [:] + static func key(_ row: Int, _ step: Int) -> String { "\(row)/\(step)" } + + func mismatches(_ reference: Trace, label: String) -> [String] { + logits.keys.sorted().filter { key in reference.logits[key].map { $0 != logits[key] } ?? false } + .map { "\(label) logits \($0)" } + + history.keys.sorted().filter { key in reference.history[key].map { $0 != history[key] } ?? false } + .map { "\(label) history \($0)" } + } + } + + /// One rank's host and the sessions of the rows it holds. + final class Rows { + let model: QwenTensorParallelModel, configuration: Data, host: CBv2StageKVHost + var sessions: [Int: QwenTensorParallelBatchSession] = [:] + var trace = Trace() + init(_ model: QwenTensorParallelModel, configuration: Data, lanes: Int) throws { + self.model = model; self.configuration = configuration + host = try .init(model: model.model, kind: .paged, lanes: lanes, maximumTokensPerRequest: 8192, + maximumChunkTokens: 512) + } + + static func digest(_ value: MLXArray) -> String { eval(value); return sha256(value.asData(access: .copy).data) } + + func historyDigest(_ row: Int) throws -> String { + let session = sessions[row]! + var roots: [MLXArray] = [] + for row in session.state.rows.compactMap({ $0 }) { + let view = row.snapshot(); roots += [view.keys, view.values] + } + guard let recurrent = session.state.recurrent.confirmedStateSnapshot() else { + throw ProbeError("Qwen TP rows check: no confirmed recurrent state") + } + for index in recurrent.keys.sorted() { + guard let conv = recurrent[index]?.conv, let ssm = recurrent[index]?.ssm else { + throw ProbeError("Qwen TP rows check: a recurrent layer has no state") + } + roots += [conv, ssm] + } + eval(roots) + return sha256(Data(roots.map { sha256($0.asData(access: .copy).data) }.joined(separator: ",").utf8)) + } + + /// Opens `row` and prefills its prompt whole. + func open(_ row: Int, length: Int) throws { + let request = try QwenLayerStageGenerationRequest(profile: QwenTensorParallelRowsCheck.profile, requestID: UUID(), + promptTokenIDs: QwenTensorParallelRowsCheck.prompt(row, length: length), chunkSize: 512, outputCount: 48, + stopTokenIDs: []) + let session = try QwenTensorParallelBatchSession(model: model, configuration: configuration, host: host, + request: request) + sessions[row] = session + var last: MLXArray? + while session.schedule.committedPromptTokens < request.promptCount { last = try session.prefill(check: {}) } + guard let last else { throw ProbeError("Qwen TP rows check: the prompt returned no logits") } + trace.logits[Trace.key(row, -1)] = Self.digest(last) + } + + /// Plain steps: `schedule(step)` names the rows that decode (in that + /// order), a row's k-th decode feeding `token(row, k)`; `joins` open + /// rows before a step and `leaves` retire them after one. History is + /// taken after a row's last step, or after every step. + func plainSteps(lengths: [Int: Int], steps: Int, schedule: (Int) -> [Int], joins: [Int: [Int]] = [:], + leaves: [Int: [Int]] = [:], everyStep: Bool = false, observing: Bool = false) throws { + var taken: [Int: Int] = [:] + func history(_ row: Int) throws { trace.history[Trace.key(row, taken[row, default: 0])] = try historyDigest(row) } + for step in 0.. (outputs: [MLXArray], roots: [MLXArray]) in + if rows.count == 1 { + let built = try rows[0].beginWindow(tokens: flat, offset: rows[0].committedTokens) + eval(built.outputs + built.roots) + try rows[0].confirmWindow(check: {}) + eval(try rows[0].settleWindow(keeping: columns)) + try rows[0].confirmSettled(check: {}) + return built + } + let built = try QwenTensorParallelBatchSession.beginWindows(rows, tokens: flat) + eval(built.outputs + built.roots) + try QwenTensorParallelBatchSession.confirmWindows(rows, check: {}) + eval(try QwenTensorParallelBatchSession.settleWindows(rows, keeping: Array(repeating: columns, count: rows.count))) + try QwenTensorParallelBatchSession.confirmSettledWindows(rows, check: {}) + return built + } + for (position, row) in members.enumerated() { + for column in 0.. Report { + func rows(_ lanes: Int) throws -> Rows { try Rows(model, configuration: configuration, lanes: lanes) } + func solo(lanes: Int, members: [Int], lengths: [Int: Int], steps: Int) throws -> Trace { + var trace = Trace() + for row in members { + let alone = try rows(lanes) + try alone.open(row, length: lengths[row]!) + try alone.plainSteps(lengths: lengths, steps: steps, schedule: { _ in [row] }, everyStep: true) + try alone.retireAll() + trace.logits.merge(alone.trace.logits) { $1 }; trace.history.merge(alone.trace.history) { $1 } + } + return trace + } + var differing: [String] = [] + let members = lengths.keys.sorted() + let soloOne = try solo(lanes: 1, members: members, lengths: lengths, steps: steps) + differing += try solo(lanes: 8, members: members, lengths: lengths, steps: steps) + .mismatches(soloOne, label: "P1 eight-lane vs one-lane host") + + // Rows 6 and 7 join before steps 3 and 5; row 1 leaves after step 6. + let wide = try rows(8) + for row in [0, 1, 2, 3, 4, 5] { try wide.open(row, length: lengths[row]!) } + try wide.plainSteps(lengths: lengths, steps: steps + 5, schedule: { step in + members.filter { row in + let first = row == 6 ? 3 : row == 7 ? 5 : 0 + return step >= first && step - first < (row == 1 ? 7 : steps) + } + }, joins: [3: [6], 5: [7]], leaves: [6: [1]]) + try wide.retireAll() + differing += wide.trace.mismatches(soloOne, label: "PB8 vs P1") + for width in [2, 4] { + let narrow = try rows(width) + let cohort = Array(members.suffix(width)) + for row in cohort { try narrow.open(row, length: lengths[row]!) } + try narrow.plainSteps(lengths: lengths, steps: steps, schedule: { _ in cohort }) + try narrow.retireAll() + differing += narrow.trace.mismatches(soloOne, label: "PB\(width) vs P1") + } + + let long = longLengths.keys.sorted(), longSteps = 8 + let longSolo = try solo(lanes: 1, members: long, lengths: longLengths, steps: longSteps) + let spanning = try rows(8) + for row in long { try spanning.open(row, length: longLengths[row]!) } + let reserved = spanning.host.backend.bytesReserved + try spanning.plainSteps(lengths: longLengths, steps: longSteps, schedule: { _ in long }) + try spanning.retireAll() + differing += spanning.trace.mismatches(longSolo, label: "PB8 across segments vs P1") + + let windowed = [0, 2, 4, 7], columns = 4, rounds = 3 + let observer = try rows(windowed.count) + for row in windowed { try observer.open(row, length: lengths[row]!) } + try observer.plainSteps(lengths: lengths, steps: columns * rounds, schedule: { _ in windowed }, observing: true) + try observer.retireAll() + differing += observer.trace.mismatches(soloOne, label: "PB4 observed vs P1") + for row in windowed { + let single = try rows(1) + try single.open(row, length: lengths[row]!) + try single.windows([row], rounds: rounds, columns: columns) + try single.retireAll() + differing += single.trace.mismatches(soloOne, label: "W singleton vs P1") + differing += single.trace.mismatches(observer.trace, label: "W singleton vs PB4 observed") + } + let cohort = try rows(windowed.count) + for row in windowed { try cohort.open(row, length: lengths[row]!) } + try cohort.windows(windowed, rounds: rounds, columns: columns) + try cohort.retireAll() + differing += cohort.trace.mismatches(soloOne, label: "W cohort vs P1") + differing += cohort.trace.mismatches(observer.trace, label: "W cohort vs PB4 observed") + + let compared = soloOne.logits.count + soloOne.history.count + longSolo.logits.count + longSolo.history.count + var tampered = soloOne + tampered.logits[Trace.key(0, 0)] = "" + guard Set(soloOne.logits.values).count == soloOne.logits.count, reserved > CBv2StageKVHost.segmentBytes, + soloOne.mismatches(soloOne, label: "").isEmpty, tampered.mismatches(soloOne, label: "").count == 1 else { + throw ProbeError("Qwen TP rows check: degenerate logits, rows within one KV segment or a blind comparison") + } + return Report(rank: rank, compared: compared, differing: differing, reservedBytesAcrossSegments: reserved, + census: QwenTensorParallelBatchSession.censusLine(rank: rank, model: model), + kernel: QwenTensorParallelBatchSession.kernelLine(rank: rank, plan: model.plan)) + } +} diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRealGeometryRowsTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRealGeometryRowsTests.swift new file mode 100644 index 0000000000..1e4e797de1 --- /dev/null +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRealGeometryRowsTests.swift @@ -0,0 +1,97 @@ +import Foundation +import MLX +import MLXLMCommon +import Testing +@testable import DarkbloomClusterRuntime + +/// Qwen3.8-27B rows at the registered per-rank widths, both ranks in one +/// process (`QwenTensorParallelRowsCheck`): a row's logits and history are +/// the same bytes alone, beside rows of other context lengths that join and +/// leave, across KV segments, while an assistant observes the cohort, and at +/// every verify-window position. GPU-gated (`QWEN_TP_REAL_GEOMETRY_GPU=1`): +/// about 3 GB of random weights for both ranks. +@Suite(.serialized) +struct QwenTensorParallelRealGeometryRowsTests { + static var gpu: Bool { ProcessInfo.processInfo.environment["QWEN_TP_REAL_GEOMETRY_GPU"] == "1" } + + private final class Wire: @unchecked Sendable { + private let condition = NSCondition() + private var values: [Int: [Float]] = [:], shapes: [Int: [Int]] = [:] + private var result: [Float] = [] + private var generation = 0, leaving = 0 + func sum(_ input: MLXArray, rank: Int) -> MLXArray { + let value = input.asArray(Float.self) + condition.lock() + let deadline = Date().addingTimeInterval(300) + while leaving > 0 { precondition(condition.wait(until: deadline)) } + let entered = generation + precondition(values[rank] == nil) + values[rank] = value; shapes[rank] = input.shape + if values.count == 2 { + precondition(shapes[0] == shapes[1]) + result = zip(values[0]!, values[1]!).map(+); leaving = 2; condition.broadcast() + } else { + while leaving == 0 && generation == entered { precondition(condition.wait(until: deadline)) } + } + let output = result; leaving -= 1 + if leaving == 0 { values = [:]; shapes = [:]; result = []; generation += 1; condition.broadcast() } + condition.unlock() + return MLXArray(output, input.shape) + } + } + private final class Rank: QwenTensorParallelReduction, @unchecked Sendable { + let rank: Int, size = 2, wire: Wire + init(_ rank: Int, _ wire: Wire) { self.rank = rank; self.wire = wire } + func allSum(_ value: MLXArray) -> MLXArray { wire.sum(value, rank: rank) } + } + private final class Results: @unchecked Sendable { + private let lock = NSLock() + private(set) var reports: [QwenTensorParallelRowsCheck.Report?] = [nil, nil] + private(set) var failures: [Error?] = [nil, nil] + func record(_ rank: Int, _ outcome: Result) { + lock.withLock { + switch outcome { + case .success(let report): reports[rank] = report + case .failure(let error): failures[rank] = error + } + } + } + } + + @Test(.enabled(if: gpu)) + func rowsEqualTheirSoloStepsAndWindowPositionsAtRealWidths() throws { + let configuration = try QwenTensorParallelRowsCheck.configuration(layers: 4) + let wire = Wire() + let models = try (0..<2).map { rank in + try Device.withDefaultDevice(.gpu) { + try QwenTensorParallelModel.assemble(configurationData: configuration, + role: .shard(rank: rank, size: 2), reduction: Rank(rank, wire)) { _, keep in + try QwenTensorParallelRowsCheck.tensors(layers: 4, keep) + } + } + } + Memory.clearCache() + // Every decode projection takes the batch-invariant kernel: six and two row-parallel + // partials a Gated DeltaNet layer, five and two an attention layer, and the head. + let census = QwenTensorParallelBatchSession.censusLine(rank: 0, model: models[0]) + print("qwen27-real-geometry " + census) + #expect(census.contains(" aqv=24 partial=8 mlx=0 ")) + + let results = Results() + DispatchQueue.concurrentPerform(iterations: 2) { rank in + Device.withDefaultDevice(.gpu) { + results.record(rank, Result { + try QwenTensorParallelRowsCheck.run(model: models[rank], configuration: configuration, rank: rank) + }) + } + } + for failure in results.failures { if let failure { throw failure } } + for report in results.reports.compactMap({ $0 }) { + print("qwen27-real-geometry rank=\(report.rank) compared=\(report.compared)" + + " reserved=\(report.reservedBytesAcrossSegments) differing=\(report.differing.count)" + + " first=\(report.differing.prefix(12))") + #expect(report.passed) + } + #expect(results.reports.compactMap({ $0 }).count == 2) + } +} From 18586ab65ebc5f836e45d40f9e982c412d9c6732 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:05:19 -0800 Subject: [PATCH 0133/1441] cluster: keep Qwen TP prompt prefixes to the request's context Qwen tensor parallel kept at most one 4,096-token prompt-prefix boundary per request, so a repeated 33K-token prompt reused 4,096 tokens where one Mac reuses 32,768. Each plain lane now keeps, on its own 512-token chunk grid: the deepest whole chunk before the final token (a repeat), the one 64 tokens before the prompt end (the next turn, from 1,024 tokens on), and one Mac's 4,096-token stripe boundaries (a shared system prompt), the stripe doubling past eight (the SSD record's grid). - QwenTensorParallelPrefixCapture copies each kept boundary's recurrent state and the attention rows once, at the deepest; shallower states view that copy. The snapshot cache counts one capture's copy once and evicts as the pipeline's tier does (other captures' shallower boundaries, then the newest's, then whole captures). The sealed vote carries every grid boundary; both ranks restore or neither does. - Memory per the owner's decision: each request is charged its own capture; LOAD and the placement quote charge one capture of the profile's longest prompt per lane and no resident banks; the resident tier is half the room LOAD measures and gives way (SSD writer drained, then entries evicted) before the reservation or running-batch gate refuses, which no longer credits kept entries as the owner's own. - Every clean capture is written to the SSD tier; a record the tier cannot hold is restored once within the request's own charge. The record scope and the load agreement bind qwen-tp-batch-prefix-depth-v2, so records of the 4,096-token policy are never offered. - The assistant lanes keep their 4,096-token frontier: their trusted history stays unflushed to it. Co-Authored-By: Claude Opus 5.5 --- .../ClusterPlacementTensorBatchBudget.swift | 2 +- .../QwenTensorParallelBatchBudget.swift | 13 +- .../QwenTensorParallelBatchPrefixBudget.swift | 130 ++++++++-- .../QwenTensorParallelBatchMTPBudget.swift | 2 +- .../QwenTensorParallelBatchPrefixCache.swift | 139 +++++++++- .../QwenTensorParallelBatchSession.swift | 35 +-- .../QwenTensorParallelMTPBudget.swift | 2 +- .../QwenTensorParallelMTPPrefixBudget.swift | 34 ++- ...wenTensorParallelNativeBatchExecutor.swift | 75 +++--- .../QwenTensorParallelPrefixDisk.swift | 26 +- .../QwenTensorParallelPrefixSnapshot.swift | 129 ++++++++- .../QwenTensorParallelRequestCharge.swift | 9 +- ...nTensorParallelResidentRuntime+Batch.swift | 25 +- .../QwenTensorParallelResidentRuntime.swift | 36 ++- ...wenTensorParallelAssistantQuoteTests.swift | 3 +- .../QwenTensorParallelBatchBudgetTests.swift | 5 +- .../QwenTensorParallelBatchPrefixTests.swift | 245 ++++++++++++++++-- .../QwenTensorParallelBatchQuoteTests.swift | 3 +- .../QwenTensorParallelBatchSessionTests.swift | 8 +- ...QwenTensorParallelNativeContextTests.swift | 2 +- .../QwenTensorParallelPrefixDepthTests.swift | 240 +++++++++++++++++ ...enTensorParallelPrefixPlacementTests.swift | 156 +++++++++++ .../QwenTensorParallelRankLedgerTests.swift | 3 +- .../QwenTensorParallelRowQuoteTests.swift | 3 +- 24 files changed, 1151 insertions(+), 174 deletions(-) create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixDepthTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixPlacementTests.swift diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/ClusterPlacementTensorBatchBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/ClusterPlacementTensorBatchBudget.swift index 4280358057..4eaae6d8e6 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/ClusterPlacementTensorBatchBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/ClusterPlacementTensorBatchBudget.swift @@ -99,7 +99,7 @@ extension ClusterPlacementArtifact { try QwenTensorParallelBatchBudget.derive(geometry: family.geometry, plan: split, tensors: canonical, maximumTokens: family.profile.maximumContextTokens, chunkSize: family.profile.maximumChunkTokens, lanes: lanes, paged: true, rank: rank, - allocationBound: allocationBound) + promptTokens: family.profile.maximumPromptTokens, allocationBound: allocationBound) } let whole = try plain(plan, rank: nil) return try .init(request: request, lanes: lanes, chunkTokens: chunkTokens, diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift index fe86f41cf0..c209fcf26d 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift @@ -22,7 +22,7 @@ struct QwenTensorParallelBatchBudget { static func derive(geometry g: QwenLongPrefillBudgetGeometry, plan: QwenTensorParallelPlan, tensors: [QwenDenseCanonicalTensor], maximumTokens: Int, chunkSize: Int, - lanes: Int, paged: Bool, rank: Int? = nil, + lanes: Int, paged: Bool, rank: Int? = nil, promptTokens: Int? = nil, allocationBound: (Int) throws -> Int) throws -> Self { guard (1...8).contains(lanes) else { throw ProbeError("Qwen TP batch budget requires 1...8 lanes") @@ -69,10 +69,13 @@ struct QwenTensorParallelBatchBudget { } // Row-M1 partials cause a second live FP32 scales/offsets bank while // singleton/prefill's ConstantArrayCastCache retains its first bank. - // The rank's own columns of both banks, and prefix copies of its own - // heads; without a rank, full canonical bytes cover either rank. + // The rank's own columns of both banks, and each lane's prefix capture + // of its own heads (`promptTokens`: the profile's longest prompt, or a + // request's own); without a rank, full canonical bytes cover either + // rank. The prefix memory tier is not charged here. let prefix = try QwenTensorParallelBatchPrefixBudget.derive(geometry: local, - maximumTokens: maximumTokens, allocationBound: allocationBound) + maximumTokens: maximumTokens, promptTokens: promptTokens, chunkSize: chunkSize, + allocationBound: allocationBound) perLaneState = try sum([perLaneState, prefix.captureBytes]) let batchConstants = scalar.projectionConstantBytes let logits = try bound(product([lanes, plan.vocabularySize, 4]), count: 3) @@ -88,7 +91,7 @@ struct QwenTensorParallelBatchBudget { bound(product([plan.hiddenSize, 4]), count: lanes), ]) : 0) let shared = try sum([scalar.fusionBytes, transient, logits, - scalar.projectionConstantBytes, batchConstants, poolSlack, prefix.residentBytes, packing, promptGather]) + scalar.projectionConstantBytes, batchConstants, poolSlack, packing, promptGather]) // A one-token batch can gather more bytes than a short prompt frame. // Control limbs and retirement votes also travel in the sealed codec. let payload = max(scalar.allowance.maximumCollectivePayloadBytes, diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift index 996bc7d878..2d7f559e0f 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift @@ -1,34 +1,128 @@ import Foundation -/// Prefix copies are distinct from each lane's full live state and restore -/// workspace. Keep at most one original-grid frontier per lane, and two such -/// worst-case banks in the resident cache. The full unsliced geometry prices -/// either rank, including unequal shares. No shape estimate replaces LOAD's -/// canonical parameter quotation. +/// A tensor-parallel Qwen request's prompt-prefix capture and the boundaries +/// it keeps, on its own chunk grid, to the request's context. +/// +/// Kept boundaries (`frontiers`), each strictly before the prompt's final +/// token and after what the request restored: +/// - the deepest whole chunk before the final token (an exact repeat); +/// - the deepest whole chunk at least `promptEndMarginTokens` before the +/// prompt end, from `marginFloorTokens` on (the next turn of a +/// conversation, whose template re-renders the generation prompt; one +/// Mac's `demandedLatestPromptEndMarginTokens` cut); +/// - every multiple of `stripeTokens` (one Mac's dense-Qwen solo stripe, +/// `EngineV2Factory.defaultDenseQwenSoloPrefillStripeTokens`: the first, +/// fork-target and stripe-end checkpoints one Mac can keep), so a prompt +/// sharing only a long system prompt finds one. Past the first, the stripe +/// doubles until at most `maximumStripeBoundaries` remain, the SSD +/// record's grid (`QwenStagePrefixDiskTier.maximumGridFrontiers`), so they +/// are also written to the record and a capture keeps at most eleven +/// recurrent states. +/// +/// A capture copies the attention rows once, at its deepest kept boundary, +/// and the recurrent state at each kept boundary +/// (`QwenTensorParallelPrefixCapture`). Each request is charged its own +/// capture (`captureBytes(promptCount:chunkSize:)`); LOAD and the planner +/// charge one capture of the profile's longest prompt per lane. The memory +/// tier that keeps captures after their requests is charged nowhere: its +/// budget is half the room LOAD measures beside that charge +/// (`QwenStagePrefixCache.budget(roomBytes:)`), and its entries give way +/// before a reservation or a running batch is refused for memory. +/// +/// The geometry prices what it is given: a rank's own heads at LOAD, the +/// full unsliced model (either rank, any shares) in the planner. struct QwenTensorParallelBatchPrefixBudget { - static let maximumTokens = 4096 - static let policy = "qwen-tp-batch-grid-prefix-4096-v1" + static let policy = "qwen-tp-batch-prefix-depth-v2" + static let stripeTokens = 4096 + static let promptEndMarginTokens = 64 + static let marginFloorTokens = 1024 + static let maximumStripeBoundaries = 8 + + /// Boundaries deeper than this are neither voted nor kept: the owner's + /// longest request. let maximumTokens: Int + /// The per-lane LOAD term: one capture of the profile's longest prompt. let captureBytes: Int - let residentBytes: Int + /// What a request's own capture is priced on; nil keeps `captureBytes` + /// for every request (fixtures). + let geometry: QwenLongPrefillBudgetGeometry? + + init(maximumTokens: Int, captureBytes: Int, geometry: QwenLongPrefillBudgetGeometry? = nil) { + self.maximumTokens = maximumTokens; self.captureBytes = captureBytes; self.geometry = geometry + } - static func derive(geometry g: QwenLongPrefillBudgetGeometry, maximumTokens: Int, - allocationBound: (Int) throws -> Int) throws -> Self { - guard maximumTokens > 0 else { throw ProbeError("Invalid TP prefix context") } - let tokens = min(Self.maximumTokens, maximumTokens) - let b = try QwenLongPrefillTensorBudget.estimate(geometry: g, maximumTokens: tokens, chunkSize: 1) + /// The boundaries a request of `promptCount` tokens keeps, ascending. + static func frontiers(promptCount: Int, chunkSize: Int, restored: Int = 0, + maximumTokens: Int = .max) -> [Int] { + guard chunkSize > 0, promptCount > 1 else { return [] } + let limit = min(promptCount - 1, maximumTokens) + let deepest = limit / chunkSize * chunkSize + guard deepest > restored, deepest > 0 else { return [] } + var kept: Set = [deepest] + let margin = (promptCount - 1 - promptEndMarginTokens) / chunkSize * chunkSize + if margin >= marginFloorTokens, margin > restored, margin < deepest { kept.insert(margin) } + let first = (stripeTokens + chunkSize - 1) / chunkSize * chunkSize + if first > restored, first < deepest { kept.insert(first) } + var stripe = first + while (deepest - 1) / stripe > maximumStripeBoundaries { stripe *= 2 } + for boundary in Swift.stride(from: stripe, to: deepest, by: stripe) where boundary > restored { + kept.insert(boundary) + } + return kept.sorted() + } + + /// The recurrent states a capture whose deepest boundary is `deepest` + /// is charged: the deepest, a margin boundary whenever one can exist, and + /// every stripe boundary below it, at most `maximumStripeBoundaries + 1`. + /// At least what any prompt with that deepest boundary keeps, and never + /// fewer for a deeper one, so the charge grows with the prompt. + static func pricedStates(deepest: Int, chunkSize: Int) -> Int { + guard deepest > 0, chunkSize > 0 else { return 0 } + let first = (stripeTokens + chunkSize - 1) / chunkSize * chunkSize + let margin = (deepest - promptEndMarginTokens) / chunkSize * chunkSize >= marginFloorTokens ? 1 : 0 + return 1 + margin + min((deepest - 1) / first, maximumStripeBoundaries + 1) + } + + /// One capture of a prompt of `promptCount` tokens at the allocator's + /// bound: every attention layer's keys and values to its deepest kept + /// boundary, and every recurrent layer's convolution and SSM state for + /// `pricedStates`; 0 when it keeps none. + static func captureBytes(geometry g: QwenLongPrefillBudgetGeometry, promptCount: Int, chunkSize: Int, + maximumTokens: Int = .max, allocationBound: (Int) throws -> Int) throws -> Int { + guard let deepest = frontiers(promptCount: promptCount, chunkSize: chunkSize, maximumTokens: maximumTokens).last else { + return 0 + } + let states = pricedStates(deepest: deepest, chunkSize: chunkSize) let product = QwenLongPrefillCheckedBytes.product, sum = QwenLongPrefillCheckedBytes.sum + let b = try QwenLongPrefillTensorBudget.estimate(geometry: g, maximumTokens: 1, chunkSize: 1) func bound(_ bytes: Int, count: Int) throws -> Int { guard count > 0 else { return 0 } let allocated = try allocationBound(bytes) guard bytes > 0, allocated >= bytes else { throw ProbeError("Invalid TP prefix allocation bound") } return try product([allocated, count]) } - let capture = try sum([ - bound(b.convolutionBytesPerLayer, count: g.recurrentLayers), - bound(b.ssmBytesPerLayer, count: g.recurrentLayers), - bound(product([tokens, g.kvHeads, g.headDimension, 2]), count: 2 * g.attentionLayers), + return try sum([ + bound(product([deepest, g.kvHeads, g.headDimension, 2]), count: 2 * g.attentionLayers), + bound(b.convolutionBytesPerLayer, count: states * g.recurrentLayers), + bound(b.ssmBytesPerLayer, count: states * g.recurrentLayers), ]) - return try .init(maximumTokens: tokens, captureBytes: capture, residentBytes: product([capture, 2])) + } + + /// This request's own capture: priced on `geometry`, else `captureBytes`. + func captureBytes(promptCount: Int, chunkSize: Int, allocationBound: (Int) throws -> Int) throws -> Int { + guard let geometry else { return captureBytes } + return try Self.captureBytes(geometry: geometry, promptCount: promptCount, chunkSize: chunkSize, + maximumTokens: maximumTokens, allocationBound: allocationBound) + } + + /// LOAD's per-lane term: one capture of a `promptTokens` prompt (the + /// profile's longest; nil: the longest a `maximumTokens` request holds). + static func derive(geometry g: QwenLongPrefillBudgetGeometry, maximumTokens: Int, promptTokens: Int? = nil, + chunkSize: Int, allocationBound: (Int) throws -> Int) throws -> Self { + guard maximumTokens > 0, chunkSize > 0 else { throw ProbeError("Invalid TP prefix context") } + let prompt = min(promptTokens ?? maximumTokens - 1, maximumTokens - 1) + let capture = try captureBytes(geometry: g, promptCount: prompt, chunkSize: chunkSize, + allocationBound: allocationBound) + return .init(maximumTokens: maximumTokens, captureBytes: capture, geometry: g) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchMTPBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchMTPBudget.swift index 32eee0641e..a727ff0537 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchMTPBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchMTPBudget.swift @@ -32,7 +32,7 @@ struct QwenTensorParallelBatchMTPBudget { } let target = try QwenTensorParallelBatchBudget.derive(geometry: geometry, plan: plan, tensors: tensors, maximumTokens: maximumTokens, chunkSize: chunkSize, - lanes: lanes, paged: true, rank: rank, allocationBound: allocationBound) + lanes: lanes, paged: true, rank: rank, promptTokens: promptTokens, allocationBound: allocationBound) let local = try geometry.tensorParallelShard(plan: plan, rank: rank) // Every decode observation can leave a separately allocated one-token // root before this lane becomes singleton again. Ordinary observations diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift index 412ba72616..35b4f43852 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift @@ -4,6 +4,8 @@ import MLX /// Immutable compact roots; no snapshot refers to mutable native page storage. protocol QwenTensorParallelPrefixSnapshot { var committedTokens: Int { get } + /// Bytes this state holds alone. States inserted together as one capture + /// also view that capture's shared bytes, counted once for all of them. var allocatedBytes: Int { get } } @@ -20,23 +22,42 @@ struct QwenTensorParallelBatchPrefixState: QwenTensorParallelPrefixSnapshot { /// two-rank vote. Insertion happens after bilateral clean native retirement. typealias QwenTensorParallelBatchPrefixCache = QwenTensorParallelSnapshotCache +/// Retention is by byte budget, as the pipeline's `QwenStagePrefixCache`: +/// the owner sets it from the room it measures (`setBudget`), and a zero +/// budget keeps nothing resident while votes still count SSD records. One +/// capture's boundaries form a group: their shared attention copy is +/// counted once and freed with the group's last entry. Under the budget the +/// shallower boundaries of other captures go first (least recently used +/// first), then the newest capture's, then whole captures, so an exact +/// repeat's deepest boundary outlives every other. `yieldingMemory` frees +/// entries before a live memory gate refuses. final class QwenTensorParallelSnapshotCache { - static var maximumEntries: Int { 32 } + /// Entries and captures kept at most (the pipeline's limits); bytes bound first. + static var maximumEntries: Int { 1024 } + static var maximumGroups: Int { 64 } + /// Boundaries one vote carries at most (the deepest ones before the final token). + static var maximumVoted: Int { 512 } let enabled: Bool - let budgetBytes: Int - private struct Entry { let state: Snapshot; var lastUse: UInt64 } + private(set) var budgetBytes: Int + private struct Entry { let state: Snapshot; var lastUse: UInt64; let group: UInt64 } + private struct Group { let sharedBytes: Int; var entries: Int; let deepest: Int } private var entries: [String: Entry] = [:] + private var groups: [UInt64: Group] = [:] + private var nextGroup: UInt64 = 0 private var clock: UInt64 = 0 private(set) var bytesInUse = 0 + private(set) var evictions = 0 init(enabled: Bool, budgetBytes: Int) { - self.enabled = enabled && budgetBytes > 0; self.budgetBytes = max(0, budgetBytes) + self.enabled = enabled; self.budgetBytes = max(0, budgetBytes) } + /// Every boundary on the request's chunk grid before its final token, at + /// most `maximumTokens` deep (the deepest `maximumVoted` of them). static func candidates(promptCount: Int, chunkSize: Int, maximumTokens: Int) -> [Int] { guard promptCount > 1, chunkSize > 0, maximumTokens > 0 else { return [] } let last = min(promptCount - 1, maximumTokens) / chunkSize * chunkSize guard last > 0 else { return [] } - return Array(stride(from: chunkSize, through: last, by: chunkSize).suffix(maximumEntries)) + return Array(stride(from: chunkSize, through: last, by: chunkSize).suffix(maximumVoted)) } static func keys(scope: String, tokens: [Int], frontiers: [Int]) -> [Int: String] { QwenStagePrefixKeys.keys(scope: scope, tokens: tokens, frontiers: Set(frontiers)) @@ -61,16 +82,108 @@ final class QwenTensorParallelSnapshotCache Bool { - guard enabled, state.allocatedBytes > 0, state.allocatedBytes <= budgetBytes else { return false } - if let old = entries.removeValue(forKey: key) { bytesInUse -= old.state.allocatedBytes } - while entries.count >= Self.maximumEntries || bytesInUse > budgetBytes - state.allocatedBytes { - guard let key = entries.min(by: { $0.value.lastUse < $1.value.lastUse })?.key, - let old = entries.removeValue(forKey: key) else { break } - bytesInUse -= old.state.allocatedBytes + !insert([(key, state)], sharedBytes: 0).isEmpty + } + + /// One capture's states, viewing `sharedBytes` together. Returns the + /// boundaries kept: those that fit the budget with the deepest (none + /// when the deepest does not fit). + @discardableResult func insert(_ states: [(key: String, state: Snapshot)], sharedBytes: Int) -> [Int] { + // An attention-only state holds nothing of its own beside the shared copy. + let sorted = states.filter { $0.state.allocatedBytes >= 0 }.sorted { $0.state.committedTokens < $1.state.committedTokens } + guard enabled, let deepest = sorted.last, sharedBytes >= 0, sharedBytes + deepest.state.allocatedBytes > 0 else { return [] } + var total = sharedBytes + deepest.state.allocatedBytes + guard total <= budgetBytes else { return [] } + var chosen = [deepest] + for entry in sorted.dropLast().reversed() where total + entry.state.allocatedBytes <= budgetBytes { + total += entry.state.allocatedBytes; chosen.append(entry) } - clock &+= 1; entries[key] = .init(state: state, lastUse: clock); bytesInUse += state.allocatedBytes + for entry in chosen { if let old = entries[entry.key] { remove(entry.key, old) } } + let group = nextGroup; nextGroup &+= 1 + evict(reserving: total, adding: chosen.count) + for entry in chosen.reversed() { + clock &+= 1 + entries[entry.key] = .init(state: entry.state, lastUse: clock, group: group) + bytesInUse += entry.state.allocatedBytes + } + groups[group] = .init(sharedBytes: sharedBytes, entries: chosen.count, deepest: deepest.state.committedTokens) + bytesInUse += sharedBytes + return chosen.map(\.state.committedTokens).sorted() + } + + /// The owner's measured budget; entries beyond it go now. + func setBudget(_ bytes: Int) { budgetBytes = max(0, bytes); evict(reserving: 0, adding: 0) } + + /// Drops the next entry `victim` names; false when there is none. + @discardableResult func evictLeastRecentlyUsed() -> Bool { + guard let (key, entry) = victim() else { return false } + remove(key, entry); evictions += 1 return true } - func sweep() { entries.removeAll(); bytesInUse = 0 } + + /// Runs `check` (a live memory gate); while it refuses, first lets the + /// SSD writer finish what it holds, then drops entries one at a time and + /// returns their buffers. Only a refusal with nothing left to free throws. + func yieldingMemory(disk: QwenStagePrefixDiskTier?, _ check: () throws -> Void) throws { + var drained = disk == nil, evicted = 0 + while true { + do { + try check() + if evicted > 0 { log("darkbloom-prefix-v1 family=qwen mode=tensor_parallel pressure-evicted=\(evicted) entries=\(entries.count) admitted=true") } + return + } catch { + if !drained, let disk { + drained = true + _ = disk.drain(timeoutSeconds: 10) + } else if enabled, evictLeastRecentlyUsed() { + evicted += 1 + } else { + if evicted > 0 { log("darkbloom-prefix-v1 family=qwen mode=tensor_parallel pressure-evicted=\(evicted) entries=\(entries.count) admitted=false") } + throw error + } + Stream.gpu.synchronize() + Memory.clearCache() + } + } + } + + func sweep() { entries.removeAll(); groups.removeAll(); bytesInUse = 0 } + + /// Boundaries held now (tests and diagnostics). + var heldFrontiers: [Int] { entries.values.map(\.state.committedTokens).sorted() } + + private func remove(_ key: String, _ entry: Entry) { + entries.removeValue(forKey: key) + bytesInUse -= entry.state.allocatedBytes + guard var group = groups[entry.group] else { return } + group.entries -= 1 + if group.entries <= 0 { groups.removeValue(forKey: entry.group); bytesInUse -= group.sharedBytes } + else { groups[entry.group] = group } + } + + private func evict(reserving: Int, adding: Int) { + while groups.count + (adding > 0 ? 1 : 0) > Self.maximumGroups || entries.count + adding > Self.maximumEntries + || (bytesInUse > 0 && bytesInUse > budgetBytes - min(budgetBytes, reserving)), + let (key, entry) = victim() { + remove(key, entry); evictions += 1 + } + } + + /// The least recently used shallower boundary of a capture other than the + /// newest, then the newest capture's shallowest, then the least recently + /// used entry (a whole capture's deepest boundary). + private func victim() -> (String, Entry)? { + guard let newest = entries.values.max(by: { $0.lastUse < $1.lastUse })?.group else { return nil } + func shallow(_ entry: Entry) -> Bool { entry.state.committedTokens < (groups[entry.group]?.deepest ?? 0) } + let order: ((key: String, value: Entry), (key: String, value: Entry)) -> Bool = { + ($0.value.lastUse, $0.value.state.committedTokens) < ($1.value.lastUse, $1.value.state.committedTokens) + } + if let other = entries.filter({ $0.value.group != newest && shallow($0.value) }).min(by: order) { return (other.key, other.value) } + if let own = entries.filter({ $0.value.group == newest && shallow($0.value) }) + .min(by: { $0.value.state.committedTokens < $1.value.state.committedTokens }) { return (own.key, own.value) } + return entries.min(by: order).map { ($0.key, $0.value) } + } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift index 5ff7bb411d..55fa7cc000 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift @@ -23,10 +23,7 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { private var inputs: QwenTensorParallelBatchInputs? private var window: QwenTensorParallelTargetWindow? private var failed = false - private let captureFrontier: Int - private let captureLimitBytes: Int - private let allocationBound: (Int) throws -> Int - private var captured: QwenTensorParallelBatchPrefixState? + private let prefixCapture: QwenTensorParallelPrefixCapture? /// `frameTiming` only: this prompt's frames so far. private var promptClock: QwenTensorParallelPromptClock? private(set) var schedule: QwenLayerStageGenerationSchedule @@ -35,24 +32,20 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { init(model: QwenTensorParallelModel, configuration: Data, host: CBv2StageKVHost, request: QwenLayerStageGenerationRequest, inputs: QwenTensorParallelBatchInputs? = nil, - restored: QwenTensorParallelBatchPrefixState? = nil, captureFrontier: Int = 0, - captureLimitBytes: Int = 0, allocationBound: ((Int) throws -> Int)? = nil) throws { + restored: QwenTensorParallelBatchPrefixState? = nil, capture: QwenTensorParallelPrefixCapture? = nil) throws { guard case .shard(_, let ranks) = model.role, ranks == 2, sha256(configuration) == model.configurationSHA256, request.profile.hiddenSize == model.plan.hiddenSize, request.profile.vocabularySize == model.plan.vocabularySize, request.reusedPrefixTokens == (restored?.committedTokens ?? 0), request.reusedPrefixTokens % request.chunkSize == 0, - captureFrontier == 0 || (captureFrontier > request.reusedPrefixTokens - && captureFrontier < request.promptCount && captureFrontier % request.chunkSize == 0), - captureLimitBytes >= 0, captureFrontier == 0 || allocationBound != nil else { + capture?.fits(request) ?? true else { throw ProbeError("Qwen TP batch session requires a matching shard and original-grid state") } let geometry = try Self.geometry(model: model, configuration: configuration, host: host, maximumTokens: request.maximumTokens) self.model = model; self.request = request; self.inputs = inputs - self.captureFrontier = captureFrontier; self.captureLimitBytes = captureLimitBytes - self.allocationBound = allocationBound ?? { _ in throw ProbeError("Unpriced TP prefix capture") } + self.prefixCapture = capture // Paged pages grow with the request (`reservePages`); the reference // contiguous backend keeps its whole-length rows. let reserved = host.kind == .paged ? Self.initialReservedTokens(request) : nil @@ -194,7 +187,7 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { eval(hidden); try checked() } try schedule.commit(frame) - if committedTokens == captureFrontier { try capturePrefix(check: checked) } + try prefixCapture?.capture(state, at: committedTokens, check: checked) if let timing, case .shard(let rank, _) = model.role { let clock = promptClock ?? QwenTensorParallelPromptClock() promptClock = clock @@ -473,18 +466,16 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { } } - private func capturePrefix(check: () throws -> Void) throws { - guard captured == nil else { throw ProbeError("Qwen TP prefix is already captured") } - captured = try .capture(state: state, frontier: captureFrontier, limitBytes: captureLimitBytes, - allocationBound: allocationBound, check: check) - } - - func takeCapturedPrefix() throws -> QwenTensorParallelBatchPrefixState? { + /// The kept boundaries' states and the attention copy they share, once, + /// after native retirement. + func takeCapturedPrefix() throws -> (states: [QwenTensorParallelBatchPrefixState], sharedBytes: Int)? { guard retired && state.isClosed else { throw ProbeError("Qwen TP prefix donation precedes native retirement") } - defer { captured = nil } - return captured + guard let prefixCapture else { return nil } + defer { prefixCapture.discard() } + let states = prefixCapture.states() + return states.isEmpty ? nil : (states, prefixCapture.sharedBytes) } - func discardCapturedPrefix() { captured = nil } + func discardCapturedPrefix() { prefixCapture?.discard() } func retire() throws { guard !retired else { return } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPBudget.swift index f30c1ee720..c7be961630 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPBudget.swift @@ -68,7 +68,7 @@ struct QwenTensorParallelMTPBudget { // prompt stays one rectangle, as before. let chunks = (promptTokens + chunkSize - 1) / chunkSize let decodeRoots = min(flushRows ?? 0, maximumTokens) - let checkpointRows = min(QwenTensorParallelBatchPrefixBudget.maximumTokens, maximumTokens) + let checkpointRows = min(QwenTensorParallelMTPPrefixBudget.maximumTokens, maximumTokens) let heldRows = flushRows.map { $0 >= promptTokens ? promptTokens : min(promptTokens, max(checkpointRows, $0 + chunkSize + 1)) } ?? promptTokens diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefixBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefixBudget.swift index 4c7009455b..b454998de2 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefixBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefixBudget.swift @@ -3,31 +3,45 @@ import Foundation /// Compact target and assistant capture has a distinct live bank and two /// resident banks. Full live pages, trusted history, restore destinations and /// first-draft prompt workspace stay in the ordinary complete MTP quotation. +/// +/// The assistant keeps one original-grid frontier per lane, at most +/// `maximumTokens` deep: its prompt history is held unflushed up to that +/// frontier (`QwenTensorParallelMTPBudget`'s checkpoint rows), so a deeper +/// frontier is a larger trusted-history bank in every assisted lane, not +/// only a larger capture. The plain lanes keep theirs to the request's +/// context (`QwenTensorParallelBatchPrefixBudget`). struct QwenTensorParallelMTPPrefixBudget { static let policy = "qwen-tp-mtp-grid-prefix-4096-v1" + static let maximumTokens = 4096 let maximumTokens: Int let targetCaptureBytes: Int let assistantCaptureBytes: Int let captureBytes: Int let residentBytes: Int - static func derive(geometry: QwenLongPrefillBudgetGeometry, maximumTokens: Int, + static func derive(geometry g: QwenLongPrefillBudgetGeometry, maximumTokens: Int, allocationBound: (Int) throws -> Int) throws -> Self { - let target = try QwenTensorParallelBatchPrefixBudget.derive(geometry: geometry, - maximumTokens: maximumTokens, allocationBound: allocationBound) + guard maximumTokens > 0 else { throw ProbeError("Invalid TP prefix context") } + let count = min(Self.maximumTokens, maximumTokens) let product = QwenLongPrefillCheckedBytes.product, sum = QwenLongPrefillCheckedBytes.sum - func bound(_ bytes: Int) throws -> Int { + let b = try QwenLongPrefillTensorBudget.estimate(geometry: g, maximumTokens: count, chunkSize: 1) + func bound(_ bytes: Int, count: Int = 1) throws -> Int { + guard count > 0 else { return 0 } let result = try allocationBound(bytes) guard bytes > 0, result >= bytes else { throw ProbeError("Qwen TP MTP prefix allocator bound differs") } - return result + return try product([result, count]) } - let count = target.maximumTokens + let target = try sum([ + bound(b.convolutionBytesPerLayer, count: g.recurrentLayers), + bound(b.ssmBytesPerLayer, count: g.recurrentLayers), + bound(product([count, g.kvHeads, g.headDimension, 2]), count: 2 * g.attentionLayers), + ]) let assistant = count < 2 ? 0 : try sum([ - bound(product([count - 1, geometry.hiddenSize, 2])), - bound(product([count - 1, 4])), bound(product([geometry.hiddenSize, 2])), + bound(product([count - 1, g.hiddenSize, 2])), + bound(product([count - 1, 4])), bound(product([g.hiddenSize, 2])), ]) - let capture = try sum([target.captureBytes, assistant]) - return try .init(maximumTokens: count, targetCaptureBytes: target.captureBytes, + let capture = try sum([target, assistant]) + return try .init(maximumTokens: count, targetCaptureBytes: target, assistantCaptureBytes: assistant, captureBytes: capture, residentBytes: product([capture, 2])) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift index 2b21249f57..433134bf15 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift @@ -9,7 +9,8 @@ final class QwenTensorParallelNativeBatchLane: QwenTensorParallelBatchLane { var accepted = QwenTensorParallelAcceptedSelections() var selectedCount = 0 var canSelectNext: Bool { !accepted.isEmpty || nextFrame?.phase == .decode } - var prefixKey: String? + /// The keys of the boundaries this request captures, by boundary. + var prefixKeys: [Int: String] = [:] /// This request's scope on the SSD tier, kept for its persist after a /// confirmed clean retirement. var prefixDiskScope: String? @@ -147,7 +148,8 @@ final class QwenTensorParallelNativeBatchExecutor agreed.frontier { captureFrontier = last; captureKey = keys[last] } + if let last = candidates.last, last > agreed.frontier, let key = keys[last] { + captureFrontier = last; captureKeys = [last: key] + } } } else if admittedAssistant == nil, let prefix, prefix.enabled, let budget = prefixBudget, let scope = prefixScope?(reservation), let allocationBound { @@ -185,14 +189,18 @@ final class QwenTensorParallelNativeBatchExecutor agreed.frontier { - captureFrontier = last; captureKey = keys[last] - } + } + // The boundaries this request keeps after what it restored, within its own charged capture. + let frontiers = QwenTensorParallelBatchPrefixBudget.frontiers(promptCount: request.promptCount, + chunkSize: request.chunkSize, restored: request.reusedPrefixTokens, maximumTokens: budget.maximumTokens) + if !frontiers.isEmpty { + captureKeys = QwenTensorParallelBatchPrefixCache.keys(scope: scope, tokens: request.promptTokenIDs, frontiers: frontiers) + capture = .init(frontiers: frontiers, limitBytes: try budget.captureBytes(promptCount: request.promptCount, + chunkSize: request.chunkSize, allocationBound: allocationBound), allocationBound: allocationBound) } } let lane = try Lane(.init(model: model, configuration: configuration, host: host, - request: request, inputs: inputs, restored: restored, captureFrontier: admittedAssistant == nil ? captureFrontier : 0, - captureLimitBytes: prefixBudget?.captureBytes ?? 0, allocationBound: allocationBound), + request: request, inputs: inputs, restored: restored, capture: admittedAssistant == nil ? capture : nil), releaseResources: { [releaseResources] in try releaseResources(reservation) }) // Keep custody before assistant checkpoint restoration can allocate. // If opening throws, the driver's existing discard path retires this @@ -203,7 +211,7 @@ final class QwenTensorParallelNativeBatchExecutor( cache: QwenTensorParallelSnapshotCache, candidates: [Int], keys: [Int: String], diskScope: String?, prompt: [Int], check: () throws -> Void, read: (QwenStagePrefixState) throws -> Snapshot? @@ -247,9 +256,13 @@ final class QwenTensorParallelNativeBatchExecutor String { - QwenStagePrefixDiskTier.planScope( - planFingerprint: [planFingerprint, plan.name, "shares=" + plan.shares.map(String.init).joined(separator: ":")] - .joined(separator: "|"), + let fields = planScopeFields(planFingerprint: planFingerprint, planName: plan.name, shares: plan.shares, + assistantPolicy: assistantPolicy) + return QwenStagePrefixDiskTier.planScope(planFingerprint: fields.planFingerprint, artifactAggregateSHA256: artifactAggregateSHA256, storageCommitmentSHA256: storageCommitmentSHA256, - rankBuildSHA256: rankBuildSHA256, generationMode: "tensor_parallel_v1", - prefillSchedule: "serial|assistant=" + (assistantPolicy ?? "none")) + rankBuildSHA256: rankBuildSHA256, generationMode: "tensor_parallel_v1", prefillSchedule: fields.prefillSchedule) + } + + /// The plan's and the prompt policy's parts of `planScope`. + static func planScopeFields(planFingerprint: String, planName: String, shares: [Int], assistantPolicy: String?) + -> (planFingerprint: String, prefillSchedule: String) { + ([planFingerprint, planName, "shares=" + shares.map(String.init).joined(separator: ":")].joined(separator: "|"), + "serial|assistant=" + (assistantPolicy ?? "none") + "|prefix=" + QwenTensorParallelBatchPrefixBudget.policy) } /// A request scope on disk: the persistent plan scope plus the request's diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefixSnapshot.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefixSnapshot.swift index 714fc8ef43..9a4d849761 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefixSnapshot.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefixSnapshot.swift @@ -10,14 +10,123 @@ extension QwenTensorParallelBatchPrefixState { throw ProbeError("Qwen TP prefix capture frontier differs") } try state.requireOpen() + let attention = try QwenTensorParallelPrefixCapture.attentionRows(state, frontier: captureFrontier) + let recurrent = try QwenTensorParallelPrefixCapture.recurrentState(state) + let roots = attention.values.flatMap { [$0.keys, $0.values] } + recurrent.values.flatMap { [$0.conv, $0.ssm] } + let allocated = try QwenTensorParallelPrefixCapture.bounded(roots, allocationBound) + guard allocated <= captureLimitBytes else { return nil } + let copies = (attention: attention.mapValues { (keys: copy($0.keys), values: copy($0.values)) }, + recurrent: recurrent.mapValues { (conv: copy($0.conv), ssm: copy($0.ssm)) }) + eval(copies.attention.values.flatMap { [$0.keys, $0.values] } + copies.recurrent.values.flatMap { [$0.conv, $0.ssm] }) + try check() + return .init(committedTokens: captureFrontier, attention: copies.attention, recurrent: copies.recurrent, + allocatedBytes: allocated) + } +} + +/// An eager copy with its own storage: later ring or page writes cannot reach it. +private func copy(_ value: MLXArray) -> MLXArray { value * MLXArray(1).asType(value.dtype) } + +/// One plain lane's prompt-prefix capture on a tensor-parallel Qwen rank: +/// the boundaries it keeps (`QwenTensorParallelBatchPrefixBudget.frontiers`), +/// within the request's own charged capture. Each kept boundary's +/// convolution and SSM state is copied when the prompt reaches it; the +/// attention rows are copied once, at the deepest boundary, and every +/// shallower state views their first rows. A boundary whose state does not +/// fit the limit beside the deepest's is not kept (the shallowest go first); +/// nothing is kept when the deepest alone does not fit. +final class QwenTensorParallelPrefixCapture { + let frontiers: [Int] + let limitBytes: Int + private let allocationBound: (Int) throws -> Int + private var kept: Set? + private var recurrent: [Int: [Int: (conv: MLXArray, ssm: MLXArray)]] = [:] + private var recurrentBytes: [Int: Int] = [:] + private var deepest: (committed: Int, rows: [Int: (keys: MLXArray, values: MLXArray)], bytes: Int)? + + init(frontiers: [Int], limitBytes: Int, allocationBound: @escaping (Int) throws -> Int) { + self.frontiers = Array(Set(frontiers.filter { $0 > 0 })).sorted() + self.limitBytes = max(0, limitBytes); self.allocationBound = allocationBound + } + + /// Whether every boundary is one a request of `request` reaches on its own grid after its restored prefix. + func fits(_ request: QwenLayerStageGenerationRequest) -> Bool { + frontiers.allSatisfy { $0 > request.reusedPrefixTokens && $0 < request.promptCount && $0 % request.chunkSize == 0 } + } + + /// After the prompt frame that committed `frontier` (`state` is the request's). + func capture(_ state: CBv2OwnedRequestState, at frontier: Int, check: () throws -> Void) throws { + guard frontiers.contains(frontier) else { return } + guard state.committedTokens == frontier else { throw ProbeError("Qwen TP prefix capture frontier differs") } + try state.requireOpen() + let last = frontiers.last! + if kept == nil { + // Measured at the first boundary reached: the deepest boundary's + // rows grow by whole positions from these; a recurrent state is + // the same size at every boundary. + let rows = try Self.attentionRows(state, frontier: frontier) + let state0 = try Self.recurrentState(state) + let perBoundary = try Self.bounded(state0.values.flatMap { [$0.conv, $0.ssm] }, allocationBound) + let deepestRows = try QwenLongPrefillCheckedBytes.sum(rows.values.flatMap { [$0.keys, $0.values] }.map { + try allocationBound($0.nbytes / frontier * last) + }) + let base = try QwenLongPrefillCheckedBytes.sum([deepestRows, perBoundary]) + if base > limitBytes { kept = [] } else { + let more = perBoundary > 0 ? (limitBytes - base) / perBoundary : frontiers.count + kept = Set(frontiers.dropLast().suffix(max(0, more))).union([last]) + } + } + guard kept?.contains(frontier) == true else { return } + let own = try Self.recurrentState(state).mapValues { (conv: copy($0.conv), ssm: copy($0.ssm)) } + eval(own.values.flatMap { [$0.conv, $0.ssm] }) + try check() + recurrent[frontier] = own + recurrentBytes[frontier] = try Self.bounded(own.values.flatMap { [$0.conv, $0.ssm] }, allocationBound) + guard frontier == last else { return } + let rows = try Self.attentionRows(state, frontier: frontier).mapValues { (keys: copy($0.keys), values: copy($0.values)) } + eval(rows.values.flatMap { [$0.keys, $0.values] }) + try check() + deepest = (frontier, rows, try Self.bounded(rows.values.flatMap { [$0.keys, $0.values] }, allocationBound)) + } + + /// The kept boundaries' states, ascending, each viewing the deepest + /// boundary's one copy of the attention rows (`sharedBytes`) and holding + /// its own recurrent state (`allocatedBytes`); empty unless the deepest + /// was reached. + func states() -> [QwenTensorParallelBatchPrefixState] { + guard let deepest else { return [] } + return recurrent.keys.sorted().compactMap { frontier in + guard frontier <= deepest.committed, let own = recurrent[frontier], let bytes = recurrentBytes[frontier] else { return nil } + let rows = deepest.rows.mapValues { pair -> (keys: MLXArray, values: MLXArray) in + frontier == deepest.committed ? pair + : (keys: pair.keys[0..., 0..., 0 ..< frontier, 0...], values: pair.values[0..., 0..., 0 ..< frontier, 0...]) + } + return .init(committedTokens: frontier, attention: rows, recurrent: own, allocatedBytes: bytes) + } + } + + /// The attention copy the kept states view together. + var sharedBytes: Int { deepest?.bytes ?? 0 } + + /// Everything this capture holds now. + var heldBytes: Int { sharedBytes + recurrentBytes.values.reduce(0, +) } + + func discard() { recurrent.removeAll(); recurrentBytes.removeAll(); deepest = nil } + + static func attentionRows(_ state: CBv2OwnedRequestState, frontier: Int) throws -> [Int: (keys: MLXArray, values: MLXArray)] { var attention: [Int: (keys: MLXArray, values: MLXArray)] = [:] for (row, kind) in zip(state.rows, state.geometry.kinds) { guard let row, let index = kind.modelLayerIndex else { throw ProbeError("Qwen TP capture lacks an attention row") } let value = row.snapshot() - guard value.offset == captureFrontier, value.keys.dim(2) == captureFrontier, - value.values.dim(2) == captureFrontier else { throw ProbeError("Qwen TP capture attention frontier differs") } + guard value.offset == frontier, value.keys.dim(2) == frontier, value.values.dim(2) == frontier else { + throw ProbeError("Qwen TP capture attention frontier differs") + } attention[index] = (value.keys, value.values) } + return attention + } + + static func recurrentState(_ state: CBv2OwnedRequestState) throws -> [Int: (conv: MLXArray, ssm: MLXArray)] { let confirmed = state.recurrent.confirmedStateSnapshot() ?? [:] var recurrent: [Int: (conv: MLXArray, ssm: MLXArray)] = [:] for layer in state.geometry.recurrent.layers { @@ -26,20 +135,14 @@ extension QwenTensorParallelBatchPrefixState { } recurrent[layer.modelLayerIndex] = (conv, ssm) } - let roots = attention.values.flatMap { [$0.keys, $0.values] } + recurrent.values.flatMap { [$0.conv, $0.ssm] } - let allocated = try QwenLongPrefillCheckedBytes.sum(roots.map { + return recurrent + } + + static func bounded(_ roots: [MLXArray], _ allocationBound: (Int) throws -> Int) throws -> Int { + try QwenLongPrefillCheckedBytes.sum(roots.map { let bytes = try allocationBound($0.nbytes) guard bytes >= $0.nbytes, $0.nbytes > 0 else { throw ProbeError("Qwen TP prefix allocation bound differs") } return bytes }) - guard allocated <= captureLimitBytes else { return nil } - func copy(_ value: MLXArray) -> MLXArray { value * MLXArray(1).asType(value.dtype) } - attention = attention.mapValues { (copy($0.keys), copy($0.values)) } - recurrent = recurrent.mapValues { (copy($0.conv), copy($0.ssm)) } - eval(attention.values.flatMap { [$0.keys, $0.values] } + recurrent.values.flatMap { [$0.conv, $0.ssm] }) - try check() - return .init(committedTokens: captureFrontier, attention: attention, recurrent: recurrent, - allocatedBytes: allocated) } - } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRequestCharge.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRequestCharge.swift index eb8b047508..e1adaa6745 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRequestCharge.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRequestCharge.swift @@ -14,13 +14,14 @@ import MLX /// assistant `QwenTensorParallelBatchMTPBudget`), at the request's context /// instead of the memory plan's: /// - the lane's own state: its KV pages (this rank's heads, BF16), the -/// replacement pages, recurrent state, prefix capture and, with the -/// assistant, its history and gathers; +/// replacement pages, recurrent state, its own prompt's prefix capture +/// (`QwenTensorParallelBatchPrefixBudget`) and, with the assistant, its +/// history and gathers; /// - the workspaces every lane shares, at the longest context any held /// request has and never below LOAD's: the full-history gather bank of one /// prompt frame (the batch driver runs at most one a step), the frame's /// attention scores and the decode and verify transients grow with the -/// context; the pool slack, logits, casts and prefix banks do not. +/// context; the pool slack, logits and casts do not. /// /// The pages themselves grow with the request (`CBv2OwnedRequestState.growReservation`); /// the charge is the whole request's, admitted once at reservation and held @@ -57,7 +58,7 @@ struct QwenTensorParallelRequestCharge { } else { let quote = try QwenTensorParallelBatchBudget.derive(geometry: geometry, plan: plan, tensors: tensors, maximumTokens: maximumTokens, chunkSize: chunkSize, lanes: lanes, paged: paged, rank: rank, - allocationBound: allocationBound) + promptTokens: promptTokens, allocationBound: allocationBound) lane = quote.perLaneStateBytes; shared = quote.sharedBytesExcludingCollectives } return .init(laneBytes: lane, sharedBytes: max(loadSharedBytes, shared)) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime+Batch.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime+Batch.swift index 1aa2837bbf..906a1f0082 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime+Batch.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime+Batch.swift @@ -76,9 +76,12 @@ extension QwenTensorParallelResidentRuntime { throw ProbeError("Qwen TP batch reservation of \(request.maximumTokens) context tokens exceeds its owner ceiling") } // Gate the entire future state before constructing positions, - // pixels, features, cache rows or request samplers' native graphs. - try requireBatchMemory(extraState: laneBytes, extraShared: charge.sharedBytes, - extraNative: mediaBudget?.nativeBytes ?? 0, extraHost: mediaBudget?.hostBytes ?? 0, entering: true) + // pixels, features, cache rows or request samplers' native graphs; + // kept prefix entries give way first. + try yieldingPrefixMemory { + try requireBatchMemory(extraState: laneBytes, extraShared: charge.sharedBytes, + extraNative: mediaBudget?.nativeBytes ?? 0, extraHost: mediaBudget?.hostBytes ?? 0, entering: true) + } let media: QwenMediaRequestWork? if let envelope = value.qwenMedia, let budget = mediaBudget, let visionInventory { media = try .init(state: .init(media: envelope, prompt: request.promptTokenIDs, @@ -116,11 +119,20 @@ extension QwenTensorParallelResidentRuntime { } public var hasStartedLanes: Bool { batchBook.hasStarted } + /// `check` (a live memory gate), with the plain lanes' kept prefix + /// entries giving way first: the SSD writer's queue drains, then entries + /// go one at a time (`QwenTensorParallelSnapshotCache.yieldingMemory`). + private func yieldingPrefixMemory(_ check: () throws -> Void) throws { + guard let batchPrefix else { return try check() } + try batchPrefix.yieldingMemory(disk: prefixDisk?.tier, check) + } + /// Full named future charge minus allocations already made by this sole /// native owner; retained casts/fusion and materialized pages are not charged /// twice in the allocator ceiling. Host media keeps its separate full bound. /// The shared workspaces are held once, at the longest context any held - /// (or entering) request has: LOAD's within the memory plan. + /// (or entering) request has: LOAD's within the memory plan. The plain + /// lanes' kept prefix entries are in no charge, so they are not credited. private func requireBatchMemory(extraState: Int = 0, extraShared: Int = 0, extraNative: Int = 0, extraHost: Int = 0, entering: Bool = false) throws { guard batchBudget != nil else { throw ProbeError("Qwen TP batch LOAD quote is missing") } @@ -130,8 +142,9 @@ extension QwenTensorParallelResidentRuntime { let native = try sum([shared, requestCharge.collectiveScratchBytes, sum(held.map(\.laneStateBytes)), sum(held.map { $0.media?.budget.nativeBytes ?? 0 }), extraState, extraNative]) let host = try sum([sum(held.map { $0.media?.budget.hostBytes ?? 0 }), extraHost]) + let kept = batchPrefix?.bytesInUse ?? 0 let remaining = try QwenResidentRequestAllowance.continuingRequirement(reservedBytes: native, - additionalBytes: 0, grownBytes: max(0, Memory.activeMemory - batchAllocationBaseline)) + additionalBytes: 0, grownBytes: max(0, Memory.activeMemory - batchAllocationBaseline - kept)) try QwenResidentResourceEnvironment.requirePower() let os = try QwenDenseStageLoadResources.observeOS() let free = try sum([remaining, host, entering ? QwenDenseStageLoadPolicy.loadingHeadroomBytes : 0]) @@ -223,7 +236,7 @@ extension QwenTensorParallelResidentRuntime { try error.check(); try self.control.check() let now = DispatchTime.now().uptimeNanoseconds if lastResourceCheck == 0 || now - lastResourceCheck >= 250_000_000 { - try self.requireBatchMemory(); lastResourceCheck = now + try self.yieldingPrefixMemory { try self.requireBatchMemory() }; lastResourceCheck = now } try error.check() }) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift index 88a70fcc69..571651c16b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift @@ -38,9 +38,12 @@ import MLXVLM /// and the output count are known to both ranks and end both at once. /// /// Prompt prefixes: each rank keeps its own heads' state at chunk boundaries, -/// resident and on its SSD tier (`QwenTensorParallelBatchPrefixCache`); a -/// request restores the longest boundary BOTH ranks hold (one sealed vote), or -/// neither restores. +/// to the request's context, resident and on its SSD tier +/// (`QwenTensorParallelBatchPrefixCache`, `QwenTensorParallelBatchPrefixBudget`); +/// a request restores the longest boundary BOTH ranks hold (one sealed vote), +/// or neither restores. Each request is charged its own capture; the +/// resident tier's budget is half the room measured at LOAD, and its entries +/// give way before a reservation or the running batch is refused for memory. /// /// Limits: the profile is the row's (`QwenResidentAdmission.profile`, the /// native context for Qwen3.8 27B); LOAD quotes every lane at the memory @@ -154,6 +157,7 @@ public final class QwenTensorParallelResidentRuntime { var batchMTPBudget: QwenTensorParallelBatchMTPBudget? var requestCharge: QwenTensorParallelRequestCharge? var loadedMTPHead: QwenTensorParallelMTPHead? + var prefixRoom = 0 do { try control.check(); try QwenResidentResourceEnvironment.require() try admission.jaccl.requireUnchanged(environment: environment, read: { try BoundedProbeInput.data($0, maximumBytes: $1) }) @@ -245,6 +249,7 @@ public final class QwenTensorParallelResidentRuntime { tensors: profile.canonicalTensors, maximumTokens: memory.maximumContextTokens, chunkSize: memory.maximumChunkTokens, lanes: batch.lanes, paged: batch.backend == .paged, rank: collective.rank, + promptTokens: memory.maximumPromptTokens, allocationBound: QwenResidentResourceEnvironment.allocationBound) batchBudget = quote return quote.allowance.reservedBytes @@ -309,6 +314,11 @@ public final class QwenTensorParallelResidentRuntime { contextTokens: memory.maximumContextTokens) try allowance.requireLive() try checked() + // The prefix memory tier, charged nowhere: the pipeline's budget, + // half the admissible room measured beside the whole LOAD quote. + if prefixEnabled { + prefixRoom = try ClusterStagePrefixBudget.roomBytes(chargeBytes: complete.reservedBytes) + } let charge = QwenTensorParallelRequestCharge(geometry: value.profile.geometry, plan: value.model.plan, tensors: value.profile.canonicalTensors, lanes: batch.lanes, paged: batch.backend == .paged, assistant: speculativeTerms.map { ($0.depth, maximumSpeculativeWidth) }, rank: collective.rank, @@ -371,6 +381,10 @@ public final class QwenTensorParallelResidentRuntime { log("darkbloom-serving-context-v1 rank=\(collective.rank) tokens=\(serving) previous=0 grown=\(grown)" + " profile=\(admission.profile.maximumContextTokens) memory_plan=\(admission.memoryProfile.maximumContextTokens)") } + let prefixBudget = prefixEnabled ? QwenStagePrefixCache.budget(roomBytes: prefixRoom) : 0 + log("darkbloom-prefix-v1 rank=\(collective.rank) family=qwen mode=tensor_parallel enabled=\(prefixEnabled)" + + " policy=\(QwenTensorParallelBatchPrefixBudget.policy) budget_bytes=\(prefixBudget)" + + " capture_charge=\(batchBudget?.prefix.captureBytes ?? 0) room_bytes=\(prefixRoom) ssd=\(prefixDisk != nil)") return QwenTensorParallelResidentRuntime(admission: admission, control: control, collective: collective, group: group, codec: codec, model: loaded, vision: loadedVision, visionInventory: loadedVisionInventory, profile: profile, shares: shares, @@ -378,7 +392,7 @@ public final class QwenTensorParallelResidentRuntime { loadAgreement: loadAgreement, capacity: capacity, receipt: receipt, linkProbe: probe, batchLanes: batch.lanes, batchHost: batchHost, batchBudget: batchBudget, batchMTPBudget: batchMTPBudget, requestCharge: requestCharge, servingContextTokens: serving, batchPrefixEnabled: prefixEnabled, - prefixDisk: prefixDisk, + batchPrefixBudgetBytes: prefixBudget, prefixDisk: prefixDisk, mtpTerms: speculativeTerms, mtpHead: loadedMTPHead, assistantReady: assistantReady) } catch { let primary = error @@ -415,7 +429,8 @@ public final class QwenTensorParallelResidentRuntime { batchLanes: Int, batchHost: CBv2StageKVHost?, batchBudget: QwenTensorParallelBatchBudget?, batchMTPBudget: QwenTensorParallelBatchMTPBudget?, requestCharge: QwenTensorParallelRequestCharge, servingContextTokens: Int?, - batchPrefixEnabled: Bool, prefixDisk: QwenTensorParallelPrefixDisk?, mtpTerms: QwenMTPTerms?, + batchPrefixEnabled: Bool, batchPrefixBudgetBytes: Int, prefixDisk: QwenTensorParallelPrefixDisk?, + mtpTerms: QwenMTPTerms?, mtpHead: QwenTensorParallelMTPHead?, assistantReady: ClusterQwenTensorAssistantReady?) { self.admission = admission; self.control = control; self.collective = collective; self.group = group self.codec = codec; self.model = model; self.profile = profile; self.shares = shares @@ -429,8 +444,8 @@ public final class QwenTensorParallelResidentRuntime { self.mtpPrefix = batchMTPBudget.map { .init(enabled: batchPrefixEnabled, budgetBytes: $0.prefix.residentBytes) } - self.batchPrefix = batchBudget.map { - .init(enabled: batchPrefixEnabled, budgetBytes: $0.prefix.residentBytes) + self.batchPrefix = batchBudget.map { _ in + .init(enabled: batchPrefixEnabled, budgetBytes: batchPrefixBudgetBytes) } self.prefixDisk = prefixDisk self.receipt = receipt.storageCommitmentSHA256 @@ -457,9 +472,10 @@ public final class QwenTensorParallelResidentRuntime { /// The serving context re-derived while idle, on each keep-warm answer /// (`ClusterWorkerEvent.keptWarm`), with the reservation gate's own - /// arithmetic: kept prefix entries are part of the charge they were - /// allocated under. Nil (and nothing changes) while a lane is held, or for - /// a row whose profile is its memory plan. Allocates nothing. + /// arithmetic: kept prefix entries count as room, since they give way to + /// a reservation (`yieldingPrefixMemory`). Nil (and nothing changes) + /// while a lane is held, or for a row whose profile is its memory plan. + /// Allocates nothing. public func refreshServingContext() -> Int? { guard servingContextTokens != nil, operation.try() else { return nil } defer { operation.unlock() } diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelAssistantQuoteTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelAssistantQuoteTests.swift index 8a5d8038ab..b3f8a94df2 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelAssistantQuoteTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelAssistantQuoteTests.swift @@ -85,7 +85,8 @@ struct QwenTensorParallelAssistantQuoteTests { chunkTokens: 16, lanes: 1, allocationBound: bound) let native = try QwenTensorParallelBatchBudget.derive(geometry: family.geometry, plan: plan, tensors: tensors, maximumTokens: family.profile.maximumContextTokens, - chunkSize: family.profile.maximumChunkTokens, lanes: 1, paged: true, allocationBound: bound) + chunkSize: family.profile.maximumChunkTokens, lanes: 1, paged: true, + promptTokens: family.profile.maximumPromptTokens, allocationBound: bound) #expect(quote.assistant == nil && quote.lanes == 1) #expect(quote.allowance == native.allowance && quote.perLaneStateBytes == native.perLaneStateBytes) #expect(quote.sharedBytesExcludingCollectives == native.sharedBytesExcludingCollectives) diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchBudgetTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchBudgetTests.swift index f9e10a81df..f00db705af 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchBudgetTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchBudgetTests.swift @@ -40,11 +40,12 @@ struct QwenTensorParallelBatchBudgetTests { * family.geometry.kvHeads * family.geometry.headDimension * 2) #expect(candidate.promptGatherBytes == bank) #expect(candidate.perLaneStateBytes + candidate.promptGatherBytes >= scalar.stateBytes) - #expect(candidate.perLaneStateBytes < scalar.stateBytes) + // Beside its own prompt-prefix capture (`QwenTensorParallelBatchPrefixBudget`). + #expect(candidate.perLaneStateBytes - candidate.prefix.captureBytes < scalar.stateBytes) #expect(candidate.allowance.requestBytesExcludingCollectives == lanes * candidate.perLaneStateBytes + candidate.sharedBytesExcludingCollectives) let logits = 3 * bound(lanes * plan.vocabularySize * 4) #expect(candidate.sharedBytesExcludingCollectives == scalar.fusionBytes + scalar.transientBytes + logits - + 2 * scalar.projectionConstantBytes + candidate.pagedPoolSlackBytes + candidate.prefix.residentBytes + + 2 * scalar.projectionConstantBytes + candidate.pagedPoolSlackBytes + candidate.promptGatherBytes) #expect(candidate.pagedPoolSlackBytes >= 2 * CBv2StageKVHost.segmentBytes) // The underlying host's entire admitted page capacity, its gather diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchPrefixTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchPrefixTests.swift index 8e2ee4fae6..5fac167cf9 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchPrefixTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchPrefixTests.swift @@ -1,3 +1,4 @@ +import DarkbloomClusterPlacement import Foundation import MLX import Testing @@ -7,10 +8,13 @@ import Testing struct QwenTensorParallelBatchPrefixTests { @Test func originalGridAndBilateralVotesNeverSplitFinalChunk() throws { for chunk in [1, 5, 128, 512] { - for count in [1, 2, 5, 511, 512, 513, 4096, 8193] { + for count in [1, 2, 5, 511, 512, 513, 4096, 8193, 33_000, 70_000] { let c = QwenTensorParallelBatchPrefixCache.candidates(promptCount: count, - chunkSize: chunk, maximumTokens: 4096) - #expect(c.count <= 32 && c.allSatisfy { $0 > 0 && $0 < count && $0 <= 4096 && $0 % chunk == 0 }) + chunkSize: chunk, maximumTokens: 65_536) + #expect(c.count <= QwenTensorParallelBatchPrefixCache.maximumVoted + && c.allSatisfy { $0 > 0 && $0 < count && $0 <= 65_536 && $0 % chunk == 0 }) + // Every grid boundary is voted when the vote holds them all. + if chunk == 512 { #expect(c.count == min(count - 1, 65_536) / 512) } #expect(try QwenTensorParallelBatchPrefixCache.agreed(candidates: c, votes: c.map { _ in 1 }) == 0) #expect(try QwenTensorParallelBatchPrefixCache.agreed(candidates: c, votes: c.map { _ in 2 }) == c.last ?? 0) } @@ -31,9 +35,6 @@ struct QwenTensorParallelBatchPrefixTests { #expect(k != other) #expect(k[2] == keys("load|media=A", [1, 2, 9, 4, 5, 6])[2]) #expect(k[4] != keys("load|media=A", [1, 2, 9, 4, 5, 6])[4]) - func state(_ frontier: Int, _ bytes: Int) -> QwenTensorParallelBatchPrefixState { - .init(committedTokens: frontier, attention: [:], recurrent: [:], allocatedBytes: bytes) - } cache.insert(key: k[2]!, state: state(2, 16)); cache.insert(key: k[4]!, state: state(4, 16)) #expect(cache.bytesInUse == 32) _ = try cache.restore(key: k[2]!, frontier: 2) @@ -49,26 +50,230 @@ struct QwenTensorParallelBatchPrefixTests { } } - @Test func fullGeometrySnapshotAndResidentBanksAreIndependentlyRounded() throws { - let g = try QwenLongPrefillBudgetGeometry(layers: 4, fullAttentionInterval: 4, hiddenSize: 256, + private func state(_ frontier: Int, _ bytes: Int) -> QwenTensorParallelBatchPrefixState { + .init(committedTokens: frontier, attention: [:], recurrent: [:], allocatedBytes: bytes) + } + + // MARK: Parity with one Mac's dense-Qwen reuse + + /// One Mac's dense-Qwen complete checkpoints for a request served alone + /// (`docs/architecture/prefix-cache.md`, streamed complete checkpoints): + /// solo stripes of 4,096 (`EngineV2Factory.defaultDenseQwenSoloPrefillStripeTokens`), + /// range ends on the 256 grid from the store's 1,024-token floor, the + /// demanded latest cut 64 tokens below the prompt end when it saves the + /// floor (`demandedLatestCheckpointRange`), and retention of the first, + /// the hinted fork target and the rolling latest (`CBv2CheckpointRetention`). + private struct OneMac { + static func latest(_ prompt: Int) -> Int { + let stripeEnd = (prompt - 1) / 4096 * 4096 + let cut = (prompt - 1 - 64) / 256 * 256 + let start = cut / 4096 * 4096 + let deepest = cut >= 1024 && cut > start && cut - start >= 1024 ? max(stripeEnd, cut) : stripeEnd + return deepest >= 1024 ? deepest : 0 + } + /// The first stripe end. + static func first(_ prompt: Int) -> Int { prompt > 4096 ? 4096 : 0 } + /// The deepest stripe end at or below a hinted repeat of `shared` tokens. + static func target(_ prompt: Int, shared: Int) -> Int { min(shared, prompt - 1) / 4096 * 4096 } + } + + /// The deepest boundary a pair restores for a prompt sharing `shared` + /// tokens with a donor of `prompt` tokens that kept `frontiers`. + private func reuse(_ frontiers: [Int], shared: Int) -> Int { frontiers.filter { $0 <= shared }.max() ?? 0 } + + @Test func keptBoundariesReuseAtLeastWhatOneMacReusesOnTheGrid() { + let chunk = 512 + for prompt in Swift.stride(from: 1_100, through: 70_000, by: 37) { + let kept = QwenTensorParallelBatchPrefixBudget.frontiers(promptCount: prompt, chunkSize: chunk) + #expect(kept.allSatisfy { $0 % chunk == 0 && $0 > 0 && $0 < prompt }) + #expect(kept.count <= QwenTensorParallelBatchPrefixBudget.maximumStripeBoundaries + 3) + // A repeated prompt: the deepest boundary before the final token. + let deepest = (prompt - 1) / chunk * chunk + #expect(kept.last == deepest) + #expect(reuse(kept, shared: prompt) >= OneMac.latest(prompt) / chunk * chunk, "repeat \(prompt)") + // The next turn shares the prompt but its re-rendered end (under + // 16 tokens for current templates; one Mac keeps a 64-token margin). + for rerendered in [1, 8, 16, 63] where prompt - rerendered > 0 { + let shared = prompt - rerendered + let mac = [OneMac.first(prompt), OneMac.latest(prompt)].filter { $0 <= shared }.max() ?? 0 + #expect(reuse(kept, shared: shared) >= mac / chunk * chunk, "turn \(prompt) shared \(shared)") + } + // Prompts sharing only a system prompt: one Mac's first stripe + // end, and with the coordinator's hint the deepest stripe end at + // or below it, while the kept stripe is one Mac's. + for system in Swift.stride(from: 4_096, to: prompt, by: 1_531) { + #expect(reuse(kept, shared: system) >= OneMac.first(prompt), "system \(system) of \(prompt)") + if (deepest - 1) / 4096 <= QwenTensorParallelBatchPrefixBudget.maximumStripeBoundaries { + #expect(reuse(kept, shared: system) >= OneMac.target(prompt, shared: system), "hinted \(system) of \(prompt)") + } + } + } + // The 33K repeat measured on one Mac (pw1): 32,768 there, at least that here. + #expect(reuse(QwenTensorParallelBatchPrefixBudget.frontiers(promptCount: 33_000, chunkSize: chunk), shared: 33_000) == 32_768) + #expect(OneMac.latest(33_000) == 32_768) + // A restored request keeps only what lies beyond its restore. + #expect(QwenTensorParallelBatchPrefixBudget.frontiers(promptCount: 33_000, chunkSize: chunk, restored: 16_384) + == [20_480, 24_576, 28_672, 32_768]) + #expect(QwenTensorParallelBatchPrefixBudget.frontiers(promptCount: 32_801, chunkSize: chunk) + == [4_096, 8_192, 12_288, 16_384, 20_480, 24_576, 28_672, 32_256, 32_768]) + #expect(QwenTensorParallelBatchPrefixBudget.frontiers(promptCount: 600, chunkSize: chunk) == [512]) + #expect(QwenTensorParallelBatchPrefixBudget.frontiers(promptCount: 512, chunkSize: chunk).isEmpty) + } + + // MARK: Memory + + private func geometry() throws -> QwenLongPrefillBudgetGeometry { + try QwenLongPrefillBudgetGeometry(layers: 4, fullAttentionInterval: 4, hiddenSize: 256, queryHeads: 4, kvHeads: 2, headDimension: 64, linearKeyHeads: 2, linearValueHeads: 4, linearKeyDimension: 64, linearValueDimension: 64, convolutionKernel: 4) - func bound(_ n: Int) -> Int { (n + 16383) / 16384 * 16384 } - for n in [1, 17, 4096, 65536] { - let actual = try QwenTensorParallelBatchPrefixBudget.derive(geometry: g, - maximumTokens: n, allocationBound: bound) - let tokens = min(n, 4096) - let b = try QwenLongPrefillTensorBudget.estimate(geometry: g, maximumTokens: tokens, chunkSize: 1) - let expected = 3 * (bound(b.convolutionBytesPerLayer) + bound(b.ssmBytesPerLayer)) - + 2 * bound(tokens * 2 * 64 * 2) - #expect(actual.captureBytes == expected && actual.residentBytes == 2 * expected) - #expect(actual.maximumTokens == tokens) + } + private func bound(_ n: Int) -> Int { (n + 16383) / 16384 * 16384 } + + @Test func aRequestIsChargedItsOwnCaptureAndLoadOneOfTheLongestPrompt() throws { + let g = try geometry() + let b = try QwenLongPrefillTensorBudget.estimate(geometry: g, maximumTokens: 1, chunkSize: 1) + let perBoundary = 3 * (bound(b.convolutionBytesPerLayer) + bound(b.ssmBytesPerLayer)) + var previous = 0 + for prompt in Swift.stride(from: 1, through: 70_000, by: 97) { + let charged = try QwenTensorParallelBatchPrefixBudget.captureBytes(geometry: g, promptCount: prompt, + chunkSize: 512, allocationBound: bound) + let kept = QwenTensorParallelBatchPrefixBudget.frontiers(promptCount: prompt, chunkSize: 512) + guard let deepest = kept.last else { #expect(charged == 0); continue } + // Its rows to the deepest boundary, and a recurrent state for at + // least every boundary a prompt with that deepest boundary keeps. + let states = QwenTensorParallelBatchPrefixBudget.pricedStates(deepest: deepest, chunkSize: 512) + #expect(states >= QwenTensorParallelBatchPrefixBudget.frontiers(promptCount: deepest + 1, chunkSize: 512).count) + #expect(states >= kept.count && states <= QwenTensorParallelBatchPrefixBudget.maximumStripeBoundaries + 3) + #expect(charged == 2 * bound(deepest * 2 * 64 * 2) + states * perBoundary) + #expect(charged >= previous, "prompt \(prompt)"); previous = charged } + // LOAD's per-lane term is one capture of the profile's longest prompt + // (at most the context), and nothing for a resident tier. + let load = try QwenTensorParallelBatchPrefixBudget.derive(geometry: g, maximumTokens: 65_536, + promptTokens: 32_768, chunkSize: 512, allocationBound: bound) + #expect(load.captureBytes == (try QwenTensorParallelBatchPrefixBudget.captureBytes(geometry: g, + promptCount: 32_768, chunkSize: 512, allocationBound: bound))) + #expect(try load.captureBytes(promptCount: 9_000, chunkSize: 512, allocationBound: bound) + == (try QwenTensorParallelBatchPrefixBudget.captureBytes(geometry: g, promptCount: 9_000, chunkSize: 512, + allocationBound: bound))) + let context = try QwenTensorParallelBatchPrefixBudget.derive(geometry: g, maximumTokens: 4096, chunkSize: 512, + allocationBound: bound) + #expect(context.captureBytes == (try QwenTensorParallelBatchPrefixBudget.captureBytes(geometry: g, + promptCount: 4095, chunkSize: 512, allocationBound: bound))) #expect(throws: (any Error).self) { - try QwenTensorParallelBatchPrefixBudget.derive(geometry: g, maximumTokens: 4096, allocationBound: { $0 - 1 }) + try QwenTensorParallelBatchPrefixBudget.derive(geometry: g, maximumTokens: 4096, chunkSize: 512, allocationBound: { $0 - 1 }) } #expect(throws: (any Error).self) { - try QwenTensorParallelBatchPrefixBudget.derive(geometry: g, maximumTokens: 4096, allocationBound: { _ in Int.max }) + try QwenTensorParallelBatchPrefixBudget.derive(geometry: g, maximumTokens: 4096, chunkSize: 512, allocationBound: { _ in Int.max }) + } + // A fixture's flat budget charges what it names. + #expect(try QwenTensorParallelBatchPrefixBudget(maximumTokens: 128, captureBytes: 7) + .captureBytes(promptCount: 100, chunkSize: 5, allocationBound: bound) == 7) + } + + @Test func oneCapturesBoundariesShareTheirCopyAndGiveWayShallowestFirst() throws { + let cache = QwenTensorParallelBatchPrefixCache(enabled: true, budgetBytes: 100) + func group(_ name: String, _ frontiers: [Int], own: Int, shared: Int) -> [Int] { + cache.insert(frontiers.map { (key: "\(name)-\($0)", state: state($0, own)) }, sharedBytes: shared) + } + // A: the copy (40) once and three states (10 each). + #expect(group("a", [4, 8, 12], own: 10, shared: 40) == [4, 8, 12]) + #expect(cache.bytesInUse == 70) + // B needs 50: A's shallower boundaries go first, never A's deepest. + #expect(group("b", [4, 8], own: 10, shared: 30) == [4, 8]) + #expect(cache.heldFrontiers == [4, 8, 12] && cache.bytesInUse == 100) + #expect(cache.holds(key: "a-12", frontier: 12) && !cache.holds(key: "a-4", frontier: 4)) + // The budget falls: the newest capture's shallower boundary goes + // before any capture's deepest; then whole captures, least recent first. + cache.setBudget(90) + #expect(cache.holds(key: "a-12", frontier: 12) && cache.holds(key: "b-8", frontier: 8) && !cache.holds(key: "b-4", frontier: 4)) + cache.setBudget(50) + #expect(!cache.holds(key: "a-12", frontier: 12) && cache.holds(key: "b-8", frontier: 8) && cache.bytesInUse == 40) + // A capture whose deepest boundary does not fit keeps nothing; with + // room for its deepest only, only that. + #expect(group("c", [4, 8], own: 10, shared: 100) == []) + cache.setBudget(60) + #expect(group("d", [4, 8], own: 10, shared: 5) == [4, 8]) + #expect(group("e", [4, 8], own: 10, shared: 45) == [8]) + // A zero budget keeps nothing resident, but the cache stays on (its votes still count SSD records). + cache.setBudget(0) + #expect(cache.enabled && cache.bytesInUse == 0 && cache.heldFrontiers.isEmpty) + #expect(group("f", [4], own: 10, shared: 0) == []) + } + + @Test func entriesGiveWayBeforeALiveGateRefuses() throws { + let cache = QwenTensorParallelBatchPrefixCache(enabled: true, budgetBytes: 100) + cache.insert([(key: "a-4", state: state(4, 10)), (key: "a-8", state: state(8, 10))], sharedBytes: 30) + cache.insert([(key: "b-4", state: state(4, 10))], sharedBytes: 30) + #expect(cache.bytesInUse == 90) + // The gate admits once at most 40 bytes are held: entries go one at a time. + try cache.yieldingMemory(disk: nil) { + if cache.bytesInUse > 40 { throw ProbeError("refused") } + } + #expect(cache.bytesInUse <= 40 && cache.evictions >= 2) + // A refusal with nothing left to give way is the gate's. + #expect(throws: ProbeError.self) { + try cache.yieldingMemory(disk: nil) { throw ProbeError("refused") } + } + #expect(cache.bytesInUse == 0) + } + + /// The SSD record's scope binds the prefix policy, so a record kept under + /// another policy (the 4,096-token one included) is never offered. + @Test func recordsOfAnotherPolicyAreNeverOffered() throws { + let plan = QwenTensorParallelPrefixDisk.planScopeFields(planFingerprint: "plan", planName: "qwen_dense_heads_and_channels_v1", + shares: [1, 1], assistantPolicy: nil) + #expect(plan.prefillSchedule.hasSuffix("|prefix=" + QwenTensorParallelBatchPrefixBudget.policy)) + #expect(QwenTensorParallelBatchPrefixBudget.policy == "qwen-tp-batch-prefix-depth-v2") + let old = plan.prefillSchedule.replacingOccurrences(of: QwenTensorParallelBatchPrefixBudget.policy, + with: "qwen-tp-batch-grid-prefix-4096-v1") + func scope(_ schedule: String) -> String { + QwenStagePrefixDiskTier.planScope(planFingerprint: plan.planFingerprint, artifactAggregateSHA256: "a", + storageCommitmentSHA256: "s", rankBuildSHA256: ["b0", "b1"], generationMode: "tensor_parallel_v1", + prefillSchedule: schedule) + } + #expect(scope(plan.prefillSchedule) != scope(old)) + } + + // MARK: The registered 27B + + private struct Inputs: Decodable { + struct Tensor: Decodable { let name: String; let shape: [Int]; let sourceDType: String; let byteCount: Int } + struct Profile: Decodable { let configuration: Data; let canonicalTensors: [Tensor] } + let twentySeven: Profile + } + + /// LOAD's quote of the registered 27B on its own heads, before (one + /// 4,096-token capture a lane and two such banks resident) and after (one + /// capture of the profile's longest prompt a lane, no resident term). + @Test func registeredTwentySevenBChargesOneCaptureOfItsLongestPromptPerLane() throws { + let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("StageMetadataChecks/Inputs/qwen-retained-inputs.json") + let value = try JSONDecoder().decode(Inputs.self, from: Data(contentsOf: url)).twentySeven + let family = try QwenDensePlacementFamily(configuration: value.configuration) + let tensors = try family.requireRegisteredInventory(value.canonicalTensors.map { + ClusterPlacementStoredTensor(name: $0.name, byteCount: $0.byteCount, dtype: $0.sourceDType, shape: $0.shape) + }) + let plan = try #require(family.tensorParallel), p = family.profile + for rank in [0, nil] as [Int?] { + let local = try family.geometry.tensorParallelShard(plan: plan, rank: rank) + let b = try QwenLongPrefillTensorBudget.estimate(geometry: local, maximumTokens: 4096, chunkSize: 1) + let before = local.recurrentLayers * (bound(b.convolutionBytesPerLayer) + bound(b.ssmBytesPerLayer)) + + 2 * local.attentionLayers * bound(4096 * local.kvHeads * local.headDimension * 2) + let after = try QwenTensorParallelBatchPrefixBudget.captureBytes(geometry: local, + promptCount: p.maximumPromptTokens, chunkSize: p.maximumChunkTokens, allocationBound: bound) + for lanes in [1, 8] { + let quote = try QwenTensorParallelBatchBudget.derive(geometry: family.geometry, plan: plan, tensors: tensors, + maximumTokens: p.maximumContextTokens, chunkSize: p.maximumChunkTokens, lanes: lanes, paged: true, + rank: rank, promptTokens: p.maximumPromptTokens, allocationBound: bound) + #expect(quote.prefix.captureBytes == after) + let now = quote.allowance.requestBytesExcludingCollectives + let then = now - lanes * after + lanes * before + 2 * before + print("qwen27-tp-prefix-quote rank=\(rank.map(String.init) ?? "either") lanes=\(lanes)" + + " prompt=\(p.maximumPromptTokens) context=\(p.maximumContextTokens)" + + " capture_before=\(before) resident_before=\(2 * before) capture_after=\(after)" + + " request_before=\(then) request_after=\(now) delta=\(now - then)") + } } } } diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchQuoteTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchQuoteTests.swift index fc083ef473..95a0dfde07 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchQuoteTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchQuoteTests.swift @@ -50,7 +50,8 @@ struct QwenTensorParallelBatchQuoteTests { let plan = try QwenTensorParallelPlan(textConfiguration: text, quantization: quantization, size: 2, shares: shares) let native = try QwenTensorParallelBatchBudget.derive(geometry: family.geometry, plan: plan, tensors: canonical, maximumTokens: family.profile.maximumContextTokens, - chunkSize: family.profile.maximumChunkTokens, lanes: lanes, paged: true, allocationBound: bound) + chunkSize: family.profile.maximumChunkTokens, lanes: lanes, paged: true, + promptTokens: family.profile.maximumPromptTokens, allocationBound: bound) #expect(quote.allowance == native.allowance) #expect(quote.perLaneStateBytes == native.perLaneStateBytes) // Cluster stage KV is paged only (a contiguous backend is refused by diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchSessionTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchSessionTests.swift index e87aac858b..9e0eab4fcd 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchSessionTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchSessionTests.swift @@ -688,7 +688,7 @@ struct QwenTensorParallelBatchSessionTests { self.mediaInputs(model, row: reservation.request.promptTokenIDs[0] - 10) }, completedDecode: { _ in }, completedPrefill: {}, releaseResources: { _ in }, prefix: warm ? caches[rank] : nil, - prefixBudget: warm ? .init(maximumTokens: 128, captureBytes: 8 << 20, residentBytes: 64 << 20) : nil, + prefixBudget: warm ? .init(maximumTokens: 128, captureBytes: 8 << 20) : nil, prefixScope: warm ? { _ in "same-authenticated-load-and-media-policy" } : nil, allocationBound: warm ? { (($0 + 16383) / 16384) * 16384 } : nil) return owner @@ -824,7 +824,7 @@ struct QwenTensorParallelBatchSessionTests { owner.executor = try .init(model: model, configuration: configuration, host: owner.host, group: reduction, prepare: { _, _ in nil }, completedDecode: { _ in }, completedPrefill: {}, releaseResources: { _ in }, prefix: warm ? caches[rank] : nil, - prefixBudget: warm ? .init(maximumTokens: 128, captureBytes: 8 << 20, residentBytes: 64 << 20) : nil, + prefixBudget: warm ? .init(maximumTokens: 128, captureBytes: 8 << 20) : nil, prefixScope: warm ? { reservation in suffix(reservation).map { load + "|" + $0 } } : nil, prefixDisk: warm ? disks[rank] : nil, prefixDiskScope: warm ? { reservation in suffix(reservation).map(disks[rank].scope) } : nil, @@ -941,7 +941,7 @@ struct QwenTensorParallelBatchSessionTests { self.mediaInputs(model, row: reservation.request.promptTokenIDs[0] - 10) }, completedDecode: { _ in }, completedPrefill: {}, releaseResources: { _ in }, prefix: caches?[rank], - prefixBudget: warm ? .init(maximumTokens: 128, captureBytes: 8 << 20, residentBytes: 64 << 20) : nil, + prefixBudget: warm ? .init(maximumTokens: 128, captureBytes: 8 << 20) : nil, prefixScope: warm ? { _ in load } : nil, prefixDisk: disks?[rank], prefixDiskScope: disks == nil ? nil : { _ in planScope + "|chunk=5|text" }, allocationBound: warm ? { (($0 + 16383) / 16384) * 16384 } : nil) @@ -1096,7 +1096,7 @@ struct QwenTensorParallelBatchSessionTests { owner.executor = try .init(model: model, configuration: configuration, host: owner.host, group: reduction, prepare: { _, _ in nil }, completedDecode: { _ in }, completedPrefill: {}, releaseResources: { _ in }, prefix: caches?[rank], - prefixBudget: warm ? .init(maximumTokens: 384, captureBytes: 16 << 20, residentBytes: 64 << 20) : nil, + prefixBudget: warm ? .init(maximumTokens: 384, captureBytes: 16 << 20) : nil, prefixScope: warm ? { _ in load } : nil, prefixDisk: disks?[rank], prefixDiskScope: disks == nil ? nil : { _ in planScope + "|chunk=16|text" }, allocationBound: warm ? { (($0 + 16383) / 16384) * 16384 } : nil) diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelNativeContextTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelNativeContextTests.swift index bc97d7449a..fd91684bd3 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelNativeContextTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelNativeContextTests.swift @@ -62,7 +62,7 @@ struct QwenTensorParallelNativeContextTests { } let quote = try QwenTensorParallelBatchBudget.derive(geometry: family.geometry, plan: plan, tensors: tensors, maximumTokens: memory.maximumContextTokens, chunkSize: memory.maximumChunkTokens, lanes: lanes, paged: true, - rank: rank, allocationBound: bound) + rank: rank, promptTokens: memory.maximumPromptTokens, allocationBound: bound) return .init(charge: .init(geometry: family.geometry, plan: plan, tensors: tensors, lanes: lanes, paged: true, assistant: nil, rank: rank, allocationBound: bound, loadSharedBytes: quote.sharedBytesExcludingCollectives, diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixDepthTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixDepthTests.swift new file mode 100644 index 0000000000..0c78b59802 --- /dev/null +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixDepthTests.swift @@ -0,0 +1,240 @@ +import DarkbloomClusterProtocol +import Foundation +import MLX +import Testing +@testable import DarkbloomClusterRuntime + +/// Prompt prefixes kept to the request's context on the 512-token grid +/// (`QwenTensorParallelBatchPrefixBudget`): a restore at a deep boundary is +/// a cold prefill on the same grid, byte for byte, on both ranks (final +/// logits, every attention row, every convolution and SSM state), for each +/// case one Mac reuses: a repeat, the next turn, a shared system prompt. +/// GatedDelta's recurrence is Metal-only, so the hybrid shards run on the GPU. +@Suite(.serialized) +struct QwenTensorParallelPrefixDepthTests { + private final class Rendezvous: @unchecked Sendable { + let condition = NSCondition() + var step = 0, leaving = 0 + var inputs: [Int: [Float]] = [:] + var result: [Float] = [] + func sum(_ array: MLXArray, rank: Int) -> MLXArray { + let values = array.asArray(Float.self) + condition.lock() + while leaving > 0 { condition.wait() } + let generation = step + inputs[rank] = values + if inputs.count == 2 { + result = zip(inputs[0]!, inputs[1]!).map(+) + leaving = 2; condition.broadcast() + } else { + let deadline = Date().addingTimeInterval(120) + while leaving == 0 && step == generation { + precondition(condition.wait(until: deadline), "TP rank failed to meet its peer") + } + } + let output = result + leaving -= 1 + if leaving == 0 { inputs = [:]; result = []; step += 1; condition.broadcast() } + condition.unlock() + return MLXArray(output, array.shape) + } + } + private final class Rank: QwenTensorParallelReduction, @unchecked Sendable { + let rank: Int, size = 2 + let shared: Rendezvous + init(_ rank: Int, _ shared: Rendezvous) { self.rank = rank; self.shared = shared } + func allSum(_ value: MLXArray) -> MLXArray { shared.sum(value, rank: rank) } + } + private struct Reservation: QwenTensorParallelBatchReservation { + let request: QwenLayerStageGenerationRequest + let deadline: UInt64 = .max + var laneStateBytes: Int { 1 } + var joinable: Bool { true } + } + private final class Owned: @unchecked Sendable { + let model: QwenTensorParallelModel + let host: CBv2StageKVHost + var executor: QwenTensorParallelNativeBatchExecutor? + var lane: QwenTensorParallelNativeBatchLane? + var output: MLXArray? + var token = 0 + var failure: Error? + init(_ model: QwenTensorParallelModel, maximumTokens: Int) throws { + self.model = model + host = try CBv2StageKVHost(model: model.model, kind: .paged, lanes: 1, + maximumTokensPerRequest: maximumTokens, maximumChunkTokens: 512) + } + } + private final class Work: @unchecked Sendable { + let body: (Owned) throws -> Void + init(_ body: @escaping (Owned) throws -> Void) { self.body = body } + } + private let ranks = TensorParallelRankThreads() + private func parallel(_ owners: [Owned], body: @escaping (Owned) throws -> Void) throws { + let work = Work(body) + ranks.run { rank in + Device.withDefaultDevice(.gpu) { + do { try work.body(owners[rank]) } catch { owners[rank].failure = error } + } + } + for owner in owners { if let error = owner.failure { owner.failure = nil; throw error } } + } + private func bytes(_ a: MLXArray) -> Data { eval(a); return a.asData(access: .copy).data } + + private static let context = 33_400 + private static func allocationBound(_ bytes: Int) -> Int { ((bytes + 16_383) / 16_384) * 16_384 } + + /// A pair of shards of one tiny hybrid checkpoint (three GatedDelta layers, + /// one attention layer); with `caches`, each rank keeps prompt prefixes + /// charged by the real per-request rule on its own heads. + private func pair(_ configuration: Data, _ tensors: [(String, MLXArray)], + caches: [QwenTensorParallelBatchPrefixCache]?) throws -> [Owned] { + let wire = Rendezvous() + return try (0..<2).map { rank in + let reduction = Rank(rank, wire) + let model = try QwenTensorParallelModel.assemble(configurationData: configuration, + role: .shard(rank: rank, size: 2), reduction: reduction) { _, keep in + for (name, value) in tensors { try keep(name, value) } + } + let owner = try Owned(model, maximumTokens: Self.context) + let geometry = try Self.geometry(configuration, model, rank: rank) + owner.executor = try .init(model: model, configuration: configuration, host: owner.host, group: reduction, + prepare: { _, _ in nil }, completedDecode: { _ in }, completedPrefill: {}, releaseResources: { _ in }, + prefix: caches?[rank], + prefixBudget: caches == nil ? nil : .init(maximumTokens: Self.context, captureBytes: 0, geometry: geometry), + prefixScope: caches == nil ? nil : { _ in "depth-load|chunk=512|kv=paged|text" }, + allocationBound: caches == nil ? nil : { Self.allocationBound($0) }) + return owner + } + } + + /// A rank's own heads of the checkpoint's budget geometry. + private static func geometry(_ configuration: Data, _ model: QwenTensorParallelModel, rank: Int) throws + -> QwenLongPrefillBudgetGeometry { + let root = try JSONSerialization.jsonObject(with: configuration) as! [String: Any] + let text = root["text_config"] as! [String: Any] + let plan = model.plan + return try QwenLongPrefillBudgetGeometry(layers: plan.layerCount, + fullAttentionInterval: plan.fullAttentionInterval, hiddenSize: plan.hiddenSize, + queryHeads: plan.attentionHeads, kvHeads: plan.kvHeads, headDimension: plan.headDim, + linearKeyHeads: plan.linearKeyHeads, linearValueHeads: plan.linearValueHeads, + linearKeyDimension: plan.linearKeyHeadDim, linearValueDimension: plan.linearValueHeadDim, + convolutionKernel: text["linear_conv_kernel_dim"] as! Int).tensorParallelShard(plan: plan, rank: rank) + } + + private func request(_ tokens: [Int], profile: QwenLayerStageGenerationProfile) throws -> QwenLayerStageGenerationRequest { + try .init(profile: profile, requestID: UUID(), promptTokenIDs: tokens, chunkSize: 512, outputCount: 4, stopTokenIDs: []) + } + + /// Serves `tokens` to its first token and retires cleanly, so each rank + /// keeps what it captured; returns what each rank restored and kept. + private func donate(_ owners: [Owned], _ request: QwenLayerStageGenerationRequest) throws -> (restored: [Int], stored: [[Int]]) { + try parallel(owners) { $0.lane = try $0.executor!.open(.init(request: request), check: {}) } + let restored = owners.map { $0.lane!.committedTokens } + while owners[0].lane!.nextFrame?.phase == .prefill { + try parallel(owners) { owner in + let lane = owner.lane! + if let token = try owner.executor!.prefill(lane, frame: lane.nextFrame!, check: {}) { owner.token = token } + } + } + for owner in owners { try owner.executor!.retire(owner.lane!, reason: .clientStop, selected: 1, last: owner.token) } + for owner in owners { try owner.executor!.confirmedRetirement(owner.lane!, clean: true) } + #expect(owners[0].token == owners[1].token && owners.allSatisfy { $0.host.isDrained }) + return (restored, owners.map { $0.lane!.storedPrefixFrontiers }) + } + + /// Opens `request` on both pairs, prefills both to the prompt's end and + /// compares, rank by rank, the final logits, every attention row and + /// every recurrent state; returns what the warm pair restored. + private func compare(_ cold: [Owned], _ warm: [Owned], _ request: QwenLayerStageGenerationRequest, + label: String) throws -> [Int] { + try parallel(cold) { $0.lane = try $0.executor!.open(.init(request: request), check: {}) } + try parallel(warm) { $0.lane = try $0.executor!.open(.init(request: request), check: {}) } + let restored = warm.map { $0.lane!.committedTokens } + #expect(cold.allSatisfy { $0.lane!.committedTokens == 0 }) + for owners in [cold, warm] { + while owners[0].lane!.nextFrame?.phase == .prefill { + try parallel(owners) { $0.output = try $0.lane!.session.prefill(check: {}) } + } + } + for rank in 0..<2 { + let a = cold[rank].lane!.session.state, b = warm[rank].lane!.session.state + #expect(bytes(cold[rank].output!) == bytes(warm[rank].output!), "\(label) logits rank=\(rank)") + #expect(a.committedTokens == request.promptCount && b.committedTokens == request.promptCount) + for (x, y) in zip(a.rows, b.rows) { + #expect(bytes(x!.snapshot().keys) == bytes(y!.snapshot().keys), "\(label) keys rank=\(rank)") + #expect(bytes(x!.snapshot().values) == bytes(y!.snapshot().values), "\(label) values rank=\(rank)") + } + let x = a.recurrent.confirmedStateSnapshot() ?? [:], y = b.recurrent.confirmedStateSnapshot() ?? [:] + #expect(!x.isEmpty && x.keys.sorted() == y.keys.sorted()) + for index in x.keys { + #expect(bytes(x[index]!.conv!) == bytes(y[index]!.conv!), "\(label) conv \(index) rank=\(rank)") + #expect(bytes(x[index]!.ssm!) == bytes(y[index]!.ssm!), "\(label) ssm \(index) rank=\(rank)") + } + } + for owner in cold + warm { + try owner.executor!.retire(owner.lane!, reason: nil, selected: 0, last: nil) + #expect(owner.host.isDrained) + } + return restored + } + + @Test(.enabled(if: ProcessInfo.processInfo.environment["QWEN_TP_BATCH_GPU"] == "1")) + func deepRestoresEqualColdPrefillOnBothRanks() throws { + try Device.withDefaultDevice(.gpu) { + let fixture = QwenTensorParallelFixtures.checkpoint(hidden: 256, layers: 4, heads: 4, kvHeads: 2, vocabulary: 256) + var root = try JSONSerialization.jsonObject(with: fixture.configuration) as! [String: Any] + var text = root["text_config"] as! [String: Any] + text["max_position_embeddings"] = 65_536 + root["text_config"] = text + let configuration = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys]) + let profile = try QwenLayerStageGenerationProfile(identifier: "qwen-tp-depth-tiny", vocabularySize: 256, + hiddenSize: 256, activationDType: "bfloat16", maximumPromptTokens: 33_300, + maximumChunkTokens: 512, maximumOutputTokens: 4, maximumContextTokens: Self.context) + var seed: UInt64 = 0x5eed + func tokens(_ count: Int) -> [Int] { + (0..> 33) % 256 } + } + let caches = (0..<2).map { _ in QwenTensorParallelBatchPrefixCache(enabled: true, budgetBytes: 1 << 30) } + let warm = try pair(configuration, fixture.tensors, caches: caches) + let cold = try pair(configuration, fixture.tensors, caches: nil) + // The donor: 33,000 tokens keep the 4,096 stripe and the deepest + // whole chunk before the final token, within each rank's charge. + let donor = tokens(33_000) + let kept = QwenTensorParallelBatchPrefixBudget.frontiers(promptCount: donor.count, chunkSize: 512) + #expect(kept == [4_096, 8_192, 12_288, 16_384, 20_480, 24_576, 28_672, 32_768]) + let first = try donate(warm, try request(donor, profile: profile)) + #expect(first.restored == [0, 0] && first.stored == [kept, kept]) + // What each rank keeps is within the charge its request was priced at. + for (rank, owner) in warm.enumerated() { + let charge = try QwenTensorParallelBatchPrefixBudget.captureBytes( + geometry: try Self.geometry(configuration, owner.model, rank: rank), promptCount: donor.count, + chunkSize: 512, allocationBound: { Self.allocationBound($0) }) + #expect(caches[rank].bytesInUse > 0 && caches[rank].bytesInUse <= charge) + } + // (a) The repeat restores the deepest boundary, 32,768. + #expect(try compare(cold, warm, request(donor, profile: profile), label: "repeat") == [32_768, 32_768]) + // (b) The next turn, whose template re-rendered the last 40 tokens + // of a 32,801-token prompt: the margin boundary 32,256 below the + // deepest, 32,768, which the turn no longer shares. + let turn = Array(donor[0..<32_801]) + let second = try donate(warm, try request(turn, profile: profile)) + #expect(second.restored == [32_768, 32_768] && second.stored == [[], []]) + for cache in caches { cache.sweep() } + _ = try donate(warm, try request(turn, profile: profile)) + #expect(caches.allSatisfy { $0.heldFrontiers.contains(32_256) && $0.heldFrontiers.contains(32_768) }) + let next = Array(turn[0..<32_761]) + tokens(300) + #expect(try compare(cold, warm, request(next, profile: profile), label: "turn") == [32_256, 32_256]) + // (c) Prompts sharing only a system prompt of 16,500 or 8,300 + // tokens: the stripe boundaries 16,384 and 8,192. + #expect(try compare(cold, warm, request(Array(donor[0..<16_500]) + tokens(700), profile: profile), + label: "system16k") == [16_384, 16_384]) + #expect(try compare(cold, warm, request(Array(donor[0..<8_300]) + tokens(400), profile: profile), + label: "system8k") == [8_192, 8_192]) + // One rank's loss of its tier: both ranks prefill from zero. + caches[0].sweep() + #expect(try compare(cold, warm, request(turn, profile: profile), label: "one-sided") == [0, 0]) + for cache in caches { cache.sweep() } + } + } +} diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixPlacementTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixPlacementTests.swift new file mode 100644 index 0000000000..aa3de601ef --- /dev/null +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixPlacementTests.swift @@ -0,0 +1,156 @@ +import DarkbloomClusterPlacement +@testable import DarkbloomClusterProtocol +import Foundation +import Testing +@testable import DarkbloomClusterRuntime + +/// Where the registered 27B still places tensor parallel once every lane's +/// quote charges its prompt-prefix capture at the profile's longest prompt +/// (`QwenTensorParallelBatchPrefixBudget`) instead of one 4,096-token capture +/// and two such banks: the actual planner, the real retained headers and +/// LOAD's own quote, on idle constructed Macs of each size (the vision tower's +/// resident bytes aside, as the served layout). No model, no GPU. +struct QwenTensorParallelPrefixPlacementTests { + private struct Retained: Decodable { + struct Tensor: Decodable { let name: String; let shape: [Int]; let sourceDType: String; let byteCount: Int } + struct Profile: Decodable { let configuration: Data; let canonicalTensors: [Tensor] } + let twentySeven: Profile + } + private struct Assistant: Decodable { + struct Tensor: Decodable { let name: String; let shape: [Int]; let dtype: String; let byteCount: Int } + let tensors: [Tensor] + } + private static let gib = 1 << 30 + private func bound(_ bytes: Int) -> Int { ((bytes + 16_383) / 16_384) * 16_384 } + + /// An idle Mac of `physicalGiB`, as the placement checks construct one + /// (`SyntheticMac.idle`): wired 3 % (at least 2.5 GiB), other programs 4 % + /// (at least 3 GiB), 1 GiB of file cache, the rest free. + private func idle(_ label: String, _ physicalGiB: Double) throws -> ClusterPlacementDevice { + let page = 16_384 + func pages(_ value: Double) -> Int { Int((value * Double(Self.gib) / Double(page)).rounded()) } + let wiredGiB = max(2.5, physicalGiB * 0.03), otherGiB = max(3, physicalGiB * 0.04) + let physical = pages(physicalGiB), wired = pages(wiredGiB), free = pages(physicalGiB - wiredGiB - otherGiB - 1) + let cache = pages(1), pageable = physical - wired, anonymous = max(0, pageable - free - cache) + let observation = QwenDenseStageLoadOSObservation(startedNanoseconds: 900, completedNanoseconds: 1_000, + timestampUTC: "2026-11-01T00:00:00Z", physicalMemoryBytes: physical * page, pageSizeBytes: page, + kernelFreePages: free, freePages: free, inactivePages: cache + anonymous / 2, speculativePages: 0, + actualFreeBytes: free * page, estimatedReclaimableBytes: (free + cache + anonymous / 2) * page, pressureLevel: 1, + swapUsedBytes: 0, activePages: anonymous - anonymous / 2, fileBackedPages: cache, anonymousPages: anonymous, + wiredPages: wired, purgeablePages: 0, compressorPages: 0, kernelFileCacheMinimumPages: nil, + inactiveFileBackedPages: cache, inactiveAnonymousPages: anonymous / 2, compressionPages: 0, swapoutPages: 0, + liveCompressionPages: 0) + let bytes = physical * page, workingSet = bytes / 4 * 3 + let profile = try ClusterDeviceProfile(chip: "Synthetic", performanceCores: 8, efficiencyCores: 4, gpuCores: nil, + osVersion: "27.0", osBuild: "SYNTH", physicalMemoryBytes: bytes, gpuRecommendedWorkingSetBytes: workingSet, + gpuMaximumBufferBytes: bytes / 2, allocatorLimitBytes: min(workingSet / 2 * 3, bytes / 100 * 95), + memory: .gate(observation, now: 1_100), + power: .init(onExternalPower: true, lowPowerMode: false, thermalState: "nominal")) + return .init(label: label, profile: profile, speed: .init(source: .measured, absolute: true, + rested: .init(prefillTokensPerSecond: 1000, decodeTokensPerSecond: 60, + tensorShardPrefillTokensPerSecond: 1500, tensorShardDecodeTokensPerSecond: 200), + sustained: nil, explanation: "constructed rates")) + } + + @Test func everyPairThatPlacedTensorParallelStillPlacesIt() throws { + let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("StageMetadataChecks/Inputs/qwen-retained-inputs.json") + let retained = try JSONDecoder().decode(Retained.self, from: Data(contentsOf: url)).twentySeven + let family = try QwenDensePlacementFamily(configuration: retained.configuration), p = family.profile + let plan = try #require(family.tensorParallel) + let text = retained.canonicalTensors.map { + ClusterPlacementStoredTensor(name: $0.name, byteCount: $0.byteCount, dtype: $0.sourceDType, shape: $0.shape) + } + // The artifact's speculative head, which its layout names (`Inputs/qwen27-tp-mtp-inventory.json`). + let head = try JSONDecoder().decode(Assistant.self, from: Data(contentsOf: URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().appendingPathComponent("Inputs/qwen27-tp-mtp-inventory.json"))).tensors.map { + ClusterPlacementStoredTensor(name: $0.name, byteCount: $0.byteCount, dtype: $0.dtype, shape: $0.shape) + } + let stored = text + head + // The served layout's planning facts, without the vision tower's + // resident bytes (the retained headers name the text model only). + var planning = family + planning.tensorParallelRequestAllowance = try QwenTensorParallelRequestBudget.derive(geometry: family.geometry, + plan: plan, tensors: family.requireRegisteredInventory(text), maximumTokens: family.largestContextTokens, + chunkSize: family.maximumChunkTokens, allocationBound: bound).allowance + let specification = family.definition.specification + var layoutObject = try JSONSerialization.jsonObject(with: ClusterModelLayoutBuilder.build(family: planning, + tensors: stored, artifactSHA256: specification.artifactSHA256, + configurationSHA256: specification.configurationSHA256).encoded()) as! [String: Any] + let listed = (layoutObject["generationModes"] as? [String] ?? []) + [ClusterGenerationMode.tensorParallel.rawValue] + layoutObject["generationModes"] = ClusterGenerationMode.allCases.map(\.rawValue).filter(listed.contains) + let layout = try ClusterModelLayout.decode(JSONSerialization.data(withJSONObject: layoutObject, options: [.sortedKeys])) + let request = try ClusterPlacementRequestScope(runtimeModelID: family.runtimeModelID, + artifactSHA256: family.definition.specification.artifactSHA256, + configurationSHA256: family.definition.specification.configurationSHA256, + promptTokens: 1024, outputTokens: 128, maximumPromptTokens: p.maximumPromptTokens, + maximumOutputTokens: p.maximumOutputTokens, maximumContextTokens: p.maximumContextTokens, + requestChargeEveryRankBytes: family.requestChargeEveryRankBytes(contextTokens: 1152)) + let link = ClusterLinkCosts(measured: true, perChunkSeconds: 0.002, perDecodeStepSeconds: [:], + handoffSecondsPerByte: 1 / 2e9, provenance: "constructed for a check", + reduction: .init(fixedSeconds: 1e-6, secondsPerByte: 1 / 5e9, keyed: true, provenance: "constructed for a check")) + // One 4,096-token capture of `geometry` and its two resident banks: the earlier per-lane and shared terms. + func earlier(_ geometry: QwenLongPrefillBudgetGeometry) throws -> Int { + let b = try QwenLongPrefillTensorBudget.estimate(geometry: geometry, maximumTokens: 4096, chunkSize: 1) + return geometry.recurrentLayers * (bound(b.convolutionBytesPerLayer) + bound(b.ssmBytesPerLayer)) + + 2 * geometry.attentionLayers * bound(4096 * geometry.kvHeads * geometry.headDimension * 2) + } + func now(_ geometry: QwenLongPrefillBudgetGeometry) throws -> Int { + try QwenTensorParallelBatchPrefixBudget.captureBytes(geometry: geometry, promptCount: p.maximumPromptTokens, + chunkSize: p.maximumChunkTokens, allocationBound: bound) + } + for lanes in [1, 8] { + let after = try ClusterPlacementArtifact.tensorBatchQuote(configuration: retained.configuration, stored: text, + request: request, chunkTokens: 512, lanes: lanes, allocationBound: bound) + // The same quote with the earlier prefix terms, rank by rank. + func shifted(_ bytes: Int, _ geometry: QwenLongPrefillBudgetGeometry) throws -> Int { + bytes - lanes * (try now(geometry)) + lanes * (try earlier(geometry)) + 2 * (try earlier(geometry)) + } + let whole = family.geometry + let before = try ClusterPlacementTensorBatchQuote(request: request, lanes: lanes, chunkTokens: 512, + perLaneStateBytes: after.perLaneStateBytes - (try now(whole)) + (try earlier(whole)), + sharedBytesExcludingCollectives: after.sharedBytesExcludingCollectives + 2 * (try earlier(whole)), + allowance: .init(maximumContextTokens: after.allowance.maximumContextTokens, + maximumChunkTokens: after.allowance.maximumChunkTokens, + requestBytesExcludingCollectives: try shifted(after.allowance.requestBytesExcludingCollectives, whole), + maximumCollectivePayloadBytes: after.allowance.maximumCollectivePayloadBytes, + maximumCollectiveFrameBytes: after.allowance.maximumCollectiveFrameBytes, allocationBound: bound), + rankQuotes: try after.rankQuotes.map { quotes in + try quotes.map { entry in + let split = try QwenTensorParallelPlan(textConfiguration: try Self.text(retained.configuration), + quantization: try Self.quantization(retained.configuration), size: 2, shares: entry.shares) + return .init(shares: entry.shares, requestBytesExcludingCollectives: try entry.requestBytesExcludingCollectives + .enumerated().map { rank, bytes in + try shifted(bytes, try family.geometry.tensorParallelShard(plan: split, rank: rank)) + }) + } + }) + for size in [24.0, 32, 36, 48, 64, 96, 128, 192, 256] { + let devices = try [idle("a", size), idle("b", size)] + func evaluate(_ quote: ClusterPlacementTensorBatchQuote) throws -> (fits: Bool, need: Int) { + var policy = ClusterPlacementPolicy(); policy.leader = "a" + policy.promptTokens = request.promptTokens; policy.outputTokens = request.outputTokens + if lanes == 1 { try quote.applySingleton(to: &policy, layout: layout) } + else { try ClusterPlacementBatchScope(request: request, lanes: lanes, tensorParallelQuote: quote).apply(to: &policy, layout: layout) } + let candidate = try ClusterPlacementPlanner.evaluate(devices: devices, cuts: [], mode: .tensorParallel, + prefillSchedule: .serial, layout: layout, policy: policy, link: link) + return (candidate.ranks.allSatisfy { $0.hardwareFits == true }, candidate.ranks.map(\.needBytes).max() ?? 0) + } + let then = try evaluate(before), today = try evaluate(after) + print("qwen27-tp-prefix-placement lanes=\(lanes) mac_gib=\(Int(size)) before_fits=\(then.fits)" + + " before_need=\(then.need) after_fits=\(today.fits) after_need=\(today.need) delta=\(today.need - then.need)") + if size >= 256 { #expect(today.fits, "2 x \(Int(size)) GiB, \(lanes) lanes") } + if lanes == 1 && then.fits { #expect(today.fits, "2 x \(Int(size)) GiB placed tensor parallel before") } + } + } + } + + private static func text(_ configuration: Data) throws -> [String: Any] { + let root = try JSONSerialization.jsonObject(with: configuration) as! [String: Any] + return root["text_config"] as! [String: Any] + } + private static func quantization(_ configuration: Data) throws -> [String: Any] { + let root = try JSONSerialization.jsonObject(with: configuration) as! [String: Any] + return root["quantization"] as! [String: Any] + } +} diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRankLedgerTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRankLedgerTests.swift index 782a6c4a66..c549c557bf 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRankLedgerTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRankLedgerTests.swift @@ -127,7 +127,8 @@ struct QwenTensorParallelRankLedgerTests { } return try QwenTensorParallelBatchBudget.derive(geometry: g, plan: plan, tensors: tensors, maximumTokens: p.maximumContextTokens, chunkSize: p.maximumChunkTokens, lanes: lanes, - paged: true, rank: rank, allocationBound: bound).allowance.requestBytesExcludingCollectives + paged: true, rank: rank, promptTokens: p.maximumPromptTokens, + allocationBound: bound).allowance.requestBytesExcludingCollectives } #expect(entry.requestBytesExcludingCollectives == native, "\(entry.shares) lanes \(lanes) depth \(depth as Any)") for rank in 0..<2 { diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRowQuoteTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRowQuoteTests.swift index aa45dd6d38..b5ab7b8cd4 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRowQuoteTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRowQuoteTests.swift @@ -56,7 +56,8 @@ struct QwenTensorParallelRowQuoteTests { stored: stored, request: request, chunkTokens: 16, lanes: lanes, allocationBound: bound) let native = try QwenTensorParallelBatchBudget.derive(geometry: family.geometry, plan: plan, tensors: canonical, maximumTokens: family.profile.maximumContextTokens, - chunkSize: family.profile.maximumChunkTokens, lanes: lanes, paged: true, allocationBound: bound) + chunkSize: family.profile.maximumChunkTokens, lanes: lanes, paged: true, + promptTokens: family.profile.maximumPromptTokens, allocationBound: bound) #expect(quote.allowance == native.allowance, "\(name) lanes=\(lanes)") #expect(quote.perLaneStateBytes == native.perLaneStateBytes) #expect(quote.allowance.maximumCollectivePayloadBytes >= lanes * plan.maximumPartialBytesPerToken) From 16b47fdb53d32b0a67a814d79e6fa6e39cddbc36 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:05:27 -0800 Subject: [PATCH 0134/1441] docs: Qwen TP prompt prefixes to the request's context The Qwen27 TP prefix sections describe the kept boundaries and their parity with one Mac's dense-Qwen reuse, the shared-copy capture, the measured resident tier and the policy bound into the SSD scope (prefix-cache.md); the per-request and LOAD charges with the registered 27B's numbers before and after and the planner's placements (hardware-support.md); the record grid, the write-behind bound and where it drops deep records (ssd-kv-cache.md); the new checks (test.md); and a summary in inference.md. One changelog fragment. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-prefix-depth.md | 6 ++ docs/architecture/hardware-support.md | 55 +++++++++++--- docs/architecture/inference.md | 19 ++++- docs/architecture/prefix-cache.md | 104 +++++++++++++++++++------- docs/developer/test.md | 14 +++- docs/reference/ssd-kv-cache.md | 5 +- 6 files changed, 160 insertions(+), 43 deletions(-) create mode 100644 changelog.d/qwen27-tp-prefix-depth.md diff --git a/changelog.d/qwen27-tp-prefix-depth.md b/changelog.d/qwen27-tp-prefix-depth.md new file mode 100644 index 0000000000..c52f6c8264 --- /dev/null +++ b/changelog.d/qwen27-tp-prefix-depth.md @@ -0,0 +1,6 @@ +### Qwen3.8 27B tensor parallel reuses whole prompt prefixes + +- A Qwen tensor-parallel pair now reuses a repeated prompt's prefix to its last whole 512-token chunk, at any length, instead of at most 4,096 tokens: a repeated 33K-token prompt restores 32,768 tokens on both Macs, as one Mac does. It also keeps the boundaries the next turn of a conversation and prompts that share a long system prompt need, so in each of these cases it reuses at least what one Mac reuses, to the nearest 512 tokens. +- A restored request returns exactly the tokens of a request that prefilled the whole prompt (checked bit for bit on synthetic pairs at 8K, 16K and 32K boundaries). Both Macs must hold a boundary; otherwise both start from zero. +- Each request reserves room for its own prompt's prefix (about 1.8 GB a Mac for a 32K-token prompt on the 27B), and a pair loads with one such prefix per lane: about 1.1 GB a Mac more than before at one lane. Every pair size that ran the 27B in tensor parallel still does. Kept prefixes use free memory only (half of what is left after loading) and are dropped first when memory runs short. Prefixes kept on SSD by an earlier build are not reused. +- The assistant (MTP) lanes still keep prefixes up to 4,096 tokens. Speed on a real pair is not measured yet. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index c91f96c2e6..b0f4d7a1b2 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1,6 +1,6 @@ # Hardware support and the provider memory model -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 What hardware the provider runs on and how it decides, in bytes, whether a model may load and how much KV cache each resident model may use. Read this to @@ -1205,17 +1205,50 @@ Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacem ### Qwen27 TP batch prefix ownership -`QwenTensorParallelBatchPrefixBudget` separately bounds every compact attention, -conv and SSM array using the native allocator metadata. Full unsliced geometry -conservatively covers either rank and unequal shares. The complete native -batch allowance adds one snapshot bank per live lane plus two banks for the -resident cache; the existing live-state, gather, replacement and collective -charges remain. The metadata planner and verified LOAD call the same helper. -A reused prefix does not lower admission or refund the destination's future -state. The configured budget is a ceiling; cache arrays materialize only on -capture. See [prefix ownership](prefix-cache.md#cluster-sliding-prefix-adoption). +`QwenTensorParallelBatchPrefixBudget` prices one plain lane's prompt-prefix +capture, separately bounding every array with the native allocator metadata: +its own heads' keys and values to its deepest kept boundary, and one +convolution and SSM state for every boundary a prompt with that deepest +boundary keeps (`pricedStates`: the deepest, the margin boundary, and the +stripe boundaries up to nine, so at most eleven, and never fewer for a longer +prompt). Each request's reservation charges its own prompt's capture +(`QwenTensorParallelRequestCharge`); LOAD and the placement quote charge one +capture of the profile's longest prompt per lane (`promptTokens`), and nothing +for a resident tier. The geometry is the rank's own heads at LOAD and in each +rank's placement quote; without a rank, the full unsliced geometry covers either +rank and unequal shares. The existing live-state, gather, replacement and +collective charges remain, and a reused prefix does not lower admission or +refund the destination's future state. + +The memory tier that keeps captures after their requests is charged nowhere. +Its budget is half the room LOAD measures beside its whole quote +(`ClusterStagePrefixBudget.roomBytes`, `QwenStagePrefixCache.budget(roomBytes:)`): +at most a thirty-second of the Mac's memory, in 256 MiB steps, and 0 when the +room is under 512 MiB. The reservation and running-batch gates do not credit +its entries as the owner's own allocations, and its entries give way before +either gate refuses (`QwenTensorParallelSnapshotCache.yieldingMemory`). A +capture always keeps what its request's charge covers. With no tier budget it +keeps nothing resident and still writes its SSD record. The assistant's lanes +keep their single 4,096-token frontier and its two charged resident banks +(`QwenTensorParallelMTPPrefixBudget`). See [prefix ownership](prefix-cache.md#cluster-sliding-prefix-adoption). + +The registered Qwen3.8 27B, one rank's own heads at the memory plan (32,768 +prompt tokens, 65,536 context, 16 KiB allocator pages; +`QwenTensorParallelBatchPrefixTests`, `QwenTensorParallelPrefixPlacementTests`): + +| Term | Before (`qwen-tp-batch-grid-prefix-4096-v1`) | Now (`qwen-tp-batch-prefix-depth-v2`) | +|---|---|---| +| A lane's capture | 212,860,928 B (4,096 tokens) | 1,764,753,408 B (rows to 32,256 and nine recurrent states) | +| Resident tier in the quote | 425,721,856 B (two banks) | 0 (half the measured room) | +| LOAD request bytes, one lane | 9,184,591,872 B | 10,310,762,496 B | +| LOAD request bytes, eight lanes | 28,471,181,312 B | 40,460,599,296 B | +| Idle pairs the planner places tensor parallel on, one lane | 2 x 36 GiB and larger | the same; a rank needs 1,126,170,624 B more | +| The same, eight lanes | 2 x 96 GiB and larger | the same; a rank needs 11,989,417,984 B more | + +The planner rows leave out the vision tower's resident bytes, as the served +layout does; both columns leave them out alike. Source: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift` -(`derive`). +(`captureBytes`, `derive`). A drained automatic batch replacement uses the device index and this pair's recorded keyed-link measurement. Missing or invalid measurements continue to diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..1015a55d17 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -5185,6 +5185,23 @@ Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Ten `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/State/CBv2OwnedRequestState.swift` (`growReservation`). +### Qwen27 tensor-parallel prompt-prefix depth + +A plain Qwen tensor-parallel lane keeps prompt-prefix boundaries to its request's +context on its own 512-token chunk grid, not to a fixed 4,096 tokens: the +deepest whole chunk before the final token, a boundary 64 tokens before the +prompt end for the next turn, and one Mac's 4,096-token stripe boundaries for +a shared system prompt (`QwenTensorParallelBatchPrefixBudget`, policy +`qwen-tp-batch-prefix-depth-v2`, which the load agreement binds). A repeated +33K-token prompt restores 32,768 tokens on both ranks, as one Mac reuses; the +restored request computes exactly what a cold one computes on the same grid. +The mechanism, the parity cases and the SSD records are in +[the Qwen27 TP prefixes](prefix-cache.md#qwen27-tp-prefix-ssd-tier) and the +section before it; the memory each request and LOAD charge is in +[Qwen27 TP batch prefix ownership](hardware-support.md#qwen27-tp-batch-prefix-ownership). +The assistant's lanes keep one boundary of at most 4,096 tokens +([assistant prefix ownership](prefix-cache.md#qwen27-tp-assistant-prefix-ownership)). + ### Qwen27 cluster media ingress ownership The scheduler routes image/video requests through `DistributedQwenMediaIngress` diff --git a/docs/architecture/prefix-cache.md b/docs/architecture/prefix-cache.md index 04293c9c21..793471e84f 100644 --- a/docs/architecture/prefix-cache.md +++ b/docs/architecture/prefix-cache.md @@ -1,6 +1,6 @@ # KV cache layouts and prefix caching -> Last updated: 2026-10-28 +> Last updated: 2026-11-01 How the provider lays out a request's KV cache, how it decides whether a previously computed prefix can be reused, and where reusable state lives: @@ -1129,12 +1129,43 @@ every such request with its prefix cache off, so both ranks neither restore nor keep it ([tenant partitions](#cluster-prefix-tenant-partitions)). Source: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Media/QwenMediaRequestState.swift`. -The exact27 multi-lane TP owner retains one compact snapshot per completed -request at an original chunk boundary, at most 4,096 prompt tokens. The resident -LRU holds at most 32 entries and two maximum-sized snapshot banks. A sealed -vote selects the longest boundary both ranks hold; a one-sided miss computes -cold on both ranks. Restoration writes fresh request-owned attention storage -and adopts immutable confirmed conv/SSM state. It never splits the final chunk. +The exact27 multi-lane TP owner keeps a completed plain request's state at +original chunk boundaries to the request's context, strictly before the final +token and after what it restored (`QwenTensorParallelBatchPrefixBudget.frontiers`, +policy `qwen-tp-batch-prefix-depth-v2`): + +| Boundary | Serves | One Mac's counterpart | +|---|---|---| +| The deepest whole chunk before the final token | a repeated prompt | the rolling latest checkpoint | +| The deepest whole chunk at least 64 tokens before the prompt end, from 1,024 tokens on | the next turn of a conversation, whose template re-renders the generation prompt | `demandedLatestPromptEndMarginTokens = 64` | +| 4,096, then every multiple of 4,096 below the deepest, the stripe doubling until at most 8 remain | prompts sharing a long system prompt | the first, fork-target and stripe-end checkpoints of `EngineV2Factory.defaultDenseQwenSoloPrefillStripeTokens` | + +On TP's 512-token grid this reuses at least one Mac's reuse rounded down to the +grid for a repeat, a next turn and a shared system prompt within the first +eight stripes. One Mac's 64-token-margin cut is on a 256-token grid, so it can +be up to 255 tokens deeper. One Mac keeps three boundaries a donor: its first, +its latest, and the fork target the coordinator's `cache_repeated_prefix_tokens` +hint names. TP gets no hint, so it keeps the stripe boundaries instead +([parity checks](../developer/test.md#qwen27-tp-warm-prefix-checks)). + +A capture copies the attention rows once, at its deepest boundary, and the +convolution and SSM state at each boundary (`QwenTensorParallelPrefixCapture`). +The shallower boundaries view the deepest copy, and the resident tier counts it +once per capture. Each request's own capture is charged in its reservation, so +a capture always keeps what its charge covers. The resident tier is charged +nowhere ([memory](hardware-support.md#qwen27-tp-batch-prefix-ownership)). Its +byte budget is set at LOAD from the room measured beside the quote +(`QwenStagePrefixCache.budget(roomBytes:)`). Under that budget it gives up other +captures' shallower boundaries first, then the newest capture's, then whole +captures, least recently used first, so an exact repeat's boundary outlives the +rest. Its entries also give way, after the SSD writer's queue drains, before a +reservation or the running batch is refused for memory +(`QwenTensorParallelSnapshotCache.yieldingMemory`). The vote carries every +chunk boundary of the prompt, at most 512, and selects the longest one both +ranks hold; a one-sided miss computes cold on both ranks. Restoration writes +fresh request-owned attention storage and adopts immutable confirmed conv/SSM +state. It never splits the final chunk. The assistant's lanes keep one boundary +of at most 4,096 tokens ([assistant prefix ownership](#qwen27-tp-assistant-prefix-ownership)). Keys bind the loaded agreement, backend, chunk size, prompt prefix and media identity. The native owner completes media preparation before reuse, so cached @@ -1148,14 +1179,17 @@ is the same batch owner one lane wide, with both tiers; other models retain their existing behavior. The SSD tier is described below. Source: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift` -(`QwenTensorParallelBatchPrefixCache`) and +(`QwenTensorParallelBatchPrefixCache`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift`, +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefixSnapshot.swift` +(`QwenTensorParallelPrefixCapture`) and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift` (`open`, `confirmedRetirement`). Tiny fixtures do not qualify full-artifact warm-prefix correctness, media parity, RDMA or useful speed. ### Qwen27 TP assistant prefix ownership -The TP assistant prefix donor binds a compact target attention/recurrent snapshot and the same assistant's trusted prompt history at one confirmed original prompt frontier. Restore creates request-owned mutable state and both ranks negotiate the common usable frontier. The bounded cache publishes donors only after checked retirement and a final cancellation/deadline vote; a failed decoder cannot donate. Captured speculative target windows, pending assistant drafts and queued accepted tokens are not prefix donors. Both resident donor banks and the temporary capture bank remain in the complete quote. +The TP assistant prefix donor binds a compact target attention/recurrent snapshot and the same assistant's trusted prompt history at one confirmed original prompt frontier, at most 4,096 tokens deep (`QwenTensorParallelMTPPrefixBudget.maximumTokens`, policy `qwen-tp-mtp-grid-prefix-4096-v1`). That bound is the assistant's history ledger as well: prefill holds the trusted history unflushed up to the checkpoint frontier, so a deeper frontier would keep a lane's whole prompt history resident, not only a larger capture. Restore creates request-owned mutable state and both ranks negotiate the common usable frontier. The bounded cache publishes donors only after checked retirement and a final cancellation/deadline vote; a failed decoder cannot donate. Captured speculative target windows, pending assistant drafts and queued accepted tokens are not prefix donors. Both resident donor banks and the temporary capture bank remain in the complete quote. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefix.swift` (`QwenTensorParallelMTPPrefixState`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefixBudget.swift`, and `libs/mlx-swift-lm/Libraries/MLXLLM/Models/Qwen35MTP+PrefixCheckpoint.swift` (`Qwen35InlineMTPAssistant`). Full-artifact warm-prefix numerical and cancellation checks remain separate from tiny ownership fixtures. @@ -1164,24 +1198,33 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Tensor Both ranks of every Qwen TP row's batch owner (9B, 27B, Qwen3.5/3.6 35B A3B) also keep their prefix snapshots in the pipeline's encrypted SSD tier (`QwenStagePrefixDiskTier`), so a repeated long prompt restores its prefix after both Macs restart. Each rank writes only its -own shard: its heads' attention rows and its recurrent state at the captured -boundary, and for a speculating owner the assistant's trusted history at that -boundary as the record's speculative history. Records are written behind -serving after bilateral clean retirement, and only for a capture the resident -tier accepted, so a restore fits that tier again. The record directory is -named by the plan and shares, the verified artifact, this rank's storage -commitment, both builds and the assistant policy, never by the membership -epoch. A restarted pair finds what the last one kept; a re-split, a reinstall -or another assistant starts a new directory. +own shard: its heads' attention rows to the deepest kept boundary, and its +recurrent state at that boundary and at each kept boundary on the record's grid +(the tier's stride, doubled until at most `maximumGridFrontiers` remain; the +kept stripe boundaries past 4,096 are on it, the margin boundary and the 4,096 +one of a prompt past the first eight stripes generally are not). For a +speculating owner, the record also carries the assistant's trusted history at +its boundary as the record's speculative history. Records are written behind +serving after bilateral clean retirement, for every clean capture, including +one the resident tier's budget does not hold. Until a record is written, the +writer holds that capture's arrays, within the queue's bounds. The record +directory is named by the plan and shares, the verified artifact, this rank's +storage commitment, both builds, the assistant policy and the prefix policy, +never by the membership epoch. A restarted pair finds what the last one kept; +a re-split, a reinstall, another assistant or another prefix policy (the +4,096-token `qwen-tp-batch-grid-prefix-4096-v1` included) starts a new +directory, so no rank offers an older policy's record. The sealed vote counts a boundary held in memory or as a complete SSD record. Each rank restores the agreed boundary from its own tiers, memory first. It checks that an SSD shard adopts into its request geometry before any page is -written, and charges the shard to the resident tier at once. A second sealed -exchange confirms that both ranks restored. Otherwise both prefill from zero, -and a rank that did read its record keeps it resident, so the next offer finds -it in memory. An unreadable or unadoptable record is deleted. The load -agreement carries `qwen-tensor-parallel-prefix-v2`. +written. The resident tier keeps the shard when its budget holds it; otherwise +the shard is restored once, within the request's own charged capture, which +covers its deepest boundary. A second sealed exchange confirms that both ranks +restored. Otherwise both prefill from zero, and a rank that did read its record +keeps it resident when the budget holds it, so the next offer finds it in +memory. An unreadable or unadoptable record is deleted. The load agreement +carries `qwen-tensor-parallel-prefix-v2` and the prefix policy. Attention rows are stored at the pair's checkpoint precision (`balanced` by default): a shard restored from its record has older rows approximate and the @@ -1191,15 +1234,20 @@ the request then differs from a cold one. The load agreement then also carries [cluster SSD prefix record encoding](inference.md#cluster-ssd-prefix-record-encoding). The tier logs `darkbloom-prefix-ssd-v1` lines (`open`, `persist`, `restore`, -`restore-confirmed`, `restore-declined`, `close`); the -`darkbloom-tp-batch-prefix-v1` events are unchanged. Shutdown closes the tier -(queued writes finish, bounded) before the model is released. +`restore-confirmed`, `restore-declined`, `restore-unkept`, `close`); the +`darkbloom-tp-batch-prefix-v1` events are unchanged (`stored` names the +deepest boundary the resident tier kept, 0 for none). LOAD logs +`darkbloom-prefix-v1 rank= family=qwen mode=tensor_parallel enabled= +policy= budget_bytes= capture_charge= +room_bytes= ssd=`. Shutdown closes the tier (queued writes +finish, bounded) before the model is released. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefixDisk.swift`, `QwenTensorParallelNativeBatchExecutor.swift` (`agreePrefix`, `confirmedRetirement`) and `QwenTensorParallelResidentRuntime.swift` (load and shutdown) in the same directory. -Tests: `QwenTensorParallelBatchSessionTests` (`ssd…AfterTheTiersReopen`) and -`QwenTensorParallelMTPSessionTests` (the SSD round trip onto a newly loaded head). +Tests: `QwenTensorParallelBatchSessionTests` (`ssd…AfterTheTiersReopen`), +`QwenTensorParallelMTPSessionTests` (the SSD round trip onto a newly loaded head) +and `QwenTensorParallelBatchPrefixTests` (`recordsOfAnotherPolicyAreNeverOffered`). ### GLM TP prefix SSD tier diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..f195f40dc7 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -2399,7 +2399,17 @@ separate hardware gates. ### Qwen27 TP warm-prefix checks `QwenTensorParallelBatchPrefixTests` checks original-grid boundaries, bilateral -misses, media/key isolation, allocator rounding and bounded LRU eviction. The +misses, media/key isolation, allocator rounding and bounded LRU eviction. It +also checks, for every prompt from 1,100 to 70,000 tokens, that the kept +boundaries reuse at least one Mac's reuse rounded to the 512-token grid (a +repeat, the next turn, a shared system prompt). It checks each request's +charge, LOAD's one capture per lane, the shared-copy eviction order, the +memory tier giving way before a refusing gate, and that a record of another +prefix policy is in another scope. On the GPU (`QWEN_TP_BATCH_GPU=1`), +`QwenTensorParallelPrefixDepthTests` restores a 33,000-token prompt's +boundaries at 32,768, 32,256, 16,384 and 8,192 on two synthetic hybrid +shards and compares the final logits and every attention, convolution and SSM +array with a cold prefill on the same grid, byte for byte, on both ranks. The real-shard `QwenTensorParallelBatchSessionTests` compares cold and restored outputs plus attention/conv/SSM state at widths 2, 4 and 8, mixed positions, reordered decode and one-sided cache loss. Run it with both contiguous and diff --git a/docs/reference/ssd-kv-cache.md b/docs/reference/ssd-kv-cache.md index 728b31a595..7e18978c8a 100644 --- a/docs/reference/ssd-kv-cache.md +++ b/docs/reference/ssd-kv-cache.md @@ -1,6 +1,6 @@ # SSD KV cache reference -> Last updated: 2026-10-28 +> Last updated: 2026-11-01 Exact on-disk format, paths, identity binding, environment knobs, size and eviction rules, and per-family reuse capability of the provider's encrypted SSD @@ -600,6 +600,9 @@ per family and bindings are in the | Restore | Decoded into page-aligned native buffers the arrays own: `[1, heads, frontier, width]` of the captured dtype, as a native record restores; older rows approximate | `QwenStagePrefixDiskRestoreWork.place` | | Restored rows written again | An encoded row whose native bytes equal the decode of the same row in the record holding the prompt's deepest kept prefix on this rank is stored as that record's bytes, not encoded again (the codec is not idempotent on its own output); that record is pinned until the new one is written, and if it cannot be read the new record is dropped (`reason=verbatim_source_unreadable`). The `persist` line logs `verbatim_rows` | `QwenStagePrefixDiskVerbatimSource`, `QwenStagePrefixDiskTier.persist` | | Switch | `DARKBLOOM_CLUSTER_PREFIX_SSD_QUANTIZATION` on the rank, from the owner ([configuration](configuration.md#cluster-ssd-prefix-record-precision)) | `QwenStagePrefixDiskEncoding.fromEnvironment` | +| Record frontiers | The deepest captured frontier's attention rows once, and the recurrent state at it and at each captured frontier on the record grid: `strideTokens` (2,048) rounded up to the block and doubled until at most `maximumGridFrontiers = 8` remain | `QwenStagePrefixDiskTier.persist` | +| Write-behind bound | At most `maximumQueuedJobs = 2` records queued and `QwenStagePrefixDiskPolicy.queuedBytesBound` host bytes (a sixty-fourth of memory, at least 256 MiB); a persist beyond either is dropped (`event=persist-dropped reason=queue_full` or `queue_bytes`) and serving never waits. A Qwen3.8 27B tensor-parallel rank's record holds 32,768 bytes a prompt token and 76,972,032 bytes a recurrent state, so a deepest frontier from about 114,688 tokens (256 GB), 49,664 (128 GB) or 20,992 (64 GB) on is not written | `QwenStagePrefixDiskConfiguration.maximumQueuedBytes`, `QwenStagePrefixDiskPolicy.queuedBytesBound` | +| Qwen tensor-parallel scope | The plan scope binds the plan and shares, artifact, storage, both builds, the assistant policy and the prefix policy (`QwenTensorParallelBatchPrefixBudget.policy`); records of another policy live in another directory and are never offered | `QwenTensorParallelPrefixDisk.planScope` | ## GLM cluster image exclusion From ad84cd4c9c14b00cf4b33fe600f7023647618ece Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:11:29 -0800 Subject: [PATCH 0135/1441] docs: Qwen TP prefix restores are exact from memory, approximate from balanced records The changelog fragment and the inference summary said every restored request computes what a cold one does; that holds for the memory tier and native SSD records, while the SSD tier's default balanced records keep older attention rows approximate (unchanged by this branch). Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-prefix-depth.md | 2 +- docs/architecture/inference.md | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/changelog.d/qwen27-tp-prefix-depth.md b/changelog.d/qwen27-tp-prefix-depth.md index c52f6c8264..8239922e03 100644 --- a/changelog.d/qwen27-tp-prefix-depth.md +++ b/changelog.d/qwen27-tp-prefix-depth.md @@ -1,6 +1,6 @@ ### Qwen3.8 27B tensor parallel reuses whole prompt prefixes - A Qwen tensor-parallel pair now reuses a repeated prompt's prefix to its last whole 512-token chunk, at any length, instead of at most 4,096 tokens: a repeated 33K-token prompt restores 32,768 tokens on both Macs, as one Mac does. It also keeps the boundaries the next turn of a conversation and prompts that share a long system prompt need, so in each of these cases it reuses at least what one Mac reuses, to the nearest 512 tokens. -- A restored request returns exactly the tokens of a request that prefilled the whole prompt (checked bit for bit on synthetic pairs at 8K, 16K and 32K boundaries). Both Macs must hold a boundary; otherwise both start from zero. +- A prefix restored from memory returns exactly the tokens of a request that prefilled the whole prompt (checked bit for bit on synthetic pairs at 8K, 16K and 32K boundaries); one restored from the SSD tier's default `balanced` records is close but not identical, as before. Both Macs must hold a boundary; otherwise both start from zero. - Each request reserves room for its own prompt's prefix (about 1.8 GB a Mac for a 32K-token prompt on the 27B), and a pair loads with one such prefix per lane: about 1.1 GB a Mac more than before at one lane. Every pair size that ran the 27B in tensor parallel still does. Kept prefixes use free memory only (half of what is left after loading) and are dropped first when memory runs short. Prefixes kept on SSD by an earlier build are not reused. - The assistant (MTP) lanes still keep prefixes up to 4,096 tokens. Speed on a real pair is not measured yet. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 1015a55d17..44fcd825b4 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -5193,8 +5193,10 @@ deepest whole chunk before the final token, a boundary 64 tokens before the prompt end for the next turn, and one Mac's 4,096-token stripe boundaries for a shared system prompt (`QwenTensorParallelBatchPrefixBudget`, policy `qwen-tp-batch-prefix-depth-v2`, which the load agreement binds). A repeated -33K-token prompt restores 32,768 tokens on both ranks, as one Mac reuses; the -restored request computes exactly what a cold one computes on the same grid. +33K-token prompt restores 32,768 tokens on both ranks, as one Mac reuses. A +request restored from memory or a native SSD record computes exactly what a +cold one computes on the same grid; the SSD tier's default `balanced` records +keep their older rows approximate. The mechanism, the parity cases and the SSD records are in [the Qwen27 TP prefixes](prefix-cache.md#qwen27-tp-prefix-ssd-tier) and the section before it; the memory each request and LOAD charge is in From 8cfe3f3cc2129d932f1b45b1baf56c8a576a125d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:14:42 -0800 Subject: [PATCH 0136/1441] cluster: past the capture limit, drop the least recent Qwen TP capture whole The snapshot cache bounded its capture count through the per-entry victim order, which thins other captures' shallower boundaries before it removes a whole one, so a 65th capture could strip many prompts' stripe boundaries before freeing a slot. As the pipeline's tier does with its prompt limit, the least recently used capture now goes whole; the byte budget and the entry limit keep the shallowest-first order. Co-Authored-By: Claude Opus 5.5 --- .../QwenTensorParallelBatchPrefixCache.swift | 13 ++++++++++++- .../QwenTensorParallelBatchPrefixTests.swift | 14 ++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift index 35b4f43852..1656bcb9d0 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift @@ -165,13 +165,24 @@ final class QwenTensorParallelSnapshotCache 0 ? 1 : 0) > Self.maximumGroups || entries.count + adding > Self.maximumEntries + // Over the capture count: the least recently used capture goes whole + // (thinning other captures would not lower the count). + while groups.count + (adding > 0 ? 1 : 0) > Self.maximumGroups, let group = leastRecentlyUsedGroup() { + for (key, entry) in entries where entry.group == group { remove(key, entry); evictions += 1 } + } + while entries.count + adding > Self.maximumEntries || (bytesInUse > 0 && bytesInUse > budgetBytes - min(budgetBytes, reserving)), let (key, entry) = victim() { remove(key, entry); evictions += 1 } } + private func leastRecentlyUsedGroup() -> UInt64? { + var latest: [UInt64: UInt64] = [:] + for entry in entries.values { latest[entry.group] = max(latest[entry.group] ?? 0, entry.lastUse) } + return latest.min(by: { ($0.value, $0.key) < ($1.value, $1.key) })?.key + } + /// The least recently used shallower boundary of a capture other than the /// newest, then the newest capture's shallowest, then the least recently /// used entry (a whole capture's deepest boundary). diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchPrefixTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchPrefixTests.swift index 5fac167cf9..9906f1ae64 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchPrefixTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchPrefixTests.swift @@ -201,6 +201,20 @@ struct QwenTensorParallelBatchPrefixTests { #expect(group("f", [4], own: 10, shared: 0) == []) } + @Test func pastTheCaptureLimitTheLeastRecentCaptureGoesWhole() throws { + let cache = QwenTensorParallelBatchPrefixCache(enabled: true, budgetBytes: 1 << 30) + let limit = QwenTensorParallelBatchPrefixCache.maximumGroups + for index in 0.. Date: Sun, 1 Nov 2026 14:16:23 -0800 Subject: [PATCH 0137/1441] docs: one Mac's latest cut can be 256 tokens deeper than Qwen TP's The parity note said up to 255 tokens. One Mac's 64-token-margin cut is on the 256-token grid, so where it lands on an odd multiple of 256 above TP's deepest 512-token boundary it is exactly 256 deeper. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/prefix-cache.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/architecture/prefix-cache.md b/docs/architecture/prefix-cache.md index 793471e84f..8d48affe48 100644 --- a/docs/architecture/prefix-cache.md +++ b/docs/architecture/prefix-cache.md @@ -1142,10 +1142,11 @@ policy `qwen-tp-batch-prefix-depth-v2`): On TP's 512-token grid this reuses at least one Mac's reuse rounded down to the grid for a repeat, a next turn and a shared system prompt within the first -eight stripes. One Mac's 64-token-margin cut is on a 256-token grid, so it can -be up to 255 tokens deeper. One Mac keeps three boundaries a donor: its first, -its latest, and the fork target the coordinator's `cache_repeated_prefix_tokens` -hint names. TP gets no hint, so it keeps the stripe boundaries instead +eight stripes. One Mac's 64-token-margin cut is on a 256-token grid, so for +some prompt lengths it is 256 tokens deeper than TP's deepest boundary. One Mac +keeps three boundaries a donor: its first, its latest, and the fork target the +coordinator's `cache_repeated_prefix_tokens` hint names. TP gets no hint, so it +keeps the stripe boundaries instead ([parity checks](../developer/test.md#qwen27-tp-warm-prefix-checks)). A capture copies the attention rows once, at its deepest boundary, and the From 86c475cf833c75bf4d9f3924eaffffee4c0ba1cc Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:16:48 -0800 Subject: [PATCH 0138/1441] Count non-finite Qwen TP logits inside the selection's sealed sum Greedy selection now sums each rank's non-finite logit count beside its maximum and first global index (as the assistant's greedy choice already does), and a sampled cohort counts its gathered rows; both ranks read the counts from the same evaluation that yields the tokens. A non-finite logit on either rank fails both ranks before any token is chosen, a sampler advances or anything is published. Before, the rank that saw it failed alone at the decode step's separate finiteness read and its peer waited in the selection collective; that read is gone (validateLogits keeps the shape and dtype checks), so a decode step pays one host synchronization fewer. Every selected token is unchanged. nativeNonfiniteRowsOnOneRankFailBothRanks puts non-finite logits on rank 1's vocabulary rows only: against the previous selection the test process trapped after the wire's 30 s deadline (the peer never met it); now both ranks fail. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-decode-loop.md | 7 +++++- docs/architecture/inference.md | 11 +++++++++ .../QwenTensorParallelBatchSession.swift | 8 ++++--- ...wenTensorParallelNativeBatchExecutor.swift | 23 +++++++++++++------ .../QwenTensorParallelBatchSessionTests.swift | 14 ++++++++++- 5 files changed, 51 insertions(+), 12 deletions(-) diff --git a/changelog.d/qwen27-tp-decode-loop.md b/changelog.d/qwen27-tp-decode-loop.md index f4b70eb48e..c471124fc0 100644 --- a/changelog.d/qwen27-tp-decode-loop.md +++ b/changelog.d/qwen27-tp-decode-loop.md @@ -1,9 +1,14 @@ -### Qwen tensor-parallel decode routes in the rank log +### Qwen tensor-parallel decode routes and finiteness check - Each rank of a Qwen tensor-parallel pair logs its decode routes once per load (`qwen-tp-decode-census-v1`): which projections take the batch-invariant kernel and at which layout per row count, the attention and residual-norm routes, and the arithmetic switches in force. +- A non-finite logit on either rank now fails both ranks in the same selection + step, before any token is published; previously the other rank waited in the + selection collective. The check moved into the selection's sealed sum, so a + decode step no longer pays a separate finiteness read. Selected tokens are + unchanged. - `darkbloom-cluster-tp-check qwen-rows` checks, on one Mac over the loopback ring, that a Qwen3.8-27B row decodes the same bytes alone, beside other rows and in verify windows at the registered per-rank widths (random weights). diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 23b3c68647..e40fb61d63 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -5091,6 +5091,17 @@ acknowledgement. Failed release retains the reservation for cleanup or the worker's process fence. Every row's singleton and batch owners publish raw selection logprobs through the committed-token channel. +Selection checks finiteness inside its own sealed sum, as the assistant's greedy +choice does (`QwenTensorParallelNativeBatchExecutor.select`): each rank adds its +rows' non-finite logit counts beside their maximum and first global index (a +sampled cohort counts the gathered rows), and both ranks read them from the +same evaluation that yields the tokens. A non-finite logit on either rank fails +both ranks before any token is chosen, a sampler advances or anything is +published; before, the rank that saw it failed alone and its peer waited in the +selection sum. The decode step no longer pays a separate finiteness read +(`QwenTensorParallelBatchSession.validateLogits` checks shape and dtype), and +every selected token is unchanged. + The batch path can restore mutually held original-grid prefix snapshots into fresh request-owned state. TP speculative rounds remain a separate integration. Installed owners propagate a priced saved width or explicit diagnostic width for every Qwen TP row; automatic placement diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift index 8f711e56f5..957c849061 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift @@ -549,12 +549,14 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { throw ProbeError("Qwen TP positions differ from request-owned three-axis slices") } } + /// Shape and dtype only: selection counts non-finite logits inside its own + /// sealed sum (`QwenTensorParallelNativeBatchExecutor.select`), so both + /// ranks refuse such a row together and no step pays a separate read. private static func validateLogits(_ value: MLXArray, rows: Int, model: QwenTensorParallelModel, request: QwenLayerStageGenerationRequest) throws { guard value.shape == [rows, model.vocabularyRange.count], - String(describing: value.dtype) == request.profile.selectedRowDType, - all(isFinite(value)).item(Bool.self) else { - throw ProbeError("Qwen TP batched logits have an invalid shape, dtype or finite value") + String(describing: value.dtype) == request.profile.selectedRowDType else { + throw ProbeError("Qwen TP batched logits have an invalid shape or dtype") } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift index 118de89de6..0366507f2d 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift @@ -415,6 +415,7 @@ final class QwenTensorParallelNativeBatchExecutor 0 { pieces.append(MLXArray.zeros([width, after], dtype: .float32)) } let full = group.allSum(pieces.count == 1 ? values : concatenated(pieces, axis: 1)) - eval(full); try check() - guard full.shape == [width, model.plan.vocabularySize], all(isFinite(full)).item(Bool.self) else { + let gatheredNonfinite = (1 - isFinite(full).asType(.float32)).sum() + eval(full, gatheredNonfinite); try check() + guard full.shape == [width, model.plan.vocabularySize], gatheredNonfinite.item(Float.self) == 0 else { throw ProbeError("Qwen TP gathered sampling rows are invalid") } var choices = MLXArray.zeros([width], dtype: .float32) @@ -441,14 +443,21 @@ final class QwenTensorParallelNativeBatchExecutor both[0..., 0], both[0..., 3], both[0..., 1]).asType(.int32) + selected = which(both[0..., 3] .> both[0..., 0], both[0..., 4], both[0..., 1]).asType(.int32) + nonfinite = both[0..., 2] + both[0..., 5] + } + eval([selected] + (nonfinite.map { [$0] } ?? [])); try check() + guard nonfinite?.asArray(Float.self).allSatisfy({ $0 == 0 }) ?? true else { + throw ProbeError("Qwen TP selection rows have a non-finite logit") } - eval(selected); try check() let tokens = selected.asArray(Int32.self).map(Int.init); try check() guard tokens.count == width, tokens.allSatisfy({ (0.. Date: Sun, 1 Nov 2026 14:45:28 -0800 Subject: [PATCH 0139/1441] cluster: keep Qwen TP prompt prefixes to each request's own context A plain lane's vote and kept boundaries were capped at the prefix budget's maximumTokens, which LOAD sets to the memory plan's context (65,536 for the 27B, whose profile serves 262,144). A prompt past it kept and restored at most 65,536 tokens, although its reservation already charged its whole capture and the docs, changelog and parity check say "to the request's context". open now votes and keeps to the request's own context, and the capture limit it hands the session is the capture the reservation charged (no LOAD cap). The GPU depth test now gives LOAD a context shorter than its requests (red with the old cap: six issues; green now). Also drops an unused capture accessor and a no-op filter in the cache's group insert. Co-Authored-By: Claude Opus 5.5 --- .../Resources/QwenTensorParallelBatchPrefixBudget.swift | 9 +++++---- .../QwenTensorParallelBatchPrefixCache.swift | 2 +- .../QwenTensorParallelNativeBatchExecutor.swift | 5 +++-- .../QwenTensorParallelPrefixSnapshot.swift | 3 --- .../QwenTensorParallelBatchPrefixTests.swift | 9 ++++++--- .../QwenTensorParallelPrefixDepthTests.swift | 6 ++++-- 6 files changed, 19 insertions(+), 15 deletions(-) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift index 2d7f559e0f..9562a9047b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift @@ -38,8 +38,8 @@ struct QwenTensorParallelBatchPrefixBudget { static let marginFloorTokens = 1024 static let maximumStripeBoundaries = 8 - /// Boundaries deeper than this are neither voted nor kept: the owner's - /// longest request. + /// The context LOAD derived `captureBytes` at (the memory plan's). It + /// does not bound a request, whose boundaries go to its own context. let maximumTokens: Int /// The per-lane LOAD term: one capture of the profile's longest prompt. let captureBytes: Int @@ -108,11 +108,12 @@ struct QwenTensorParallelBatchPrefixBudget { ]) } - /// This request's own capture: priced on `geometry`, else `captureBytes`. + /// This request's own capture, as its reservation charged it + /// (`QwenTensorParallelRequestCharge`): priced on `geometry`, else `captureBytes`. func captureBytes(promptCount: Int, chunkSize: Int, allocationBound: (Int) throws -> Int) throws -> Int { guard let geometry else { return captureBytes } return try Self.captureBytes(geometry: geometry, promptCount: promptCount, chunkSize: chunkSize, - maximumTokens: maximumTokens, allocationBound: allocationBound) + allocationBound: allocationBound) } /// LOAD's per-lane term: one capture of a `promptTokens` prompt (the diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift index 1656bcb9d0..ea24eb7fb0 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift @@ -92,8 +92,8 @@ final class QwenTensorParallelSnapshotCache [Int] { + let sorted = states.sorted { $0.state.committedTokens < $1.state.committedTokens } // An attention-only state holds nothing of its own beside the shared copy. - let sorted = states.filter { $0.state.allocatedBytes >= 0 }.sorted { $0.state.committedTokens < $1.state.committedTokens } guard enabled, let deepest = sorted.last, sharedBytes >= 0, sharedBytes + deepest.state.allocatedBytes > 0 else { return [] } var total = sharedBytes + deepest.state.allocatedBytes guard total <= budgetBytes else { return [] } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift index 433134bf15..8d014ac16e 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift @@ -174,8 +174,9 @@ final class QwenTensorParallelNativeBatchExecutor [Int: (keys: MLXArray, values: MLXArray)] { diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchPrefixTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchPrefixTests.swift index 9906f1ae64..a1cb3e1ab1 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchPrefixTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchPrefixTests.swift @@ -153,9 +153,12 @@ struct QwenTensorParallelBatchPrefixTests { promptTokens: 32_768, chunkSize: 512, allocationBound: bound) #expect(load.captureBytes == (try QwenTensorParallelBatchPrefixBudget.captureBytes(geometry: g, promptCount: 32_768, chunkSize: 512, allocationBound: bound))) - #expect(try load.captureBytes(promptCount: 9_000, chunkSize: 512, allocationBound: bound) - == (try QwenTensorParallelBatchPrefixBudget.captureBytes(geometry: g, promptCount: 9_000, chunkSize: 512, - allocationBound: bound))) + // A request is charged and captures to its own context, past LOAD's memory plan too. + for prompt in [9_000, 100_000, 262_143] { + #expect(try load.captureBytes(promptCount: prompt, chunkSize: 512, allocationBound: bound) + == (try QwenTensorParallelBatchPrefixBudget.captureBytes(geometry: g, promptCount: prompt, chunkSize: 512, + allocationBound: bound))) + } let context = try QwenTensorParallelBatchPrefixBudget.derive(geometry: g, maximumTokens: 4096, chunkSize: 512, allocationBound: bound) #expect(context.captureBytes == (try QwenTensorParallelBatchPrefixBudget.captureBytes(geometry: g, diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixDepthTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixDepthTests.swift index 0c78b59802..ea546de379 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixDepthTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixDepthTests.swift @@ -86,7 +86,9 @@ struct QwenTensorParallelPrefixDepthTests { /// A pair of shards of one tiny hybrid checkpoint (three GatedDelta layers, /// one attention layer); with `caches`, each rank keeps prompt prefixes - /// charged by the real per-request rule on its own heads. + /// charged by the real per-request rule on its own heads. LOAD's memory + /// plan is shorter than the requests, as the 27B's is beside its native + /// context: boundaries still go to each request's own context. private func pair(_ configuration: Data, _ tensors: [(String, MLXArray)], caches: [QwenTensorParallelBatchPrefixCache]?) throws -> [Owned] { let wire = Rendezvous() @@ -101,7 +103,7 @@ struct QwenTensorParallelPrefixDepthTests { owner.executor = try .init(model: model, configuration: configuration, host: owner.host, group: reduction, prepare: { _, _ in nil }, completedDecode: { _ in }, completedPrefill: {}, releaseResources: { _ in }, prefix: caches?[rank], - prefixBudget: caches == nil ? nil : .init(maximumTokens: Self.context, captureBytes: 0, geometry: geometry), + prefixBudget: caches == nil ? nil : .init(maximumTokens: 8_192, captureBytes: 0, geometry: geometry), prefixScope: caches == nil ? nil : { _ in "depth-load|chunk=512|kv=paged|text" }, allocationBound: caches == nil ? nil : { Self.allocationBound($0) }) return owner From cbe418ed423146b0923d5ee644f16d4812b36c13 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:45:36 -0800 Subject: [PATCH 0140/1441] cluster: Qwen TP memory gates after per-request prefix captures Two gate regressions the per-request capture introduced: - reserveLane required every request within the memory plan's context to fit LOAD's per-lane quote. LOAD prices one capture of the plan's longest prompt (32,768), so a longer prompt within that context (for example 60,000 prompt + 4,000 output tokens) now exceeded it by about 1 GB and was refused, where it was admitted before. A request is within the memory plan only when its prompt is too (QwenTensorParallelRequestCharge.withinMemoryPlan); a longer prompt is charged at its own and gated live, as a longer context already is. - requireBatchMemory credits allocations since LOAD as the owner's own. Every clean capture is now written to SSD, including captures the resident tier does not keep, so the writer can hold up to its queue byte bound (a sixty-fourth of memory) of retired captures that no charge covers, and the gate credited them. While the writer is busy the gate no longer credits up to that bound; a refusal drains the writer first, as before. Co-Authored-By: Claude Opus 5.5 --- .../QwenTensorParallelRequestCharge.swift | 8 ++++++++ .../QwenTensorParallelResidentRuntime+Batch.swift | 11 ++++++++--- .../QwenTensorParallelNativeContextTests.swift | 15 +++++++++++++++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRequestCharge.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRequestCharge.swift index e1adaa6745..992761457b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRequestCharge.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRequestCharge.swift @@ -64,6 +64,14 @@ struct QwenTensorParallelRequestCharge { return .init(laneBytes: lane, sharedBytes: max(loadSharedBytes, shared)) } + /// Whether a request lies within the memory plan LOAD quoted every lane + /// at, whose per-lane quote its lane must then fit: its context and its + /// prompt, since its prefix capture grows with its prompt. Any other + /// request is charged at its own context and prompt alone. + static func withinMemoryPlan(maximumTokens: Int, promptTokens: Int, memory: QwenLayerStageGenerationProfile) -> Bool { + maximumTokens <= memory.maximumContextTokens && promptTokens <= memory.maximumPromptTokens + } + /// The longest request of `contextTokens` within `profile`: its longest /// prompt that leaves an output token, in the profile's chunks. func charge(contextTokens: Int, profile: QwenLayerStageGenerationProfile) throws -> Charge { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime+Batch.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime+Batch.swift index 906a1f0082..226209b53b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime+Batch.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime+Batch.swift @@ -50,7 +50,8 @@ extension QwenTensorParallelResidentRuntime { let laneBytes = charge.laneBytes // Within the memory plan, a lane fits the quote LOAD admitted it under. let loadLaneBytes = batchMTPBudget?.perLaneStateBytes ?? batchBudget.perLaneStateBytes - guard request.maximumTokens > admission.memoryProfile.maximumContextTokens || laneBytes <= loadLaneBytes else { + guard !QwenTensorParallelRequestCharge.withinMemoryPlan(maximumTokens: request.maximumTokens, + promptTokens: request.promptCount, memory: admission.memoryProfile) || laneBytes <= loadLaneBytes else { throw ProbeError("Tensor-parallel lane state exceeds its LOAD budget") } let mediaBudget: QwenMediaBudget? @@ -132,7 +133,9 @@ extension QwenTensorParallelResidentRuntime { /// twice in the allocator ceiling. Host media keeps its separate full bound. /// The shared workspaces are held once, at the longest context any held /// (or entering) request has: LOAD's within the memory plan. The plain - /// lanes' kept prefix entries are in no charge, so they are not credited. + /// lanes' kept prefix entries are in no charge, so they are not credited; + /// nor are the retired captures the SSD writer may still hold while it + /// writes (at most its queue's byte bound; a refusal drains it first). private func requireBatchMemory(extraState: Int = 0, extraShared: Int = 0, extraNative: Int = 0, extraHost: Int = 0, entering: Bool = false) throws { guard batchBudget != nil else { throw ProbeError("Qwen TP batch LOAD quote is missing") } @@ -142,7 +145,9 @@ extension QwenTensorParallelResidentRuntime { let native = try sum([shared, requestCharge.collectiveScratchBytes, sum(held.map(\.laneStateBytes)), sum(held.map { $0.media?.budget.nativeBytes ?? 0 }), extraState, extraNative]) let host = try sum([sum(held.map { $0.media?.budget.hostBytes ?? 0 }), extraHost]) - let kept = batchPrefix?.bytesInUse ?? 0 + // A zero-second drain only asks whether the writer is idle. + let writing = prefixDisk.map { !$0.tier.drain(timeoutSeconds: 0) } ?? false + let kept = try sum([batchPrefix?.bytesInUse ?? 0, writing ? prefixDisk?.tier.configuration.maximumQueuedBytes ?? 0 : 0]) let remaining = try QwenResidentRequestAllowance.continuingRequirement(reservedBytes: native, additionalBytes: 0, grownBytes: max(0, Memory.activeMemory - batchAllocationBaseline - kept)) try QwenResidentResourceEnvironment.requirePower() diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelNativeContextTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelNativeContextTests.swift index fd91684bd3..59b0fe5573 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelNativeContextTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelNativeContextTests.swift @@ -94,6 +94,21 @@ struct QwenTensorParallelNativeContextTests { } } + /// A prompt past the memory plan's within its context: its own prefix + /// capture lifts its lane above LOAD's, so it is not within the memory + /// plan, and the gate charges it at its own prompt as it does a longer context. + @Test(arguments: [1, 8], [nil, 3] as [Int?]) + func aPromptPastTheMemoryPlansIsChargedAtItsOwn(lanes: Int, depth: Int?) throws { + let load = try Self.loaded(lanes: lanes, depth: depth) + let memory = try Self.input().0.profile + let within = QwenTensorParallelRequestCharge.withinMemoryPlan + #expect(within(65_536, 32_768, memory) && within(513, 512, memory)) + #expect(!within(65_537, 32_768, memory) && !within(64_000, 32_769, memory)) + let value = try load.charge.charge(maximumTokens: 64_000, promptTokens: 60_000, chunkSize: 512) + #expect(value.laneBytes > load.laneBytes, "lanes=\(lanes) depth=\(String(describing: depth))") + #expect(!within(64_000, 60_000, memory)) + } + /// Past the memory plan a request is charged at its own context: its lane /// grows by its KV pages (this rank's heads, BF16, both K and V of every /// attention layer) and the shared workspaces grow from LOAD's. From b01a8d37b5b399a540de28a3217e3ae76694a238 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:45:43 -0800 Subject: [PATCH 0141/1441] docs: Qwen TP prefixes past the memory plan, the gates and the assistant's gap - prefix-cache: plain-lane boundaries go to the request's own context, past LOAD's memory plan too; a capture whose deepest boundary exceeds the resident tier's budget is not kept resident (about 235,000 tokens of the 27B under an 8 GiB budget); requests an assistant lane serves still reuse at most 4,096 tokens, stated as a known gap. - hardware-support: the gates do not credit the SSD writer's held captures, and a prompt past the memory plan's is charged at its own. - inference: "within the memory plan" covers the prompt too; the native context figures move to the per-request capture (LOAD 60.4 GB a rank at eight lanes with the depth-3 assistant, 6.2 GB a lane; a 262,144-token request beside seven standard ones 89.0 GB a rank, a 23.1 GB lane and 22.4 GB shared), from the test's own print line. - changelog: no "any length" claim; the assistant's 4,096 gap plainly. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-prefix-depth.md | 4 ++-- docs/architecture/hardware-support.md | 12 ++++++++---- docs/architecture/inference.md | 14 +++++++++----- docs/architecture/prefix-cache.md | 15 +++++++++------ 4 files changed, 28 insertions(+), 17 deletions(-) diff --git a/changelog.d/qwen27-tp-prefix-depth.md b/changelog.d/qwen27-tp-prefix-depth.md index 8239922e03..81b1598c15 100644 --- a/changelog.d/qwen27-tp-prefix-depth.md +++ b/changelog.d/qwen27-tp-prefix-depth.md @@ -1,6 +1,6 @@ ### Qwen3.8 27B tensor parallel reuses whole prompt prefixes -- A Qwen tensor-parallel pair now reuses a repeated prompt's prefix to its last whole 512-token chunk, at any length, instead of at most 4,096 tokens: a repeated 33K-token prompt restores 32,768 tokens on both Macs, as one Mac does. It also keeps the boundaries the next turn of a conversation and prompts that share a long system prompt need, so in each of these cases it reuses at least what one Mac reuses, to the nearest 512 tokens. +- A Qwen tensor-parallel pair now reuses a repeated prompt's prefix to its last whole 512-token chunk instead of at most 4,096 tokens, including prompts longer than 32,768 tokens: a repeated 33K-token prompt restores 32,768 tokens on both Macs, as one Mac does. It also keeps the boundaries the next turn of a conversation and prompts that share a long system prompt need, so in each of these cases it reuses at least what one Mac reuses, to the nearest 512 tokens. - A prefix restored from memory returns exactly the tokens of a request that prefilled the whole prompt (checked bit for bit on synthetic pairs at 8K, 16K and 32K boundaries); one restored from the SSD tier's default `balanced` records is close but not identical, as before. Both Macs must hold a boundary; otherwise both start from zero. - Each request reserves room for its own prompt's prefix (about 1.8 GB a Mac for a 32K-token prompt on the 27B), and a pair loads with one such prefix per lane: about 1.1 GB a Mac more than before at one lane. Every pair size that ran the 27B in tensor parallel still does. Kept prefixes use free memory only (half of what is left after loading) and are dropped first when memory runs short. Prefixes kept on SSD by an earlier build are not reused. -- The assistant (MTP) lanes still keep prefixes up to 4,096 tokens. Speed on a real pair is not measured yet. +- Requests served by the assistant (MTP) lanes still reuse at most 4,096 prompt tokens, less than one Mac reuses for a long prompt; deepening them is a separate change. Speed on a real pair is not measured yet. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index b0f4d7a1b2..4a3146d8b8 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1225,10 +1225,14 @@ Its budget is half the room LOAD measures beside its whole quote (`ClusterStagePrefixBudget.roomBytes`, `QwenStagePrefixCache.budget(roomBytes:)`): at most a thirty-second of the Mac's memory, in 256 MiB steps, and 0 when the room is under 512 MiB. The reservation and running-batch gates do not credit -its entries as the owner's own allocations, and its entries give way before -either gate refuses (`QwenTensorParallelSnapshotCache.yieldingMemory`). A -capture always keeps what its request's charge covers. With no tier budget it -keeps nothing resident and still writes its SSD record. The assistant's lanes +its entries as the owner's own allocations, nor, while the SSD writer is busy, +up to its queue's byte bound for the retired captures it still holds; the +writer drains and then the entries give way before either gate refuses +(`QwenTensorParallelSnapshotCache.yieldingMemory`). A capture always keeps what +its request's charge covers. With no tier budget it keeps nothing resident and +still writes its SSD record. A request whose prompt exceeds the memory plan's +is charged at its own prompt, outside LOAD's per-lane quote +([native context](inference.md#qwen27-tensor-parallel-native-context)). The assistant's lanes keep their single 4,096-token frontier and its two charged resident banks (`QwenTensorParallelMTPPrefixBudget`). See [prefix ownership](prefix-cache.md#cluster-sliding-prefix-adoption). diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 44fcd825b4..e96afca2e0 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -5135,17 +5135,21 @@ and verify transients. The shared charge is never below LOAD's. Each rank's live gate (`reserveLane`, with the same OS and allocator checks) admits the whole charge or refuses that request alone. The endpoint then answers 503 with the context the pair serves now, and the pair keeps serving. A request within the -memory plan is charged as before and must still fit LOAD's per-lane quote. +memory plan, at most its context and its prompt, must still fit LOAD's per-lane +quote. A longer prompt within that context is charged at its own prompt, as a +longer context is, because each request's prefix capture grows with its prompt +(`QwenTensorParallelRequestCharge.withinMemoryPlan`). READY's request capacity is the larger of LOAD's quote and one request at 262,144 tokens. READY, and every keep-warm answer while no lane is held, carry the longest context the reservation gate admits now (`servingContextTokens`, computed with the gate's own arithmetic). The pair refuses a longer request before either rank is asked. With the registered inventory on an M5 Ultra -(256 GB), eight lanes with the depth-3 assistant reserve 48.4 GB a rank at LOAD -(4.6 GB a lane). A 262,144-token request beside seven standard ones is charged -69.4 GB a rank (a 13.9 GB lane and 22.8 GB of shared workspaces), beside at most -16.3 GB of weights (`QwenTensorParallelNativeContextTests`). +(256 GB), eight lanes with the depth-3 assistant reserve 60.4 GB a rank at LOAD +(6.2 GB a lane). A 262,144-token request beside seven standard ones is charged +89.0 GB a rank (a 23.1 GB lane, including its own prompt's prefix capture, and +22.4 GB of shared workspaces), beside at most 16.3 GB of weights +(`QwenTensorParallelNativeContextTests`). The pipeline and hand-off modes stay at the memory plan. Their LOAD gates size it, and they refuse a longer reservation (`requireWithinMemoryProfile`). Provider diff --git a/docs/architecture/prefix-cache.md b/docs/architecture/prefix-cache.md index 8d48affe48..4f5c076ba1 100644 --- a/docs/architecture/prefix-cache.md +++ b/docs/architecture/prefix-cache.md @@ -1130,9 +1130,10 @@ keep it ([tenant partitions](#cluster-prefix-tenant-partitions)). Source: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Media/QwenMediaRequestState.swift`. The exact27 multi-lane TP owner keeps a completed plain request's state at -original chunk boundaries to the request's context, strictly before the final -token and after what it restored (`QwenTensorParallelBatchPrefixBudget.frontiers`, -policy `qwen-tp-batch-prefix-depth-v2`): +original chunk boundaries to the request's own context (past LOAD's memory +plan too), strictly before the final token and after what it restored +(`QwenTensorParallelBatchPrefixBudget.frontiers`, policy +`qwen-tp-batch-prefix-depth-v2`): | Boundary | Serves | One Mac's counterpart | |---|---|---| @@ -1159,8 +1160,10 @@ byte budget is set at LOAD from the room measured beside the quote (`QwenStagePrefixCache.budget(roomBytes:)`). Under that budget it gives up other captures' shallower boundaries first, then the newest capture's, then whole captures, least recently used first, so an exact repeat's boundary outlives the -rest. Its entries also give way, after the SSD writer's queue drains, before a -reservation or the running batch is refused for memory +rest. A capture whose deepest boundary does not fit the budget is not kept +resident at all (on a 256 GB Mac, an 8 GiB budget holds the 27B's capture to +about 235,000 tokens). Its entries also give way, after the SSD writer's queue +drains, before a reservation or the running batch is refused for memory (`QwenTensorParallelSnapshotCache.yieldingMemory`). The vote carries every chunk boundary of the prompt, at most 512, and selects the longest one both ranks hold; a one-sided miss computes cold on both ranks. Restoration writes @@ -1190,7 +1193,7 @@ warm-prefix correctness, media parity, RDMA or useful speed. ### Qwen27 TP assistant prefix ownership -The TP assistant prefix donor binds a compact target attention/recurrent snapshot and the same assistant's trusted prompt history at one confirmed original prompt frontier, at most 4,096 tokens deep (`QwenTensorParallelMTPPrefixBudget.maximumTokens`, policy `qwen-tp-mtp-grid-prefix-4096-v1`). That bound is the assistant's history ledger as well: prefill holds the trusted history unflushed up to the checkpoint frontier, so a deeper frontier would keep a lane's whole prompt history resident, not only a larger capture. Restore creates request-owned mutable state and both ranks negotiate the common usable frontier. The bounded cache publishes donors only after checked retirement and a final cancellation/deadline vote; a failed decoder cannot donate. Captured speculative target windows, pending assistant drafts and queued accepted tokens are not prefix donors. Both resident donor banks and the temporary capture bank remain in the complete quote. +The TP assistant prefix donor binds a compact target attention/recurrent snapshot and the same assistant's trusted prompt history at one confirmed original prompt frontier, at most 4,096 tokens deep (`QwenTensorParallelMTPPrefixBudget.maximumTokens`, policy `qwen-tp-mtp-grid-prefix-4096-v1`). That bound is the assistant's history ledger as well: prefill holds the trusted history unflushed up to the checkpoint frontier, so a deeper frontier would keep a lane's whole prompt history resident, not only a larger capture. A request an assistant lane serves therefore reuses at most 4,096 prompt tokens, less than one Mac reuses for a long prompt: a known gap, not covered by the plain lanes' parity. Restore creates request-owned mutable state and both ranks negotiate the common usable frontier. The bounded cache publishes donors only after checked retirement and a final cancellation/deadline vote; a failed decoder cannot donate. Captured speculative target windows, pending assistant drafts and queued accepted tokens are not prefix donors. Both resident donor banks and the temporary capture bank remain in the complete quote. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefix.swift` (`QwenTensorParallelMTPPrefixState`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefixBudget.swift`, and `libs/mlx-swift-lm/Libraries/MLXLLM/Models/Qwen35MTP+PrefixCheckpoint.swift` (`Qwen35InlineMTPAssistant`). Full-artifact warm-prefix numerical and cancellation checks remain separate from tiny ownership fixtures. From 86d479a44836880c9ae99b36fc761f30bc02ed1e Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:51:05 -0800 Subject: [PATCH 0142/1441] Bind the Qwen TP selection sum into the load agreement The greedy selection's sealed all-sum now carries six words a row (each rank's maximum, first global index and non-finite count) where it carried four. Bind that into the decode agreement fields (qwen-tensor-parallel-selection-nonfinite-in-sum-v1), as the routed-expert packed collective and the fenced sums are bound, so a rank whose selection sums other words refuses to load beside this one instead of meeting it in a sealed sum of another length. A pair of the same build is unchanged. nativeNonfiniteSampledRowsOnOneRankFailBothRanks covers the gather path: a sampled row with logprobs whose non-finite logits sit on rank 1 only fails both ranks before rank 0 samples or captures a logprob. The non-finite cases now also check that each rank's failure is selection's own refusal. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 7 +++++-- .../QwenTensorParallelBatchSession.swift | 10 ++++++---- .../QwenTensorParallelBatchSessionTests.swift | 20 ++++++++++++++++--- 3 files changed, 28 insertions(+), 9 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index e40fb61d63..edbe8dcc48 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -5097,8 +5097,11 @@ rows' non-finite logit counts beside their maximum and first global index (a sampled cohort counts the gathered rows), and both ranks read them from the same evaluation that yields the tokens. A non-finite logit on either rank fails both ranks before any token is chosen, a sampler advances or anything is -published; before, the rank that saw it failed alone and its peer waited in the -selection sum. The decode step no longer pays a separate finiteness read +published, so neither rank waits in a collective its peer never enters. The +load agreement binds this selection sum +(`qwen-tensor-parallel-selection-nonfinite-in-sum-v1`): a rank whose selection +sums other words refuses to load beside it rather than meet it in a sum of +another length. The decode step pays no separate finiteness read (`QwenTensorParallelBatchSession.validateLogits` checks shape and dtype), and every selected token is unchanged. diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift index 957c849061..dcb0f42ef4 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift @@ -261,12 +261,14 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { static var usesExactVectors: Bool { exactVectorsOverride ?? exactVectors } /// Bound into the tensor-parallel load agreement: both ranks resolve the - /// decode projections alike, or the pair refuses to load (never a mixed - /// configuration). Each rank's words per lane is its own arithmetic - /// (a rank sums only its own partials) and is not bound. + /// decode projections alike and sum the same selection words (each row's + /// non-finite counts ride the greedy sum), or the pair refuses to load + /// (never a mixed configuration). Each rank's words per lane is its own + /// arithmetic (a rank sums only its own partials) and is not bound. static var decodeAgreementFields: [String] { ["qwen-tensor-parallel-decode-projections-v1", usesExactVectors ? "batch-invariant-affine" : "mlx-kernels", - "qwen-tensor-parallel-fenced-sums-v1", sumsAreFencedInputs ? "on" : "off"] + "qwen-tensor-parallel-fenced-sums-v1", sumsAreFencedInputs ? "on" : "off", + "qwen-tensor-parallel-selection-nonfinite-in-sum-v1"] } /// Whether the residual step's kernel waits for each all-sum itself: MLX diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchSessionTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchSessionTests.swift index 255296155b..bcbc526170 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchSessionTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelBatchSessionTests.swift @@ -464,7 +464,13 @@ struct QwenTensorParallelBatchSessionTests { try verifySelectionBoundary(nonfinite: true, upperRankOnly: true) } - private func verifySelectionBoundary(nonfinite: Bool, upperRankOnly: Bool = false) throws { + /// The same for a sampled row with logprobs: both ranks gather the row + /// and refuse it before rank 0 samples or captures a logprob. + @Test func nativeNonfiniteSampledRowsOnOneRankFailBothRanks() throws { + try verifySelectionBoundary(nonfinite: true, upperRankOnly: true, sampled: true) + } + + private func verifySelectionBoundary(nonfinite: Bool, upperRankOnly: Bool = false, sampled: Bool = false) throws { try Device.withDefaultDevice(device) { let fixture = QwenTensorParallelFixtures.checkpoint(hidden: 256, layers: 4, heads: 4, kvHeads: 2, vocabulary: 256) var root = try JSONSerialization.jsonObject(with: fixture.configuration) as! [String: Any] @@ -505,8 +511,12 @@ struct QwenTensorParallelBatchSessionTests { } defer { for owner in owners { for lane in owner.nativeLanes { try? lane.session.retire() } } } for row in 0..<(nonfinite ? 1 : 8) { + let sampling: ClusterWorkerSampling? = sampled ? .init(temperature: 0.7, topP: 0.9, topK: 32, minP: 0.01, + repetitionPenalty: 1.1, repetitionContextSize: 12, frequencyPenalty: 0.15, presencePenalty: 0.2, + seed: UInt64(77 + row), stream: UInt64(5 * row + 1), logitBias: [.init(tokenID: row + 3, bias: 0.5)], + topLogprobs: 5) : nil let request = try QwenLayerStageGenerationRequest(profile: profile, requestID: UUID(), - promptTokenIDs: [1, 2, row + 3], chunkSize: 5, outputCount: 12, stopTokenIDs: []) + promptTokenIDs: [1, 2, row + 3], chunkSize: 5, outputCount: 12, stopTokenIDs: [], sampling: sampling) for owner in owners { owner.nativeLanes.append(try owner.executor!.open(.init(request: request), check: {})) } let body: (Owned) throws -> Void = { owner in let lane = owner.nativeLanes[row] @@ -514,7 +524,11 @@ struct QwenTensorParallelBatchSessionTests { } if nonfinite { #expect(throws: ProbeError.self) { try parallel(owners, body: body) } - #expect(owners.allSatisfy { $0.failure != nil && $0.selected.isEmpty }) + // Both ranks refuse the row in selection itself: the greedy sum's counts, or the gathered rows. + let refusal = sampled ? "Qwen TP gathered sampling rows are invalid" + : "Qwen TP selection rows have a non-finite logit" + #expect(owners.allSatisfy { ($0.failure as? ProbeError)?.description == refusal && $0.selected.isEmpty }) + #expect(try owners[0].executor!.takeLogprobs(owners[0].nativeLanes[row]) == nil) } else { try parallel(owners, body: body) } From 53faf8e8d0fe9b55182b7ec426ad8f9b4325a463 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:51:05 -0800 Subject: [PATCH 0143/1441] Name the Qwen TP decode census as a darkbloom line and tighten the rows check The census is logged on every load, so it takes the darkbloom- prefix that every always-on runtime line has (darkbloom-qwen-tp-decode-census-v1); the unprefixed qwen-tp-*/glm-* lines are timing diagnostics. Its documentation now says what the line does not show: a Gated DeltaNet layer's four input projections run as one fused call, SwiGLU fuses only while the decode fusions are on, and a routed-expert row's switch projections are not listed. QwenTensorParallelRowsCheck counts a candidate digest that its reference lacks as a difference instead of skipping it, and marks non-finite logits rows, refusing to report a marked reference after both ranks' last collective. Selection now holds the serving finiteness check, and the check never selects. qwen-rows synthesize refuses a malformed --layers. Docs: inference.md says when the census is logged, what the rows check refuses and that qwen-rows run reads a checkpoint without the product's verified load; test.md lists QWEN_TP_REAL_GEOMETRY_GPU=1 and the qwen-rows commands, and names MLX_QMV_BATCH_INVARIANT=1 for the QWEN_TP_MTP_GPU=1 runs; the changelog leads with the behaviour change. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-decode-loop.md | 18 +++++++-------- docs/architecture/inference.md | 17 ++++++++++---- docs/developer/test.md | 13 ++++++++--- .../TensorParallelCheck/QwenRowsCheck.swift | 5 ++-- .../QwenTensorParallelBatchSession.swift | 17 ++++++++------ .../QwenTensorParallelRowsCheck.swift | 23 +++++++++++++------ ...nTensorParallelRealGeometryRowsTests.swift | 18 +++++++++++++++ 7 files changed, 79 insertions(+), 32 deletions(-) diff --git a/changelog.d/qwen27-tp-decode-loop.md b/changelog.d/qwen27-tp-decode-loop.md index c471124fc0..d293d89243 100644 --- a/changelog.d/qwen27-tp-decode-loop.md +++ b/changelog.d/qwen27-tp-decode-loop.md @@ -1,14 +1,14 @@ ### Qwen tensor-parallel decode routes and finiteness check -- Each rank of a Qwen tensor-parallel pair logs its decode routes once per load - (`qwen-tp-decode-census-v1`): which projections take the batch-invariant - kernel and at which layout per row count, the attention and residual-norm - routes, and the arithmetic switches in force. -- A non-finite logit on either rank now fails both ranks in the same selection - step, before any token is published; previously the other rank waited in the - selection collective. The check moved into the selection's sealed sum, so a - decode step no longer pays a separate finiteness read. Selected tokens are - unchanged. +- A non-finite logit on either rank of a Qwen tensor-parallel pair now fails + both ranks in the same selection step, before any token is published; + previously the other rank waited in the selection collective. The check moved + into the selection's sealed sum, so a decode step no longer pays a separate + finiteness read. Selected tokens are unchanged. +- Each rank logs its decode routes once per load, when it first serves + (`darkbloom-qwen-tp-decode-census-v1`): which projections take the + batch-invariant kernel and at which layout per row count, the attention and + residual-norm routes, and the arithmetic switches in force. - `darkbloom-cluster-tp-check qwen-rows` checks, on one Mac over the loopback ring, that a Qwen3.8-27B row decodes the same bytes alone, beside other rows and in verify windows at the registered per-rank widths (random weights). diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index edbe8dcc48..d6f890b7bc 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -5116,7 +5116,7 @@ placement to tensor parallel as before. Synthetic CPU and both-chip native fixtures are not full-artifact, RDMA, tower, throughput or endpoint evidence. Each rank logs its decode routes once per loaded model when its native -executor starts (`qwen-tp-decode-census-v1`, +executor first starts serving (`darkbloom-qwen-tp-decode-census-v1`, `QwenTensorParallelBatchSession.censusLine`): every projection's route (the batch-invariant kernel `aqv`, a row-parallel FP32 partial on it `partial`, or MLX's own kernels with the reason, `mlx-...`) and each projection shape's @@ -5124,6 +5124,10 @@ layout per vector count (plain rows of one to eight and their four-column windows), the residual-norm form, the paged attention geometry and partition size, the selection, and any arithmetic switch the launcher set. A registered 27B rank reports `mlx=0`. Only host values are read; nothing is evaluated. +Layouts are listed per checkpoint projection: the SDK multiplies a Gated +DeltaNet layer's four input projections as one call of their summed rows, and +fuses gate, up and SwiGLU at `swiglu_fused_vectors` only while its decode +fusions are on. A routed-expert row's switch projections are not listed. `QwenTensorParallelRowsCheck` checks the row contract at the registered 27B per-rank widths with random weights (affine 4-bit, group 64, BF16 scales, @@ -5136,9 +5140,14 @@ ranks run it in one process (`QwenTensorParallelRealGeometryRowsTests`, `QWEN_TP_REAL_GEOMETRY_GPU=1`) or as two processes over the loopback ring (`darkbloom-cluster-tp-check qwen-rows`, native or sealed sums, with the worker's arithmetic environment); on an M5 Ultra every comparison is bitwise -equal. It covers neither the registered weights nor JACCL's streamed sealed -sums, the driver under live traffic or the HTTP stream; `qwen-rows run` also -loads a registered checkpoint directory on a Mac with the memory for it. +equal. It refuses to report when a logit is not finite, when its reference +logits are not all distinct, when the long rows fit one KV segment, or when its +comparison misses a planted difference. It covers neither the registered weights nor +JACCL's streamed sealed sums, the driver under live traffic or the HTTP stream. +`qwen-rows run` also loads a registered checkpoint directory on a Mac with the +memory for it, reading the files directly as `tp-check run` does, not through +the product's verified load (`QwenTensorParallelVerifiedLoad`: no artifact +hashes, inventory or load memory gate). Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift` (`QwenTensorParallelBatchSession`, `censusLine`), diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..20083e4c0d 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -1123,7 +1123,7 @@ arm64-apple-macosx26.2 -Xswiftc -enable-testing`), stage the source-matched with the same flags plus `--skip-build --no-parallel`. Without environment switches the run evaluates synthetic models on the GPU by default; the GPU-only cases (`QWEN_TP_BATCH_GPU=1`, `QWEN_TP_MTP_GPU=1`, `QWEN_TP_MOE_GPU=1`, -`QWEN_TP_AQV_GPU=1`) run each in a process of their own with their filter. On +`QWEN_TP_AQV_GPU=1`, `QWEN_TP_REAL_GEOMETRY_GPU=1`) run each in a process of their own with their filter. On an M5 GPU MLX computes float32 matrix products in TF32 unless the process starts with `MLX_ENABLE_TF32=0` (`libs/mlx-swift-lm/CONTRIBUTING.md`): the forward comparison in `GLM5NextStageSessionTests` asserts a float32 tolerance @@ -2435,7 +2435,7 @@ requests on both Macs after a native pin change. Run SDK `QwenMTPPagedHistoryTests` for paged assistant append/trim/copy/restore and failed-constructor custody. Native `QwenTensorParallelMTPPolicyTests`, `QwenTensorParallelMTPBudgetTests`, `QwenTensorParallelBatchMTPBudgetTests` and `QwenTensorParallelAssistantQuoteTests` check exact inventory, complete singleton/cohort reservations and metadata/native quote equality. `QwenTensorAssistantStartupTests` exercises real bilateral worker arguments; Process `TensorAssistantReadinessCheck` checks real child READY mismatch rejection. Provider `DistributedAutomaticBatchPlannerTests` covers automatic inline discovery, malformed/off cases, complete initial quote and saved-policy preservation through wider replans. -Set `QWEN_TP_MTP_GPU=1` only in an isolated native test run with the matching Metal resource. Run `QwenTensorParallelBatchMTPWindowTests` and `QwenTensorParallelBatchMTPTransitionTests` with `--no-parallel` so suites do not race global MLX state. Actual tiny targets test unequal histories/keep counts, rejected-suffix settlement, greedy target-column continuation, singleton/wider transitions, independent accepted-token credits, survivor retirement, mixed ordinary rows and poisoned-cohort cleanup. The trained head remains single-row; the decoder creates the target cohort. Tied-head transition fixtures do not establish full-model acceptance behavior or sampled equivalence. +Set `QWEN_TP_MTP_GPU=1` only in an isolated native test run with the matching Metal resource, and start that process with `MLX_QMV_BATCH_INVARIANT=1` as every cluster process runs (`ClusterQuantizedRowRouting`): MLX reads it once per process, and `QwenTensorParallelBatchMTPWindowTests.sharedWindowCallsKeepEveryRowsQuantizedArithmetic` checks MLX's own grouped quantized calls, which keep each row's bits only with it. Run `QwenTensorParallelBatchMTPWindowTests` and `QwenTensorParallelBatchMTPTransitionTests` with `--no-parallel` so suites do not race global MLX state. Actual tiny targets test unequal histories/keep counts, rejected-suffix settlement, greedy target-column continuation, singleton/wider transitions, independent accepted-token credits, survivor retirement, mixed ordinary rows and poisoned-cohort cleanup. The trained head remains single-row; the decoder creates the target cohort. Tied-head transition fixtures do not establish full-model acceptance behavior or sampled equivalence. Exact drafts (`QWEN_TP_MTP_GPU=1`): `QwenTensorParallelExactDraftRowsTests` runs a round's later draft steps for two to eight requests through one assistant forward (`Qwen35InlineMTPAssistant.draftHiddens`) and checks every row byte for byte against the same request's one-row step, over unequal histories, for two consecutive steps, at the suites' and the 9B's head ratios. `QwenTensorParallelMTPHeadRowsTests.exactDraftProjectionsKeepEachRowsOwnProductAtQwen27Shapes` checks the head and assistant projections at Qwen27's shapes, and `QwenTensorParallelBatchMTPTransitionTests.exactDraftRowsEqualTheirSoloRunsAndThePlainTargetAtEveryWidth` checks that every row of one to eight concurrent requests equals its solo run (tokens, MTP statistics and native state on both ranks) and emits the plain target's greedy tokens, with exact and with MLX drafts, with every proposal accepted and with proposals rejected. `QWEN_TP_ACCEPT_BENCH_MODEL= QWEN_TP_ACCEPT_BENCH_PROMPTS=` runs `QwenTensorParallelMTPAcceptanceRealTests`: the real row's two ranks in one process, each prompt decoded plainly and speculatively with each draft kernel; it requires lossless output and reports rounds, tokens per round, acceptance by position and where the two kernels' proposals differ. @@ -2473,6 +2473,13 @@ interior-axis cut is a row-major copy whose quantized products equal the former batched decode rows on the cached FP32 constants (`QuantizedLinear.independentRowsForward`) equal the call that widened them inside the matmul and each row alone. `QwenTensorParallelBatchMTPTransitionTests.nineBRatioAssistantSurvivesCreditJoinsRectanglesAndResumedSpeculation` runs the resident assistant's transitions on the 9B ratio (`QWEN_TP_MTP_GPU=1`). +`QWEN_TP_REAL_GEOMETRY_GPU=1` runs `QwenTensorParallelRealGeometryRowsTests` (about 3 GB of random +weights): the 27B row contract at its registered per-rank widths (`QwenTensorParallelRowsCheck`), both +ranks in one process; start it with the worker's arithmetic environment. +`darkbloom-cluster-tp-check qwen-rows synthesize --output DIR` writes that checkpoint (about 2.1 GB), and +`darkbloom-cluster-tp-check qwen-rows run --model-dir DIR --report FILE` runs the check as two processes +(`MLX_RANK`, `MLX_HOSTFILE` with two free `127.0.0.1` ports; `--backend ring` or `socket`, +`--reduction native` or `sealed-bench`). `QWEN_TP_MOE_BATCH_MODEL=` runs `QwenTensorParallelRoutedCohortRealTests`: the artifact's real shards, both ranks in one process on the GPU, rows of one cohort against the same rows alone, byte for byte. The reference rows in these tests (and the singleton owner of the capacity-parity diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift index 57ad341195..93d795dca3 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift @@ -25,8 +25,9 @@ enum QwenRowsCheck { } if command == "synthesize" { guard let output = options["output"], output.hasPrefix("/") else { throw Failure("synthesize needs --output /DIR") } - let layers = Int(options["layers"] ?? "4") ?? 4 - guard (1...8).contains(layers) else { throw Failure("--layers takes 1 to 8") } + guard let layers = Int(options["layers"] ?? "4"), (1...8).contains(layers) else { + throw Failure("--layers takes 1 to 8") + } try Device.withDefaultDevice(.gpu) { try QwenTensorParallelRowsCheck.writeCheckpoint(directory: URL(fileURLWithPath: output), layers: layers) } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift index dcb0f42ef4..ba654740c1 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift @@ -299,12 +299,15 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { static let censusCounts = [1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 28, 32] /// The decode route of every projection of a loaded shard - /// (`qwen-tp-decode-census-v1`), so a pair's log shows what each row count - /// runs: the batch-invariant kernel (`aqv`), a row-parallel FP32 partial on - /// it (`partial`), or MLX's own kernels and why (`mlx-...`), with each - /// shape's layout per vector count (layouts never change a result), and - /// the attention, residual-norm and selection routes. Host only: no - /// array is evaluated. + /// (`darkbloom-qwen-tp-decode-census-v1`), so a pair's log shows what each + /// row count runs: the batch-invariant kernel (`aqv`), a row-parallel FP32 + /// partial on it (`partial`), or MLX's own kernels and why (`mlx-...`), + /// with each shape's layout per vector count (layouts never change a + /// result), and the attention, residual-norm and selection routes. Host + /// only: no array is evaluated. Layouts are per checkpoint projection: + /// the SDK multiplies a Gated DeltaNet layer's four input projections as + /// one call of their summed rows, and fuses gate, up and SwiGLU at + /// `swiglu_fused_vectors` only while its decode fusions are on. static func censusLine(rank: Int, model: QwenTensorParallelModel) -> String { var routes: [String: Int] = [:], layouts: [String: String] = [:], tally: [String: Int] = [:] for (path, module) in model.model.leafModules().flattened() { @@ -357,7 +360,7 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { "DARKBLOOM_RESIDUAL_RMS_NORM", "DARKBLOOM_CBV2_PAGED_PTOK_TARGET", "DARKBLOOM_TTFT_GDN_BLOCKED"] .compactMap { key in environment[key].map { "\(key)=\($0)" } } let hidden = model.plan.hiddenSize - return "qwen-tp-decode-census-v1 rank=\(rank) exact_vectors=\(usesExactVectors ? "on" : "off")" + return "darkbloom-qwen-tp-decode-census-v1 rank=\(rank) exact_vectors=\(usesExactVectors ? "on" : "off")" + " aqv=\(tally["aqv", default: 0]) partial=\(tally["partial", default: 0]) mlx=\(tally["mlx", default: 0])" + " routes=" + routes.sorted { $0.key < $1.key }.map { "\($0.key)*\($0.value)" }.joined(separator: ",") + " layouts=" + layouts.sorted { $0.key < $1.key }.map { "\($0.key):\($0.value)" }.joined(separator: ",") diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift index 71cf13f782..e74818bd2e 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift @@ -133,11 +133,11 @@ public enum QwenTensorParallelRowsCheck { var history: [String: String] = [:] static func key(_ row: Int, _ step: Int) -> String { "\(row)/\(step)" } + /// Every digest of this trace that differs from the reference's, or + /// that the reference lacks (so a mislabeled trace is never skipped). func mismatches(_ reference: Trace, label: String) -> [String] { - logits.keys.sorted().filter { key in reference.logits[key].map { $0 != logits[key] } ?? false } - .map { "\(label) logits \($0)" } - + history.keys.sorted().filter { key in reference.history[key].map { $0 != history[key] } ?? false } - .map { "\(label) history \($0)" } + logits.keys.sorted().filter { reference.logits[$0] != logits[$0] }.map { "\(label) logits \($0)" } + + history.keys.sorted().filter { reference.history[$0] != history[$0] }.map { "\(label) history \($0)" } } } @@ -152,7 +152,13 @@ public enum QwenTensorParallelRowsCheck { maximumChunkTokens: 512) } - static func digest(_ value: MLXArray) -> String { eval(value); return sha256(value.asData(access: .copy).data) } + /// A logits row's digest, marked when a value is not finite (serving + /// refuses such a row in selection, which this check never runs). + /// `run` refuses a marked reference after both ranks' last collective. + static func digest(_ value: MLXArray) -> String { + (all(isFinite(value)).item(Bool.self) ? "" : nonfinite) + sha256(value.asData(access: .copy).data) + } + static let nonfinite = "nonfinite:" func historyDigest(_ row: Int) throws -> String { let session = sessions[row]! @@ -330,9 +336,12 @@ public enum QwenTensorParallelRowsCheck { let compared = soloOne.logits.count + soloOne.history.count + longSolo.logits.count + longSolo.history.count var tampered = soloOne tampered.logits[Trace.key(0, 0)] = "" - guard Set(soloOne.logits.values).count == soloOne.logits.count, reserved > CBv2StageKVHost.segmentBytes, + // A candidate's non-finite row differs from a finite reference or matches a marked one. + let finite = !(soloOne.logits.values.contains { $0.hasPrefix(Rows.nonfinite) } + || longSolo.logits.values.contains { $0.hasPrefix(Rows.nonfinite) }) + guard finite, Set(soloOne.logits.values).count == soloOne.logits.count, reserved > CBv2StageKVHost.segmentBytes, soloOne.mismatches(soloOne, label: "").isEmpty, tampered.mismatches(soloOne, label: "").count == 1 else { - throw ProbeError("Qwen TP rows check: degenerate logits, rows within one KV segment or a blind comparison") + throw ProbeError("Qwen TP rows check: non-finite or degenerate logits, rows within one KV segment or a blind comparison") } return Report(rank: rank, compared: compared, differing: differing, reservedBytesAcrossSegments: reserved, census: QwenTensorParallelBatchSession.censusLine(rank: rank, model: model), diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRealGeometryRowsTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRealGeometryRowsTests.swift index 1e4e797de1..a5602e7911 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRealGeometryRowsTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRealGeometryRowsTests.swift @@ -58,6 +58,24 @@ struct QwenTensorParallelRealGeometryRowsTests { } } + /// The runner's comparison (no weights, CPU): a changed digest and a + /// digest the reference lacks both count; a non-finite row is marked. + @Test func comparisonCountsChangedAndUnmatchedDigestsAndMarksNonfiniteRows() { + typealias Trace = QwenTensorParallelRowsCheck.Trace + typealias Rows = QwenTensorParallelRowsCheck.Rows + var reference = Trace(), candidate = Trace() + reference.logits = ["0/0": "a", "0/1": "b"]; reference.history = ["0/1": "h", "0/2": "i"] + candidate.logits = ["0/0": "a", "0/1": "c", "1/0": "d"]; candidate.history = ["0/2": "i"] + #expect(candidate.mismatches(reference, label: "x") == ["x logits 0/1", "x logits 1/0"]) + #expect(reference.mismatches(reference, label: "x").isEmpty) + Device.withDefaultDevice(.cpu) { + let finite = Rows.digest(MLXArray([Float(1), 2])) + #expect(finite.count == 64 && !finite.hasPrefix(Rows.nonfinite)) + #expect(Rows.digest(MLXArray([Float(1), .nan])).hasPrefix(Rows.nonfinite)) + #expect(Rows.digest(MLXArray([Float.infinity, 2])).hasPrefix(Rows.nonfinite)) + } + } + @Test(.enabled(if: gpu)) func rowsEqualTheirSoloStepsAndWindowPositionsAtRealWidths() throws { let configuration = try QwenTensorParallelRowsCheck.configuration(layers: 4) From c4c9d777f6433decb3db1b309e7a3c391558ac0d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:38:07 -0800 Subject: [PATCH 0144/1441] Decode Qwen3.8-27B TP rows alone and in cohorts to the same bits On the registered 27B weights a tensor-parallel row decoded other bytes beside other rows and in verify windows than alone (`qwen-rows run`: 379 mismatches across the cohort and window comparisons, both ranks). The first difference was in layer 50's SwiGLU, in one value: the one-row step takes the SDK's fused gate/up/SwiGLU kernel, whose sigmoid used Metal's fast `exp`, and the other row counts take MLX's compiled SwiGLU with its precise `exp`. A gate of bf16 -6.84375 rounds to another result. The SDK bump (mlx-swift-lm ad2ed74b) gives the fused kernel MLX's expression; every row count and window position now matches the one-row step, native and sealed. The rows check missed this because its random weights put every gate far into the SiLU's flat range: codes from `randInt(0, Int32.max)` never set the top bit, which biased every eighth input. The fixture now follows the registered artifact's statistics (MLX's affine quantization of near-normal weights: signed scales, biases -8 x scale, codes about 8; its norm, convolution, `A_log` and `dt_bias` ranges; gate rows reaching its SwiGLU input range), so the real-geometry test fails without the SDK fix. A test compares the fused SwiGLU with the two projections and the compiled SwiGLU at every normal bf16 and f16 gate value. `tp-check qwen-rows layers` names the first decoder layer where a row's step beside another leaves its solo bits, through the SDK's per-layer observer on the decode path. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-decode-loop.md | 10 +- docs/architecture/inference.md | 46 +++++--- .../TensorParallelCheck/QwenRowsCheck.swift | 17 ++- .../TensorParallelCheck.swift | 5 +- .../QwenTensorParallelRowsCheck.swift | 101 ++++++++++++++---- .../AffineQuantizedVectorsTests.swift | 50 ++++++++- libs/mlx-swift-lm | 2 +- 7 files changed, 188 insertions(+), 43 deletions(-) diff --git a/changelog.d/qwen27-tp-decode-loop.md b/changelog.d/qwen27-tp-decode-loop.md index c471124fc0..28cd588861 100644 --- a/changelog.d/qwen27-tp-decode-loop.md +++ b/changelog.d/qwen27-tp-decode-loop.md @@ -1,4 +1,4 @@ -### Qwen tensor-parallel decode routes and finiteness check +### Qwen tensor-parallel decode routes, row exactness and finiteness check - Each rank of a Qwen tensor-parallel pair logs its decode routes once per load (`qwen-tp-decode-census-v1`): which projections take the batch-invariant @@ -11,4 +11,10 @@ unchanged. - `darkbloom-cluster-tp-check qwen-rows` checks, on one Mac over the loopback ring, that a Qwen3.8-27B row decodes the same bytes alone, beside other rows - and in verify windows at the registered per-rank widths (random weights). + and in verify windows at the registered per-rank widths, with random weights + that follow the registered artifact's value statistics or with the registered + checkpoint itself; `qwen-rows layers` names the first layer that differs. +- A Qwen3.8-27B tensor-parallel row now decodes the same bytes alone as beside + other rows and in verify windows on the registered weights. The one-row + step's fused SwiGLU used a faster `exp` than the cohort path's SwiGLU, which + rounded one gate value differently and could change later tokens. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index e40fb61d63..5b4be59e7d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3790,7 +3790,17 @@ forwards fuse, on the families measured byte-equal to the unfused operations the Gated DeltaNet convolution step (concatenation, depthwise convolution and SiLU) and its q/k normalization, the attention output gate, the SwiGLU product, and a single vector's gate, up and SwiGLU in one launch (a window keeps the two -projections: the fused kernel measured slower there). A residual stream +projections: the fused kernel measured slower there). That one-launch SwiGLU +(`AffineQuantizedVectors.projectSwiGLU`) computes its sigmoid as MLX's +`Sigmoid` does, with `metal::precise::exp`: with Metal's default fast `exp` it +rounded the bf16 gate -6.84375 to another SwiGLU value, so a registered 27B +row's one-row step left the bits of its cohort and window steps. A test +compares it with the two projections and the compiled SwiGLU at every normal +bf16 and f16 gate value. The convolution step's SiLU (`GatedDeltaConvolution`) +still uses the default `exp`, so it can round differently from the unfused +SiLU (`Qwen35DecodeFusionParityTests` finds f16 and f32 differences); every +decode row count and window of up to eight columns takes that kernel, so rows +still agree. A residual stream narrower than its norms (the Prism/Bonsai packs: FP16 packed embedding rows under FP32 norms and projections) keeps the unfused sum that promotes it to FP32 on every family (`Qwen35DecoderLayer.residualNorm`); the fused step @@ -5123,19 +5133,27 @@ size, the selection, and any arithmetic switch the launcher set. A registered 27B rank reports `mlx=0`. Only host values are read; nothing is evaluated. `QwenTensorParallelRowsCheck` checks the row contract at the registered 27B -per-rank widths with random weights (affine 4-bit, group 64, BF16 scales, -biases and norms; three Gated DeltaNet layers and one attention layer; the -whole 248,320-row vocabulary): a row's logits and history equal its run alone, -on a one- or an eight-lane host, beside rows of 100 to 4,600 tokens that join -and leave, across two KV segments, while an assistant observes the cohort, and -at every position of a four-column verify window alone and in a cohort. Both -ranks run it in one process (`QwenTensorParallelRealGeometryRowsTests`, -`QWEN_TP_REAL_GEOMETRY_GPU=1`) or as two processes over the loopback ring -(`darkbloom-cluster-tp-check qwen-rows`, native or sealed sums, with the -worker's arithmetic environment); on an M5 Ultra every comparison is bitwise -equal. It covers neither the registered weights nor JACCL's streamed sealed -sums, the driver under live traffic or the HTTP stream; `qwen-rows run` also -loads a registered checkpoint directory on a Mac with the memory for it. +per-rank widths (three Gated DeltaNet layers and one attention layer; the +whole 248,320-row vocabulary) with random weights that follow the registered +artifact's value statistics: MLX's affine 4-bit quantization of near-normal +weights (group 64, signed BF16 scales of 0.001 to 0.005, biases -8 times the +scale, codes about 8), its norm, convolution, `A_log` and `dt_bias` ranges, +and gate rows whose SwiGLU inputs reach its range (about ±30). A row's logits +and history equal its run alone, on a one- or an eight-lane host, beside rows +of 100 to 4,600 tokens that join and leave, across two KV segments, while an +assistant observes the cohort, and at every position of a four-column verify +window alone and in a cohort. Both ranks run it in one process +(`QwenTensorParallelRealGeometryRowsTests`, `QWEN_TP_REAL_GEOMETRY_GPU=1`) or +as two processes over the loopback ring (`darkbloom-cluster-tp-check +qwen-rows`, native or sealed sums, with the worker's arithmetic environment). +`qwen-rows run` also loads a registered checkpoint directory on a Mac with the +memory for it, and `qwen-rows layers` names the first decoder layer where a +row's step beside another leaves its solo bits +(`QwenTensorParallelRowsCheck.firstDifferingLayers`, through +`Qwen35LayerSubmission.observer`). On an M5 Ultra every comparison is bitwise +equal, with the fixture and with the registered checkpoint. It covers neither +JACCL's streamed sealed sums, the driver under live traffic nor the HTTP +stream. Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift` (`QwenTensorParallelBatchSession`, `censusLine`), diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift index 57ad341195..3299ef3dd5 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift @@ -9,10 +9,12 @@ import MLX // --report FILE [--backend ring|socket] [--reduction native|sealed-bench] // Each rank compares its own digests (a row alone, in cohorts, across KV // segments, observed, in verify windows) and both agree on the verdict. +// `layers` (same options, [--target 7 --other 6]) reports the first decoder +// layer where a row's step beside another leaves its solo bits. enum QwenRowsCheck { static func run(_ arguments: [String]) throws { - guard let command = arguments.first, ["synthesize", "run"].contains(command) else { - throw Failure("usage: darkbloom-cluster-tp-check qwen-rows synthesize|run ...") + guard let command = arguments.first, ["synthesize", "run", "layers"].contains(command) else { + throw Failure("usage: darkbloom-cluster-tp-check qwen-rows synthesize|run|layers ...") } var options: [String: String] = [:] var index = 1 @@ -54,6 +56,17 @@ enum QwenRowsCheck { group.sealed = codec } note("rank \(group.rank) of \(group.size) over \(backend.rawValue), \(reduction) sums") + if command == "layers" { + let lines = try Device.withDefaultDevice(.gpu) { () throws -> [String] in + let model = try QwenTensorParallelModel.load(modelDirectory: url, role: .shard(rank: group.rank, size: 2), + reduction: group) + return try QwenTensorParallelRowsCheck.firstDifferingLayers(model: model, configuration: configuration, + target: Int(options["target"] ?? "7") ?? 7, other: Int(options["other"] ?? "6") ?? 6) + } + try lines.joined(separator: "\n").write(toFile: reportPath, atomically: true, encoding: .utf8) + lines.forEach { note($0) } + return + } let report = try Device.withDefaultDevice(.gpu) { () throws -> QwenTensorParallelRowsCheck.Report in let model = try QwenTensorParallelModel.load(modelDirectory: url, role: .shard(rank: group.rank, size: 2), reduction: group) diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift index 8fe4f9c905..927254686a 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift @@ -22,8 +22,9 @@ import MLX // tensor parallel against one rank without a registered model; never a model pass) // darkbloom-cluster-tp-check record --rank0 FILE --rank1 FILE --reference FILE [--reference FILE] --model-dir DIR // --output FILE [--partials float32|bfloat16] [--near-tie-ulps U] (appends one qualification record line) -// darkbloom-cluster-tp-check qwen-rows synthesize|run ... (27B batch rows at the registered per-rank widths: -// each row against itself alone and in verify windows over the loopback ring; `QwenRowsCheck`) +// darkbloom-cluster-tp-check qwen-rows synthesize|run|layers ... (27B batch rows at the registered per-rank +// widths: each row against itself alone and in verify windows over the loopback ring, or the first layer +// that differs; `QwenRowsCheck`) // // `full` is the unsharded model on one Mac (this code path's single-Mac // reference); `simulated` is the single-process tensor-parallel oracle (the diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift index 71cf13f782..b8605b6c2e 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift @@ -45,47 +45,62 @@ public enum QwenTensorParallelRowsCheck { /// Every checkpoint tensor of `layers` layers, each drawn from its own /// name's seed, so both ranks cut the same values without holding the - /// whole checkpoint at once. + /// whole checkpoint at once. The values follow the registered artifact's + /// statistics: MLX's affine quantization of near-normal weights (signed + /// scales of 0.001-0.005, biases -8 x scale, codes about 8), its norm, + /// convolution, `A_log` and `dt_bias` ranges, and gate rows whose SwiGLU + /// inputs reach its range (its gates reach |33| in later layers). static func tensors(layers: Int, _ keep: (String, MLXArray) throws -> Void) throws { let h = 5120, inter = 17408, vocabulary = 248_320, hq = 24, hkv = 4, hd = 256, nk = 16, nv = 48 let lk = nk * 128, lv = nv * 128 func key(_ name: String) -> MLXArray { MLXRandom.key(name.utf8.reduce(UInt64(0xCBF2_9CE4_8422_2325)) { ($0 ^ UInt64($1)) &* 0x100_0000_01B3 }) } - func q(_ name: String, _ out: Int, _ input: Int) throws { - let keys = MLXRandom.split(key: key(name), into: 2) - let scales = MLXRandom.uniform(low: Float(0.002), high: Float(0.02), [out, input / 64], key: keys[0]) - .asType(.bfloat16) - try keep(name + ".weight", MLXRandom.randInt(low: 0, high: Int32.max, [out, input / 8], key: keys[1]) - .asType(.uint32)) - try keep(name + ".scales", scales) - try keep(name + ".biases", (scales * -7.5).asType(.bfloat16)) + // `rowGains`: each row's scales times 1 to 8 (log-uniform), as the gate's. + func q(_ name: String, _ out: Int, _ input: Int, rowGains: Bool = false) throws { + let keys = MLXRandom.split(key: key(name), into: 5) + let groups = [out, input / 64] + var scales = MLXRandom.uniform(low: Float(0.001), high: Float(0.005), groups, key: keys[0]) + * which(MLXRandom.bernoulli(groups, key: keys[1]), Float(1), Float(-1)) + if rowGains { + scales = scales * MLX.pow(Float(2), MLXRandom.uniform(low: Float(0), high: Float(3), [out, 1], key: keys[2])) + } + let rounded = scales.asType(.bfloat16) + // Codes 1-15 about 8: two 3-bit draws a code, eight codes a word. + func draws(_ key: MLXArray) -> MLXArray { + MLXRandom.randInt(low: 0, high: Int32.max, [out, input / 8], key: key).asType(.uint32) + & MLXArray(UInt32(0x7777_7777)) + } + try keep(name + ".weight", draws(keys[3]) + draws(keys[4]) + MLXArray(UInt32(0x1111_1111))) + try keep(name + ".scales", rounded) + try keep(name + ".biases", (rounded * -8).asType(.bfloat16)) } - func norm(_ name: String, _ n: Int) throws { - try keep(name, MLXRandom.uniform(low: Float(0.9), high: Float(1.1), [n], key: key(name)).asType(.bfloat16)) + func uniform(_ name: String, _ n: Int, _ low: Float, _ high: Float) throws { + try keep(name, MLXRandom.uniform(low: low, high: high, [n], key: key(name)).asType(.bfloat16)) } try q("language_model.model.embed_tokens", vocabulary, h) try q("language_model.lm_head", vocabulary, h) - try norm("language_model.model.norm.weight", h) + try uniform("language_model.model.norm.weight", h, 0.7, 2.7) for layer in 0.. [String] { + final class Outputs: @unchecked Sendable { var layers: [MLXArray] = [] } + func observed(_ rows: Rows, members: [Int], position: Int) throws -> [(layers: [MLXArray], logits: MLXArray)] { + try (0..`) cannot complete a stop sequence on its own. - A stop sequence that names a marker no longer fires on it: ``, or From ce95ac8d406f2e1941773f35bb35818b823bc115 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Mon, 2 Nov 2026 02:24:21 -0800 Subject: [PATCH 0175/1441] ci: re-run checks after runner checkout timeouts No file changes. In CI run 41412596359, Provider Unit Tests shards 4 and 5 hung in actions/checkout on self-hosted runners and reached the job time limit before any test ran; Docs Impact in the Contribution Policy run hung the same way. Co-Authored-By: Claude Opus 5.5 From 253801c32c7aac7783b137928d2c74b2ff62c548 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Mon, 2 Nov 2026 06:17:37 -0800 Subject: [PATCH 0176/1441] ci: one more run after a runner checkout timeout No file changes. CI run 41428558024 on the identical tree had Provider Unit Tests shard 1 hang in actions/checkout on a self-hosted runner until the job time limit; shards 2-5 passed there and shards 1-3 passed in run 41412596359. Co-Authored-By: Claude Opus 5.5 From db7ad31d8b753b2d51c2a7c27e25600ba524ebf6 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 2 Nov 2026 14:39:39 -0800 Subject: [PATCH 0177/1441] fix(provider): the update recovery rollback also restores a promoted release The journaled rollback (`UpdateRecoveryStore.rollback`) required a pending candidate, so once an installed release passed its 10-minute stabilization the retained predecessor could no longer be restored and nothing could quarantine the promoted release. - `UpdateRecoveryState.rollbackSource` names the release a rollback replaces: the pending candidate, else a promoted release that is not the retained predecessor. `completeRollback` quarantines it; for a pending candidate nothing changes. - The rollback journal records its quarantine reason, so a replay records the same reason. A replay after the state write no longer bumps the install generation a second time. Tests (`UpdateRollbackRecoveryTests`, temporary install roots): a promoted release rolls back, records one generation and is quarantined; every journal boundary leaves one complete release that the next lease holder finishes; afterwards neither the in-process 30-minute check nor the watchdog reinstalls it, and a newer release installs. All three failed on master ("there is no pending release candidate to roll back"). Co-Authored-By: Claude Opus 5.5 --- .../Update/UpdateRecoveryState.swift | 15 +- .../Update/UpdateRecoveryStore.swift | 27 +- .../Update/UpdateRollbackRecoveryTests.swift | 243 ++++++++++++++++++ 3 files changed, 275 insertions(+), 10 deletions(-) create mode 100644 provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackRecoveryTests.swift diff --git a/provider-swift/Sources/ProviderCore/Update/UpdateRecoveryState.swift b/provider-swift/Sources/ProviderCore/Update/UpdateRecoveryState.swift index 5fe234660f..8187749169 100644 --- a/provider-swift/Sources/ProviderCore/Update/UpdateRecoveryState.swift +++ b/provider-swift/Sources/ProviderCore/Update/UpdateRecoveryState.swift @@ -302,12 +302,21 @@ public struct UpdateRecoveryState: Codable, Sendable, Equatable { return true } + /// The installed release a rollback replaces: the pending candidate, else + /// a promoted release that is not the retained predecessor. Nil once a + /// rollback has completed (`current` is then the predecessor's record). + public var rollbackSource: InstalledReleaseRecord? { + if let candidate { return candidate.release } + guard let current, let predecessor, current != predecessor.release else { return nil } + return current + } + public mutating func completeRollback(now: Double, reason: String) { - guard let failed = candidate, let predecessor else { return } + guard let replaced = rollbackSource, let predecessor else { return } current = predecessor.release quarantine = FailedReleaseQuarantine( - version: failed.release.version, - failureCount: failed.failureCount, + version: replaced.version, + failureCount: candidate?.failureCount ?? 0, quarantinedAt: now, reason: reason ) diff --git a/provider-swift/Sources/ProviderCore/Update/UpdateRecoveryStore.swift b/provider-swift/Sources/ProviderCore/Update/UpdateRecoveryStore.swift index f0f73b4938..008f11b098 100644 --- a/provider-swift/Sources/ProviderCore/Update/UpdateRecoveryStore.swift +++ b/provider-swift/Sources/ProviderCore/Update/UpdateRecoveryStore.swift @@ -60,6 +60,9 @@ final class UpdateRecoveryStore: @unchecked Sendable { var layout: VerifiedPredecessor.Layout var stagingRoot: String var createdAt: Double + /// The rollback's quarantine reason, for a replay to record. Absent + /// in journals of earlier releases, which ignore it. + var reason: String? enum CodingKeys: String, CodingKey { case schema @@ -69,6 +72,7 @@ final class UpdateRecoveryStore: @unchecked Sendable { case layout case stagingRoot = "staging_root" case createdAt = "created_at" + case reason } } @@ -208,7 +212,8 @@ final class UpdateRecoveryStore: @unchecked Sendable { } else { state.completeRollback( now: now, - reason: "recovered an interrupted rollback of \(transaction.target.version)" + reason: transaction.reason + ?? "recovered an interrupted rollback of \(transaction.target.version)" ) } try writeState(state) @@ -262,16 +267,19 @@ final class UpdateRecoveryStore: @unchecked Sendable { try finish(remove: staged.stagingRoot) } + /// Restore the verified predecessor over the installed release (a pending + /// candidate, or a promoted release for an operator rollback) and + /// quarantine that release. func rollback(now: Double, reason: String) throws -> String { try recoverInterruptedTransaction(now: now) var state = try loadState() - guard let candidate = state.candidate else { + guard let predecessor = state.predecessor else { throw StoreError.missingPredecessor( - "there is no pending release candidate to roll back") + "v\(state.rollbackSource?.version ?? state.current?.version ?? "unknown") has no recorded predecessor") } - guard let predecessor = state.predecessor else { + guard state.rollbackSource != nil else { throw StoreError.missingPredecessor( - "v\(candidate.release.version) has no recorded predecessor") + "v\(predecessor.release.version), the recorded predecessor, is already installed") } try verifyPredecessor(predecessor) let (rollbackGeneration, overflow) = @@ -294,7 +302,8 @@ final class UpdateRecoveryStore: @unchecked Sendable { target: predecessor.release, layout: predecessor.layout, stagingRoot: stagingRoot.path, - createdAt: now + createdAt: now, + reason: reason ) try persist(transaction) try faultInjector(.transactionPersisted) @@ -405,6 +414,9 @@ final class UpdateRecoveryStore: @unchecked Sendable { ) } case .rollback: + // A replay after the state write (death before the journal was + // removed) finds the rollback already recorded: count it once. + guard state.rollbackSource != nil else { break } let (generation, overflow) = state.installGeneration.addingReportingOverflow(1) guard !overflow else { @@ -413,7 +425,8 @@ final class UpdateRecoveryStore: @unchecked Sendable { state.installGeneration = generation state.completeRollback( now: now, - reason: "recovered rollback after \(state.candidate?.failureCount ?? 0) failed starts" + reason: transaction.reason + ?? "recovered rollback after \(state.candidate?.failureCount ?? 0) failed starts" ) } try writeState(state) diff --git a/provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackRecoveryTests.swift b/provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackRecoveryTests.swift new file mode 100644 index 0000000000..81ab6f1f9a --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackRecoveryTests.swift @@ -0,0 +1,243 @@ +/// Rolling a single Mac back to its retained predecessor after the installed +/// release was promoted, through the watchdog's journaled rollback. +/// +/// Every install root is a temporary `UpdateRecoveryFixture`; releases come +/// from the loopback `MockCoordinator`; restarts and the launchd baseline are +/// injected. No real binary, launchd job or provider process is touched. + +import Foundation +import Testing +@testable import ProviderCore + +/// v2 installed over v1 by the updater, with v1 retained as the verified +/// predecessor. `promote` passes v2's stabilization through the watchdog's +/// health observation, as on a Mac where a release served for 10 minutes. +struct InstalledUpdate { + let fixture: UpdateRecoveryFixture + let mock: MockCoordinator + let baseURL: URL + + var store: UpdateRecoveryStore { + UpdateRecoveryStore(installRoot: fixture.installRoot, verifyCodeSignatures: false) + } + + /// The updater of the rolled-back v1 install (the restarted provider and watchdog). + var updater: SelfUpdater { fixture.updater(baseURL: baseURL) } + + static func make(promote: Bool) async throws -> InstalledUpdate { + let fixture = try UpdateRecoveryFixture() + let mock = MockCoordinator(release: fixture.mockReleaseFixture(), releaseArtifact: fixture.artifact) + let installed = InstalledUpdate(fixture: fixture, mock: mock, baseURL: try await mock.start()) + let outcome = await installed.updater.update() + guard case .updated(_, "2.0.0") = outcome else { + await installed.shutdown() + throw InstalledUpdateSetupError.installFailed("\(outcome)") + } + if promote { + let health = watchdogRecovery(installed.updater, stabilizationSeconds: 0).observeHealthyProvider( + providerRunning: true, + daemonState: DaemonState(pid: 4242, version: "2.0.0", writtenAt: 150, startedAt: 120), + now: 150) + guard health == .promoted(version: "2.0.0") else { + await installed.shutdown() + throw InstalledUpdateSetupError.promotionFailed("\(health)") + } + } + return installed + } + + func shutdown() async { + await mock.shutdown() + fixture.cleanup() + } + + /// The live `Darkbloom.app` is one complete release and `bin/` resolves into it. + func liveRelease() throws -> String? { + let app = fixture.installRoot.appendingPathComponent("Darkbloom.app/Contents/MacOS") + let bin = fixture.installRoot.appendingPathComponent("bin") + func read(_ url: URL) throws -> String { try String(contentsOf: url, encoding: .utf8) } + let binary = try read(app.appendingPathComponent("darkbloom")) + guard let version = binary.split(separator: "-").first.map(String.init), + try read(app.appendingPathComponent("darkbloom-enclave")) == "\(version)-enclave", + try read(app.appendingPathComponent("mlx.metallib")) == "\(version)-metallib", + try read(bin.appendingPathComponent("darkbloom")) == binary, + try read(bin.appendingPathComponent("mlx.metallib")) == "\(version)-metallib" + else { return nil } + return version + } + + func leftoverRollbackFiles() throws -> [String] { + let root = try FileManager.default.contentsOfDirectory(atPath: fixture.installRoot.path) + .filter { $0.hasPrefix(".rollback-staging-") || $0.hasPrefix(".recovery-restore-") } + let journal = FileManager.default.fileExists( + atPath: store.recoveryRoot.appendingPathComponent("transaction.json").path) + return root + (journal ? ["transaction.json"] : []) + } +} + +enum InstalledUpdateSetupError: Error { + case installFailed(String) + case promotionFailed(String) +} + +func watchdogRecovery( + _ updater: SelfUpdater, + restarts: RecoveryRestartCounter = RecoveryRestartCounter(), + stabilizationSeconds: Double = 180 +) -> WatchdogRecoveryService { + WatchdogRecoveryService( + updater: updater, + dependencies: .init( + kickstartIfLoaded: { + restarts.increment() + return true + }, + launchSnapshot: { nil }, + processAlive: { _ in true }, + log: { _ in } + ), + stabilizationSeconds: stabilizationSeconds, + candidateStartupTimeoutSeconds: 300 + ) +} + +/// A loop with no coordinator connection, as in `AutoUpdateCycleTests`. +func rollbackAutoUpdateLoop() throws -> ProviderLoop { + let config = ProviderLoopConfig( + coordinatorURL: "ws://127.0.0.1:0/ignored", + hardware: HardwareInfo( + machineModel: "Mac16,5", chipName: "Apple M4 Max", chipFamily: .m4, chipTier: .max, + memoryGb: 128, memoryAvailableGb: 124, + cpuCores: CpuCores(total: 16, performance: 12, efficiency: 4), + gpuCores: 40, memoryBandwidthGbs: 546), + models: [ModelInfo(id: "org/model-a", modelType: "gpt_oss", sizeBytes: 1, estimatedMemoryGb: 1)], + config: ProviderConfig( + provider: ProviderSettings( + name: "update-rollback-test", memoryReserveGB: 1, autoUpdate: true, updateJitterSeconds: 0), + backend: BackendSettings( + model: nil, enabledModels: ["org/model-a"], idleTimeoutMins: 0, preloadModels: []), + coordinator: CoordinatorSettings(heartbeatIntervalSecs: 60))) + return try ProviderLoop(config: config, attestationSigner: nil) +} + +@Suite("Update rollback recovery", .serialized) +struct UpdateRollbackRecoveryTests { + @Test("rolling back a promoted release restores the predecessor, records the generation and quarantines it") + func promotedReleaseRollsBack() async throws { + let installed = try await InstalledUpdate.make(promote: true) + defer { Task { await installed.shutdown() } } + let before = try installed.store.loadState() + #expect(before.candidate == nil) + #expect(before.current?.version == "2.0.0") + let predecessor = try #require(before.predecessor) + + let session = try installed.updater.beginUpdateSession(operation: "test-rollback") + defer { session.release() } + try session.recover(now: 500) + let restored = try session.rollback(now: 500, reason: "operator rollback") + + #expect(restored == "1.0.0") + #expect(try installed.liveRelease() == "1.0.0") + #expect(try installed.fixture.persistentStateIsIntact()) + #expect(try installed.leftoverRollbackFiles().isEmpty) + let after = try installed.store.loadState() + #expect(after.installGeneration == before.installGeneration + 1) + #expect(after.current == predecessor.release) + #expect(after.candidate == nil) + #expect(after.predecessor == predecessor) + #expect(after.quarantine == FailedReleaseQuarantine( + version: "2.0.0", failureCount: 0, quarantinedAt: 500, reason: "operator rollback")) + } + + @Test("every boundary of a promoted-release rollback leaves a runnable bundle that recovery finishes") + func everyBoundaryLeavesARunnableBundle() async throws { + enum ProcessDeath: Error { case injected } + let boundaries: [UpdateRecoveryStore.FaultPoint] = [ + .transactionPersisted, .liveLayoutExchanged, .liveLayoutReplaced, .statePersisted, .transactionRemoved, + ] + for boundary in boundaries { + let installed = try await InstalledUpdate.make(promote: true) + let generation = try installed.store.loadState().installGeneration + let dying = UpdateRecoveryStore( + installRoot: installed.fixture.installRoot, + verifyCodeSignatures: false, + faultInjector: { if $0 == boundary { throw ProcessDeath.injected } }) + let lock = try UpdateProcessLock.acquire(at: dying.lockPath, operation: "dies-at-\(boundary)") + #expect(throws: ProcessDeath.self, "\(boundary)") { + try dying.rollback(now: 500, reason: "operator rollback") + } + lock.release() + // Whatever the boundary, the live layout is one complete release. + let interrupted = try installed.liveRelease() + #expect(interrupted == "1.0.0" || interrupted == "2.0.0", "\(boundary): \(String(describing: interrupted))") + + // The next lease holder (watchdog tick, provider start) finishes it. + let session = try installed.updater.beginUpdateSession(operation: "next-tick") + try session.recover(now: 501) + session.release() + #expect(try installed.liveRelease() == "1.0.0", "\(boundary)") + // After `.transactionRemoved` only the swapped-out staging copy is + // left; the next staging pass removes it (`removeStaleUpdateDirs`). + let leftovers = try installed.leftoverRollbackFiles() + #expect(boundary == .transactionRemoved + ? leftovers.allSatisfy { $0.hasPrefix(".rollback-staging-") } + : leftovers.isEmpty, "\(boundary): \(leftovers)") + let state = try installed.store.loadState() + #expect(state.current?.version == "1.0.0", "\(boundary)") + #expect(state.quarantine?.version == "2.0.0", "\(boundary)") + #expect(state.installGeneration == generation + 1, "\(boundary)") + await installed.shutdown() + } + } + + @Test("after a rollback neither auto-update path reinstalls the release, and a newer one installs") + func quarantineHoldsForBothAutoUpdatePaths() async throws { + let installed = try await InstalledUpdate.make(promote: true) + defer { Task { await installed.shutdown() } } + let session = try installed.updater.beginUpdateSession(operation: "test-rollback") + try session.recover(now: 500) + _ = try session.rollback(now: 500, reason: "operator rollback") + session.release() + + // The restarted v1 provider's next in-process check (every 30 minutes). + let loop = try rollbackAutoUpdateLoop() + let restarts = RecoveryRestartCounter() + let cycle = await loop.performAutoUpdateCheck( + coordinatorURL: installed.baseURL.absoluteString, updater: installed.updater, + launchSnapshot: { nil }, restart: { _ = restarts.increment() }) + #expect(cycle == .quarantined("2.0.0")) + + // The watchdog's down-path update, from the v1 watchdog and from a + // v2 watchdog process that outlived the rollback. + let staleWatchdog = SelfUpdater( + coordinatorBaseURL: installed.baseURL.absoluteString, installRoot: installed.fixture.installRoot, + verifyCodeSignatures: false, currentVersion: "2.0.0") + for updater in [installed.updater, staleWatchdog] { + let outcome = await watchdogRecovery(updater, restarts: restarts) + .recoverDownProvider(autoUpdateEnabled: true, now: 600) + #expect(outcome == .restartIssued(updatedTo: nil, rolledBackTo: nil)) + } + #expect(restarts.value == 2) + #expect(try installed.liveRelease() == "1.0.0") + #expect(try installed.store.loadState().candidate == nil) + + // The next release installs normally, through either path. + let newer = try UpdateRecoveryFixture(oldVersion: "1.0.0", newVersion: "3.0.0") + defer { newer.cleanup() } + let newerMock = MockCoordinator(release: newer.mockReleaseFixture(), releaseArtifact: newer.artifact) + let newerURL = try await newerMock.start() + defer { Task { await newerMock.shutdown() } } + let newerUpdater = SelfUpdater( + coordinatorBaseURL: newerURL.absoluteString, installRoot: installed.fixture.installRoot, + verifyCodeSignatures: false, currentVersion: "1.0.0", now: { 700 }) + let next = await loop.performAutoUpdateCheck( + coordinatorURL: newerURL.absoluteString, updater: newerUpdater, + launchSnapshot: { nil }, restart: { _ = restarts.increment() }) + #expect(next == .restarted(from: "1.0.0", to: "3.0.0", drained: true)) + #expect(try installed.liveRelease() == "3.0.0") + let state = try installed.store.loadState() + #expect(state.candidate?.release.version == "3.0.0") + #expect(state.predecessor?.release.version == "1.0.0") + #expect(state.quarantine?.version == "2.0.0") + } +} From efb1064dcfd71559afedd3c4401b6d7a2ed244ff Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 2 Nov 2026 14:39:45 -0800 Subject: [PATCH 0178/1441] feat(provider): `darkbloom update --rollback` returns a Mac to its previous release A provider whose Mac auto-updated into a regressing release had no verb to return to the predecessor the updater keeps, and turned auto-update off. - `darkbloom update --rollback` prints the plan (installed and restored versions, the install generation it records), asks `Roll back to vX? [y/N]` (`--yes` skips it), drains the provider through `ServiceDrain` (which holds the cross-process update lease), swaps through the watchdog's journaled rollback, restarts the provider and rearms the watchdog, as `darkbloom update` activates an installed release. - The rolled-back release is quarantined with the existing single-slot quarantine, so the in-process check, the startup check and the watchdog skip it and the next newer release installs normally. `darkbloom update --override-quarantine` installs it again on request. - `SelfUpdater.rollbackPlan` / `rollBackToPredecessor` refuse, changing nothing, when the lease is held, no predecessor is kept, the predecessor is already installed or not older, the live bundle is not the recorded release, or the predecessor fails verification. The plan is re-checked under the lease after confirmation (a promotion in between is the same rollback); a rollback that fails after its journal was written is finished under that lease before the provider restarts. - The CLI refuses on a `darkbloom cluster` Mac (pairs run one release) and while a foreground provider runs, and restarts a drained provider even when the rollback fails. It contacts no coordinator. - Quarantine messages no longer say "after failed starts". Docs: `darkbloom update` reference, installation (roll back), troubleshooting, provider-release rollback, threat model T-043; changelog fragment. Co-Authored-By: Claude Opus 5.5 --- changelog.d/provider-update-rollback.md | 7 + docs/operations/provider-release.md | 10 +- docs/provider/cli-reference.md | 29 ++- docs/provider/installation.md | 40 ++- docs/provider/troubleshooting.md | 5 +- docs/threat-model.yaml | 7 + .../ProviderLoop+AutoUpdate.swift | 2 +- .../Update/AutoUpdateController.swift | 2 +- .../Update/SelfUpdater+Rollback.swift | 132 ++++++++++ .../ProviderCore/Update/SelfUpdater.swift | 2 +- .../darkbloom/Start/StartCommand+Modes.swift | 2 +- .../Sources/darkbloom/UpdateCommand.swift | 28 +- .../Sources/darkbloom/UpdateRollback.swift | 162 ++++++++++++ .../UpdateRollbackCommandTests.swift | 239 ++++++++++++++++++ .../Update/UpdateRollbackPlanTests.swift | 172 +++++++++++++ 15 files changed, 826 insertions(+), 13 deletions(-) create mode 100644 changelog.d/provider-update-rollback.md create mode 100644 provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift create mode 100644 provider-swift/Sources/darkbloom/UpdateRollback.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackPlanTests.swift diff --git a/changelog.d/provider-update-rollback.md b/changelog.d/provider-update-rollback.md new file mode 100644 index 0000000000..d4872886af --- /dev/null +++ b/changelog.d/provider-update-rollback.md @@ -0,0 +1,7 @@ +### Roll a Mac back to its previous release + +- `darkbloom update --rollback` restores the release a Mac ran before its last update. When the updater installs a release, it keeps the signed release it replaces; the rollback puts that release back, also after the new one has served for 10 minutes and was promoted. +- It shows the installed and restored versions and asks `Roll back to vX? [y/N]` before changing anything (`--yes` skips the question). The running provider finishes its accepted requests (`--timeout`, `--force` as for `darkbloom update`), the kept release replaces the installed one in the watchdog's journaled swap under the update lease, and the provider restarts on it. It contacts no coordinator. +- The rolled-back release is quarantined on that Mac: the provider's 30-minute update check, the startup check and the watchdog do not reinstall it, and the next newer release installs normally, so automatic updates can stay on. `darkbloom update --override-quarantine` installs it again on request. +- It refuses and changes nothing on a Mac that serves in a `darkbloom cluster` pair, while another update or recovery runs, when no earlier release is kept or the kept one is already installed, when the installed bundle is not the release the updater recorded, and when the kept release fails its hash or signature check. +- Only one earlier release is kept. A Mac rolls back to the release it ran before its last update, not further. diff --git a/docs/operations/provider-release.md b/docs/operations/provider-release.md index b00c7d71f3..c1b3e897c2 100644 --- a/docs/operations/provider-release.md +++ b/docs/operations/provider-release.md @@ -1,6 +1,6 @@ # Release A Provider Version -> Last updated: 2026-10-31 +> Last updated: 2026-11-02 Build, sign, notarize and publish an explicitly authorized provider artifact. The pipeline registers its exact official identity through the external platform @@ -1030,6 +1030,14 @@ do not replace its bytes or re-register it with a different artifact. 4. Adjust the GitHub release's public status and record the actual outcome. Fix forward with a new reviewed patch version, never overwritten signed bytes. +Deactivation stops new installs only: a Mac already on the bad release stays on +it, because the updater never installs an older version. A provider who needs +the previous release on a Mac now runs `darkbloom update --rollback` there +([roll back](../provider/installation.md#roll-back-to-the-previous-release)). It +restores the release the updater kept when it installed the bad one and +quarantines the bad one on that Mac, contacts no coordinator, and leaves +automatic updates on, so the fixed patch version installs normally. + Permanent binary revocation is distinct from release deactivation. An authorized platform administrator can use `POST /v1/admin/app-attest/builds/revoke`; registration retries cannot undo its tombstone. Recover with another reviewed signed build, diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 40a06cdb8c..9469697fc8 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -740,12 +740,32 @@ and mixed prompt arrivals, see [the profiling workflow](https://github.com/Layr- |---|---|---|---| | `--coordinator ` | `String?` | config URL | Release source | | `--check-only` | flag | `false` | Report; do not install | -| `--override-quarantine` | flag | `false` | Reinstall a version quarantined after 3 failed starts | -| `--timeout ` | integer, 0–3600 | `600` | Drain the running service before activating the installed update | -| `--force` | flag | `false` | Explicitly permit interruption during update activation | +| `--override-quarantine` | flag | `false` | Reinstall a quarantined version: one that failed 3 starts, or one rolled back with `--rollback` | +| `--rollback` | flag | `false` | Restore the release kept for rollback (the retained predecessor) and quarantine the installed release. Contacts no coordinator | +| `--yes`, `-y` | flag | `false` | With `--rollback`: do not ask for confirmation. Required when standard input is not a terminal | +| `--timeout ` | integer, 0–3600 | `600` | Drain the running service before activating the installed update or the rollback | +| `--force` | flag | `false` | Explicitly permit interruption during update or rollback activation | Exit 1 on `quarantined`, `busy`, `cancelled`, `downloadFailed`, `hashMismatch`, `replaceFailed`, or a failed check (`UpdateResult`, `provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift`). + +`--rollback` cannot be combined with `--check-only`, `--override-quarantine` or +`--coordinator`, and `--yes` applies only to it. It prints the plan (installed +version, restored version, the install generation it records) and asks +`Roll back to vX? [y/N]`. A loaded provider is drained, the layout is swapped +through the watchdog's journaled rollback under the update lease, and the +provider is restarted and the watchdog rearmed, as for an installed update; a +stopped provider is only swapped +(`provider-swift/Sources/darkbloom/UpdateRollback.swift`, `UpdateRollback`; +`provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift`, +`rollbackPlan`, `rollBackToPredecessor`). It exits 1 and changes nothing when +this Mac serves in a `darkbloom cluster` pair (a running cluster service or a +loaded cluster-member provider job), a provider runs outside launchd +(`darkbloom start --foreground`), another update or recovery holds the lease, +no release is kept for rollback, the installed release is already that +release, the installed `Darkbloom.app` is not the recorded release, or the kept +release fails its hash or signature check (`RollbackRefusal`). Steps are in +[installation → Roll back to the previous release](./installation.md#roll-back-to-the-previous-release). See [installation → Update](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/docs/provider/installation.md). ### `darkbloom enroll` / `darkbloom unenroll` @@ -1828,12 +1848,15 @@ Check for and apply provider updates. ```bash darkbloom update [--check-only] [--coordinator ] [--timeout ] [--force] +darkbloom update --rollback [--yes] [--timeout ] [--force] ``` | Flag | Description | |------|-------------| | `--check-only` | Report whether an update is available without installing | | `--coordinator ` | Override coordinator URL | +| `--rollback` | Restore the release kept for rollback and quarantine the installed one ([details](#darkbloom-update)) | +| `--yes`, `-y` | With `--rollback`: do not ask for confirmation | | `--timeout ` | Drain deadline: default `600`, valid 0–3600 seconds | | `--force` | Explicitly permit interruption during activation; default `false` | diff --git a/docs/provider/installation.md b/docs/provider/installation.md index 4d777dfbcb..3c1182e3ff 100644 --- a/docs/provider/installation.md +++ b/docs/provider/installation.md @@ -1,6 +1,6 @@ # Install, update, and uninstall the provider -> Last updated: 2026-10-23 +> Last updated: 2026-11-02 How to put the `darkbloom` CLI on an Apple Silicon Mac with `scripts/install.sh`, what the script verifies before it touches an existing install, how the binary @@ -216,6 +216,44 @@ that exact version is blocked; a newer release installs normally. `darkbloom update --override-quarantine` reinstalls it anyway, and `darkbloom doctor` reports the quarantine under `up to date`. +### Roll back to the previous release + +When the updater installs a release, it keeps the signed release it replaced +in `~/.darkbloom/recovery/predecessor/` (`provider-swift/Sources/ProviderCore/Update/UpdateInstallLayout.swift`, +`snapshotLiveAsPredecessor`). A release that runs but regresses can be rolled +back to it on one Mac, with automatic updates left on: + +1. On a Mac that serves in a `darkbloom cluster` pair, first stop the pair: + `darkbloom cluster stop` (or `darkbloom stop` for a cluster-member provider + service). Roll back both Macs, then start the pair again with + `darkbloom cluster`. The command refuses while the pair serves. +2. Run the rollback and answer `y`: + + ```bash + darkbloom update --rollback + ``` + + It prints the installed and restored versions first and changes nothing + until you confirm (`--yes` skips the question). The running provider + finishes its accepted requests (`--timeout`, as for `darkbloom update`), + the kept release replaces the installed one in one journaled swap, and the + provider restarts on it. The installed release is quarantined: the + provider's own checks, the startup check and the watchdog skip it, and the + next newer release installs normally. + +Only one earlier release is kept, so a second rollback is refused. To install +the rolled-back release again, run `darkbloom update --override-quarantine`. + +Verify: + +```bash +darkbloom --version # the restored version +darkbloom update --check-only # "Latest release vX is quarantined on this machine." +``` + +Refusals and flags are listed in the +[`darkbloom update` reference](./cli-reference.md#darkbloom-update). + If the watchdog exits after starting a candidate but before recording the launch receipt, its next health observations reconcile the saved intent with launchd's run count or process identity for the same job. For each comparison, diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index 1b3c147873..f3c84c5cda 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -1,6 +1,6 @@ # Provider troubleshooting -> Last updated: 2026-10-27 +> Last updated: 2026-11-02 Symptom → check → fix for the `darkbloom` provider: installer exits, `doctor` check names, service lifecycle, coordinator connection, updates, models and the @@ -148,7 +148,8 @@ tail -50 ~/.darkbloom/provider.log ~/.darkbloom/watchdog.log | Symptom | Cause | Fix | |---|---|---| -| `Latest release vX is quarantined on this machine.` | vX crashed `rollbackThreshold` times before surviving `defaultStabilizationSeconds` (`provider-swift/Sources/ProviderCore/Update/UpdateRecoveryState.swift`; values in [runtime constants](./cli-reference.md#runtime-constants)) | Wait for the next release (it installs normally), or `darkbloom update --override-quarantine` | +| `Latest release vX is quarantined on this machine.` | vX crashed `rollbackThreshold` times before surviving `defaultStabilizationSeconds`, or was rolled back with `darkbloom update --rollback` (`provider-swift/Sources/ProviderCore/Update/UpdateRecoveryState.swift`; values in [runtime constants](./cli-reference.md#runtime-constants)) | Wait for the next release (it installs normally), or `darkbloom update --override-quarantine` | +| A new release runs but regresses | Automatic updates install every newer release | `darkbloom update --rollback` restores the previous release and quarantines this one; leave automatic updates on ([roll back](./installation.md#roll-back-to-the-previous-release)) | | `vX is already installed on disk but this process is vY.` | Update landed, daemon not restarted | `darkbloom restart` | | `SHA-256 hash mismatch!` | Download ≠ `bundle_hash`/`binary_hash`/`metallib_hash` | Retry; persistent mismatch means the release record and artifact disagree | | `another update/recovery operation is active` | Watchdog recovery or a previous update holds the lock | Wait a minute; retry | diff --git a/docs/threat-model.yaml b/docs/threat-model.yaml index 2e36f2ae07..74f59881c9 100644 --- a/docs/threat-model.yaml +++ b/docs/threat-model.yaml @@ -1883,6 +1883,13 @@ threats: verified install; predecessor material is hash+signature verified against the pinned designated requirement before any restore. status: implemented + - description: > + The operator rollback (`darkbloom update --rollback`) is the same + journaled rollback under the same update lease, with the same + predecessor verification and the same single-slot exact-version + quarantine; it also refuses an installed bundle that differs from + the recorded release and never rolls back one Mac of a cluster pair. + status: implemented - description: > Bounded watchdog network I/O (URLSession request/resource timeouts) plus a safe-point per-tick budget so a stalled download or wedged diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+AutoUpdate.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+AutoUpdate.swift index 5e7e4ad3ea..35c76ceb09 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+AutoUpdate.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+AutoUpdate.swift @@ -154,7 +154,7 @@ extension ProviderLoop { case .upToDate: logger.info("Auto-update: already running latest version") case .quarantined(let version): - logger.warning("Auto-update: v\(version) is quarantined after failed starts") + logger.warning("Auto-update: v\(version) is quarantined on this Mac") case .checkFailed(let reason): logger.warning("Auto-update: check failed: \(reason)") case .stageFailed(let reason): diff --git a/provider-swift/Sources/ProviderCore/Update/AutoUpdateController.swift b/provider-swift/Sources/ProviderCore/Update/AutoUpdateController.swift index efb644f4dd..4898b13bee 100644 --- a/provider-swift/Sources/ProviderCore/Update/AutoUpdateController.swift +++ b/provider-swift/Sources/ProviderCore/Update/AutoUpdateController.swift @@ -124,7 +124,7 @@ public struct AutoUpdateController: Sendable { case cancelled /// Already on the latest version. case upToDate - /// Latest release is the exact locally quarantined failed version. + /// Latest release is the exact locally quarantined version. case quarantined(String) /// The version check failed. case checkFailed(String) diff --git a/provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift b/provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift new file mode 100644 index 0000000000..422c48f1a0 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift @@ -0,0 +1,132 @@ +import Foundation + +/// Operator rollback (`darkbloom update --rollback`): replace the installed +/// release with the retained, verified predecessor and quarantine it. It runs +/// the watchdog's journaled rollback (`UpdateSession.rollback`) under the +/// caller's cross-process update lease, so it shares its verification, +/// power-loss replay and single-slot quarantine. A promoted release is rolled +/// back as well as a pending candidate (`UpdateRecoveryState.rollbackSource`). +extension SelfUpdater { + public struct RollbackPlan: Sendable, Equatable { + /// The installed release that is replaced and quarantined. + public let from: String + /// `from` has not passed its stabilization window yet. + public let fromIsCandidate: Bool + /// The retained predecessor that is restored. + public let to: String + /// The install generation the predecessor was installed at. + public let toGeneration: UInt64 + /// The install generation the rollback records. + public let generation: UInt64 + } + + /// Why no rollback was carried out. Every refusal leaves the install unchanged. + public enum RollbackRefusal: Error, Equatable, CustomStringConvertible { + case busy(String) + case noPredecessor + case nothingToRollBack(installed: String) + case predecessorNotOlder(installed: String, predecessor: String) + case installNotRecorded(String) + case predecessorUnusable(String) + case changedSinceConfirmation(installed: String, predecessor: String) + + public var description: String { + switch self { + case .busy(let reason): + return "Another update or recovery operation is running (\(reason)). Nothing was changed; retry when it finishes." + case .noPredecessor: + return "This Mac keeps no earlier release to roll back to. One is kept only when the updater installs a " + + "release over a signed one. Nothing was changed." + case .nothingToRollBack(let installed): + return "v\(installed) is installed and is already the release kept for rollback; this Mac keeps one " + + "earlier release, so there is nothing older to roll back to. Nothing was changed." + case .predecessorNotOlder(let installed, let predecessor): + return "The release kept for rollback, v\(predecessor), is not older than the installed v\(installed). " + + "Nothing was changed." + case .installNotRecorded(let detail): + return "The installed \(BuildEnvironment.current.appBundleName) is not the release the updater recorded " + + "(v\(detail)); it was changed outside the updater. Nothing was changed; reinstall with install.sh." + case .predecessorUnusable(let reason): + return "The release kept for rollback cannot be restored: \(reason). Nothing was changed." + case .changedSinceConfirmation(let installed, let predecessor): + return "The installed release changed after the rollback was confirmed (now v\(installed), " + + "kept for rollback v\(predecessor)). Nothing was changed; run the command again." + } + } + } + + /// Plans a rollback under a lease of its own, released before returning, + /// so the caller can ask for confirmation without holding it. + public func rollbackPlan() throws -> RollbackPlan { + let session: UpdateSession + do { + session = try beginUpdateSession(operation: "operator-rollback-plan", timeout: 0) + } catch UpdateError.lockBusy(let reason, _) { + throw RollbackRefusal.busy(reason) + } + defer { session.release() } + try session.recover(now: now()) + return try rollbackPlan(session: session) + } + + /// Plans a rollback from the recovery state `session` reads: the installed + /// release must be the recorded one, and the predecessor must verify. + public func rollbackPlan(session: UpdateSession) throws -> RollbackPlan { + let state = try session.readState() + guard let predecessor = state.predecessor else { throw RollbackRefusal.noPredecessor } + guard let installed = state.rollbackSource else { + throw RollbackRefusal.nothingToRollBack( + installed: state.current?.version ?? predecessor.release.version) + } + guard Self.isNewer(latest: installed.version, current: predecessor.release.version) else { + throw RollbackRefusal.predecessorNotOlder( + installed: installed.version, predecessor: predecessor.release.version) + } + let liveIsRecorded: Bool + do { + liveIsRecorded = try session.store.liveMatches(installed) + } catch { + throw RollbackRefusal.installNotRecorded("\(installed.version): \(error)") + } + guard liveIsRecorded else { throw RollbackRefusal.installNotRecorded(installed.version) } + do { + try session.store.verifyPredecessor(predecessor) + } catch { + throw RollbackRefusal.predecessorUnusable("\(error)") + } + let (generation, overflow) = state.installGeneration.addingReportingOverflow(1) + guard !overflow else { throw RollbackRefusal.predecessorUnusable("install generation overflow") } + return RollbackPlan( + from: installed.version, + fromIsCandidate: state.candidate != nil, + to: predecessor.release.version, + toGeneration: predecessor.release.installGeneration, + generation: generation) + } + + /// Carries out a confirmed `plan` while the caller holds `session` (for a + /// running provider, the lease its drain took). Returns the restored version. + @discardableResult + public func rollBackToPredecessor(session: UpdateSession, plan: RollbackPlan) throws -> String { + try session.recover(now: now()) + // The plan was confirmed without the lease. A promotion since then is + // the same rollback; any other install or rollback is not. + let current = try rollbackPlan(session: session) + guard current.from == plan.from, current.to == plan.to, current.generation == plan.generation else { + throw RollbackRefusal.changedSinceConfirmation(installed: current.from, predecessor: current.to) + } + let reason = "rolled back by the operator to v\(plan.to) (\(BuildEnvironment.current.cliName) update --rollback)" + do { + return try session.rollback(now: now(), reason: reason) + } catch { + // Finish a rollback that failed after its journal was written while + // this lease is still held, so no restart runs an unfinished layout. + try? session.recover(now: now()) + if let state = try? session.readState(), state.rollbackSource == nil, + state.current?.version == plan.to, state.quarantine?.version == plan.from { + return plan.to + } + throw error + } + } +} diff --git a/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift b/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift index 26c202b68b..a73c27253e 100644 --- a/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift +++ b/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift @@ -62,7 +62,7 @@ public struct SelfUpdater: Sendable { /// `checkForUpdate` uses, from the same injected seam. internal let currentVersion: String private let urlSession: URLSession - private let now: @Sendable () -> Double + let now: @Sendable () -> Double /// Test seam threaded into every `UpdateRecoveryStore` this updater /// constructs; production always uses the no-op default. private let recoveryFaultInjector: diff --git a/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift b/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift index c21ba8cdb2..c290cea28d 100644 --- a/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift +++ b/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift @@ -410,7 +410,7 @@ extension Start { throw error } case .quarantined(let version, let reason): - printError("auto-update skipped: v\(version) is quarantined after failed starts (\(reason))") + printError("auto-update skipped: v\(version) is quarantined on this Mac (\(reason))") case .busy(let reason): printError("auto-update skipped: another update/recovery operation is active (\(reason))") case .cancelled(let reason): diff --git a/provider-swift/Sources/darkbloom/UpdateCommand.swift b/provider-swift/Sources/darkbloom/UpdateCommand.swift index 0e331f813a..ded28a024c 100644 --- a/provider-swift/Sources/darkbloom/UpdateCommand.swift +++ b/provider-swift/Sources/darkbloom/UpdateCommand.swift @@ -37,10 +37,25 @@ struct Update: AsyncParsableCommand { @Flag( name: .long, - help: "Explicitly reinstall a locally quarantined failed version." + help: "Explicitly reinstall a locally quarantined version (failed starts or --rollback)." ) var overrideQuarantine = false + @Flag(help: "Restore the release this Mac ran before its last update and quarantine the installed one.") + var rollback = false + + @Flag(name: .shortAndLong, help: "With --rollback: don't ask for confirmation.") + var yes = false + + func validate() throws { + if rollback, checkOnly || overrideQuarantine || coordinator != nil { + throw ValidationError("--rollback cannot be combined with --check-only, --override-quarantine or --coordinator.") + } + if yes, !rollback { + throw ValidationError("--yes applies only to --rollback.") + } + } + mutating func run() async throws { let config = try loadUpdateConfig(configPath: configOptions.config) @@ -51,6 +66,15 @@ struct Update: AsyncParsableCommand { let coordinatorURL = coordinator ?? config.coordinator.url let updater = SelfUpdater(coordinatorBaseURL: coordinatorURL) + if rollback { + try await UpdateRollback( + updater: updater, + host: .live(drain: drain, configPath: configOptions.config), + say: { print($0) } + ).run(skipConfirmation: yes) + return + } + if checkOnly { let result = await updater.checkForUpdate( manualOverride: overrideQuarantine @@ -117,7 +141,7 @@ struct Update: AsyncParsableCommand { } case .quarantined(let version, let reason): - printError("v\(version) is quarantined after failed starts: \(reason)") + printError("v\(version) is quarantined on this Mac: \(reason)") printError("A strictly newer release will install automatically.") printError("Use --override-quarantine for an explicit operator retry.") throw ExitCode.failure diff --git a/provider-swift/Sources/darkbloom/UpdateRollback.swift b/provider-swift/Sources/darkbloom/UpdateRollback.swift new file mode 100644 index 0000000000..f56a3d9c97 --- /dev/null +++ b/provider-swift/Sources/darkbloom/UpdateRollback.swift @@ -0,0 +1,162 @@ +import ArgumentParser +import Foundation +import ProviderCore + +/// `darkbloom update --rollback`: the operator's way back from a bad release on +/// one Mac. It restores the release kept for rollback through the watchdog's +/// journaled rollback (`SelfUpdater.rollBackToPredecessor`) and quarantines the +/// installed one, between the drain and restart `darkbloom update` uses: the +/// running provider drains first (the drain holds the update lease), the +/// layout is swapped, then the provider restarts. +struct UpdateRollback { + /// This Mac's provider service, injected so tests never reach launchd. + enum Provider { + /// The launchd provider service is loaded. + case service + /// A provider runs outside launchd (`darkbloom start --foreground`). + case foreground + case stopped + } + + struct Host { + /// A `darkbloom cluster` service runs, or the provider job runs a cluster member. + var servesInCluster: () -> Bool + var provider: () -> Provider + var canAsk: () -> Bool + var readAnswer: () -> String? + /// Drains the running provider and returns the update lease the drain holds. + var drain: () async throws -> SelfUpdater.UpdateSession + /// Relaunches the drained provider and rearms the watchdog. + var restart: () async throws -> Void + /// Waits until the relaunched provider is freshly authorized. + var waitForRestart: () async throws -> Void + } + + /// A refusal or failure, printed as is (a runtime failure, not a usage mistake). + struct Failure: Error, CustomStringConvertible { + let description: String + } + + let updater: SelfUpdater + let host: Host + let say: (String) -> Void + + static let clusterRefusal = """ + This Mac serves in a two-Mac cluster. Both Macs of a pair run one release, so `\(cli) update --rollback` \ + does not roll back one Mac of a pair. Stop the pair first (`\(cli) cluster stop`, or `\(cli) stop` for a \ + cluster member service), run `\(cli) update --rollback` on each Mac, then start the pair again with \ + `\(cli) cluster`. Nothing was changed. + """ + + static let foregroundRefusal = """ + A provider runs outside its launchd service (`\(cli) start --foreground`), and the rollback cannot drain \ + and restart it. Stop it (Ctrl-C), then run `\(cli) update --rollback` again. Nothing was changed. + """ + + private static var cli: String { BuildEnvironment.current.cliName } + + func run(skipConfirmation: Bool) async throws { + guard !host.servesInCluster() else { throw Failure(description: Self.clusterRefusal) } + let provider = host.provider() + guard provider != .foreground else { throw Failure(description: Self.foregroundRefusal) } + let plan = try await refusingClearly { try updater.rollbackPlan() } + let loaded = provider == .service + Self.describe(plan, providerLoaded: loaded).forEach(say) + if !skipConfirmation { + guard host.canAsk() else { + throw Failure(description: "Confirm in an interactive terminal, or pass --yes to roll back without a prompt.") + } + say("Roll back to v\(plan.to)? [y/N]") + let answer = host.readAnswer()?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "" + guard ["y", "yes"].contains(answer) else { + say("Nothing changed.") + return + } + } + + let session = try await refusingClearly { + if loaded { return try await host.drain() } + return try updater.beginUpdateSession(operation: "operator-rollback", timeout: 0) + } + defer { session.release() } + let outcome = Result { try updater.rollBackToPredecessor(session: session, plan: plan) } + // A drained provider restarts whether or not the rollback completed: + // the layout is always one complete release (the journal guarantees it). + var restartFailure: Error? + if loaded { + do { try await host.restart() } catch { restartFailure = error } + } + session.release() + let notRestarted = restartFailure.map { + " The provider did not restart: \($0). Run `\(Self.cli) restart`." + } ?? "" + + let restored: String + switch outcome { + case .success(let version): + restored = version + case .failure(let error): + throw Failure(description: "Rollback did not complete: \(error)." + + (loaded && restartFailure == nil ? " The provider restarted on the installed release." : notRestarted)) + } + say("Rolled back: v\(plan.from) -> v\(restored).") + say("v\(plan.from) is quarantined on this Mac: automatic updates skip it, and the next newer release installs " + + "normally. To install v\(plan.from) again anyway: \(Self.cli) update --override-quarantine") + if restartFailure != nil { + throw Failure(description: "Rolled back to v\(restored)." + notRestarted) + } + if loaded { + say("Provider relaunched on v\(restored); waiting for fresh authorization...") + try await host.waitForRestart() + } else { + say("The provider is not running; `\(Self.cli) start` starts v\(restored).") + } + } + + static func describe(_ plan: SelfUpdater.RollbackPlan, providerLoaded: Bool) -> [String] { + let installed = plan.fromIsCandidate ? "installed, not yet promoted" : "installed" + return [ + "Roll back this Mac:", + " v\(plan.from) (\(installed)) -> v\(plan.to) (the release kept for rollback, install generation \(plan.toGeneration))", + providerLoaded + ? " The provider finishes its accepted requests, stops, and restarts on v\(plan.to)." + : " The provider is not running; nothing is drained or restarted.", + " v\(plan.from) is quarantined: automatic updates skip it until a newer release is published.", + " This rollback is recorded as install generation \(plan.generation).", + ] + } + + /// Lease contention and every rollback refusal print as one plain line. + private func refusingClearly(_ body: () async throws -> Value) async throws -> Value { + do { + return try await body() + } catch let refusal as SelfUpdater.RollbackRefusal { + throw Failure(description: refusal.description) + } catch UpdateError.lockBusy(let reason, _) { + throw Failure(description: SelfUpdater.RollbackRefusal.busy(reason).description) + } + } +} + +extension UpdateRollback.Host { + static func live(drain options: DrainOptions, configPath: String?) -> Self { + let previous = LaunchAgent.launchSnapshot()?.process + return Self( + servesInCluster: { + ClusterService.running() || (LaunchAgent.isLoaded() && LaunchAgent.installedJobIsClusterMember()) + }, + provider: { + if LaunchAgent.isLoaded() { return .service } + return DaemonStateFile.read()?.processIdentity?.isCurrent() == true ? .foreground : .stopped + }, + canAsk: { isatty(STDIN_FILENO) != 0 }, + readAnswer: { readLine() }, + drain: { try await ServiceDrain.prepare(options: options) }, + restart: { + try await ServiceDrain.stopDrainedProvider(unloadService: false) + try LaunchAgent.restartAfterDrain() + ServiceDrain.rearmWatchdog(explicitConfig: configPath) + }, + waitForRestart: { try await ServiceDrain.waitForRestart(previous: previous, timeout: 180) }) + } +} diff --git a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift new file mode 100644 index 0000000000..df3175c178 --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift @@ -0,0 +1,239 @@ +import ArgumentParser +import Foundation +import Testing +@testable import darkbloom +@testable import ProviderCore + +/// `darkbloom update --rollback` against a temporary install root. The host +/// (cluster check, launchd, drain, restart, prompt) is injected, so no real +/// install, launchd job or provider process is touched. +@Suite("Update rollback command", .serialized) +struct UpdateRollbackCommandTests { + @Test("update parses --rollback with --yes and the drain options, and refuses mixed flags") + func parsing() throws { + let update = try #require(try Darkbloom.parseAsRoot(["update", "--rollback", "--yes", "--timeout", "30"]) as? Update) + #expect(update.rollback) + #expect(update.yes) + #expect(update.drain.timeout == 30) + for arguments in [ + ["update", "--rollback", "--check-only"], + ["update", "--rollback", "--override-quarantine"], + ["update", "--rollback", "--coordinator", "https://override.invalid"], + ["update", "--yes"], + ] { + #expect(throws: (any Error).self, "\(arguments)") { try Darkbloom.parseAsRoot(arguments) } + } + } + + @Test("a confirmed rollback drains, swaps, restarts and quarantines") + func confirmedRollbackOfARunningProvider() async throws { + let install = try RollbackInstall() + defer { install.remove() } + let host = RecordingHost(install: install, loaded: true, answer: "y") + + try await install.rollback(host: host, yes: false) + + #expect(host.events == ["drain", "restart", "wait"]) + #expect(try install.liveBinary() == "1.0.0-darkbloom") + let state = try install.store.loadState() + #expect(state.current?.version == "1.0.0") + #expect(state.quarantine?.version == "2.0.0") + #expect(host.said.contains("Roll back this Mac:")) + #expect(host.said.contains(" v2.0.0 (installed) -> v1.0.0 (the release kept for rollback, install generation 0)")) + #expect(host.said.contains("Roll back to v1.0.0? [y/N]")) + #expect(host.said.contains("Rolled back: v2.0.0 -> v1.0.0.")) + } + + @Test("--yes skips the prompt, and a stopped provider is swapped without a drain or restart") + func yesWithAStoppedProvider() async throws { + let install = try RollbackInstall() + defer { install.remove() } + let host = RecordingHost(install: install, loaded: false, canAsk: false) + + try await install.rollback(host: host, yes: true) + + #expect(host.events.isEmpty) + #expect(try install.liveBinary() == "1.0.0-darkbloom") + #expect(!host.said.contains { $0.contains("[y/N]") }) + #expect(host.said.contains("The provider is not running; `darkbloom start` starts v1.0.0.")) + } + + @Test("a declined or unanswerable prompt changes nothing") + func declinedPrompt() async throws { + let install = try RollbackInstall() + defer { install.remove() } + let declining = RecordingHost(install: install, loaded: true, answer: "") + try await install.rollback(host: declining, yes: false) + #expect(declining.said.last == "Nothing changed.") + + let noTerminal = RecordingHost(install: install, loaded: true, canAsk: false) + let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: noTerminal, yes: false) } + #expect(error?.description.contains("--yes") == true) + + #expect(declining.events.isEmpty && noTerminal.events.isEmpty) + #expect(try install.liveBinary() == "2.0.0-darkbloom") + #expect(try install.store.loadState().quarantine == nil) + } + + @Test("a cluster Mac, a foreground provider, a held lease and a missing predecessor are refused before any drain") + func refusals() async throws { + let install = try RollbackInstall() + defer { install.remove() } + + let cluster = RecordingHost(install: install, loaded: true, inCluster: true) + let clusterError = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: cluster, yes: true) } + #expect(clusterError?.description.contains("darkbloom cluster stop") == true) + + let foreground = RecordingHost(install: install, loaded: false, foreground: true) + let foregroundError = await #expect(throws: UpdateRollback.Failure.self) { + try await install.rollback(host: foreground, yes: true) + } + #expect(foregroundError?.description.contains("start --foreground") == true) + + let holder = try install.updater.beginUpdateSession(operation: "watchdog-recovery") + let busy = RecordingHost(install: install, loaded: true) + let busyError = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: busy, yes: true) } + #expect(busyError?.description.contains("watchdog-recovery") == true) + holder.release() + + let fresh = try RollbackInstall(updated: false) + defer { fresh.remove() } + let none = RecordingHost(install: fresh, loaded: true) + let noneError = await #expect(throws: UpdateRollback.Failure.self) { try await fresh.rollback(host: none, yes: true) } + #expect(noneError?.description.contains("no earlier release") == true) + + #expect(cluster.events.isEmpty && foreground.events.isEmpty && busy.events.isEmpty && none.events.isEmpty) + #expect(try install.liveBinary() == "2.0.0-darkbloom") + #expect(try fresh.liveBinary() == "1.0.0-darkbloom") + } + + @Test("a rollback that fails after the drain still restarts the provider on a complete release") + func failureAfterDrainRestarts() async throws { + let install = try RollbackInstall() + defer { install.remove() } + // The predecessor changes between confirmation and the swap. + let host = RecordingHost(install: install, loaded: true, answer: "yes", beforeDrain: { + try Data("tampered".utf8).write(to: install.root.appendingPathComponent( + "recovery/predecessor/Darkbloom.app/Contents/MacOS/darkbloom")) + }) + + let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: host, yes: false) } + + #expect(error?.description.contains("Rollback did not complete") == true) + #expect(error?.description.contains("restarted on the installed release") == true) + #expect(host.events == ["drain", "restart"]) + #expect(try install.liveBinary() == "2.0.0-darkbloom") + #expect(try install.store.loadState().quarantine == nil) + // The lease is free again for the watchdog and the restarted provider. + try install.updater.beginUpdateSession(operation: "lease-check").release() + } +} + +/// v1 installed, then v2 installed and promoted by the updater, in a temporary root. +private struct RollbackInstall { + let root: URL + let scratch: URL + + init(updated: Bool = true) throws { + let fm = FileManager.default + scratch = fm.temporaryDirectory.appendingPathComponent("update-rollback-cli-\(UUID().uuidString)") + root = scratch.appendingPathComponent("install") + try Self.writeApp(version: "1.0.0", in: root) + let bin = root.appendingPathComponent("bin") + try fm.createDirectory(at: bin, withIntermediateDirectories: true) + for name in ["darkbloom", "darkbloom-enclave", "mlx.metallib"] { + try fm.createSymbolicLink( + atPath: bin.appendingPathComponent(name).path, + withDestinationPath: "../Darkbloom.app/Contents/MacOS/\(name)") + } + guard updated else { return } + + let source = scratch.appendingPathComponent("release") + try Self.writeApp(version: "2.0.0", in: source) + let flat = source.appendingPathComponent("bin") + try fm.createDirectory(at: flat, withIntermediateDirectories: true) + for name in ["darkbloom", "darkbloom-enclave", "mlx.metallib"] { + try fm.copyItem( + at: source.appendingPathComponent("Darkbloom.app/Contents/MacOS/\(name)"), + to: flat.appendingPathComponent(name)) + } + let tarball = scratch.appendingPathComponent("release.tar.gz") + let tar = Process() + tar.executableURL = URL(fileURLWithPath: "/usr/bin/tar") + tar.arguments = ["czf", tarball.path, "-C", source.path, "."] + try tar.run() + tar.waitUntilExit() + let release = ReleaseInfo(version: "2.0.0", platform: "macos-arm64", url: "unused://", bundleHash: "unused") + let installer = SelfUpdater( + coordinatorBaseURL: "http://127.0.0.1:9", installRoot: root, verifyCodeSignatures: false, + currentVersion: "1.0.0") + guard case .success = installer.installBundleForTesting(from: tarball, release: release, installDir: root) else { + throw CocoaError(.fileWriteUnknown) + } + var state = try store.loadState() + state.promoteCandidate() + try store.writeState(state) + } + + var updater: SelfUpdater { + SelfUpdater( + coordinatorBaseURL: "http://127.0.0.1:9", installRoot: root, verifyCodeSignatures: false, + currentVersion: "2.0.0") + } + + var store: UpdateRecoveryStore { UpdateRecoveryStore(installRoot: root, verifyCodeSignatures: false) } + + func rollback(host: RecordingHost, yes: Bool) async throws { + try await UpdateRollback(updater: updater, host: host.host, say: host.say).run(skipConfirmation: yes) + } + + func liveBinary() throws -> String { + try String(contentsOf: root.appendingPathComponent("Darkbloom.app/Contents/MacOS/darkbloom"), encoding: .utf8) + } + + func remove() { try? FileManager.default.removeItem(at: scratch) } + + private static func writeApp(version: String, in root: URL) throws { + let macOS = root.appendingPathComponent("Darkbloom.app/Contents/MacOS") + try FileManager.default.createDirectory(at: macOS, withIntermediateDirectories: true) + try Data("".utf8).write(to: macOS.deletingLastPathComponent().appendingPathComponent("Info.plist")) + for (name, suffix) in [("darkbloom", "darkbloom"), ("darkbloom-enclave", "enclave"), ("mlx.metallib", "metallib")] { + try Data("\(version)-\(suffix)".utf8).write(to: macOS.appendingPathComponent(name)) + } + } +} + +/// The injected host: records drains, restarts and printed lines. +private final class RecordingHost: @unchecked Sendable { + private final class Log: @unchecked Sendable { + let lock = NSLock() + var events: [String] = [] + var lines: [String] = [] + } + + private let log: Log + let host: UpdateRollback.Host + var events: [String] { log.lock.withLock { log.events } } + var said: [String] { log.lock.withLock { log.lines } } + + init(install: RollbackInstall, loaded: Bool, foreground: Bool = false, inCluster: Bool = false, canAsk: Bool = true, + answer: String? = nil, beforeDrain: @escaping () throws -> Void = {}) { + let log = Log() + self.log = log + let record = { (event: String) in log.lock.withLock { log.events.append(event) } } + host = UpdateRollback.Host( + servesInCluster: { inCluster }, + provider: { loaded ? .service : foreground ? .foreground : .stopped }, + canAsk: { canAsk }, + readAnswer: { answer }, + drain: { + record("drain") + try beforeDrain() + return try install.updater.beginUpdateSession(operation: "provider-lifecycle", timeout: 0) + }, + restart: { record("restart") }, + waitForRestart: { record("wait") }) + } + + func say(_ line: String) { log.lock.withLock { log.lines.append(line) } } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackPlanTests.swift b/provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackPlanTests.swift new file mode 100644 index 0000000000..ddd147086b --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackPlanTests.swift @@ -0,0 +1,172 @@ +/// The operator rollback API behind `darkbloom update --rollback`: its plan, +/// each refusal, and a failure finished under the same lease. + +import Foundation +import Testing +@testable import ProviderCore + +@Suite("Operator rollback plan", .serialized) +struct UpdateRollbackPlanTests { + @Test("the plan names the installed release, the predecessor and the generation it records") + func planForPromotedAndPendingReleases() async throws { + for promote in [true, false] { + let installed = try await InstalledUpdate.make(promote: promote) + let state = try installed.store.loadState() + let plan = try installed.updater.rollbackPlan() + #expect(plan == SelfUpdater.RollbackPlan( + from: "2.0.0", fromIsCandidate: !promote, to: "1.0.0", + toGeneration: try #require(state.predecessor).release.installGeneration, + generation: state.installGeneration + 1)) + await installed.shutdown() + } + } + + @Test("rolling back a pending candidate quarantines it with its failed starts") + func pendingCandidateRollsBack() async throws { + let installed = try await InstalledUpdate.make(promote: false) + defer { Task { await installed.shutdown() } } + // The watchdog launches v2 once, and that start fails. + let watchdog = watchdogRecovery(installed.updater) + _ = await watchdog.recoverDownProvider(autoUpdateEnabled: false, now: 200) + _ = await watchdog.recoverDownProvider(autoUpdateEnabled: false, now: 300) + + let plan = try installed.updater.rollbackPlan() + let session = try installed.updater.beginUpdateSession(operation: "test-rollback") + defer { session.release() } + #expect(try installed.updater.rollBackToPredecessor(session: session, plan: plan) == "1.0.0") + + #expect(try installed.liveRelease() == "1.0.0") + let state = try installed.store.loadState() + #expect(state.candidate == nil) + #expect(state.current?.version == "1.0.0") + #expect(state.installGeneration == plan.generation) + #expect(state.quarantine?.version == "2.0.0") + #expect(state.quarantine?.failureCount == 1) + #expect(state.quarantine?.reason.contains("update --rollback") == true) + } + + @Test("each refusal leaves the install as it was") + func refusals() async throws { + // Never updated: nothing was retained. + let fresh = try UpdateRecoveryFixture() + defer { fresh.cleanup() } + #expect(throws: SelfUpdater.RollbackRefusal.noPredecessor) { + try fresh.updater(baseURL: URL(string: "http://127.0.0.1:9")!).rollbackPlan() + } + + let installed = try await InstalledUpdate.make(promote: true) + defer { Task { await installed.shutdown() } } + + // Another update holds the cross-process lease. + let holder = try installed.updater.beginUpdateSession(operation: "watchdog-recovery") + #expect { + try installed.updater.rollbackPlan() + } throws: { error in + guard case .busy(let reason) = error as? SelfUpdater.RollbackRefusal else { return false } + return reason.contains("watchdog-recovery") + } + holder.release() + + // A live bundle replaced outside the updater is not the recorded release. + let liveBinary = installed.fixture.installRoot.appendingPathComponent("Darkbloom.app/Contents/MacOS/darkbloom") + let original = try Data(contentsOf: liveBinary) + try Data("hand-copied".utf8).write(to: liveBinary) + #expect(throws: SelfUpdater.RollbackRefusal.installNotRecorded("2.0.0")) { + try installed.updater.rollbackPlan() + } + try original.write(to: liveBinary) + + // A changed predecessor is never restored. + let predecessorBinary = installed.fixture.installRoot + .appendingPathComponent("recovery/predecessor/Darkbloom.app/Contents/MacOS/darkbloom") + let retained = try Data(contentsOf: predecessorBinary) + try Data("tampered".utf8).write(to: predecessorBinary) + #expect { + try installed.updater.rollbackPlan() + } throws: { error in + guard case .predecessorUnusable(let reason) = error as? SelfUpdater.RollbackRefusal else { return false } + return reason.contains("hash mismatch") + } + try retained.write(to: predecessorBinary) + #expect(try installed.liveRelease() == "2.0.0") + #expect(try installed.store.loadState().quarantine == nil) + + // Once rolled back, the predecessor is installed: nothing older remains. + let plan = try installed.updater.rollbackPlan() + let session = try installed.updater.beginUpdateSession(operation: "test-rollback") + try installed.updater.rollBackToPredecessor(session: session, plan: plan) + #expect(throws: SelfUpdater.RollbackRefusal.nothingToRollBack(installed: "1.0.0")) { + try installed.updater.rollbackPlan(session: session) + } + // A plan confirmed before the install changed is not carried out. + #expect(throws: SelfUpdater.RollbackRefusal.self) { + try installed.updater.rollBackToPredecessor(session: session, plan: plan) + } + session.release() + #expect(try installed.liveRelease() == "1.0.0") + } + + @Test("a promotion after confirmation is the same rollback; a newer install is not") + func confirmationAgainstLaterChanges() async throws { + let promotedLater = try await InstalledUpdate.make(promote: false) + defer { Task { await promotedLater.shutdown() } } + let pendingPlan = try promotedLater.updater.rollbackPlan() + #expect(pendingPlan.fromIsCandidate) + let health = watchdogRecovery(promotedLater.updater, stabilizationSeconds: 0).observeHealthyProvider( + providerRunning: true, + daemonState: DaemonState(pid: 4242, version: "2.0.0", writtenAt: 150, startedAt: 120), + now: 150) + #expect(health == .promoted(version: "2.0.0")) + let promotedSession = try promotedLater.updater.beginUpdateSession(operation: "test-rollback") + #expect(try promotedLater.updater.rollBackToPredecessor(session: promotedSession, plan: pendingPlan) == "1.0.0") + promotedSession.release() + + let updatedLater = try await InstalledUpdate.make(promote: true) + defer { Task { await updatedLater.shutdown() } } + let plan = try updatedLater.updater.rollbackPlan() + let newer = try UpdateRecoveryFixture(oldVersion: "1.0.0", newVersion: "3.0.0") + defer { newer.cleanup() } + let newerMock = MockCoordinator(release: newer.mockReleaseFixture(), releaseArtifact: newer.artifact) + let newerURL = try await newerMock.start() + defer { Task { await newerMock.shutdown() } } + let v2Updater = SelfUpdater( + coordinatorBaseURL: newerURL.absoluteString, installRoot: updatedLater.fixture.installRoot, + verifyCodeSignatures: false, currentVersion: "2.0.0") + guard case .updated(_, "3.0.0") = await v2Updater.update() else { + Issue.record("v3 did not install") + return + } + let session = try updatedLater.updater.beginUpdateSession(operation: "test-rollback") + defer { session.release() } + #expect(throws: SelfUpdater.RollbackRefusal.changedSinceConfirmation(installed: "3.0.0", predecessor: "2.0.0")) { + try updatedLater.updater.rollBackToPredecessor(session: session, plan: plan) + } + #expect(try updatedLater.liveRelease() == "3.0.0") + } + + @Test("a rollback that fails after its journal was written is finished under the same lease") + func failureIsFinishedUnderTheLease() async throws { + struct InjectedFailure: Error {} + let installed = try await InstalledUpdate.make(promote: true) + defer { Task { await installed.shutdown() } } + let once = OneShotFault() + let failing = SelfUpdater( + coordinatorBaseURL: installed.baseURL.absoluteString, installRoot: installed.fixture.installRoot, + verifyCodeSignatures: false, currentVersion: "2.0.0", + recoveryFaultInjector: { point in + if point == .liveLayoutExchanged, once.claim() { throw InjectedFailure() } + }) + + let plan = try failing.rollbackPlan() + let session = try failing.beginUpdateSession(operation: "test-rollback") + defer { session.release() } + #expect(try failing.rollBackToPredecessor(session: session, plan: plan) == "1.0.0") + + #expect(try installed.liveRelease() == "1.0.0") + #expect(try installed.leftoverRollbackFiles().isEmpty) + let state = try installed.store.loadState() + #expect(state.current?.version == "1.0.0") + #expect(state.quarantine?.version == "2.0.0") + #expect(state.installGeneration == plan.generation) + } +} From 9090c6ac61de1ca465b3d07f49d68fa97928eed1 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 2 Nov 2026 14:42:11 -0800 Subject: [PATCH 0179/1441] fix(provider): the enabled-model filter wins over coordinator model changes A provider whose operator set enabled_models obeyed every coordinator nudge for a model outside it. With autopilot off, autopilotAllowsModel admitted any model that is not Autopilot inventory, and reconcileDesiredModels promoted a selected build's alias successor into the ordinary selection. In production the takeover alias gemma-4-26b names gemma-4-26b-qat-4bit as desired and gemma-4-26b as previous, so a provider serving the 8-bit gemma-4-26b with qat-4bit deselected (or its weights removed) re-downloaded qat-4bit, advertised it, dropped gemma-4-26b, and loaded qat-4bit on the warm pool's load_model. The provider now keeps the operator's filter: a nonempty enabled_models with the start selection, then each live switch's selection. Coordinator load_model, prefetch_model, desired builds and alias successors outside it are refused (model_not_selected) or skipped with a log line. An empty enabled_models filters nothing, and Autopilot's consented paths keep their own gates. Tests: OperatorModelFilterTests (three fail before this change, one pins the unchanged empty-filter and in-filter rollout). The successor and switch-replay tests now select the successor, or expect the refusal. Co-Authored-By: Claude Opus 5.5 --- changelog.d/provider-enabled-filter-wins.md | 7 + docs/architecture/model-autopilot.md | 8 +- docs/operations/model-migration.md | 11 +- docs/provider/cli-reference.md | 2 +- docs/provider/troubleshooting.md | 5 +- docs/reference/configuration.md | 4 +- docs/reference/protocol-messages.md | 11 +- .../ProviderLoop+AutopilotControl.swift | 2 +- .../ProviderLoop+ModelSelection.swift | 16 ++- .../ProviderCore/ProviderLoop+Prefetch.swift | 14 +- .../Sources/ProviderCore/ProviderLoop.swift | 7 + .../Autopilot/AutopilotInventoryTests.swift | 9 +- .../OperatorModelFilterTests.swift | 135 ++++++++++++++++++ .../Service/ProviderModelSwitchTests.swift | 22 +-- 14 files changed, 224 insertions(+), 29 deletions(-) create mode 100644 changelog.d/provider-enabled-filter-wins.md create mode 100644 provider-swift/Tests/ProviderCoreTests/ProviderLoop/OperatorModelFilterTests.swift diff --git a/changelog.d/provider-enabled-filter-wins.md b/changelog.d/provider-enabled-filter-wins.md new file mode 100644 index 0000000000..aa2b7e923c --- /dev/null +++ b/changelog.d/provider-enabled-filter-wins.md @@ -0,0 +1,7 @@ +### The enabled-model filter wins over coordinator model changes + +- A provider with an `enabled_models` filter no longer serves, downloads or loads a model outside it because the coordinator asked. Before, a public model rollout could bring back a model you deselected: with `gemma-4-26b` selected and `gemma-4-26b-qat-4bit` deselected, the coordinator's `gemma-4-26b` rollout downloaded `gemma-4-26b-qat-4bit` again (also after `darkbloom models remove`), served it in place of `gemma-4-26b`, and `darkbloom status` showed `Serving outside the enabled model filter: gemma-4-26b-qat-4bit`. +- The provider now refuses a coordinator `load_model` or `prefetch_model` for a model outside the filter (`model_not_selected`), and does not move a selected model to a newer build outside the filter. It keeps serving the selected build and logs `desired_models: → is outside the enabled model filter; not converging`. +- `darkbloom switch` makes its selection the filter at once, without a restart. +- With an empty `enabled_models` (serve every downloaded model) nothing changes. To take a new build of a selected model, add it with `darkbloom switch`. +- Autopilot keeps its own consent-based downloads and placements. diff --git a/docs/architecture/model-autopilot.md b/docs/architecture/model-autopilot.md index 73226f9dd9..cfb26e1bcf 100644 --- a/docs/architecture/model-autopilot.md +++ b/docs/architecture/model-autopilot.md @@ -1,6 +1,6 @@ # Provider Autopilot -> Last updated: 2026-10-27 +> Last updated: 2026-11-02 Provider Autopilot offers an external controller the models of a Mac whose operator saved Autopilot consent: the saved selection plus every verified @@ -244,6 +244,12 @@ stops the driver at its next candidate, and the current step finishes normally. 9. Without saved consent, or with downloads turned off, there is no download, no `inventory_downloads` capability and no `download_storage` (`autopilotDownloadsEnabled`, `handlePrefetchModelRequest`). +10. Ordinary coordinator commands reach only the operator's filter: a nonempty + `enabled_models` with the start selection, then each live switch. + `load_model`, `prefetch_model`, a desired build and a selected build's alias + successor outside it are refused or skipped (`autopilotAllowsModel`, + `operatorFilterAllows`); an empty `enabled_models` filters nothing. Consented + downloads and operations keep their own gates. ## Failure modes diff --git a/docs/operations/model-migration.md b/docs/operations/model-migration.md index f1631ca6b7..9f2f8ee4f0 100644 --- a/docs/operations/model-migration.md +++ b/docs/operations/model-migration.md @@ -1,6 +1,6 @@ # Migrate a public model to a new build -> Last updated: 2026-10-15 +> Last updated: 2026-11-02 Runbook for moving a public model name (an **alias**, e.g. `gemma-4-26b`) from one concrete build to another with no downtime and without consumers ever @@ -74,6 +74,15 @@ coordinator logs `provider now advertises build (models_update)` and against the desired build — capacity never black-holes. There are no weights, ramps, or migration controllers. +**The operator's filter wins.** A provider whose operator set `enabled_models` +(or switched models with `darkbloom switch`) converges only when the desired +build is in that filter. Otherwise it keeps serving the previous build, which +routing still accepts as the alias fallback, and logs `desired_models: → + is outside the enabled model filter; not converging`. Such an operator +moves by adding the new build with `darkbloom switch`. Providers with an empty +`enabled_models` converge as before. Count the providers still advertising the +previous build before you retire it. + ## Steps ### 1. Reuse a valid upload or publish the new build diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 40a06cdb8c..5936607b05 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -2180,7 +2180,7 @@ override `provider.toml` for one process, are in | `[provider] auto_update` | `true` | Startup + periodic self-update | | `[provider] auto_restart` | `true` | Arm the watchdog LaunchAgent | | `[provider] update_jitter_seconds` | `300` | Max random delay before an automatic install or a network provider drains a model for a prepared MTP replacement; serving continues during the delay. `0` disables jitter; capped at `3600`. Standalone MTP upgrades skip this delay. Random staggering provides no fleet availability guarantee (`provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift`, `updateJitterSeconds`; `provider-swift/Sources/ProviderCore/Update/UpdateJitter.swift`, `delay`; `provider-swift/Sources/ProviderCore/ProviderLoop+MTPDrain.swift`, `waitBeforeMTPUpgradeDrain`) | -| `[backend] enabled_models` | `[]` | Advertise only these ids; empty = all serveable | +| `[backend] enabled_models` | `[]` | Advertise only these ids; empty = all serveable. When set, coordinator `load_model`, `prefetch_model` and model rollouts never load or download a model outside it; a live `switch` replaces it at once | | `[backend] model_cache_directory` | unset | Explicit saved hub directory; set or import once with `models location`, clear with `--reset`. Ambient cache variables never override it; hand-written relative paths are anchored to the config file (`provider-swift/Sources/ProviderCore/Config/ModelCacheConfiguration.swift`, `ConfigManager.modelCacheDirectory`) | | `[backend] idle_timeout_mins` | `60` | Unload a model idle this long; `0` disables; paused during active or explicitly paused Autopilot | | `[backend] max_model_slots` | `3` | Resident models | diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index 1b3c147873..839ed7d25a 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -1,6 +1,6 @@ # Provider troubleshooting -> Last updated: 2026-10-27 +> Last updated: 2026-11-02 Symptom → check → fix for the `darkbloom` provider: installer exits, `doctor` check names, service lifecycle, coordinator connection, updates, models and the @@ -167,7 +167,8 @@ are tabulated in [`cli-reference.md`](./cli-reference.md#runtime-constants). | `model fits in RAM` FAIL / `Cold load blocked (memory)` in status | The live no-eviction load budget is below the scanner's complete model estimate plus activation and minimum-KV serving reserve, and request-time idle eviction cannot close the gap. The nominal `Inference memory` hardware figure is not live free RAM. Status and doctor show both the preload gap and the smaller eviction-aware cold-load gap ([load gate](../architecture/hardware-support.md#load-gate-modelloadadmission)). A busy machine with an active request gets a temporary verdict instead | Free at least the **cold-load** shortfall with margin, rerun `darkbloom doctor`, then `darkbloom restart` to retry preload when enabled; or select a smaller model ([hardware requirements](./hardware-requirements.md)). A request cannot cold-load at the same memory level. | | `Preload skipped (no eviction)` in status | The model does not fit alongside the current resident slots. The request-time allowance can fit it by evicting idle models; startup preload deliberately avoids that churn | Keep the current serving set, or free memory if both models should stay resident. | | A load refusal says `Not evictable: (… GB: …)`, or status says `Not evictable for a load now: …` | That resident model cannot be evicted for the load: an Autopilot placement hold (until the UTC time shown), requests in flight, a local request, an Autopilot pin, an unload or an MTP upgrade in progress. `adopted by Autopilot outside the selected models` means an Autopilot operation placed it there, not your selection ([placements](../architecture/model-autopilot.md#placements-after-an-operation)) | Wait for the hold to expire or the requests to finish, then retry the load; a hold also ends when an operation unloads the model or Autopilot is disabled. | -| `Serving outside the enabled model filter: ` in status | The running daemon serves a model your saved `enabled_models` omits: an Autopilot operation adopted it, it is in the running daemon's selection (a changed filter applies only at the next start), or a live Autopilot lease published it | For an adoption see `darkbloom autopilot status`; otherwise `darkbloom restart` applies the saved filter. | +| `Serving outside the enabled model filter: ` in status | The running daemon serves a model your saved `enabled_models` omits: an Autopilot operation adopted it, it is in the running daemon's selection (a hand-edited filter applies only at the next start), or a live Autopilot lease published it. Coordinator `load_model`, `prefetch_model` and model rollouts never bring in a model outside the filter; before this release a rollout could (for example `gemma-4-26b-qat-4bit` coming back in place of a selected `gemma-4-26b`, and downloading again after `darkbloom models remove`) | For an adoption see `darkbloom autopilot status`; otherwise `darkbloom restart` applies the saved filter. | +| The log says `desired_models: → is outside the enabled model filter; not converging` | The coordinator moved a public model you serve to a newer build that your filter does not list. The provider keeps serving the build you selected | To take the new build, add it with `darkbloom switch`; to keep your build, nothing. | | Model missing from `darkbloom models list` | Not in `~/.cache/huggingface/hub`, or filtered by `enabled_models` | `darkbloom models download `; `darkbloom models list --all` | | Load fails after a catalog update | New build published for the alias | `darkbloom models remove ` then `darkbloom models download ` | | `Skipping : model_type … has no engine-v2 adapter` | Family not served by CBv2 | Use a supported family; the model is never advertised | diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 0aa1e29379..14863554e4 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1,6 +1,6 @@ # Configuration reference -> Last updated: 2026-10-31 +> Last updated: 2026-11-02 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. @@ -198,7 +198,7 @@ mode or update configuration changes are part of this addition. | Setting | Default / precedence | Consumer | |---|---|---| -| `backend.enabled_models` | `[]` means all eligible local models; a successful `switch` pins its complete nonempty selection | `provider-swift/Sources/ProviderCore/Service/ProviderModelSelection.swift` (`save`) | +| `backend.enabled_models` | `[]` means all eligible local models; a successful `switch` pins its complete nonempty selection. A nonempty list (with the start selection) is the operator filter: coordinator `load_model`, `prefetch_model` and `desired_models` never load or download a model outside it, and a live `switch` replaces it at once | `provider-swift/Sources/ProviderCore/Service/ProviderModelSelection.swift` (`save`); `provider-swift/Sources/ProviderCore/ProviderLoop+ModelSelection.swift` (`operatorFilterAllows`) | | launchd-managed `start --foreground --model` | Explicitly pinned `enabled_models` overrides stale baked arguments, including restart and watchdog recovery | `provider-swift/Sources/darkbloom/Start/StartCommand.swift` (`usesPinnedModelSelection`); `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift` (`runForeground`) | | direct manual `start --foreground --model` | Explicit command-line IDs still override the saved selection | `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift` (`runForeground`) | | later scheduled serving windows | Read full current Autopilot settings/consent plus saved selection. Disabling between windows restores ordinary `enabled_models` even if unchanged; otherwise keep the initial foreground selection until a live switch or saved selection change. Resolve an empty ordinary list to eligible local models, validate/hash before reopening and retain the original window end. With consent, cached Autopilot builds verified at start or by the previous window's provider (downloads and background checks) stay while their bytes hash unchanged. All other inputs remain frozen | `provider-swift/Sources/darkbloom/ScheduledWindowSelection.swift` (`ScheduledWindowSelection`); `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift` (`runScheduled`) | diff --git a/docs/reference/protocol-messages.md b/docs/reference/protocol-messages.md index e647691090..f7b9681aaf 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-30 +> Last updated: 2026-11-02 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 @@ -1449,7 +1449,14 @@ backend and attested capability guards apply. Alias entries describe aliases whose desired, previous, or retired build is in the provider's advertised inventory; an empty set revokes old targets. Revision-aware providers stage the exact artifact and drain before activation; ID-only providers retain the legacy prefetch path. -Both announce completed updates through `models_update`. A `cluster_member` +Both announce completed updates through `models_update`. A provider with an +operator filter (a non-empty `enabled_models`, or the selection of a live +switch) converges only to a desired build inside it: an alias successor outside +the filter is not fetched, not served and does not drop the previous build +(`operatorFilterAllows`, +`provider-swift/Sources/ProviderCore/ProviderLoop+ModelSelection.swift`). The +same filter refuses `load_model` and `prefetch_model` for a model outside it +with `model_not_selected`, before Autopilot's consented paths apply. A `cluster_member` connection is offered no entries and receives only the empty set; a nonempty set is refused for a member connection or a pair-held device. Source: [coordinator/registry/model_commands.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/registry/model_commands.go) (`DesiredModelsForProvider`, `RefreshDesiredModels`). diff --git a/provider-swift/Sources/ProviderCore/Autopilot/ProviderLoop+AutopilotControl.swift b/provider-swift/Sources/ProviderCore/Autopilot/ProviderLoop+AutopilotControl.swift index aebfa0d401..513844eca2 100644 --- a/provider-swift/Sources/ProviderCore/Autopilot/ProviderLoop+AutopilotControl.swift +++ b/provider-swift/Sources/ProviderCore/Autopilot/ProviderLoop+AutopilotControl.swift @@ -52,7 +52,7 @@ extension ProviderLoop { func autopilotAllowsModel(_ id: String) -> Bool { if ordinaryServingModelIDs.contains(id) { return true } if !autopilotSettings.enabled { - return autopilotInventoryModels[id] == nil + return autopilotInventoryModels[id] == nil && operatorFilterAllows(id) } // Inventory is observational until a valid live lease. Never let // waiting, shadow, paused, expired or disconnected control widen it. diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ModelSelection.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ModelSelection.swift index b9167e6be5..7e24744d43 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ModelSelection.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ModelSelection.swift @@ -15,6 +15,7 @@ extension ProviderLoop { }.sorted { $0.id < $1.id }, fingerprints: modelHashFingerprints) let previouslyPersistedSwitch = hasPersistedModelSwitch + let previousFilter = operatorModelFilter var persistedReplacement: ProviderModelSelection.Replacement? var mutationStarted = false do { @@ -45,7 +46,10 @@ extension ProviderLoop { } guard servingDrain.owner == .modelSwitch, !isShuttingDown, !Task.isCancelled else { throw error } do { - if mutationStarted { try await applyModelSelection(previous) } + if mutationStarted { + try await applyModelSelection(previous) + operatorModelFilter = previousFilter + } await client.stageModelSelection(previous.models) if let persistedReplacement { try ProviderModelSelection.restore(persistedReplacement) @@ -101,6 +105,8 @@ extension ProviderLoop { try checkModelSwitchOwnership() advertisedModels = next ordinaryServingModelIDs = Set(next.keys) + // The switch persists this selection as `enabled_models`. + operatorModelFilter = Set(next.keys) modelHashes = Dictionary(uniqueKeysWithValues: models.compactMap { model in model.weightHash.map { (model.id, $0) } }) @@ -114,6 +120,14 @@ extension ProviderLoop { persistLoadedModelSet() } + /// Coordinator commands (`load_model`, `prefetch_model`, a desired build + /// and an alias successor) never reach a model outside the operator's + /// filter, so a nudge cannot re-select or re-download what the operator + /// deselected or removed. Autopilot's consented paths keep their own gates. + func operatorFilterAllows(_ id: String) -> Bool { + operatorModelFilter?.contains(id) ?? true + } + internal func validateModelSwitchSelfTests(_ models: [ModelInfo]) throws { for model in models { if retiringModels.contains(model.id) { diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Prefetch.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Prefetch.swift index ffc4ff9815..69d9317a63 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+Prefetch.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Prefetch.swift @@ -345,11 +345,12 @@ extension ProviderLoop { return } // A declared successor of a selected build remains that model's - // existing update workflow. Unrelated observation-only inventory never - // inherits permission merely by appearing in desired state. + // existing update workflow, inside the operator's filter only. + // Unrelated observation-only inventory never inherits permission + // merely by appearing in desired state. for entry in entries { if let previous = entry.previousBuild, ordinaryServingModelIDs.contains(previous), - !entry.desiredBuild.isEmpty { + !entry.desiredBuild.isEmpty, operatorFilterAllows(entry.desiredBuild) { ordinaryServingModelIDs.insert(entry.desiredBuild) if autopilotConsented && !autopilotSetAllows(entry.desiredBuild) { autopilotSuccessorNeedsInventoryRefresh = true @@ -378,7 +379,12 @@ extension ProviderLoop { for entry in entries { let desired = entry.desiredBuild - guard !desired.isEmpty, autopilotAllowsModel(desired) else { continue } + guard !desired.isEmpty, autopilotAllowsModel(desired) else { + if !desired.isEmpty, !operatorFilterAllows(desired) { + logger.info("desired_models: \(entry.modelName) → \(desired) is outside the enabled model filter; not converging") + } + continue + } guard ModelRuntimeRequirements.isEligible( modelID: desired, available: loopConfig.runtimeCapabilities) else { diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index 3d8265a633..096dcfcc20 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -218,6 +218,10 @@ public actor ProviderLoop { internal var appAttestStallRetryAt: ContinuousClock.Instant? internal let loopConfig: ProviderLoopConfig internal var ordinaryServingModelIDs: Set + /// The operator's explicit selection: `enabled_models` with the start + /// selection, then each live switch. Nil when `enabled_models` is empty, + /// which serves any model the coordinator pushes (`operatorFilterAllows`). + internal var operatorModelFilter: Set? internal var autopilotSuccessorNeedsInventoryRefresh = false internal var autopilotInventoryModels: [String: ModelInfo] internal let keyPair: NodeKeyPair @@ -939,6 +943,9 @@ public actor ProviderLoop { sink: logSinkForTesting) self.loopConfig = config self.ordinaryServingModelIDs = Set(config.models.map(\.id)) + let enabledModels = config.config.backend.enabledModels + self.operatorModelFilter = enabledModels.isEmpty + ? nil : Set(enabledModels).union(config.models.map(\.id)) self.autopilotInventoryModels = Dictionary(config.autopilotInventory.filter { $0.weightHash?.isEmpty == false && EngineV2SupportedModels.isSupported(model: $0) && ModelRuntimeRequirements.isEligible(modelID: $0.id, available: config.runtimeCapabilities) diff --git a/provider-swift/Tests/ProviderCoreTests/Autopilot/AutopilotInventoryTests.swift b/provider-swift/Tests/ProviderCoreTests/Autopilot/AutopilotInventoryTests.swift index 8851e6c5ec..9acefaf3e6 100644 --- a/provider-swift/Tests/ProviderCoreTests/Autopilot/AutopilotInventoryTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Autopilot/AutopilotInventoryTests.swift @@ -15,12 +15,12 @@ struct AutopilotInventoryTests { .init(sessionId: "session", revision: "inventory", enabled: true, expiresAtMs: expiry ?? Int64(Date().timeIntervalSince1970 * 1000) + 120_000, observeOnly: shadow) } - private func loop() throws -> ProviderLoop { + private func loop(enabledModels: [String]? = nil) throws -> ProviderLoop { let settings = ModelAutopilotSettings(enabled: true, consentRecorded: true, selectedModels: [selected.id, cached.id], revision: "inventory") return try ProviderLoop(config: .init(coordinatorURL: "ws://127.0.0.1:0/unused", hardware: hardware, models: [selected], config: .init(provider: .init(name: "inventory-test"), - backend: .init(enabledModels: [selected.id], modelAutopilot: settings)), + backend: .init(enabledModels: enabledModels ?? [selected.id], modelAutopilot: settings)), autopilotInventory: [selected, cached]), attestationSigner: nil) } @@ -52,10 +52,11 @@ struct AutopilotInventoryTests { } @Test func selectedModelSuccessorDoesNotRequireAutopilotInventoryConsent() async throws { - let loop = try loop() - await loop.handleAutopilotControl(control(shadow: true)) let successor = "selected-model-next-build" let unrelated = "unrelated-next-build" + // The successor is converged to only inside the operator's filter. + let loop = try loop(enabledModels: [selected.id, successor]) + await loop.handleAutopilotControl(control(shadow: true)) #expect(await loop.autopilotSettings.selectedModels.contains(successor) == false) await loop.reconcileDesiredModels([ .init(modelName: "selected-alias", desiredBuild: successor, previousBuild: selected.id), diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/OperatorModelFilterTests.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/OperatorModelFilterTests.swift new file mode 100644 index 0000000000..d5c192c28c --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/OperatorModelFilterTests.swift @@ -0,0 +1,135 @@ +import Foundation +import Testing +@testable import ProviderCore + +/// The operator selected the 8-bit `gemma-4-26b` and deselected +/// `gemma-4-26b-qat-4bit`. The takeover alias `gemma-4-26b` names the QAT build +/// as desired and the 8-bit build as previous, so the coordinator offers the +/// QAT build to every provider that advertises the 8-bit one. +@Suite("Operator enabled-model filter", .serialized) +struct OperatorModelFilterTests { + private static let selected = "gemma-4-26b" + private static let deselected = "gemma-4-26b-qat-4bit" + private static let other = "gpt-oss-20b" + private static let takeover = CoordinatorMessage.DesiredModelEntry( + modelName: selected, desiredBuild: deselected, previousBuild: selected) + + private static let hardware = HardwareInfo( + machineModel: "Mac16,5", chipName: "Apple M4 Max", chipFamily: .m4, chipTier: .max, + memoryGb: 128, memoryAvailableGb: 124, cpuCores: CpuCores(total: 16, performance: 12, efficiency: 4), + gpuCores: 40, memoryBandwidthGbs: 546) + + private static func model(_ id: String) -> ModelInfo { + ModelInfo(id: id, modelType: "gpt_oss", sizeBytes: 1024, estimatedMemoryGb: 1, + weightHash: String(repeating: id == selected ? "a" : "b", count: 64)) + } + + private func loop(enabledModels: [String]) throws -> ProviderLoop { + let models = [Self.model(Self.selected), Self.model(Self.other)] + return try ProviderLoop(config: ProviderLoopConfig( + coordinatorURL: "ws://127.0.0.1:0/unused", hardware: Self.hardware, models: models, + config: ProviderConfig(provider: ProviderSettings(name: "model-filter-test", memoryReserveGB: 1), + backend: BackendSettings(enabledModels: enabledModels, idleTimeoutMins: 0)), + modelHashes: Dictionary(uniqueKeysWithValues: models.map { ($0.id, $0.weightHash ?? "") })), + attestationSigner: nil) + } + + private func installRecordingPrefetch(_ loop: ProviderLoop) async -> (FilterRecordingPrefetcher, ModelPrefetchCoordinator) { + let prefetcher = FilterRecordingPrefetcher() + let coordinator = ModelPrefetchCoordinator(prefetcher: prefetcher, preCheck: { _ in .needsFetch }, + onVerified: { _ in }) + let client = CoordinatorClient(config: CoordinatorClientConfig(url: "ws://127.0.0.1:0/unused", + hardware: Self.hardware, models: [], backendName: "mlx-swift"), + stats: AtomicProviderStats(), state: ProviderState()) + await loop.installPrefetchCoordinatorForTesting(coordinator, client: client) + return (prefetcher, coordinator) + } + + /// A refused command never starts work, so give a wrongly accepted one + /// time to reach the prefetcher before asserting nothing did. + private func settle() async throws { try await Task.sleep(for: .milliseconds(200)) } + + @Test func aTakeoverSuccessorOutsideTheFilterIsNeitherSelectedNorDownloaded() async throws { + let loop = try loop(enabledModels: [Self.selected, Self.other]) + let (prefetcher, coordinator) = await installRecordingPrefetch(loop) + await loop.reconcileDesiredModels([Self.takeover], send: SendHandle { _ in }) + try await settle() + #expect(prefetcher.startedIDs.isEmpty) + #expect(await !loop.ordinaryServingModelIDs.contains(Self.deselected)) + #expect(await !loop.autopilotAllowsModel(Self.deselected)) + #expect(await loop.desiredPrefetchTargets.isEmpty) + #expect(await loop.desiredSwapDrop.isEmpty) + #expect(await loop.isModelAdvertised(Self.selected)) + await coordinator.shutdown(timeout: .seconds(3)) + } + + @Test func loadAndPrefetchCommandsOutsideTheFilterAreRefused() async throws { + let loop = try loop(enabledModels: [Self.selected, Self.other]) + let (prefetcher, coordinator) = await installRecordingPrefetch(loop) + let replies = FilterReplyRecorder() + await loop.handlePrefetchModelRequest(modelId: Self.deselected, priority: 1, send: SendHandle(replies.append)) + await loop.handleLoadModelRequest(modelId: Self.deselected, send: SendHandle(replies.append)) + try await settle() + #expect(replies.prefetchErrors == ["model_not_selected"]) + #expect(replies.loadErrors == ["model_not_selected"]) + #expect(prefetcher.startedIDs.isEmpty) + #expect(await loop.preloadTasks.isEmpty) + await coordinator.shutdown(timeout: .seconds(3)) + } + + @Test func aLiveSwitchMakesTheSwitchedSelectionTheFilter() async throws { + let loop = try loop(enabledModels: []) + let (prefetcher, coordinator) = await installRecordingPrefetch(loop) + await loop.beginServingDrain(owner: .modelSwitch) + try await loop.applyModelSelection(.init(models: [Self.model(Self.selected)], fingerprints: [:])) + await loop.reconcileDesiredModels([Self.takeover], send: SendHandle { _ in }) + try await settle() + #expect(prefetcher.startedIDs.isEmpty) + #expect(await !loop.ordinaryServingModelIDs.contains(Self.deselected)) + #expect(await loop.isModelAdvertised(Self.selected)) + await coordinator.shutdown(timeout: .seconds(3)) + } + + /// Unchanged: with no filter, or with the successor in it, the alias + /// successor stays the selected build's update. + @Test(arguments: [[String](), ["gemma-4-26b", "gpt-oss-20b", "gemma-4-26b-qat-4bit"]]) + func aSuccessorTheFilterAllowsStillConverges(enabledModels: [String]) async throws { + let loop = try loop(enabledModels: enabledModels) + let (prefetcher, coordinator) = await installRecordingPrefetch(loop) + await loop.reconcileDesiredModels([Self.takeover], send: SendHandle { _ in }) + var started = false + for _ in 0..<300 where !started { + started = prefetcher.startedIDs == [Self.deselected] + if !started { try await Task.sleep(for: .milliseconds(10)) } + } + #expect(started) + #expect(await loop.desiredSwapDrop[Self.deselected] == Self.selected) + await coordinator.shutdown(timeout: .seconds(3)) + } +} + +/// Records each build whose download started, then blocks until cancelled. +private final class FilterRecordingPrefetcher: ModelPrefetcher, @unchecked Sendable { + private let lock = NSLock() + private var started: [String] = [] + var startedIDs: [String] { lock.withLock { started } } + func prefetchToDisk(modelID: String, onByteProgress: @Sendable @escaping (Int64, Int64) -> Void) async throws { + lock.withLock { started.append(modelID) } + while true { + try Task.checkCancellation() + try await Task.sleep(for: .milliseconds(10)) + } + } +} + +private final class FilterReplyRecorder: @unchecked Sendable { + private let lock = NSLock() + private var messages: [OutboundMessage] = [] + func append(_ message: OutboundMessage) { lock.withLock { messages.append(message) } } + var prefetchErrors: [String?] { + lock.withLock { messages.compactMap { if case .prefetchModelStatus(_, _, _, _, let error) = $0 { return .some(error) }; return nil } } + } + var loadErrors: [String?] { + lock.withLock { messages.compactMap { if case .loadModelStatus(_, _, let error) = $0 { return .some(error) }; return nil } } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderModelSwitchTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderModelSwitchTests.swift index 1d16c49210..bfad2fb0ef 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderModelSwitchTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderModelSwitchTests.swift @@ -534,11 +534,14 @@ struct ProviderModelSwitchTests { let commitMessages = try #require(try await mock.waitForSnapshot { $0.modelsReplacements.count == 2 }) let commit = try #require(commitMessages.modelsReplacements.last) #expect(await loop.deferredDesiredModels == nil) - let current = CoordinatorMessage.DesiredModelEntry(modelName: "retained-alias", + // An alias successor outside the switched selection, which the + // operator's filter refuses, and a desired build the selection holds. + let successor = CoordinatorMessage.DesiredModelEntry(modelName: "retained-alias", desiredBuild: "org/current-\(UUID().uuidString)", previousBuild: "old-model") + let current = [successor, .init(modelName: "new-model", desiredBuild: "new-model")] if delivery != "after-ack" { - try await mock.pushDesiredModels([current]) - #expect(try await switchEventually { await loop.deferredDesiredModels == [current] }) + try await mock.pushDesiredModels(current) + #expect(try await switchEventually { await loop.deferredDesiredModels == current }) } if delivery == "disconnected" { await mock.dropActiveWebSocket() @@ -553,16 +556,15 @@ struct ProviderModelSwitchTests { #expect(await committing.value) if delivery == "after-ack" { // The forced snapshot follows the successful ack on the same socket. - try await mock.pushDesiredModels([current]) - #expect(try await switchEventually { await loop.deferredDesiredModels == [current] }) + try await mock.pushDesiredModels(current) + #expect(try await switchEventually { await loop.deferredDesiredModels == current }) } await loop.resumeAfterModelSwitch() - let prefetched = try #require(try await mock.waitForSnapshot { - $0.prefetchModelStatuses.contains { $0.modelId == current.desiredBuild && $0.status == .started } + #expect(try await switchEventually { await loop.desiredPrefetchTargets == ["new-model"] }) + #expect(!mock.snapshot().prefetchModelStatuses.contains { + $0.modelId == obsolete.desiredBuild || $0.modelId == successor.desiredBuild }) - #expect(!prefetched.prefetchModelStatuses.contains { $0.modelId == obsolete.desiredBuild }) - #expect(await loop.desiredSwapDrop[current.desiredBuild] == "old-model") - #expect(await loop.desiredPrefetchTargets == [current.desiredBuild]) + #expect(await loop.desiredSwapDrop.isEmpty) #expect(await loop.deferredDesiredModels == nil) #expect(await !loop.state.refusingNewWork) #expect(await loop.isModelAdvertised("old-model")) From 3ebf7ff1db83d637347be0f0ebeee43c5ba37dd3 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 2 Nov 2026 14:50:53 -0800 Subject: [PATCH 0180/1441] fix(provider): `update --rollback` re-checks the provider under the lease, with an end-to-end test The plan and the prompt run without the update lease. A provider started in that window was swapped under while still running the replaced release, and a provider stopped in that window was restarted by the rollback. Under the lease the command now reads the provider again: one started since is refused with nothing changed, and one stopped since is swapped without a restart, as `darkbloom update` already does for an installed update. Also: a failed rollback no longer prints a doubled period; the `--override-quarantine` warning and the `update` abstract cover rollbacks. `UpdateRollbackEndToEndTests` rolls back two ad-hoc-signed bundles of the built `darkbloom` product in a temporary root with the launchd/drain host faked, then runs the restored CLI itself (`--version`, `update --check-only` against a loopback release endpoint, with its home redirected to the scratch directory). Co-Authored-By: Claude Opus 5.5 --- changelog.d/provider-update-rollback.md | 2 +- docs/provider/cli-reference.md | 5 +- docs/provider/installation.md | 2 +- .../Sources/darkbloom/UpdateCommand.swift | 6 +- .../Sources/darkbloom/UpdateRollback.swift | 19 +- .../UpdateRollbackCommandTests.swift | 33 ++- .../UpdateRollbackEndToEndTests.swift | 271 ++++++++++++++++++ 7 files changed, 324 insertions(+), 14 deletions(-) create mode 100644 provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift diff --git a/changelog.d/provider-update-rollback.md b/changelog.d/provider-update-rollback.md index d4872886af..ffa75cc843 100644 --- a/changelog.d/provider-update-rollback.md +++ b/changelog.d/provider-update-rollback.md @@ -3,5 +3,5 @@ - `darkbloom update --rollback` restores the release a Mac ran before its last update. When the updater installs a release, it keeps the signed release it replaces; the rollback puts that release back, also after the new one has served for 10 minutes and was promoted. - It shows the installed and restored versions and asks `Roll back to vX? [y/N]` before changing anything (`--yes` skips the question). The running provider finishes its accepted requests (`--timeout`, `--force` as for `darkbloom update`), the kept release replaces the installed one in the watchdog's journaled swap under the update lease, and the provider restarts on it. It contacts no coordinator. - The rolled-back release is quarantined on that Mac: the provider's 30-minute update check, the startup check and the watchdog do not reinstall it, and the next newer release installs normally, so automatic updates can stay on. `darkbloom update --override-quarantine` installs it again on request. -- It refuses and changes nothing on a Mac that serves in a `darkbloom cluster` pair, while another update or recovery runs, when no earlier release is kept or the kept one is already installed, when the installed bundle is not the release the updater recorded, and when the kept release fails its hash or signature check. +- It refuses and changes nothing on a Mac that serves in a `darkbloom cluster` pair, while a provider runs in the foreground (`darkbloom start --foreground`), while another update or recovery runs, when no earlier release is kept or the kept one is already installed, when the installed bundle is not the release the updater recorded, and when the kept release fails its hash or signature check. - Only one earlier release is kept. A Mac rolls back to the release it ran before its last update, not further. diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 9469697fc8..8da05355f4 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -755,13 +755,14 @@ version, restored version, the install generation it records) and asks `Roll back to vX? [y/N]`. A loaded provider is drained, the layout is swapped through the watchdog's journaled rollback under the update lease, and the provider is restarted and the watchdog rearmed, as for an installed update; a -stopped provider is only swapped +stopped provider, or one stopped while the prompt was open, is only swapped (`provider-swift/Sources/darkbloom/UpdateRollback.swift`, `UpdateRollback`; `provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift`, `rollbackPlan`, `rollBackToPredecessor`). It exits 1 and changes nothing when this Mac serves in a `darkbloom cluster` pair (a running cluster service or a loaded cluster-member provider job), a provider runs outside launchd -(`darkbloom start --foreground`), another update or recovery holds the lease, +(`darkbloom start --foreground`) or started after the plan was shown, another +update or recovery holds the lease, no release is kept for rollback, the installed release is already that release, the installed `Darkbloom.app` is not the recorded release, or the kept release fails its hash or signature check (`RollbackRefusal`). Steps are in diff --git a/docs/provider/installation.md b/docs/provider/installation.md index 3c1182e3ff..78d976e8b5 100644 --- a/docs/provider/installation.md +++ b/docs/provider/installation.md @@ -248,7 +248,7 @@ Verify: ```bash darkbloom --version # the restored version -darkbloom update --check-only # "Latest release vX is quarantined on this machine." +darkbloom update --check-only # while vX is the latest: "Latest release vX is quarantined on this machine." ``` Refusals and flags are listed in the diff --git a/provider-swift/Sources/darkbloom/UpdateCommand.swift b/provider-swift/Sources/darkbloom/UpdateCommand.swift index ded28a024c..c2f359746c 100644 --- a/provider-swift/Sources/darkbloom/UpdateCommand.swift +++ b/provider-swift/Sources/darkbloom/UpdateCommand.swift @@ -23,7 +23,7 @@ func loadUpdateConfig(configPath: String?) throws -> ProviderConfig { struct Update: AsyncParsableCommand { static let configuration = CommandConfiguration( commandName: "update", - abstract: "Check for updates and self-update the provider binary." + abstract: "Check for updates and self-update the provider binary, or roll back to the previous release." ) @OptionGroup var configOptions: ConfigOptions @@ -114,8 +114,8 @@ struct Update: AsyncParsableCommand { } if overrideQuarantine { - printError("WARNING: overriding local failed-version quarantine by explicit request.") - printError("The failed release may crash this provider again.") + printError("WARNING: overriding the local release quarantine by explicit request.") + printError("The quarantined release failed its starts or was rolled back; it may fail or regress again.") } print("Checking for updates...") let result = await updater.update(manualOverride: overrideQuarantine) diff --git a/provider-swift/Sources/darkbloom/UpdateRollback.swift b/provider-swift/Sources/darkbloom/UpdateRollback.swift index f56a3d9c97..24f2c4e220 100644 --- a/provider-swift/Sources/darkbloom/UpdateRollback.swift +++ b/provider-swift/Sources/darkbloom/UpdateRollback.swift @@ -53,6 +53,11 @@ struct UpdateRollback { and restart it. Stop it (Ctrl-C), then run `\(cli) update --rollback` again. Nothing was changed. """ + static let startedRefusal = """ + A provider started after the rollback was planned. Nothing was changed; run \ + `\(cli) update --rollback` again to drain and restart it. + """ + private static var cli: String { BuildEnvironment.current.cliName } func run(skipConfirmation: Bool) async throws { @@ -79,11 +84,16 @@ struct UpdateRollback { return try updater.beginUpdateSession(operation: "operator-rollback", timeout: 0) } defer { session.release() } + // The plan and prompt ran without the lease: a provider started since + // is not swapped under, and one stopped since is not restarted. + let providerNow = host.provider() + guard loaded || providerNow == .stopped else { throw Failure(description: Self.startedRefusal) } + let restarts = loaded && providerNow == .service let outcome = Result { try updater.rollBackToPredecessor(session: session, plan: plan) } // A drained provider restarts whether or not the rollback completed: // the layout is always one complete release (the journal guarantees it). var restartFailure: Error? - if loaded { + if restarts { do { try await host.restart() } catch { restartFailure = error } } session.release() @@ -96,8 +106,9 @@ struct UpdateRollback { case .success(let version): restored = version case .failure(let error): - throw Failure(description: "Rollback did not complete: \(error)." - + (loaded && restartFailure == nil ? " The provider restarted on the installed release." : notRestarted)) + let reason = "\(error)" + throw Failure(description: "Rollback did not complete: \(reason)\(reason.hasSuffix(".") ? "" : ".")" + + (restarts && restartFailure == nil ? " The provider restarted on the installed release." : notRestarted)) } say("Rolled back: v\(plan.from) -> v\(restored).") say("v\(plan.from) is quarantined on this Mac: automatic updates skip it, and the next newer release installs " @@ -105,7 +116,7 @@ struct UpdateRollback { if restartFailure != nil { throw Failure(description: "Rolled back to v\(restored)." + notRestarted) } - if loaded { + if restarts { say("Provider relaunched on v\(restored); waiting for fresh authorization...") try await host.waitForRestart() } else { diff --git a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift index df3175c178..8c95cff765 100644 --- a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift @@ -121,12 +121,32 @@ struct UpdateRollbackCommandTests { #expect(error?.description.contains("Rollback did not complete") == true) #expect(error?.description.contains("restarted on the installed release") == true) + #expect(error?.description.contains("..") == false) #expect(host.events == ["drain", "restart"]) #expect(try install.liveBinary() == "2.0.0-darkbloom") #expect(try install.store.loadState().quarantine == nil) // The lease is free again for the watchdog and the restarted provider. try install.updater.beginUpdateSession(operation: "lease-check").release() } + + @Test("a provider started during the prompt is not swapped under, and one stopped during it is not restarted") + func providerChangesDuringThePrompt() async throws { + let install = try RollbackInstall() + defer { install.remove() } + let started = RecordingHost(install: install, loaded: false, answer: "y", providerOnceAnswered: .service) + let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: started, yes: false) } + #expect(error?.description == UpdateRollback.startedRefusal) + #expect(started.events.isEmpty) + #expect(try install.liveBinary() == "2.0.0-darkbloom") + #expect(try install.store.loadState().quarantine == nil) + + let stopped = RecordingHost(install: install, loaded: true, answer: "y", providerOnceAnswered: .stopped) + try await install.rollback(host: stopped, yes: false) + #expect(stopped.events == ["drain"]) + #expect(try install.liveBinary() == "1.0.0-darkbloom") + #expect(try install.store.loadState().quarantine?.version == "2.0.0") + #expect(stopped.said.last == "The provider is not running; `darkbloom start` starts v1.0.0.") + } } /// v1 installed, then v2 installed and promoted by the updater, in a temporary root. @@ -209,6 +229,7 @@ private final class RecordingHost: @unchecked Sendable { let lock = NSLock() var events: [String] = [] var lines: [String] = [] + var provider: UpdateRollback.Provider = .stopped } private let log: Log @@ -216,16 +237,22 @@ private final class RecordingHost: @unchecked Sendable { var events: [String] { log.lock.withLock { log.events } } var said: [String] { log.lock.withLock { log.lines } } + /// `providerOnceAnswered` is the provider's state from the prompt's answer on. init(install: RollbackInstall, loaded: Bool, foreground: Bool = false, inCluster: Bool = false, canAsk: Bool = true, - answer: String? = nil, beforeDrain: @escaping () throws -> Void = {}) { + answer: String? = nil, providerOnceAnswered: UpdateRollback.Provider? = nil, + beforeDrain: @escaping () throws -> Void = {}) { let log = Log() + log.provider = loaded ? .service : foreground ? .foreground : .stopped self.log = log let record = { (event: String) in log.lock.withLock { log.events.append(event) } } host = UpdateRollback.Host( servesInCluster: { inCluster }, - provider: { loaded ? .service : foreground ? .foreground : .stopped }, + provider: { log.lock.withLock { log.provider } }, canAsk: { canAsk }, - readAnswer: { answer }, + readAnswer: { + if let providerOnceAnswered { log.lock.withLock { log.provider = providerOnceAnswered } } + return answer + }, drain: { record("drain") try beforeDrain() diff --git a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift new file mode 100644 index 0000000000..5e56325cd8 --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift @@ -0,0 +1,271 @@ +import Foundation +import Hummingbird +import NIOCore +import Testing +@testable import darkbloom +@testable import ProviderCore + +/// `darkbloom update --rollback --yes` on two bundles of the built `darkbloom` +/// product, ad-hoc signed, in a temporary install root. Only the host (cluster +/// check, launchd, drain, restart) is faked. The restored binary is then run +/// itself: `--version`, and `update --check-only` against a loopback release +/// endpoint, with its home redirected into the scratch directory. No launchd +/// job, provider process or real install is touched. +@Suite("Update rollback end to end", .serialized) +struct UpdateRollbackEndToEndTests { + @Test("the built CLI is rolled back to the old bundle, runs it, and its update check skips the rolled-back release") + func rollbackOfBuiltBundles() async throws { + let products = Bundle(for: EndToEndBundleSentinel.self).bundleURL.deletingLastPathComponent() + let cli = products.appendingPathComponent("darkbloom") + let enclave = products.appendingPathComponent("darkbloom-enclave") + try #require(FileManager.default.isExecutableFile(atPath: cli.path), "built CLI missing: \(cli.path)") + try #require(FileManager.default.isExecutableFile(atPath: enclave.path), "built enclave missing: \(enclave.path)") + let patch = ProviderCore.version.split(separator: ".").compactMap { Int($0) } + try #require(patch.count == 3, "ProviderCore.version is not MAJOR.MINOR.PATCH: \(ProviderCore.version)") + // The restored release reports the built version; the release it replaces and a later one are newer labels. + let old = ProviderCore.version + let new = "\(patch[0]).\(patch[1]).\(patch[2] + 1)" + let newer = "\(patch[0]).\(patch[1]).\(patch[2] + 2)" + + let fm = FileManager.default + let scratch = URL(fileURLWithPath: try #require(realpath(fm.temporaryDirectory.path, nil).map { + defer { free($0) } + return String(cString: $0) + })).appendingPathComponent("update-rollback-e2e-\(UUID().uuidString)", isDirectory: true) + defer { try? fm.removeItem(at: scratch) } + let root = scratch.appendingPathComponent("install", isDirectory: true) + let liveApp = root.appendingPathComponent("Darkbloom.app", isDirectory: true) + + try Self.makeSignedApp(version: old, cli: cli, enclave: enclave, at: liveApp) + let bin = root.appendingPathComponent("bin", isDirectory: true) + try fm.createDirectory(at: bin, withIntermediateDirectories: true) + for name in ["darkbloom", "darkbloom-enclave", "mlx.metallib"] { + try fm.createSymbolicLink( + atPath: bin.appendingPathComponent(name).path, + withDestinationPath: "../Darkbloom.app/Contents/MacOS/\(name)") + } + let oldTree = try UpdateAtomicFilesystem.treeHash(root: liveApp) + + // v`new` is installed over v`old` by the updater, which keeps v`old`, and is promoted. + let release = scratch.appendingPathComponent("release", isDirectory: true) + try Self.makeSignedApp(version: new, cli: cli, enclave: enclave, + at: release.appendingPathComponent("Darkbloom.app", isDirectory: true)) + let flat = release.appendingPathComponent("bin", isDirectory: true) + try fm.createDirectory(at: flat, withIntermediateDirectories: true) + for name in ["darkbloom", "darkbloom-enclave", "mlx.metallib"] { + try Self.run("/bin/cp", ["-c", release.appendingPathComponent("Darkbloom.app/Contents/MacOS/\(name)").path, + flat.appendingPathComponent(name).path]) + } + let tarball = scratch.appendingPathComponent("release.tar.gz") + try Self.run("/usr/bin/tar", ["czf", tarball.path, "-C", release.path, "."]) + let installer = SelfUpdater( + coordinatorBaseURL: "http://127.0.0.1:9", installRoot: root, verifyCodeSignatures: false, currentVersion: old) + let installed = installer.installBundleForTesting( + from: tarball, + release: ReleaseInfo(version: new, platform: "macos-arm64", url: "unused://", bundleHash: "unused"), + installDir: root) + guard case .success = installed else { + Issue.record("v\(new) did not install: \(installed)") + return + } + let store = UpdateRecoveryStore(installRoot: root, verifyCodeSignatures: false) + var promoted = try store.loadState() + promoted.promoteCandidate() + try store.writeState(promoted) + let newTree = try UpdateAtomicFilesystem.treeHash(root: liveApp) + #expect(newTree != oldTree) + #expect(try Self.bundleVersion(liveApp) == new) + + // `darkbloom update --rollback --yes`, with no terminal to ask on. + let command = try #require(try Darkbloom.parseAsRoot(["update", "--rollback", "--yes"]) as? Update) + let updater = SelfUpdater( + coordinatorBaseURL: "http://127.0.0.1:9", installRoot: root, verifyCodeSignatures: false, currentVersion: new) + let log = EndToEndLog() + let host = UpdateRollback.Host( + servesInCluster: { false }, + provider: { .service }, + canAsk: { false }, + readAnswer: { nil }, + drain: { + log.record("drain") + return try updater.beginUpdateSession(operation: "provider-lifecycle", timeout: 0) + }, + restart: { log.record("restart") }, + waitForRestart: { log.record("wait") }) + try await UpdateRollback(updater: updater, host: host, say: { log.say($0) }).run(skipConfirmation: command.yes) + + #expect(log.events == ["drain", "restart", "wait"]) + #expect(log.lines.contains("Rolled back: v\(new) -> v\(old).")) + // The live bundle is the old one, byte for byte, and its signature still verifies. + #expect(try UpdateAtomicFilesystem.treeHash(root: liveApp) == oldTree) + #expect(try Self.bundleVersion(liveApp) == old) + try Self.run("/usr/bin/codesign", ["--verify", "--deep", "--strict", liveApp.path]) + let state = try store.loadState() + #expect(state.current?.version == old) + #expect(state.candidate == nil) + #expect(state.predecessor?.release.version == old) + #expect(state.quarantine?.version == new) + #expect(state.quarantine?.reason.contains("update --rollback") == true) + #expect(state.installGeneration == promoted.installGeneration + 1) + let leftovers = try fm.contentsOfDirectory(atPath: root.path).filter { $0.hasPrefix(".") } + #expect(leftovers.isEmpty, "\(leftovers)") + #expect(!fm.fileExists(atPath: root.appendingPathComponent("recovery/transaction.json").path)) + + // The restored CLI runs, from the operator's bin/ link. + let home = scratch.appendingPathComponent("home", isDirectory: true) + try fm.createDirectory(at: home, withIntermediateDirectories: true) + let environment = [ + "HOME": home.path, "CFFIXED_USER_HOME": home.path, "PATH": "/usr/bin:/bin", + "DARKBLOOM_NO_UPDATE_CHECK": "1", "NO_COLOR": "1", + ] + let restored = bin.appendingPathComponent("darkbloom").path + #expect(try Self.run(restored, ["--version"], environment: environment).trimmingCharacters(in: .whitespacesAndNewlines) == old) + + // Its update check reads this root's recovery state and skips the rolled-back release. + let config = scratch.appendingPathComponent("provider.toml") + try ConfigManager.save(ProviderConfig( + provider: ProviderSettings(name: "update-rollback-e2e", memoryReserveGB: 1), + backend: BackendSettings(modelCacheDirectory: scratch.appendingPathComponent("hub").path), + coordinator: CoordinatorSettings(url: "http://127.0.0.1:9", heartbeatIntervalSecs: 5)), to: config) + let latest = LatestRelease(version: new) + try await LatestRelease.serve(latest) { endpoint in + let check = ["update", "--check-only", "--config", config.path, "--coordinator", endpoint.absoluteString] + let blocked = try Self.run(restored, check, environment: environment) + #expect(blocked.contains("Current version: \(old)")) + #expect(blocked.contains("Latest release v\(new) is quarantined on this machine.")) + #expect(blocked.contains("Reason: rolled back by the operator to v\(old)")) + #expect(!blocked.contains("Update available")) + + let overridden = try Self.run(restored, check + ["--override-quarantine"], environment: environment) + #expect(overridden.contains("Update available: v\(old) -> v\(new)")) + + latest.version = newer + let next = try Self.run(restored, check, environment: environment) + #expect(next.contains("Update available: v\(old) -> v\(newer)")) + } + #expect(latest.requests == 3) + // The child resolved its install root from its own bundle, never from its home. + #expect(try fm.contentsOfDirectory(atPath: home.path).filter { $0.hasPrefix(".darkbloom") }.isEmpty) + } + + /// A signed `Darkbloom.app` of the built CLI whose bundle version is `version`. + private static func makeSignedApp(version: String, cli: URL, enclave: URL, at app: URL) throws { + let macOS = app.appendingPathComponent("Contents/MacOS", isDirectory: true) + try FileManager.default.createDirectory(at: macOS, withIntermediateDirectories: true) + try run("/bin/cp", ["-c", cli.path, macOS.appendingPathComponent("darkbloom").path]) + try run("/bin/cp", ["-c", enclave.path, macOS.appendingPathComponent("darkbloom-enclave").path]) + // Hashed and swapped like the real library; nothing here loads it. + try Data("mlx.metallib of the update rollback end-to-end test".utf8) + .write(to: macOS.appendingPathComponent("mlx.metallib")) + let info: [String: Any] = [ + "CFBundleIdentifier": "io.darkbloom.provider", + "CFBundleExecutable": "darkbloom", + "CFBundlePackageType": "APPL", + "CFBundleShortVersionString": version, + "CFBundleVersion": version, + ] + try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0) + .write(to: app.appendingPathComponent("Contents/Info.plist")) + for name in ["mlx.metallib", "darkbloom-enclave", "darkbloom"] { + try run("/usr/bin/codesign", ["--force", "--sign", "-", macOS.appendingPathComponent(name).path]) + } + try run("/usr/bin/codesign", ["--force", "--sign", "-", app.path]) + try run("/usr/bin/codesign", ["--verify", "--deep", "--strict", app.path]) + } + + private static func bundleVersion(_ app: URL) throws -> String? { + let data = try Data(contentsOf: app.appendingPathComponent("Contents/Info.plist")) + let plist = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] + return plist?["CFBundleShortVersionString"] as? String + } + + /// Runs a child to completion and returns its standard output; a nonzero exit is an error. + @discardableResult + private static func run(_ path: String, _ arguments: [String], environment: [String: String]? = nil) throws -> String { + let process = Process() + process.executableURL = URL(fileURLWithPath: path) + process.arguments = arguments + if let environment { process.environment = environment } + let output = Pipe() + let errors = Pipe() + process.standardOutput = output + process.standardError = errors + try process.run() + let stdout = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + let stderr = String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw ChildFailure(command: ([path] + arguments).joined(separator: " "), + status: process.terminationStatus, output: stdout + stderr) + } + return stdout + } + + private struct ChildFailure: Error, CustomStringConvertible { + let command: String + let status: Int32 + let output: String + var description: String { "\(command) exited \(status): \(output)" } + } +} + +private final class EndToEndBundleSentinel {} + +private final class EndToEndLog: @unchecked Sendable { + private let lock = NSLock() + private var recordedEvents: [String] = [] + private var recordedLines: [String] = [] + var events: [String] { lock.withLock { recordedEvents } } + var lines: [String] { lock.withLock { recordedLines } } + func record(_ event: String) { lock.withLock { recordedEvents.append(event) } } + func say(_ line: String) { lock.withLock { recordedLines.append(line) } } +} + +/// `GET /v1/releases/latest` on an ephemeral loopback port. +private final class LatestRelease: @unchecked Sendable { + private let lock = NSLock() + private var current: String + private var served = 0 + + init(version: String) { current = version } + + var version: String { + get { lock.withLock { current } } + set { lock.withLock { current = newValue } } + } + + var requests: Int { lock.withLock { served } } + + private func body() -> Data { + let version = lock.withLock { () -> String in + served += 1 + return current + } + let object: [String: Any] = [ + "version": version, "platform": "macos-arm64", + "url": "http://127.0.0.1:9/darkbloom-\(version).tar.gz", "bundle_hash": "bundle-\(version)", + ] + return (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])) ?? Data() + } + + static func serve(_ release: LatestRelease, _ body: (URL) async throws -> Void) async throws { + let router = Router() + router.get("/v1/releases/latest") { _, _ -> Response in + Response(status: .ok, body: .init(byteBuffer: ByteBuffer(bytes: Array(release.body())))) + } + let (ports, port) = AsyncStream.makeStream(of: Int.self) + let app = Application( + router: router, + configuration: .init(address: .hostname("127.0.0.1", port: 0)), + onServerRunning: { channel in + port.yield(channel.localAddress?.port ?? 0) + port.finish() + }) + let server = Task { try await app.runService(gracefulShutdownSignals: []) } + defer { server.cancel() } + var iterator = ports.makeAsyncIterator() + let bound = try #require(await iterator.next()) + try #require(bound >= 49152, "not an ephemeral port: \(bound)") + try await body(URL(string: "http://127.0.0.1:\(bound)")!) + } +} From 9759c1ce8db4c6ae8e3c9f0a68319010b000e166 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 2 Nov 2026 14:55:30 -0800 Subject: [PATCH 0181/1441] cluster: a pair's quarantine line no longer says "after failed starts" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A quarantine can also come from `darkbloom update --rollback` (the provider rollback PR), so the pair update cycle reports "v… is quarantined on this Mac". The line was checked in a trial merge of both PRs, where this PR's update suites pass with it. Co-Authored-By: Claude Opus 5.5 --- .../Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift b/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift index 267b29212a..88da167303 100644 --- a/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift +++ b/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift @@ -346,7 +346,7 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { publish(.idle, detail: "up to date") environment.log("cluster update: up to date" + (current.map { " (v\($0))" } ?? "")) case .quarantined(let version): - publish(.failed, detail: "v\(version) is quarantined on this Mac after failed starts") + publish(.failed, detail: "v\(version) is quarantined on this Mac") case .checkFailed(let failure): publish(.failed, detail: failure) environment.log("cluster update: the check failed (\(failure))" + retry) From 81ae40b001715508fedeaccde6938957a146b67e Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 2 Nov 2026 14:55:42 -0800 Subject: [PATCH 0182/1441] test(provider): replay the reported gemma rollout end to end through the serve loop Runs ProviderLoop.run() against the loopback mock coordinator with the reporter's enabled_models (gemma-4-26b, nvidia-nemotron-3.5-lightning, gpt-oss-20b) and sends what production sends: the gemma-4-26b alias entry (desired gemma-4-26b-qat-4bit, previous gemma-4-26b, with revision fields), then prefetch_model and load_model for the QAT build. The same replay runs again after a register reconnect and after a live switch to the same selection. On the parent commit all three rounds fail (18 issues): load_model is accepted (started), prefetch_model starts a download, and the QAT build becomes ordinary, a desired target, a staged revision and a hard-swap. With the fix every round refuses both commands with model_not_selected, stages nothing and keeps gemma-4-26b advertised. MockCoordinator gains pushPrefetchModel. Co-Authored-By: Claude Opus 5.5 --- .../Helpers/MockCoordinator.swift | 4 + .../OperatorModelFilterTests.swift | 73 +++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/provider-swift/Tests/ProviderCoreTests/Helpers/MockCoordinator.swift b/provider-swift/Tests/ProviderCoreTests/Helpers/MockCoordinator.swift index 559cdbaa0e..3d97b29ddf 100644 --- a/provider-swift/Tests/ProviderCoreTests/Helpers/MockCoordinator.swift +++ b/provider-swift/Tests/ProviderCoreTests/Helpers/MockCoordinator.swift @@ -457,6 +457,10 @@ public final class MockCoordinator: @unchecked Sendable { try await sendCoordinatorMessage(msg) } + public func pushPrefetchModel(modelId: String, priority: Int = 0) async throws { + try await sendCoordinatorMessage(.prefetchModel(.init(modelId: modelId, priority: priority))) + } + /// Echo a member acceptance exactly as the coordinator sends it; the /// client's negotiation refuses any nonce that is not its own. public func pushClusterMemberAcceptance(nonce: String, providerID: String = "mock-provider") async throws { diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/OperatorModelFilterTests.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/OperatorModelFilterTests.swift index d5c192c28c..1391626cc3 100644 --- a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/OperatorModelFilterTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/OperatorModelFilterTests.swift @@ -106,6 +106,79 @@ struct OperatorModelFilterTests { #expect(await loop.desiredSwapDrop[Self.deselected] == Self.selected) await coordinator.shutdown(timeout: .seconds(3)) } + + /// The reported machine, end to end through `ProviderLoop.run()` and the + /// mock coordinator: the production alias entry (the retired + /// `gemma-4-26b-8bit` only decides who receives it, so it is not on the + /// wire), then the warm pool's `prefetch_model` and `load_model`. The + /// coordinator re-sends the entry after every `register` and every switch. + @Test func theReportedRolloutNeverReachesTheProviderAfterReconnectOrSwitch() async throws { + let enabled = [Self.selected, "nvidia-nemotron-3.5-lightning", Self.other] + let fixture = try await ServeLoopFixture.make(models: enabled.map(Self.model), + backend: BackendSettings(enabledModels: enabled, idleTimeoutMins: 0, startupPreload: false)) + let task = fixture.start() + _ = try await fixture.awaitRegistration() + try await replayRollout(fixture, round: 1) + + await fixture.mock.dropActiveWebSocket() + let reconnected = try #require(try await fixture.mock.waitForSnapshot(timeout: .seconds(20)) { + $0.registers.count == 2 + }) + #expect(reconnected.registers.allSatisfy { Set($0.models.map(\.id)) == Set(enabled) }) + try await replayRollout(fixture, round: 2) + + await fixture.loop.resolveSwitchSnapshots(to: try Self.switchSnapshot(in: fixture.directory)) + let switched = await fixture.loop.switchModels(request: .init( + target: try #require(ProcessIdentity.current()), models: enabled, timeoutSeconds: 10)) + #expect(switched.outcome == .switched, "\(switched.message ?? "")") + #expect(Set(fixture.mock.snapshot().modelsReplacements.last?.models.map(\.id) ?? []) == Set(enabled)) + try await replayRollout(fixture, round: 3) + + #expect(await fixture.stop(task)) + } + + private func replayRollout(_ fixture: ServeLoopFixture, round: Int) async throws { + let rollout = CoordinatorMessage.DesiredModelEntry(modelName: Self.selected, desiredBuild: Self.deselected, + previousBuild: Self.selected, revision: "qat", aggregateSHA256: String(repeating: "c", count: 64)) + try await fixture.mock.pushDesiredModels([rollout]) + try await fixture.mock.pushPrefetchModel(modelId: Self.deselected, priority: 1) + try await fixture.mock.pushLoadModel(modelId: Self.deselected) + _ = try #require(try await fixture.mock.waitForSnapshot(timeout: .seconds(10)) { captured in + captured.loadModelStatuses.filter { $0.modelId == Self.deselected && $0.status != .started }.count >= round + && captured.prefetchModelStatuses.contains { $0.modelId == Self.deselected } + }, "round \(round): no load_model reply") + try await settle() + let captured = fixture.mock.snapshot() + let loads = captured.loadModelStatuses.filter { $0.modelId == Self.deselected } + let prefetches = captured.prefetchModelStatuses.filter { $0.modelId == Self.deselected } + #expect(loads.count == round && loads.allSatisfy { $0.status == .failed && $0.error == "model_not_selected" }, + "round \(round): \(loads)") + #expect(prefetches.count == round + && prefetches.allSatisfy { $0.status == .failed && $0.error == "model_not_selected" }, + "round \(round): \(prefetches)") + #expect(!captured.modelsUpdates.contains { $0.models.contains { $0.id == Self.deselected } }) + let loop = fixture.loop + #expect(await loop.isModelAdvertised(Self.selected)) + #expect(await !loop.isModelAdvertised(Self.deselected)) + #expect(await !loop.ordinaryServingModelIDs.contains(Self.deselected)) + #expect(await loop.desiredPrefetchTargets.isEmpty) + #expect(await loop.desiredModelRevisions.isEmpty) + #expect(await loop.desiredSwapDrop.isEmpty) + #expect(await loop.preloadTasks.isEmpty) + #expect(!FileManager.default.fileExists(atPath: ModelDownloader.cacheModelDirectory(for: Self.deselected).path)) + } + + private static func switchSnapshot(in directory: URL) throws -> URL { + let snapshot = directory.appendingPathComponent("switch-snapshot") + try FileManager.default.createDirectory(at: snapshot, withIntermediateDirectories: true) + try Data(#"{"model_type":"gpt_oss"}"#.utf8).write(to: snapshot.appendingPathComponent("config.json")) + try Data(repeating: 0x61, count: 1024).write(to: snapshot.appendingPathComponent("model.safetensors")) + return snapshot + } +} + +private extension ProviderLoop { + func resolveSwitchSnapshots(to snapshot: URL) { modelSwitchSnapshotResolver = { _ in snapshot } } } /// Records each build whose download started, then blocks until cancelled. From 4194ade9943a2a45121c48cc2d8e6eff795a3082 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 2 Nov 2026 14:55:42 -0800 Subject: [PATCH 0183/1441] docs(provider): one home for the operator filter; correct the rollout and 0.10.6 guidance - reference/configuration.md owns the operator filter; cli-reference, protocol-messages and the Autopilot invariant link to it. - protocol-messages: the load_model / prefetch_model refusals move to their own sections and no longer claim to run before Autopilot's consented paths (prefetch takes the consented branch first). - model-migration: a flip now converges only providers with an empty filter; ResolveModel sends alias traffic to the desired build first, so previous-build providers serve overflow only. Operators act after the flip, when the picker maps the alias to the new build. - troubleshooting: a row for provider 0.10.6 and earlier, including that selecting the rollback build gemma-4-26b-8bit does not stop the push (it is a retired build of the alias). - changelog: lead with what operators see and must do at a rollout. - reconcileDesiredModels: split the empty-build guard from the filter log guard; no behavior change. Co-Authored-By: Claude Opus 5.5 --- changelog.d/provider-enabled-filter-wins.md | 10 ++++----- docs/architecture/model-autopilot.md | 10 ++++----- docs/operations/model-migration.md | 21 ++++++++++++------- docs/provider/cli-reference.md | 2 +- docs/provider/troubleshooting.md | 5 +++-- docs/reference/configuration.md | 2 +- docs/reference/protocol-messages.md | 21 ++++++++++++------- .../ProviderCore/ProviderLoop+Prefetch.swift | 5 +++-- 8 files changed, 44 insertions(+), 32 deletions(-) diff --git a/changelog.d/provider-enabled-filter-wins.md b/changelog.d/provider-enabled-filter-wins.md index aa2b7e923c..fcf1abe7b2 100644 --- a/changelog.d/provider-enabled-filter-wins.md +++ b/changelog.d/provider-enabled-filter-wins.md @@ -1,7 +1,7 @@ ### The enabled-model filter wins over coordinator model changes -- A provider with an `enabled_models` filter no longer serves, downloads or loads a model outside it because the coordinator asked. Before, a public model rollout could bring back a model you deselected: with `gemma-4-26b` selected and `gemma-4-26b-qat-4bit` deselected, the coordinator's `gemma-4-26b` rollout downloaded `gemma-4-26b-qat-4bit` again (also after `darkbloom models remove`), served it in place of `gemma-4-26b`, and `darkbloom status` showed `Serving outside the enabled model filter: gemma-4-26b-qat-4bit`. -- The provider now refuses a coordinator `load_model` or `prefetch_model` for a model outside the filter (`model_not_selected`), and does not move a selected model to a newer build outside the filter. It keeps serving the selected build and logs `desired_models: → is outside the enabled model filter; not converging`. -- `darkbloom switch` makes its selection the filter at once, without a restart. -- With an empty `enabled_models` (serve every downloaded model) nothing changes. To take a new build of a selected model, add it with `darkbloom switch`. -- Autopilot keeps its own consent-based downloads and placements. +- A model you deselect with `darkbloom switch` or delete with `darkbloom models remove` no longer comes back on its own. Before, when the coordinator moved a public model to a newer build, every Mac serving that model downloaded the newer build, served it in place of the build its operator chose and loaded it, even when `enabled_models` left it out. For example, with `gemma-4-26b` selected and `gemma-4-26b-qat-4bit` deselected, `gemma-4-26b-qat-4bit` returned within minutes and `darkbloom status` showed `Serving outside the enabled model filter: gemma-4-26b-qat-4bit`. +- With `enabled_models` set, the provider now refuses a coordinator `load_model` or `prefetch_model` for a model outside it (`model_not_selected`), and keeps serving the build you selected when its public model moves to a build you did not list. The log then says `desired_models: → is outside the enabled model filter; not converging`. +- **Your provider no longer moves to a new build of a model by itself.** To take one, run `darkbloom switch` and pick the model's public name; the picker shows its newest build under that name. Until you do, the newer build gets that model's requests first. +- `darkbloom switch` applies its selection as the filter at once, without a restart. +- Nothing changes with an empty `enabled_models` (serve every downloaded model), or for Autopilot's consented downloads and placements. diff --git a/docs/architecture/model-autopilot.md b/docs/architecture/model-autopilot.md index cfb26e1bcf..637c2a6680 100644 --- a/docs/architecture/model-autopilot.md +++ b/docs/architecture/model-autopilot.md @@ -244,11 +244,11 @@ stops the driver at its next candidate, and the current step finishes normally. 9. Without saved consent, or with downloads turned off, there is no download, no `inventory_downloads` capability and no `download_storage` (`autopilotDownloadsEnabled`, `handlePrefetchModelRequest`). -10. Ordinary coordinator commands reach only the operator's filter: a nonempty - `enabled_models` with the start selection, then each live switch. - `load_model`, `prefetch_model`, a desired build and a selected build's alias - successor outside it are refused or skipped (`autopilotAllowsModel`, - `operatorFilterAllows`); an empty `enabled_models` filters nothing. Consented +10. Without Autopilot, coordinator `load_model`, `prefetch_model` and desired + builds stay inside the + [operator filter](../reference/configuration.md#provider-model-selection), and + a selected build's alias successor becomes ordinary only inside it, with or + without consent (`autopilotAllowsModel`, `operatorFilterAllows`). Consented downloads and operations keep their own gates. ## Failure modes diff --git a/docs/operations/model-migration.md b/docs/operations/model-migration.md index 9f2f8ee4f0..eb754d40d3 100644 --- a/docs/operations/model-migration.md +++ b/docs/operations/model-migration.md @@ -74,14 +74,19 @@ coordinator logs `provider now advertises build (models_update)` and against the desired build — capacity never black-holes. There are no weights, ramps, or migration controllers. -**The operator's filter wins.** A provider whose operator set `enabled_models` -(or switched models with `darkbloom switch`) converges only when the desired -build is in that filter. Otherwise it keeps serving the previous build, which -routing still accepts as the alias fallback, and logs `desired_models: → - is outside the enabled model filter; not converging`. Such an operator -moves by adding the new build with `darkbloom switch`. Providers with an empty -`enabled_models` converge as before. Count the providers still advertising the -previous build before you retire it. +**The operator's filter wins.** A provider converges only when the desired +build is in its [operator filter](../reference/configuration.md#provider-model-selection). +A background `darkbloom start` and every `darkbloom switch` save that filter, so +almost every provider has one and almost none lists a newly published build: a +flip converges providers with an empty `enabled_models` and nobody else until +operators pick the new build. The others keep serving the previous build and log +`desired_models: → is outside the enabled model filter; not +converging`. `ResolveModel` sends alias traffic to the desired build whenever a +provider can take it, so previous-build providers then serve only overflow, and +providers on a retired build serve none of it. After the flip, ask operators to +run `darkbloom switch` and pick the public model's name, which the picker then +maps to the desired build; before retiring the previous build, count the +providers still advertising it. ## Steps diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 5936607b05..83e30a5a95 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -2180,7 +2180,7 @@ override `provider.toml` for one process, are in | `[provider] auto_update` | `true` | Startup + periodic self-update | | `[provider] auto_restart` | `true` | Arm the watchdog LaunchAgent | | `[provider] update_jitter_seconds` | `300` | Max random delay before an automatic install or a network provider drains a model for a prepared MTP replacement; serving continues during the delay. `0` disables jitter; capped at `3600`. Standalone MTP upgrades skip this delay. Random staggering provides no fleet availability guarantee (`provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift`, `updateJitterSeconds`; `provider-swift/Sources/ProviderCore/Update/UpdateJitter.swift`, `delay`; `provider-swift/Sources/ProviderCore/ProviderLoop+MTPDrain.swift`, `waitBeforeMTPUpgradeDrain`) | -| `[backend] enabled_models` | `[]` | Advertise only these ids; empty = all serveable. When set, coordinator `load_model`, `prefetch_model` and model rollouts never load or download a model outside it; a live `switch` replaces it at once | +| `[backend] enabled_models` | `[]` | Advertise only these ids; empty = all serveable. When set, it also bounds coordinator model commands and rollouts ([operator filter](../reference/configuration.md#provider-model-selection)) | | `[backend] model_cache_directory` | unset | Explicit saved hub directory; set or import once with `models location`, clear with `--reset`. Ambient cache variables never override it; hand-written relative paths are anchored to the config file (`provider-swift/Sources/ProviderCore/Config/ModelCacheConfiguration.swift`, `ConfigManager.modelCacheDirectory`) | | `[backend] idle_timeout_mins` | `60` | Unload a model idle this long; `0` disables; paused during active or explicitly paused Autopilot | | `[backend] max_model_slots` | `3` | Resident models | diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index 839ed7d25a..68b6a050eb 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -167,8 +167,9 @@ are tabulated in [`cli-reference.md`](./cli-reference.md#runtime-constants). | `model fits in RAM` FAIL / `Cold load blocked (memory)` in status | The live no-eviction load budget is below the scanner's complete model estimate plus activation and minimum-KV serving reserve, and request-time idle eviction cannot close the gap. The nominal `Inference memory` hardware figure is not live free RAM. Status and doctor show both the preload gap and the smaller eviction-aware cold-load gap ([load gate](../architecture/hardware-support.md#load-gate-modelloadadmission)). A busy machine with an active request gets a temporary verdict instead | Free at least the **cold-load** shortfall with margin, rerun `darkbloom doctor`, then `darkbloom restart` to retry preload when enabled; or select a smaller model ([hardware requirements](./hardware-requirements.md)). A request cannot cold-load at the same memory level. | | `Preload skipped (no eviction)` in status | The model does not fit alongside the current resident slots. The request-time allowance can fit it by evicting idle models; startup preload deliberately avoids that churn | Keep the current serving set, or free memory if both models should stay resident. | | A load refusal says `Not evictable: (… GB: …)`, or status says `Not evictable for a load now: …` | That resident model cannot be evicted for the load: an Autopilot placement hold (until the UTC time shown), requests in flight, a local request, an Autopilot pin, an unload or an MTP upgrade in progress. `adopted by Autopilot outside the selected models` means an Autopilot operation placed it there, not your selection ([placements](../architecture/model-autopilot.md#placements-after-an-operation)) | Wait for the hold to expire or the requests to finish, then retry the load; a hold also ends when an operation unloads the model or Autopilot is disabled. | -| `Serving outside the enabled model filter: ` in status | The running daemon serves a model your saved `enabled_models` omits: an Autopilot operation adopted it, it is in the running daemon's selection (a hand-edited filter applies only at the next start), or a live Autopilot lease published it. Coordinator `load_model`, `prefetch_model` and model rollouts never bring in a model outside the filter; before this release a rollout could (for example `gemma-4-26b-qat-4bit` coming back in place of a selected `gemma-4-26b`, and downloading again after `darkbloom models remove`) | For an adoption see `darkbloom autopilot status`; otherwise `darkbloom restart` applies the saved filter. | -| The log says `desired_models: → is outside the enabled model filter; not converging` | The coordinator moved a public model you serve to a newer build that your filter does not list. The provider keeps serving the build you selected | To take the new build, add it with `darkbloom switch`; to keep your build, nothing. | +| `Serving outside the enabled model filter: ` in status | The running daemon serves a model your saved `enabled_models` omits: an Autopilot operation adopted it, it is in the running daemon's selection (a hand-edited filter applies only at the next start), or a live Autopilot lease published it. A coordinator command or model rollout never adds one ([operator filter](../reference/configuration.md#provider-model-selection)); on provider 0.10.6 or earlier, see the next row | For an adoption see `darkbloom autopilot status`; otherwise `darkbloom restart` applies the saved filter. | +| Provider 0.10.6 or earlier: a build you deselected with `darkbloom switch` or deleted with `darkbloom models remove` comes back within minutes, downloads again and replaces the build you selected (for example `gemma-4-26b-qat-4bit` replacing `gemma-4-26b`); status shows `Serving outside the enabled model filter: ` | The coordinator moved a public model you serve to ``, and these providers follow that rollout even when `enabled_models` omits it. It reaches every Mac that serves any build of that public model, including its rollback build (`gemma-4-26b-8bit`) | Update the provider. Until then, serve the newest build (pick the public model's name in `darkbloom switch`) or select no build of that public model; a restart, a new login or selecting the rollback build does not stop it. | +| The log says `desired_models: → is outside the enabled model filter; not converging` | A public model you serve moved to a newer build that your `enabled_models` does not list. The provider keeps serving your build. The coordinator now sends the public model's requests to the newer build first, so your build gets them only when no Mac with the newer build has room | To keep your build, nothing. To take the new build, run `darkbloom switch` and pick the public model's name (the picker shows its newest build under that name and downloads it), with your other models. | | Model missing from `darkbloom models list` | Not in `~/.cache/huggingface/hub`, or filtered by `enabled_models` | `darkbloom models download `; `darkbloom models list --all` | | Load fails after a catalog update | New build published for the alias | `darkbloom models remove ` then `darkbloom models download ` | | `Skipping : model_type … has no engine-v2 adapter` | Family not served by CBv2 | Use a supported family; the model is never advertised | diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 14863554e4..f36c2e3244 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -198,7 +198,7 @@ mode or update configuration changes are part of this addition. | Setting | Default / precedence | Consumer | |---|---|---| -| `backend.enabled_models` | `[]` means all eligible local models; a successful `switch` pins its complete nonempty selection. A nonempty list (with the start selection) is the operator filter: coordinator `load_model`, `prefetch_model` and `desired_models` never load or download a model outside it, and a live `switch` replaces it at once | `provider-swift/Sources/ProviderCore/Service/ProviderModelSelection.swift` (`save`); `provider-swift/Sources/ProviderCore/ProviderLoop+ModelSelection.swift` (`operatorFilterAllows`) | +| `backend.enabled_models` | `[]` means all eligible local models; a background `start` and a successful `switch` save their complete nonempty selection. A nonempty list, with the models the daemon started with, is the running daemon's operator filter: without Autopilot, coordinator `load_model`, `prefetch_model` and `desired_models` (including a selected build's alias successor) never load, download or advertise a model outside it. A live `switch` replaces the filter at once; a hand edit applies at the next start. `[]` filters nothing | `provider-swift/Sources/ProviderCore/Service/ProviderModelSelection.swift` (`save`); `provider-swift/Sources/ProviderCore/ProviderLoop+ModelSelection.swift` (`operatorFilterAllows`) | | launchd-managed `start --foreground --model` | Explicitly pinned `enabled_models` overrides stale baked arguments, including restart and watchdog recovery | `provider-swift/Sources/darkbloom/Start/StartCommand.swift` (`usesPinnedModelSelection`); `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift` (`runForeground`) | | direct manual `start --foreground --model` | Explicit command-line IDs still override the saved selection | `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift` (`runForeground`) | | later scheduled serving windows | Read full current Autopilot settings/consent plus saved selection. Disabling between windows restores ordinary `enabled_models` even if unchanged; otherwise keep the initial foreground selection until a live switch or saved selection change. Resolve an empty ordinary list to eligible local models, validate/hash before reopening and retain the original window end. With consent, cached Autopilot builds verified at start or by the previous window's provider (downloads and background checks) stay while their bytes hash unchanged. All other inputs remain frozen | `provider-swift/Sources/darkbloom/ScheduledWindowSelection.swift` (`ScheduledWindowSelection`); `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift` (`runScheduled`) | diff --git a/docs/reference/protocol-messages.md b/docs/reference/protocol-messages.md index f7b9681aaf..783f4660fc 100644 --- a/docs/reference/protocol-messages.md +++ b/docs/reference/protocol-messages.md @@ -1409,7 +1409,9 @@ Go `LoadModelMessage` · Swift `LoadModel`. `model_id` (req). Sent only to Active or explicitly paused Autopilot providers block this legacy residency path and use explicit `model_autopilot` commands instead. Never sent to a `cluster_member` connection or to a device held by a verified pair (`beginVerifiedPairAwareModelCommand`, -`darkbloom-platform:coordinator/registry/verified_pair_commands.go`). +`darkbloom-platform:coordinator/registry/verified_pair_commands.go`). Without +Autopilot, a model outside the [operator filter](configuration.md#provider-model-selection) +is refused `model_not_selected` (`autopilotAllowsModel`). ### `prefetch_model` @@ -1417,7 +1419,9 @@ Go `PrefetchModelMessage` · Swift `PrefetchModel`. `model_id` (req); `priority` (`int`, opt, advisory). Download + verify only, no GPU load; for a build in ordinary serving the provider replies with `prefetch_model_status` and then `models_update`. Refused for a `cluster_member` connection or a pair-held -device, like `load_model`. +device, like `load_model`. Without saved Autopilot consent, a model outside the +[operator filter](configuration.md#provider-model-selection) is refused +`model_not_selected` before any download. With saved Autopilot consent and downloads not turned off by the operator (capability `inventory_downloads`; on by default), a build outside ordinary @@ -1450,13 +1454,14 @@ whose desired, previous, or retired build is in the provider's advertised invent an empty set revokes old targets. Revision-aware providers stage the exact artifact and drain before activation; ID-only providers retain the legacy prefetch path. Both announce completed updates through `models_update`. A provider with an -operator filter (a non-empty `enabled_models`, or the selection of a live -switch) converges only to a desired build inside it: an alias successor outside -the filter is not fetched, not served and does not drop the previous build +[operator filter](configuration.md#provider-model-selection) converges only to a +desired build inside it: an alias successor outside the filter is not fetched, +not staged, not served and does not drop the previous build (`operatorFilterAllows`, -`provider-swift/Sources/ProviderCore/ProviderLoop+ModelSelection.swift`). The -same filter refuses `load_model` and `prefetch_model` for a model outside it -with `model_not_selected`, before Autopilot's consented paths apply. A `cluster_member` +`provider-swift/Sources/ProviderCore/ProviderLoop+ModelSelection.swift`); the +provider logs `desired_models: → is outside the enabled model +filter; not converging`. With Autopilot enabled, only its lease and set gates can +admit such a build. A `cluster_member` connection is offered no entries and receives only the empty set; a nonempty set is refused for a member connection or a pair-held device. Source: [coordinator/registry/model_commands.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/registry/model_commands.go) (`DesiredModelsForProvider`, `RefreshDesiredModels`). diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Prefetch.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Prefetch.swift index 69d9317a63..1e3c7e4eb3 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+Prefetch.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Prefetch.swift @@ -379,8 +379,9 @@ extension ProviderLoop { for entry in entries { let desired = entry.desiredBuild - guard !desired.isEmpty, autopilotAllowsModel(desired) else { - if !desired.isEmpty, !operatorFilterAllows(desired) { + guard !desired.isEmpty else { continue } + guard autopilotAllowsModel(desired) else { + if !operatorFilterAllows(desired) { logger.info("desired_models: \(entry.modelName) → \(desired) is outside the enabled model filter; not converging") } continue From 1a341b05fcfd613ec0091ada76e7a20f19ab2ebc Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 21:21:23 -0600 Subject: [PATCH 0184/1441] fix(provider): show the registered models and bound the Autopilot re-registration wait The Models page showed a model as serving when it was only selected. The network routes only the models the live registration carries. The provider now keeps that set (register, written models_update, accepted models_replace) and writes it to the daemon state file. The desktop API reports it per model, and the Models page shows it. A Mac with Autopilot that was busy at every capacity tick, or always under a lease, never re-registered a newly verified build. After 10 minutes, in-flight work and a live lease no longer defer the re-registration. The planned reconnect drains accepted work first and cancels none. Co-Authored-By: Claude Opus 5.5 --- .../models-page-network-registration.md | 5 ++ .../renderer/features/models/ManualModels.tsx | 2 + .../features/models/ModelRegistration.tsx | 8 ++++ .../src/renderer/features/models/PoolRow.tsx | 5 ++ desktop-app/src/renderer/models/facts.ts | 16 +++++++ desktop-app/src/shared/contracts.ts | 4 ++ desktop-app/tests/modelsAutopilot.test.tsx | 23 +++++++++- desktop-app/tests/modelsManual.test.tsx | 23 +++++++++- docs/architecture/model-autopilot.md | 20 +++++--- docs/reference/configuration.md | 6 ++- docs/reference/desktop-control.md | 18 +++++++- docs/reference/protocol-messages.md | 5 +- .../ProviderLoop+AutopilotModelSet.swift | 46 +++++++++++++------ .../CoordinatorClient+Connection.swift | 5 +- .../CoordinatorClient+ModelSwitch.swift | 2 + .../CoordinatorClient+Registration.swift | 1 + .../Coordinator/CoordinatorClientState.swift | 25 ++++++++++ .../OutboundMessage+WriteCompletion.swift | 11 +++++ .../ProviderCore/ProviderLoop+Trust.swift | 1 + .../Sources/ProviderCore/ProviderLoop.swift | 3 ++ .../Service/DaemonState+Coding.swift | 4 +- .../Service/DaemonStateFile.swift | 15 ++++++ .../darkbloom/Desktop/DesktopSnapshot.swift | 11 +++++ .../DesktopModelRegistrationTests.swift | 13 ++++++ .../Autopilot/AutopilotDownloadTests.swift | 38 +++++++++++++++ .../CoordinatorModelSwitchTests.swift | 37 +++++++++++++++ .../DaemonStateServedCountTests.swift | 28 +++++++++++ 27 files changed, 347 insertions(+), 28 deletions(-) create mode 100644 changelog.d/models-page-network-registration.md create mode 100644 desktop-app/src/renderer/features/models/ModelRegistration.tsx create mode 100644 provider-swift/Tests/DarkbloomCLITests/DesktopModelRegistrationTests.swift diff --git a/changelog.d/models-page-network-registration.md b/changelog.d/models-page-network-registration.md new file mode 100644 index 0000000000..e38dff93e8 --- /dev/null +++ b/changelog.d/models-page-network-registration.md @@ -0,0 +1,5 @@ +### The Models page shows what the network registered + +- Each model on the Models page now says whether this Mac's live registration carries it: "Registered with the network" (the network sends it requests), "Registered for Autopilot" (Autopilot can load it), or, for a selected or pool model, a warning "Not registered with the network yet". Before, the page showed only what was selected, downloaded or loaded, so a selected model the network did not know looked like it was serving. +- The provider writes the registered set to its state file (`registered_models`). +- A Mac with Autopilot that is busy at every check, or always under a lease, now reports a newly verified build after at most 10 minutes. The re-registration closes admission, lets accepted requests finish, then reconnects. Before, such a Mac could wait without end, and Autopilot could not use the build. diff --git a/desktop-app/src/renderer/features/models/ManualModels.tsx b/desktop-app/src/renderer/features/models/ManualModels.tsx index 7e87329e96..b9daffe305 100644 --- a/desktop-app/src/renderer/features/models/ManualModels.tsx +++ b/desktop-app/src/renderer/features/models/ManualModels.tsx @@ -10,6 +10,7 @@ import { RemoveModelDialog } from './RemoveModelDialog'; import { ModelEarningsAmount } from './ModelEarnings'; import type { ModelEarnings } from './earnings'; import { ExpandableModelList } from './ExpandableModelList'; +import { ModelRegistration } from './ModelRegistration'; const filters = [ { id: 'all', label: 'All' }, @@ -142,6 +143,7 @@ export function ManualModels({ {model.reason && {model.reason}} +
diff --git a/desktop-app/src/renderer/features/models/ModelRegistration.tsx b/desktop-app/src/renderer/features/models/ModelRegistration.tsx new file mode 100644 index 0000000000..b5436e85ff --- /dev/null +++ b/desktop-app/src/renderer/features/models/ModelRegistration.tsx @@ -0,0 +1,8 @@ +import type { NativeModel } from '../../../shared/contracts'; +import { registrationLine } from '../../models/facts'; + +export function ModelRegistration({ model, expected }: { model: NativeModel; expected: boolean }) { + const line = registrationLine(model, expected); + if (!line) return null; + return {line.text}; +} diff --git a/desktop-app/src/renderer/features/models/PoolRow.tsx b/desktop-app/src/renderer/features/models/PoolRow.tsx index b21d88cbe9..22d3c73200 100644 --- a/desktop-app/src/renderer/features/models/PoolRow.tsx +++ b/desktop-app/src/renderer/features/models/PoolRow.tsx @@ -3,6 +3,7 @@ import type { NativeModel, Operation } from '../../../shared/contracts'; import { Button } from '../../components/UI'; import { modelFacts } from '../../models/facts'; import { ModelGlyph } from './ModelGlyph'; +import { ModelRegistration } from './ModelRegistration'; import { ModelEarningsAmount } from './ModelEarnings'; import type { ModelEarnings } from './earnings'; import { poolLabels, type PoolState } from './pool'; @@ -78,6 +79,10 @@ export function PoolRow({ {modelFacts(model, true)} + {model.description && (
Model details diff --git a/desktop-app/src/renderer/models/facts.ts b/desktop-app/src/renderer/models/facts.ts index 62157ffc02..9cd1b7ce01 100644 --- a/desktop-app/src/renderer/models/facts.ts +++ b/desktop-app/src/renderer/models/facts.ts @@ -22,6 +22,22 @@ export function modelFacts(model: NativeModel, network = false) { .join(' · '); } +// Whether the network knows this Mac has the model. Selected or downloaded is not enough: only a +// model the live registration carries gets requests. `expected` is true for a model this Mac +// should register, so its absence is a warning; otherwise absence is not shown. +export function registrationLine(model: NativeModel, expected: boolean) { + switch (model.registration) { + case 'routable': + return { text: 'Registered with the network', warning: false }; + case 'autopilot': + return { text: 'Registered for Autopilot', warning: false }; + case 'none': + return expected ? { text: 'Not registered with the network yet', warning: true } : undefined; + default: + return undefined; + } +} + export function pinnedMemoryLine(snapshot: Snapshot, pinned: string[], noun: string) { const { needed, measured, exceeds, limit } = pinnedMemory(snapshot, pinned); const count = `${pinned.length} ${noun}`; diff --git a/desktop-app/src/shared/contracts.ts b/desktop-app/src/shared/contracts.ts index 805455adef..938cfe0b69 100644 --- a/desktop-app/src/shared/contracts.ts +++ b/desktop-app/src/shared/contracts.ts @@ -40,6 +40,10 @@ export interface NativeModel { // Listed by the Darkbloom catalog. Only these can be served to the network or enrolled in // Autopilot; a model found only on disk runs in Local only. Absent from older runtimes. network?: boolean; + // What this Mac's live coordinator registration carries for the model: `routable` in its + // models (the network sends it requests), `autopilot` in its Autopilot inventory only, `none` + // in neither. Null or absent when not connected or on an older runtime. + registration?: 'routable' | 'autopilot' | 'none' | null; description?: string | null; context_length?: number | null; family?: string | null; diff --git a/desktop-app/tests/modelsAutopilot.test.tsx b/desktop-app/tests/modelsAutopilot.test.tsx index 92b4d994c1..212867d7f1 100644 --- a/desktop-app/tests/modelsAutopilot.test.tsx +++ b/desktop-app/tests/modelsAutopilot.test.tsx @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import '@testing-library/jest-dom/vitest'; -import type { Action, Snapshot } from '../src/shared/contracts'; +import type { Action, NativeModel, Snapshot } from '../src/shared/contracts'; import { Models } from '../src/renderer/features/models/Models'; import { backendWith } from './onboardingFixtures'; import { poolSnapshot, succeeded } from './modelsFixtures'; @@ -282,3 +282,24 @@ describe('Autopilot phases', () => { await waitFor(() => expect(sent()).toEqual([{ action: 'autopilot_disable' }])); }); }); + +it('says which pool models the network has registered', () => { + const state = poolSnapshot(); + const registration: Record = { + 'gpt-oss-20b': 'routable', + 'gemma-4-26b': 'autopilot', + 'qwen-3.5-9b': 'none', + 'qwen-3.6-35b': 'none', + }; + renderModels({ + ...state, + models: state.models.map((model) => ({ ...model, registration: registration[model.id] })), + }); + expect(row('GPT-OSS 20B')).toHaveTextContent('Registered with the network'); + expect(row('Gemma 4 26B')).toHaveTextContent('Registered for Autopilot'); + const warning = within(row('Qwen 3.5 9B')).getByText('Not registered with the network yet'); + expect(warning).toHaveClass('warning-text'); + // Not downloaded, so not expected to register; unknown shows nothing either. + expect(row('Qwen 3.6 35B A3B')).not.toHaveTextContent(/registered/i); + expect(row('Kimi K2.6')).not.toHaveTextContent(/registered/i); +}); diff --git a/desktop-app/tests/modelsManual.test.tsx b/desktop-app/tests/modelsManual.test.tsx index 548ac7a01c..2787eadb33 100644 --- a/desktop-app/tests/modelsManual.test.tsx +++ b/desktop-app/tests/modelsManual.test.tsx @@ -2,7 +2,7 @@ import { afterEach, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; import '@testing-library/jest-dom/vitest'; -import type { Action } from '../src/shared/contracts'; +import type { Action, NativeModel } from '../src/shared/contracts'; import { Models } from '../src/renderer/features/models/Models'; import { backendWith } from './onboardingFixtures'; import { poolSnapshot, succeeded } from './modelsFixtures'; @@ -140,3 +140,24 @@ it('locks the manual selection while Autopilot is turning on', async () => { fireEvent.click(screen.getByRole('button', { name: /Apply selection/ })); expect(backend.act).not.toHaveBeenCalled(); }); + +it('says which selected models the network has registered', () => { + const state = poolSnapshot({ enabled: false, phase: 'off' }); + const registration: Record = { + 'gpt-oss-20b': 'routable', + 'gemma-4-26b': 'none', + 'qwen-3.5-9b': 'none', + }; + renderModels({ + ...state, + models: state.models.map((model) => ({ ...model, registration: registration[model.id] })), + }); + fireEvent.click(screen.getByRole('button', { name: /Show \d+ more models/ })); + const row = (name: string) => + screen.getByRole('heading', { name }).closest('article') as HTMLElement; + expect(row('GPT-OSS 20B')).toHaveTextContent('Registered with the network'); + const warning = within(row('Gemma 4 26B')).getByText('Not registered with the network yet'); + expect(warning).toHaveClass('warning-text'); + // Downloaded but not selected: not registering it is expected. + expect(row('Qwen 3.5 9B')).not.toHaveTextContent(/registered/i); +}); diff --git a/docs/architecture/model-autopilot.md b/docs/architecture/model-autopilot.md index 73226f9dd9..f3871490ed 100644 --- a/docs/architecture/model-autopilot.md +++ b/docs/architecture/model-autopilot.md @@ -1,6 +1,6 @@ # Provider Autopilot -> Last updated: 2026-10-27 +> Last updated: 2026-11-02 Provider Autopilot offers an external controller the models of a Mac whose operator saved Autopilot consent: the saved selection plus every verified @@ -84,9 +84,14 @@ valid. The coordinator learns inventory metadata (`ModelInfo`) only from heartbeat's `selected_models`, and the provider re-registers once (`refreshAutopilotInventoryRegistration`, a planned reconnect) on the first capacity tick with no busy reason, no operation, no live lease, no running or -queued download and the background verification finished. A busy provider -keeps waiting rather than interrupting work; a registration made for any other -reason also ends the wait (`registeredAutopilotInventoryIDs`). +queued download and the background verification finished. A registration made +for any other reason also ends the wait (`registeredAutopilotInventoryIDs`). +After `autopilotInventoryRegistrationMaxWait` (10 minutes), in-flight work and a +live lease no longer defer it. The planned reconnect then closes admission, lets +accepted work finish, and reconnects; it never cancels accepted work. An +operation, every other busy reason, a download and the verification still +defer it. `models_update` cannot carry the build: the coordinator would make it +ordinary and publicly routable. ## Downloads on the operator's behalf @@ -262,12 +267,15 @@ stops the driver at its next candidate, and the current step finishes normally. recorded downloads in the set until the next start. - Until the provider re-registers, a coordinator sees a newly downloaded build only as an ID in `selected_models`; operations on it are refused as not - cached. A provider that is never idle keeps waiting. + cached. A provider that is never idle at a capacity tick waits at most + `autopilotInventoryRegistrationMaxWait`. - A build at the 256-ID bound downloads but stays out of the set and its download reports `model_not_supported`. - A re-registration closes admission briefly, like any planned reconnect, and fails coordinator-side operations queued for that machine; it waits for an - idle tick and happens once per batch of new builds. + idle tick, or for the end of the bounded wait, and happens once per batch of + new builds. After the bounded wait it also ends a live lease, as any + reconnect does. ## External Policy diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 4f18264fac..85c1c54a96 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1,6 +1,6 @@ # Configuration reference -> Last updated: 2026-10-31 +> Last updated: 2026-11-02 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. @@ -100,6 +100,10 @@ Provider `auto_update`, `idle_timeout_mins`, schedule windows, and startup preloading retain their existing native configuration. The app writes them through the [versioned desktop API](desktop-control.md), using expected revisions. +The Models page reads which models the network registered from the daemon state +file (`registered_models`), not from configuration. It has no setting. See +[model registration](desktop-control.md) in the desktop API. + ## Runtime metallib snapshots The provider creates an anonymous snapshot before binding the runtime metallib. diff --git a/docs/reference/desktop-control.md b/docs/reference/desktop-control.md index 97f624e9af..e51516bd5b 100644 --- a/docs/reference/desktop-control.md +++ b/docs/reference/desktop-control.md @@ -1,6 +1,6 @@ # Desktop control API -> Last updated: 2026-10-18 +> Last updated: 2026-11-02 The Electron app controls the Swift CLI/backend through its authenticated local API. The backend owns provider operations, configuration, model state, credentials, @@ -231,6 +231,22 @@ The list is the catalog plus every model found on disk, so a local-only model can be `eligible` for Local only yet never be advertised or enrolled in Autopilot (`DesktopBackend.state`). +Each entry also reports `registration`: what the live coordinator registration +carries for the model (`DesktopBackend.modelRegistration`). + +| Value | Meaning | +|---|---| +| `routable` | In the registration's `models`. The network sends it requests. | +| `autopilot` | In `autopilot_inventory` only. Autopilot can load it. | +| `none` | In neither. The network does not know this Mac has it. | +| `null` | Not known: the daemon is stopped, stale, Local only, not connected, or older. | + +The daemon writes the set to `registered_models` in its state file: the +`register` sent on the live connection, plus each written `models_update`, +replaced by an accepted `models_replace` (`ProviderState.registeredModels`). +`serving` is different: it is the selection. The Models page warns when a selected +or pool model is `none` (`ModelRegistration`). + `Snapshot.autopilot` contains `configured` (consent recorded), `enabled`, `paused`, `selected` and `pinned`. Its `phase` is populated only by a fresh live daemon; enrollment alone never implies active control (`DesktopBackend.autopilotSnapshot`). diff --git a/docs/reference/protocol-messages.md b/docs/reference/protocol-messages.md index e647691090..97bfb2e37b 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-30 +> Last updated: 2026-11-02 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 @@ -1428,7 +1428,8 @@ registration inventory, and sends **no** `models_update`, because that would mak it ordinary and publicly routable. It never loads or advertises the build; an Autopilot operation may load it. With consent but downloads off, such a request is refused `model_not_selected` and never takes the ordinary path. The provider then re-registers once when idle (no busy reason, -operation, live lease or other download) +operation, live lease or other download), or after a bounded wait during which +only in-flight work or a live lease deferred it, so `register.autopilot_inventory` carries the build's `ModelInfo` ([Autopilot set](../architecture/model-autopilot.md#the-autopilot-model-set)). diff --git a/provider-swift/Sources/ProviderCore/Autopilot/ProviderLoop+AutopilotModelSet.swift b/provider-swift/Sources/ProviderCore/Autopilot/ProviderLoop+AutopilotModelSet.swift index 9692b58780..3dbeaf51ef 100644 --- a/provider-swift/Sources/ProviderCore/Autopilot/ProviderLoop+AutopilotModelSet.swift +++ b/provider-swift/Sources/ProviderCore/Autopilot/ProviderLoop+AutopilotModelSet.swift @@ -104,30 +104,48 @@ extension ProviderLoop { await coordinatorClient?.sendEventHeartbeat() } - /// Re-registers once, on a capacity tick with nothing busy, when the set - /// gained a build the last registration did not carry. A planned - /// reconnect at an idle moment interrupts no request; a busy provider - /// keeps waiting. Each build is tried once. - func refreshAutopilotInventoryRegistration() async { - guard !autopilotInventoryAwaitingRegistration.isEmpty else { return } + /// The longest a build waits for an idle capacity tick. After it, in-flight + /// work and a live lease no longer defer the re-registration. + static let autopilotInventoryRegistrationMaxWait: Duration = .seconds(600) + + /// Re-registers once, on a capacity tick, when the set gained a build the + /// last registration did not carry. Each build is tried once. + /// - First the provider waits for a tick with nothing busy and no live + /// lease, so the planned reconnect interrupts no request. + /// - A provider that is never idle at a tick stops waiting after + /// `autopilotInventoryRegistrationMaxWait`. The planned reconnect then + /// makes the idle gap itself: it closes admission and lets accepted work + /// finish before it reconnects. It never cancels accepted work. + func refreshAutopilotInventoryRegistration(now: ContinuousClock.Instant = .now) async { let registered = state.registeredAutopilotInventoryIDs ?? [] autopilotInventoryAwaitingRegistration = autopilotInventoryAwaitingRegistration.filter { !registered.contains($0) && autopilotInventoryModels[$0] != nil && autopilotSetAllows($0) } - guard isIdleForInventoryRegistration, await autopilotDownloadsAreIdle(), - await autopilotRegistrationIsLive(), isIdleForInventoryRegistration else { return } + guard !autopilotInventoryAwaitingRegistration.isEmpty else { + autopilotInventoryAwaitingSince = nil + return + } + let since = autopilotInventoryAwaitingSince ?? now + autopilotInventoryAwaitingSince = since + let overdue = now - since >= Self.autopilotInventoryRegistrationMaxWait + guard inventoryRegistrationAllowed(overdue: overdue), await autopilotDownloadsAreIdle(), + await autopilotRegistrationIsLive(), inventoryRegistrationAllowed(overdue: overdue) else { return } let builds = autopilotInventoryAwaitingRegistration.sorted() - // Tried once; a refused request keeps waiting for the next idle tick. + // Tried once; a refused request keeps waiting for the next tick. guard requestAutopilotInventoryRegistration() else { return } - logger.info("Re-registering to report Autopilot inventory: \(builds.joined(separator: ", "))") + let wait = overdue ? " (no idle tick in time; draining first)" : "" + logger.info("Re-registering to report Autopilot inventory\(wait): \(builds.joined(separator: ", "))") autopilotInventoryAwaitingRegistration.removeAll() + autopilotInventoryAwaitingSince = nil } - /// Rechecked after every hop: consent, a reported set, no live lease, no - /// operation and no busy reason, so the reconnect interrupts nothing. - private var isIdleForInventoryRegistration: Bool { + /// Rechecked after every hop: consent, a reported set, no operation, no + /// transition and the background verification finished. Before the wait + /// is overdue, also no live lease and no in-flight work. + private func inventoryRegistrationAllowed(overdue: Bool) -> Bool { !autopilotInventoryAwaitingRegistration.isEmpty && autopilotConsented && !autopilotNeedsInventoryRefresh - && !modelAutopilotEnabled && autopilotCommand == nil && autopilotBusyReasons().isEmpty + && (overdue || !modelAutopilotEnabled) && autopilotCommand == nil + && autopilotBusyReasons().allSatisfy { overdue && $0 == .inflightWork } && autopilotCandidateVerificationIsIdle } diff --git a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift index a082f93ba8..17fd58c429 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift @@ -147,6 +147,8 @@ extension CoordinatorClient { self.detachNativePairMember() self.failDrainBarriers() self.failModelReplacements() + // Nothing is registered once the connection is gone. + self.state.registeredModelIDs = nil self.state.resetCapacitySession() // Detach the inference-chunk fast path from this connection (drops any // queued chunks; their requests are cancelled on disconnect). Guarded @@ -288,7 +290,8 @@ extension CoordinatorClient { for await msg in outboundStream { if self.shutdownRequested { break } let json = self.encodeOutbound(msg) - self.sendTextFrame(json, on: connection, identifier: "chunk", onWritten: msg.onWritten) + self.sendTextFrame(json, on: connection, identifier: "chunk", + onWritten: msg.onWritten ?? self.registeredSetUpdate(msg)) } } diff --git a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+ModelSwitch.swift b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+ModelSwitch.swift index fc841e5a7f..bc289a4052 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+ModelSwitch.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+ModelSwitch.swift @@ -121,6 +121,8 @@ extension CoordinatorClient { } if !validateOnly { if acknowledgedSwitchDrain == drainID { acknowledgedSwitchDrain = nil } + // The coordinator committed the complete inventory. + state.registeredModelIDs = Set(models.map(\.id)) } case .failure(let error): switch error { diff --git a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Registration.swift b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Registration.swift index d7ed1f16d2..f4612051d4 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Registration.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Registration.swift @@ -74,6 +74,7 @@ extension CoordinatorClient { } if case .register(let sent) = registration { state.registeredAutopilotInventoryIDs = Set((sent.autopilotInventory ?? []).map(\.id)) + state.registeredModelIDs = Set(sent.models.map(\.id)) } } diff --git a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClientState.swift b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClientState.swift index 3677f84975..62f78dad91 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClientState.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClientState.swift @@ -204,6 +204,7 @@ public final class ProviderState: @unchecked Sendable { private var _modelAutopilot: ModelAutopilotSnapshot? = nil private var _autopilotInventory: [ModelInfo]? = nil private var _registeredAutopilotInventoryIDs: Set? = nil + private var _registeredModelIDs: Set? = nil private var _capacityModelAutopilot: ModelAutopilotSnapshot? = nil private var _prefixCacheV2Sources: [String: any DurablePrefixCacheEvidenceSource] = [:] private var _prefixCacheMemorySources: [String: ResidentPrefixCacheEvidence] = [:] @@ -266,6 +267,30 @@ public final class ProviderState: @unchecked Sendable { set { lock.withLock { _registeredAutopilotInventoryIDs = newValue } } } + /// The ordinary model IDs the coordinator on the live connection was + /// told about: the `register.models` sent on it, plus each written + /// `models_update`, replaced by an accepted `models_replace`. The + /// coordinator routes only these. Nil while no registration is live. + var registeredModelIDs: Set? { + get { lock.withLock { _registeredModelIDs } } + set { lock.withLock { _registeredModelIDs = newValue } } + } + + /// `models_update` merges into the registered set; it never starts one. + func noteModelsUpdateWritten(_ ids: [String]) { + lock.withLock { _registeredModelIDs?.formUnion(ids) } + } + + /// What the live registration carries, for the daemon state file. + var registeredModels: DaemonState.RegisteredModels? { + lock.withLock { + _registeredModelIDs.map { + DaemonState.RegisteredModels(models: $0.sorted(), + autopilotInventory: (_registeredAutopilotInventoryIDs ?? []).sorted()) + } + } + } + public var modelAutopilot: ModelAutopilotSnapshot? { get { lock.withLock { _modelAutopilot } } set { lock.withLock { _modelAutopilot = newValue } } diff --git a/provider-swift/Sources/ProviderCore/Coordinator/OutboundMessage+WriteCompletion.swift b/provider-swift/Sources/ProviderCore/Coordinator/OutboundMessage+WriteCompletion.swift index 5b4c0bb15e..bc6a28b288 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/OutboundMessage+WriteCompletion.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/OutboundMessage+WriteCompletion.swift @@ -7,3 +7,14 @@ extension OutboundMessage { return nil } } + +extension CoordinatorClient { + /// A written `models_update` joins the registered set + /// (`ProviderState.registeredModelIDs`); other messages change nothing. + nonisolated func registeredSetUpdate(_ message: OutboundMessage) -> (@Sendable () -> Void)? { + guard case .modelsUpdate(let models) = message else { return nil } + let state = self.state + let ids = models.map(\.id) + return { state.noteModelsUpdateWritten(ids) } + } +} diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift index 258275d504..ab122d6e49 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift @@ -47,6 +47,7 @@ extension ProviderLoop { warmModels: state.warmModels, advertisedModels: advertisedModels.keys.sorted(), servingSelection: ordinaryServingModelIDs.sorted(), + registeredModels: state.registeredModels, evictionExclusions: evictionExclusionRecords(), startupPreloadPendingModels: startupPreloadPendingModels, inferenceActive: state.inferenceActive, diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index 3d8265a633..e5a7e16567 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -372,6 +372,9 @@ public actor ProviderLoop { /// Builds added to the Autopilot inventory since the last registration; /// the coordinator learns inventory metadata only from `register`. internal var autopilotInventoryAwaitingRegistration: Set = [] + /// When the current batch of `autopilotInventoryAwaitingRegistration` + /// began to wait; nil while nothing waits. + internal var autopilotInventoryAwaitingSince: ContinuousClock.Instant? /// Last check that cached Autopilot builds are still on disk. internal var autopilotCacheSweepAt: ContinuousClock.Instant? /// Background verification of the cached builds the start path left diff --git a/provider-swift/Sources/ProviderCore/Service/DaemonState+Coding.swift b/provider-swift/Sources/ProviderCore/Service/DaemonState+Coding.swift index 313d016e6e..03dfda4180 100644 --- a/provider-swift/Sources/ProviderCore/Service/DaemonState+Coding.swift +++ b/provider-swift/Sources/ProviderCore/Service/DaemonState+Coding.swift @@ -10,7 +10,7 @@ extension DaemonState { enum CodingKeys: String, CodingKey { case schema, pid, processIdentity, version, writtenAt case startedAt, attestationPublicKey, trust, coordinatorUrl, currentModel - case warmModels, advertisedModels, servingSelection, evictionExclusions + case warmModels, advertisedModels, servingSelection, registeredModels, evictionExclusions case startupPreloadPendingModels, lifecycle, modelSwitch case configPath, runtimeCapabilities, inferenceActive, requestWorkPending, loadTransitionActive case stats, system, capacity, lastModelLoadError, slots @@ -33,6 +33,7 @@ extension DaemonState { warmModels = try c.decode([String].self, forKey: .warmModels) advertisedModels = try c.decodeIfPresent([String].self, forKey: .advertisedModels) servingSelection = try c.decodeIfPresent([String].self, forKey: .servingSelection) + registeredModels = try c.decodeIfPresent(RegisteredModels.self, forKey: .registeredModels) evictionExclusions = try c.decodeIfPresent([EvictionExclusion].self, forKey: .evictionExclusions) startupPreloadPendingModels = try c.decodeIfPresent([String].self, forKey: .startupPreloadPendingModels) lifecycle = try c.decodeIfPresent(ProviderDrainStatus.self, forKey: .lifecycle) @@ -72,6 +73,7 @@ extension DaemonState { try c.encode(warmModels, forKey: .warmModels) try c.encodeIfPresent(advertisedModels, forKey: .advertisedModels) try c.encodeIfPresent(servingSelection, forKey: .servingSelection) + try c.encodeIfPresent(registeredModels, forKey: .registeredModels) try c.encodeIfPresent(evictionExclusions, forKey: .evictionExclusions) try c.encodeIfPresent(startupPreloadPendingModels, forKey: .startupPreloadPendingModels) try c.encodeIfPresent(lifecycle, forKey: .lifecycle) diff --git a/provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift b/provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift index 0d22a5f01b..b2fe0275cd 100644 --- a/provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift +++ b/provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift @@ -51,6 +51,19 @@ public struct DaemonState: Codable, Sendable, Equatable { /// `enabled_models` applies to it only at a (re)start. Nil for older /// daemons. public var servingSelection: [String]? + /// What the live coordinator registration carries (`ProviderState.registeredModels`). + /// Nil while no registration is live, and for older daemons. + public var registeredModels: RegisteredModels? + + /// Only `models` get requests. `autopilotInventory` is what Autopilot may load. + public struct RegisteredModels: Codable, Sendable, Equatable { + public var models: [String] + public var autopilotInventory: [String] + public init(models: [String], autopilotInventory: [String]) { + self.models = models + self.autopilotInventory = autopilotInventory + } + } /// Resident models no load can evict now, each with every reason /// (`ProviderLoop.evictionExclusions`). Nil for older daemons. public var evictionExclusions: [EvictionExclusion]? @@ -360,6 +373,7 @@ public struct DaemonState: Codable, Sendable, Equatable { warmModels: [String] = [], advertisedModels: [String]? = nil, servingSelection: [String]? = nil, + registeredModels: RegisteredModels? = nil, evictionExclusions: [EvictionExclusion]? = nil, startupPreloadPendingModels: [String]? = nil, inferenceActive: Bool = false, @@ -396,6 +410,7 @@ public struct DaemonState: Codable, Sendable, Equatable { self.warmModels = warmModels self.advertisedModels = advertisedModels self.servingSelection = servingSelection + self.registeredModels = registeredModels self.evictionExclusions = evictionExclusions self.startupPreloadPendingModels = startupPreloadPendingModels self.lifecycle = lifecycle diff --git a/provider-swift/Sources/darkbloom/Desktop/DesktopSnapshot.swift b/provider-swift/Sources/darkbloom/Desktop/DesktopSnapshot.swift index a6827a0f8d..11c7c1ef44 100644 --- a/provider-swift/Sources/darkbloom/Desktop/DesktopSnapshot.swift +++ b/provider-swift/Sources/darkbloom/Desktop/DesktopSnapshot.swift @@ -30,6 +30,8 @@ extension DesktopBackend { fresh ? (daemon?.lifecycle?.outcome == .draining ? "draining" : "running") : (current ? "stale" : (localEndpoint == nil ? "stopped" : "running")) + // Unknown (nil) for a stale or Local-only daemon, as for an older one. + let registered = fresh && !localOnly ? daemon?.registeredModels : nil let supported = Set(EngineV2SupportedModels.partition(localModels).supported.map(\.id)) let capabilities = Set( (daemon?.runtimeCapabilities ?? []).map { ProviderRuntimeCapability(rawValue: $0) }) @@ -60,6 +62,7 @@ extension DesktopBackend { "size_gb": .number(entry?.sizeGb ?? local.map { Double($0.sizeBytes) / 1_073_741_824 }), "memory_gb": .number(local?.estimatedMemoryGb), "downloaded": .bool(local != nil), "serving": .bool(selected.contains(id)), "loaded": .bool(resident.contains(id)), + "registration": Self.modelRegistration(id, registered: registered), "eligible": .bool(reason == nil), "reason": reason.map(DV.string) ?? .null, // Only catalog models can be advertised or enrolled in Autopilot; a // model found only on disk is eligible for local-only serving. @@ -156,4 +159,12 @@ extension DesktopBackend { ]) } + /// What the live coordinator registration carries for a model: `routable` + /// in its models (the network sends it requests), `autopilot` in its + /// Autopilot inventory only, `none` in neither. Null when not known. + static func modelRegistration(_ id: String, registered: DaemonState.RegisteredModels?) -> JSONValue { + guard let registered else { return .null } + if registered.models.contains(id) { return .string("routable") } + return .string(registered.autopilotInventory.contains(id) ? "autopilot" : "none") + } } diff --git a/provider-swift/Tests/DarkbloomCLITests/DesktopModelRegistrationTests.swift b/provider-swift/Tests/DarkbloomCLITests/DesktopModelRegistrationTests.swift new file mode 100644 index 0000000000..c8df364087 --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/DesktopModelRegistrationTests.swift @@ -0,0 +1,13 @@ +import Testing +import ProviderCore +@testable import darkbloom + +/// The Models page shows what the live registration carries, not only the selection. +@Test func modelRegistrationNamesWhatTheLiveRegistrationCarries() { + let registered = DaemonState.RegisteredModels(models: ["served"], autopilotInventory: ["cached"]) + #expect(DesktopBackend.modelRegistration("served", registered: registered) == .string("routable")) + #expect(DesktopBackend.modelRegistration("cached", registered: registered) == .string("autopilot")) + #expect(DesktopBackend.modelRegistration("selected", registered: registered) == .string("none")) + // No live registration, or an older daemon: unknown, never "none". + #expect(DesktopBackend.modelRegistration("served", registered: nil) == .null) +} diff --git a/provider-swift/Tests/ProviderCoreTests/Autopilot/AutopilotDownloadTests.swift b/provider-swift/Tests/ProviderCoreTests/Autopilot/AutopilotDownloadTests.swift index fe44d50652..b04b4a80fd 100644 --- a/provider-swift/Tests/ProviderCoreTests/Autopilot/AutopilotDownloadTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Autopilot/AutopilotDownloadTests.swift @@ -484,6 +484,44 @@ struct AutopilotDownloadTests { #expect(reconnects.requests == 0) } + /// A Mac that is busy at every tick, or always under a lease, still + /// reports a new build: after the bounded wait the planned reconnect + /// drains accepted work first instead of waiting for an idle tick. + @Test func aBusyProviderReRegistersOnceTheWaitIsOverdue() async throws { + let fixture = try await Fixture.make() + defer { fixture.release() } + let loop = fixture.loop + _ = await fixture.installDownloads { id in try fixture.writeBuild(id) } + #expect(await loop.prefetchForTesting(Self.downloaded).terminal?.status == .verified) + let reconnects = ReconnectLog(accept: true) + reconnects.registered = true + await loop.setAutopilotRegistrationSeamForTesting(reconnects) + let start = ContinuousClock.now + let overdue = start.advanced(by: ProviderLoop.autopilotInventoryRegistrationMaxWait) + + // In-flight work and a live lease defer it until the wait is over. + await loop.raiseBusyFlagForTesting(.inflightWork) + await loop.activateAutopilotForTesting(revision: Fixture.revision) + await loop.refreshAutopilotInventoryRegistration(now: start) + await loop.refreshAutopilotInventoryRegistration(now: overdue.advanced(by: .seconds(-1))) + #expect(reconnects.requests == 0) + // Any other busy reason still defers it after the wait. + await loop.raiseBusyFlagForTesting(.modelLoading) + await loop.refreshAutopilotInventoryRegistration(now: overdue) + #expect(reconnects.requests == 0) + await loop.lowerBusyFlagForTesting(.modelLoading) + + // Overdue: one planned reconnect for the batch. + await loop.refreshAutopilotInventoryRegistration(now: overdue) + #expect(reconnects.requests == 1) + #expect(await loop.autopilotInventoryAwaitingRegistration.isEmpty) + #expect(await loop.autopilotInventoryAwaitingSince == nil) + await loop.refreshAutopilotInventoryRegistration(now: overdue) + #expect(reconnects.requests == 1) + await loop.lowerBusyFlagForTesting(.inflightWork) + await loop.clearAutopilotControl() + } + @Test func registrationCarriesTheEffectiveInventoryFilteredByTheSet() throws { let config = CoordinatorClientConfig(url: "ws://127.0.0.1:0/unused", hardware: ModelLoadingFixtures.defaultHardware, models: [], backendName: "mlx-swift", autopilotInventory: []) diff --git a/provider-swift/Tests/ProviderCoreTests/Coordinator/CoordinatorModelSwitchTests.swift b/provider-swift/Tests/ProviderCoreTests/Coordinator/CoordinatorModelSwitchTests.swift index b6be1373ff..22fffcfc1d 100644 --- a/provider-swift/Tests/ProviderCoreTests/Coordinator/CoordinatorModelSwitchTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Coordinator/CoordinatorModelSwitchTests.swift @@ -153,4 +153,41 @@ struct CoordinatorModelSwitchTests { #expect(await client.acknowledgedSwitchDrain == nil) #expect(mock.snapshot().registers.count == 1) } + + /// The registered set is what the coordinator on the live connection was + /// told: `register.models`, plus written `models_update`s, replaced by an + /// accepted `models_replace`; a reconnect registers it again. + @Test func theRegisteredSetFollowsRegisterUpdateAndReplacement() async throws { + let mock = MockCoordinator() + let url = try await mock.start() + defer { Task { await mock.shutdown() } } + let client = switchTransportClient(url.mockProviderWebSocketURL()) + let state = await client.state + #expect(state.registeredModelIDs == nil) + let (events, send) = await client.start() + defer { Task { await client.shutdown() } } + for await event in events { if case .connected = event { break } } + let reader = Task { + for await event in events { + if case .drainAck(let id) = event { await client.completeDrainAcknowledgement(id) } + } + } + defer { reader.cancel() } + #expect(state.registeredModelIDs == ["old"]) + + send(.modelsUpdate(models: [switchTransportModel("added")])) + _ = try #require(try await mock.waitForSnapshot { !$0.modelsUpdates.isEmpty }) + #expect(await modelLoadingWaitUntil { state.registeredModelIDs == ["old", "added"] }) + + let drain = try #require(await client.prepareModelSwitch(timeout: .seconds(2))) + try await client.validateModelSelectionAfterDrain([switchTransportModel("new")], drainID: drain, timeout: .seconds(2)) + #expect(state.registeredModelIDs == ["old", "added"]) + try await client.replaceModelsAfterDrain([switchTransportModel("new")], drainID: drain, timeout: .seconds(2)) + #expect(state.registeredModelIDs == ["new"]) + #expect(state.registeredModels == DaemonState.RegisteredModels(models: ["new"], autopilotInventory: [])) + + await mock.dropActiveWebSocket() + _ = try #require(try await mock.waitForSnapshot(timeout: .seconds(10)) { $0.registers.count == 2 }) + #expect(await modelLoadingWaitUntil { state.registeredModelIDs == ["new"] }) + } } diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/DaemonStateServedCountTests.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/DaemonStateServedCountTests.swift index 375c5ecfe9..7ddd4b863d 100644 --- a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/DaemonStateServedCountTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/DaemonStateServedCountTests.swift @@ -46,4 +46,32 @@ struct DaemonStateServedCountTests { #expect(written["cancellations_partial_complete"] as? Int == 1) #expect(DaemonStateFile.read(from: file)?.stats.cancellationsPartialComplete == 1) } + + /// The Models page reads what the live registration carries from here. + @Test func theStateFileCarriesTheLiveRegistration() async throws { + let loop = try makeLoop() + #expect(await loop.currentDaemonState().registeredModels == nil) + let state = await loop.state + state.registeredModelIDs = ["b", "a"] + state.registeredAutopilotInventoryIDs = ["c"] + state.noteModelsUpdateWritten(["d"]) + + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("daemon-state-registered-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + let file = directory.appendingPathComponent("daemon-state.json") + DaemonStateFile.write(await loop.currentDaemonState(), to: file) + + let written = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]) + let registered = try #require(written["registered_models"] as? [String: Any]) + #expect(registered["models"] as? [String] == ["a", "b", "d"]) + #expect(registered["autopilot_inventory"] as? [String] == ["c"]) + #expect(DaemonStateFile.read(from: file)?.registeredModels + == DaemonState.RegisteredModels(models: ["a", "b", "d"], autopilotInventory: ["c"])) + + // A models_update without a live registration starts nothing. + state.registeredModelIDs = nil + state.noteModelsUpdateWritten(["d"]) + #expect(await loop.currentDaemonState().registeredModels == nil) + } } From 9f8a3079444daf5fe19ddf8b9dea631b93938af3 Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 21:24:11 -0600 Subject: [PATCH 0185/1441] fix(provider): restart through launchd when App Attest becomes unsupported After a self-update, about 10 % of macOS 27 Macs report is_supported_false and lose their App Attest lease for hours. Nothing restarted the provider for this state. - A provider that launchd runs now relaunches through launchd after a startup self-update, as the background update already did. Only a provider that launchd does not run keeps the in-place exec. The route check now also requires that this process is the agent's job, so a foreground provider never hands its work to the LaunchAgent. - When a ready answers is_supported_false on a Mac that the coordinator verified for App Attest in the last 7 days, the stall-restart monitor restarts the provider once through launchd. It waits until the state lasts 5 minutes and the provider is idle, reads Apple's answer again after the drain, and shares the stall restart's 6 h limit and marker. - The provider records its last App Attest authorization in app-attest-verified.json beside the daemon state file. Linear DBLM-992. Co-Authored-By: Claude Opus 5.5 --- changelog.d/app-attest-unsupported-restart.md | 5 + docs/provider/attestation.md | 10 +- docs/provider/cli-reference.md | 8 +- docs/reference/app-attest-shadow.md | 7 +- .../AppAttestStallRestart.swift | 92 ++++++++++- .../AppleAppAttestService.swift | 7 + .../ProviderLoop+AppAttestShadow.swift | 2 + .../ProviderLoop+AppAttestStall.swift | 146 +++++++++++++++--- .../ProviderCore/ProviderLoop+Trust.swift | 1 + .../Sources/ProviderCore/ProviderLoop.swift | 9 ++ .../Service/ProcessLifecycle.swift | 64 +++++--- .../darkbloom/Start/StartCommand+Modes.swift | 6 +- .../StalledOperationAndRotationTests.swift | 68 ++++++++ ...ProviderAuthorizationConnectionTests.swift | 41 +++-- .../Service/ProcessLifecycleTests.swift | 11 ++ .../Service/ProviderLifecycleTests.swift | 113 ++++++++++++++ 16 files changed, 519 insertions(+), 71 deletions(-) create mode 100644 changelog.d/app-attest-unsupported-restart.md diff --git a/changelog.d/app-attest-unsupported-restart.md b/changelog.d/app-attest-unsupported-restart.md new file mode 100644 index 0000000000..3aa50187af --- /dev/null +++ b/changelog.d/app-attest-unsupported-restart.md @@ -0,0 +1,5 @@ +### App Attest recovers by itself after a self-update + +- A provider that launchd runs now relaunches through launchd after a startup self-update, as it already did after a background update. Only a provider that launchd does not run, such as `darkbloom start --foreground` in a terminal, replaces itself in place. A background update or App Attest restart in such a provider no longer starts the LaunchAgent instead. +- When App Attest reports `is_supported_false` on a Mac that the coordinator verified for App Attest in the last 7 days, the provider restarts once through launchd. It waits until the state lasts 5 minutes and the provider is idle, and it checks Apple's answer again after the drain. This restart and the stall restart share one limit: one automatic App Attest restart per 6 hours. +- The provider keeps the time of its last App Attest authorization in `app-attest-verified.json` beside the daemon state file. diff --git a/docs/provider/attestation.md b/docs/provider/attestation.md index 214edd1003..7d7a514cb8 100644 --- a/docs/provider/attestation.md +++ b/docs/provider/attestation.md @@ -1,6 +1,6 @@ # Reaching and keeping `hardware` trust -> Last updated: 2026-10-13 +> Last updated: 2026-11-02 How to check provider verification and retain legacy `hardware` trust where eligible. New providers require macOS 27 or later and current qualified App @@ -99,6 +99,14 @@ The log line starts with `App Attest: Apple operation stalled`. An explicit `darkbloom restart` uses the same graceful lifecycle; it is not instant or proof that Apple will accept the next call. +After a self-update, some macOS 27 Macs report App Attest as unsupported +(`is_supported_false`) although it worked before. If the coordinator granted +this Mac App Attest in the last 7 days and launchd runs the provider, the +provider restarts once through launchd when the state lasts 5 minutes and the +provider is idle. This restart shares the stall restart's limit of one per 6 +hours. The log line starts with `App Attest: isSupported is false`. See the +[thresholds and limits](../reference/app-attest-shadow.md#bounds-and-credential-lifecycle). + The separate [supervised worker candidate](../architecture/security/identity-binding.md#supervised-app-attest-worker-candidate) is internal, defaults off and is **not ready for production**. It retires the worker rather than restarting the inference process; do not enable its diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 557fb57fb4..4a2b6fb3db 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1,6 +1,6 @@ # Provider CLI reference -> Last updated: 2026-10-30 +> Last updated: 2026-11-02 Reference for the `darkbloom` command-line tool: every subcommand and flag, the files and identifiers it creates, the `provider.toml` keys it reads with their @@ -434,7 +434,8 @@ drains it instead of ending the process at once. `SIGHUP` is not a stop signal in two cases: the provider's launchd job does not take it, so it has whatever action launchd started the job with, and a start that arrived with `SIGHUP` ignored, for example under `nohup`, keeps ignoring it. A provider that -re-executes itself in place for a self-update carries the same choice into the +re-executes itself in place for a self-update (one that launchd does not run; +launchd relaunches its own provider) carries the same choice into the new process (`ProviderStopSignals` in `provider-swift/Sources/ProviderCore/Service/ProviderStopSignals.swift`). The signal deadline is configurable with @@ -2114,7 +2115,8 @@ qualification or performance. Sources: | Verified weight hashes | `~/.darkbloom/verified-weights.json` (`DARKBLOOM_VERIFIED_WEIGHTS_FILE`), `0600`; managed GLM load hashes bound to file identities, reused for startup registration | `provider-swift/Sources/ProviderCore/Service/VerifiedWeightHashStore.swift` | | Watchdog state | `~/.darkbloom/watchdog-state.json` (`DARKBLOOM_WATCHDOG_STATE`) | `provider-swift/Sources/ProviderCore/Service/WatchdogState.swift` | | KV-backend crash-loop guard | `~/.darkbloom/kv-backend-guard.json` (`DARKBLOOM_KV_BACKEND_GUARD`) | `provider-swift/Sources/ProviderCore/Service/KVBackendGuard.swift` | -| App Attest stall restart marker | `app-attest-stall-restart.json` beside the daemon state file, `0600`; time of the last automatic restart for a stalled DeviceCheck call ([limits](../reference/app-attest-shadow.md#bounds-and-credential-lifecycle)) | `provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift` (`AppAttestStallRestartMarker`) | +| App Attest stall restart marker | `app-attest-stall-restart.json` beside the daemon state file, `0600`; time of the last automatic App Attest restart, for a stalled DeviceCheck call or for `is_supported_false` ([limits](../reference/app-attest-shadow.md#bounds-and-credential-lifecycle)) | `provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift` (`AppAttestStallRestartMarker`) | +| App Attest verified marker | `app-attest-verified.json` beside the daemon state file, `0600`; time of the last coordinator App Attest authorization, rewritten at most once per hour. It only allows the `is_supported_false` restart; it never authorizes serving | `provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift` (`AppAttestVerifiedMarker`) | | Provider run marker | `provider-run.json` beside the daemon state file, `0600`. Set to `running` when a serve process starts and to `clean` (with cause) after its drain or before an update/stall relaunch. Explicit update/stall relaunch causes survive later generic termination callbacks; a failed hand-off restores running state and clears the cause. The next process derives `previous_exit` and `start_reason` from it | `provider-swift/Sources/ProviderCore/Service/ProviderRunMarker.swift`, `ProviderProcessRun.swift` | | APNs push history | `apns-push-history.json` beside the daemon state file, `0600`. The last 50 code-identity push receipt times and reply times, plus whether a device token was present. No token, nonce or payload | `provider-swift/Sources/ProviderCore/Apns/APNsPushHistory.swift` | | Provider LaunchAgent | label `io.darkbloom.provider`; `~/Library/LaunchAgents/io.darkbloom.provider.plist`; `RunAtLoad = true`, `KeepAlive = false`; stdout/stderr → `~/.darkbloom/provider.log` | `provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift` (`label`, `plistPath`, `logPath`) | diff --git a/docs/reference/app-attest-shadow.md b/docs/reference/app-attest-shadow.md index 7e206c0324..dc62177c6f 100644 --- a/docs/reference/app-attest-shadow.md +++ b/docs/reference/app-attest-shadow.md @@ -1,6 +1,6 @@ # App Attest shadow protocol, machine inventory, and evidence -> Last updated: 2026-10-13 +> Last updated: 2026-11-02 App Attest shadow collection records stable machine identities, fleet adoption, submitted proofs and receipts alongside legacy verification. Shadow alone changes no routing, rewards or trust. The separately enabled [provider authorization path](provider-authorization.md) uses qualified evidence for MDM-optional serving and rewards. DeviceCheck's separate two-bit API remains deferred. @@ -50,9 +50,9 @@ Local daemon history is refreshed after every attestation/assertion exchange, no | Field | Type and bounds | Sent on | Source (provider) | Answers | |---|---|---|---|---| -| `process_started_at` | int64 Unix seconds, 2020-01-01 to coordinator now + 1 day | `ready` | Kernel start time of this process (`proc_pidinfo` `pbi_start_tvsec`); an in-place exec (startup self-update) keeps it | With `boot_time`, whether a key died across a reboot or a process restart. | +| `process_started_at` | int64 Unix seconds, 2020-01-01 to coordinator now + 1 day | `ready` | Kernel start time of this process (`proc_pidinfo` `pbi_start_tvsec`); an in-place exec (a self-update of a provider that launchd does not run) keeps it | With `boot_time`, whether a key died across a reboot or a process restart. | | `previous_exit` | `clean`, `unclean`, `unknown` | `ready` | Local marker `provider-run.json` beside `daemon-state.json` (0600): written `running` once the serve process holds the single-instance lock, `clean` after the drain (SIGTERM, CLI stop/restart, schedule end) or right before an update/stall-restart relaunch. Next start: running → `unclean` (crash, SIGKILL/jetsam, power loss, reboot without drain), clean → `clean`, missing/unreadable → `unknown`. A run is identified by the kernel's microsecond start time, so a replacement started within the same second is a new run, while an in-place exec keeps its earlier answer | Whether a clean shutdown preceded a key failure. | -| `start_reason` | `launchd`, `watchdog`, `update`, `stall_restart`, `manual`, `unknown` | `ready` | First match wins; "recent" is a timestamp from 120 s before process start up to classification time (so evidence written after start, e.g. across the in-place exec of a startup self-update, counts): `stall_restart` (recent App Attest stall-restart marker or recorded stall relaunch), `watchdog` (recent watchdog `last_restart_at`), `update` (version differs within the exact same kernel process identity, or recent recorded update relaunch), `manual` (recent CLI lifecycle stop, or not started by launchd), `launchd` (`XPC_SERVICE_NAME` is the provider LaunchAgent label: login/boot/kickstart) | Why this process started. | +| `start_reason` | `launchd`, `watchdog`, `update`, `stall_restart`, `manual`, `unknown` | `ready` | First match wins; "recent" is a timestamp from 120 s before process start up to classification time (so evidence written after start, e.g. across an in-place exec, counts): `stall_restart` (recent App Attest restart marker, written by the stall restart and by the `is_supported_false` restart, or a recorded relaunch of either), `watchdog` (recent watchdog `last_restart_at`), `update` (version differs within the exact same kernel process identity, or recent recorded update relaunch), `manual` (recent CLI lifecycle stop, or not started by launchd), `launchd` (`XPC_SERVICE_NAME` is the provider LaunchAgent label: login/boot/kickstart) | Why this process started. | | `console_user_active` | bool | `ready` | `SCDynamicStoreCopyConsoleUser` returns a user other than `loginwindow`/`root`/`_mbsetupuser` (doctor's console-session rule); `false` when nobody is logged in or the store is unavailable. The name is never sent | With `launch_session = background`: a user is logged in but the provider runs outside that session. | | `sip_enabled` | bool | `ready` | `csrutil status` (`SIPStatusChecker`) reports SIP fully enabled; `false` = disabled or Custom Configuration; omitted when `csrutil` fails or its output is unrecognised. Probed once per process | Whether boot-security changes line up with `isSupported == false`. | | `authenticated_root` | bool | `ready` | `checkAuthenticatedRootEnabled` (`csrutil authenticated-root status`, then `diskutil info /` Sealed); `true` only on a positive result; omitted when neither command ran. Once per process | As above, for the sealed system volume. | @@ -127,6 +127,7 @@ provider-local Apple callback, retry, key-budget and socket fences remain separa | Session recovery | Generic or server-unavailable Apple API failures retry after one minute, then five minutes, then at most the normal ten-minute assertion interval. Other transient coordinator/storage failures retain the one-minute, five-minute, then hourly backoff. Every attempt gets a new session/nonce and reloads durable acceptance/counters. Successful assertions reset backoff. An Apple API error is an unknown prospective verdict and grants no permission; verified crypto/policy rejections remain terminal, and cancellation stops retries. Persistent generic errors still need native domain/code diagnostics from a signed upgraded client. [Dead-key rotation](#dead-key-rotation) and the [invalid-key enrollment backoff](#invalid-key-enrollment-backoff) replace this delay in their specific cases. Code: [coordinator/internal/appattest/recovery/recovery_policy.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/internal/appattest/recovery/recovery_policy.go) (`ExchangeRetryDelay`), [coordinator/internal/appattest/recovery/driver.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/internal/appattest/recovery/driver.go) (`Driver.Run`); session wiring in [coordinator/appattest/service/retry.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/appattest/service/retry.go) (`run`). | | First-risk-receipt wait | A valid first assertion with no verified risk receipt yet, including an initial `renewal_required` receipt, stays unknown. Without an existing authorization record, a fresh assertion retries after one minute, five minutes, then at the normal ten-minute cadence while Apple's receipt renewal runs independently. Only complete fresh evidence can authorize serving. Code: [coordinator/appattest/service/authorization_identity.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/appattest/service/authorization_identity.go) and `retry.go`. | | Apple callbacks | 25-second waiter deadline. The actual uncancellable Apple operation retains admission until its callback arrives; retries receive `busy` in the meantime. A token fences duplicate late callbacks from unlocking a newer operation. A pre-cancelled call does not acquire admission. The gate records when it was acquired: once held longer than `AppleOperationStall.threshold` (15 min), `ready` replies return `busy` with `operation_stalled_seconds`, and the provider restarts itself through the background-update path (update lease, drain, `waitForSafeDisconnect`, `ProcessLifecycle.restartAfterUpdate`) only when no inference is in flight or loading and no update or lifecycle drain is running, at most once per `AppAttestStallRestartPolicy.minimumInterval` (6 h, persisted in `app-attest-stall-restart.json` beside the daemon state file before the restart is issued). An attempt that drains but cannot restart reopens serving and waits before draining again in the same process: `AppAttestStallRestartPolicy.drainRetryDelay` (15 min) when accepted work or the coordinator's drain acknowledgement did not finish in time, and a full `minimumInterval` when the marker cannot be written, since no restart may be issued without it. After the drain, and after its last suspension point, it checks again (`AppAttestStallRestartPolicy.afterDrain`): if Apple's callback released the gate, or a CLI stop, OS termination or scheduled shutdown took over the drain, it releases the update lease without restarting, and a lifecycle-owned drain stays closed. Code: `AppleOperationGate.swift`, `AppleAppAttestService.swift`, `AppleOperationStall.swift` and `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | +| `isSupported` false after verification | When a `ready` answers `is_supported_false` (macOS 27 or later), the provider restarts once through launchd if all of these hold: the coordinator granted this Mac an App Attest authorization within `AppAttestStallRestartPolicy.verifiedWithin` (7 days; the time is kept in `app-attest-verified.json` beside the daemon state file, rewritten at most once per hour); launchd runs this provider (`ProcessLifecycle.RelaunchRoute`: its agent is loaded and `XPC_SERVICE_NAME` is its label); and the embedded provisioning profile has not expired. The live `DCAppAttestService.isSupported` must stay false for `AppAttestStallRestartPolicy.unsupportedThreshold` (5 min) and again after the drain. The restart uses the stall restart's monitor, idle checks, drain, `app-attest-stall-restart.json` limit (one automatic App Attest restart per 6 h, for both causes) and `start_reason` `stall_restart`. It never uses an in-place exec. Code: `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | | Coordinator-driven rotation (client side) | An `attest` for a key this client already attested, with no cached proof, clears the key ID and replies `key_unregistered` without calling Apple. The next `prepare` generates a replacement within the per-key one-hour cooldown and the shared five-per-hour generation budget. Released 0.9.8 and 0.9.9 clients behave the same way. Code: `provider-swift/Sources/ProviderAppAttest/AppAttestShadowClient.swift`; pinned by `provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift`. | | Attestation retries | At most three attempts, 2/8-second waits, only for service unavailable. `ShadowEnrollmentAttempt` persists the original key/hash, status, session and timestamp across later coordinator retries and reconnects (the provider serves protocol 3 only; an attempt recorded under an earlier protocol is retired), as [Apple requires](https://developer.apple.com/documentation/devicecheck/dcerror-swift.struct/code/serverunavailable). Successful recovery uses the original stored server transaction; a subsequent serving assertion always signs fresh status/challenge/endpoint. Expired or malformed retry state retires under existing generation limits. | | Failed one-time enrollment | Non-service-unavailable Apple failures retire the enrollment key identifier under the existing generation limits. The app persists `attestationStartedAt` before calling Apple; an interrupted attempt without a saved proof is retired on the next prepare. Cached successful proofs remain recoverable. Generic assertion failures do not make the client rotate an accepted key on its own; an explicit invalid-key response can retire it, and the coordinator can request [dead-key rotation](#dead-key-rotation). Code: `provider-swift/Sources/ProviderAppAttest/EnrollmentKeyLifecycle.swift` and `AppAttestShadowClient.swift`. | diff --git a/provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift b/provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift index 821688e92e..54cdda642d 100644 --- a/provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift +++ b/provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift @@ -1,13 +1,35 @@ import Foundation -/// When a stalled DeviceCheck operation may trigger a graceful provider -/// restart. Only a new process releases the stranded Apple admission. +/// What may justify an automatic graceful provider restart. +public enum AppAttestRestartTrigger: Sendable, Equatable { + /// An Apple callback has held admission for this many seconds. Only a new + /// process releases the stranded Apple admission. + case stalled(seconds: Int) + /// `DCAppAttestService.isSupported` has been false for this many seconds + /// on a Mac whose App Attest the coordinator verified before. A new + /// process started by launchd usually reads it as supported again. + case unsupported(seconds: Int) +} + +/// When a stalled DeviceCheck operation, or App Attest that stopped being +/// supported, may trigger a graceful provider restart. Both triggers share one +/// rate limit and one persisted marker. public enum AppAttestStallRestartPolicy { /// At most one automatic restart per interval, across process restarts. public static let minimumInterval: TimeInterval = 6 * 3600 + /// How long `isSupported` must stay false before a restart. It can flip + /// back on its own, so one failed `ready` alone does not drain the provider. + public static let unsupportedThreshold: TimeInterval = 5 * 60 + + /// A coordinator verification older than this does not justify a restart: + /// the Mac may have lost App Attest support for good. + public static let verifiedWithin: TimeInterval = 7 * 24 * 3600 + public enum SkipReason: String, Sendable, Equatable { case notStalled = "not_stalled" + /// `isSupported` has been false for less than `unsupportedThreshold`. + case unsupportedBriefly = "unsupported_briefly" case recentlyRestarted = "recently_restarted" /// An earlier attempt in this process drained but could not restart. case retryDeferred = "retry_deferred" @@ -48,8 +70,19 @@ public enum AppAttestStallRestartPolicy { /// process's in-memory deferral after a failed attempt. public static func decide(stalledSeconds: Int?, inferenceActive: Bool, lifecycleBusy: Bool, lastRestartAt: Date?, retryDeferred: Bool, now: Date) -> Decision { - guard let stalledSeconds, Double(stalledSeconds) > AppleOperationStall.threshold else { + decide(trigger: stalledSeconds.map { .stalled(seconds: $0) }, inferenceActive: inferenceActive, + lifecycleBusy: lifecycleBusy, lastRestartAt: lastRestartAt, retryDeferred: retryDeferred, now: now) + } + + public static func decide(trigger: AppAttestRestartTrigger?, inferenceActive: Bool, lifecycleBusy: Bool, + lastRestartAt: Date?, retryDeferred: Bool, now: Date) -> Decision { + switch trigger { + case nil: return .skip(.notStalled) + case .stalled(let seconds): + guard Double(seconds) > AppleOperationStall.threshold else { return .skip(.notStalled) } + case .unsupported(let seconds): + guard Double(seconds) >= unsupportedThreshold else { return .skip(.unsupportedBriefly) } } if let lastRestartAt, abs(now.timeIntervalSince(lastRestartAt)) < minimumInterval { return .skip(.recentlyRestarted) @@ -79,8 +112,25 @@ public enum AppAttestStallRestartPolicy { /// Decided after the drain's last suspension point. Losing ownership of /// the drain wins over everything else: the process is being stopped. public static func afterDrain(updateOwnsDrain: Bool, heldSince: Date?, now: Date) -> AfterDrain { + afterDrain(updateOwnsDrain: updateOwnsDrain, stillBlocked: stillStalled(heldSince: heldSince, now: now)) + } + + /// `stillBlocked`: the trigger still holds after the drain (the Apple call + /// is still unanswered, or `isSupported` is still false). + public static func afterDrain(updateOwnsDrain: Bool, stillBlocked: Bool) -> AfterDrain { guard updateOwnsDrain else { return .lifecycleTookOver } - return stillStalled(heldSince: heldSince, now: now) ? .restart : .recovered + return stillBlocked ? .restart : .recovered + } + + /// Whether `isSupported == false` may lead to a restart at all. The + /// coordinator must have verified App Attest on this Mac within + /// `verifiedWithin`; launchd must start the new process (an in-place exec + /// is a suspected cause of this state, so it is never the remedy); and the provisioning + /// profile must not have expired, because a restart cannot renew it. + public static func unsupportedRestartEligible(lastVerifiedAt: Date?, relaunchesThroughLaunchd: Bool, + profileExpired: Bool?, now: Date) -> Bool { + guard relaunchesThroughLaunchd, profileExpired != true, let lastVerifiedAt else { return false } + return abs(now.timeIntervalSince(lastVerifiedAt)) < verifiedWithin } } @@ -118,3 +168,37 @@ public struct AppAttestStallRestartMarker: Sendable { try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) } } + +/// Persisted time when the coordinator last granted this Mac an App Attest +/// authorization. It only enables the restart for `isSupported == false`; it +/// never authorizes serving. +public struct AppAttestVerifiedMarker: Sendable { + public static let fileName = "app-attest-verified.json" + /// The running provider rewrites the marker at most this often. + public static let refreshInterval: TimeInterval = 3600 + public let url: URL + + public init(directory: URL) { + url = directory.appendingPathComponent(Self.fileName) + } + + private struct Record: Codable { + let verifiedAt: Double + enum CodingKeys: String, CodingKey { case verifiedAt = "verified_at" } + } + + /// Nil when the marker is missing or unreadable: no evidence, no restart. + public func lastVerified() -> Date? { + guard let data = try? Data(contentsOf: url), + let record = try? JSONDecoder().decode(Record.self, from: data), record.verifiedAt.isFinite else { return nil } + return Date(timeIntervalSince1970: record.verifiedAt) + } + + public func record(_ date: Date) throws { + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), + withIntermediateDirectories: true) + let data = try JSONEncoder().encode(Record(verifiedAt: date.timeIntervalSince1970)) + try data.write(to: url, options: .atomic) + try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) + } +} diff --git a/provider-swift/Sources/ProviderAppAttest/AppleAppAttestService.swift b/provider-swift/Sources/ProviderAppAttest/AppleAppAttestService.swift index 324408e330..1245dad98d 100644 --- a/provider-swift/Sources/ProviderAppAttest/AppleAppAttestService.swift +++ b/provider-swift/Sources/ProviderAppAttest/AppleAppAttestService.swift @@ -20,6 +20,13 @@ public actor AppleAppAttestService: AppAttestService { operations = AppleOperationGate(now: now) } + /// Live `DCAppAttestService.isSupported` alone. The restart for an + /// unsupported state reads it again before and after its drain, because + /// the state can clear inside the same process. + public static func isSupportedNow() -> Bool { + DCAppAttestService.shared.isSupported + } + public func operationHeldSince() -> Date? { operations.heldSince } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestShadow.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestShadow.swift index a0e19eb650..26334d5788 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestShadow.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestShadow.swift @@ -63,6 +63,8 @@ extension ProviderLoop { appAttestLocalStatus = published writeDaemonState() } + // Only `ready` carries the availability answer. + if prepared { noteAppAttestAvailability(localStatus) } // Only these results can leave an unanswered Apple call holding admission. if !usesAppAttestWorker && (response.result == "busy" || response.result == "operation_timeout") { startAppAttestStallMonitorIfNeeded() } appAttestShadowTask = nil diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift index f5e849fefb..a645eca8d6 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift @@ -6,6 +6,11 @@ import ProviderAppAttest /// lease, drain and launchd path as a background update, at most once per /// `AppAttestStallRestartPolicy.minimumInterval`, and never while accepted /// inference or another lifecycle operation is in progress. +/// +/// The same monitor, rate limit and restart path cover App Attest that stops +/// being supported (`isSupported == false`, most often right after a +/// self-update) on a Mac whose App Attest the coordinator verified before. +/// That restart goes through launchd only, never an in-place exec. extension ProviderLoop { private static let appAttestStallCheckInterval: Duration = .seconds(60) private static let appAttestStallDrainTimeout: Duration = .seconds(120) @@ -29,33 +34,95 @@ extension ProviderLoop { appAttestStallMonitorTask = nil } + /// Called with each `ready` this process answers. Starts the monitor when + /// `isSupported` is false on a Mac that may restart for it. + internal func noteAppAttestAvailability(_ status: AppAttestLocalStatus?, now: Date = Date()) { + guard serveUsesHostServices, !usesAppAttestWorker, status?.availabilityReason == .isSupportedFalse, + appAttestUnsupportedRestartEligible(status, now: now) else { + appAttestUnsupportedSince = nil + return + } + if appAttestUnsupportedSince == nil { + appAttestUnsupportedSince = now + logger.warning("App Attest: isSupported is false on a Mac the coordinator verified before; restarting through launchd if it stays false for \(Int(AppAttestStallRestartPolicy.unsupportedThreshold / 60)) min while idle") + } + startAppAttestStallMonitorIfNeeded() + } + + private func appAttestUnsupportedRestartEligible(_ status: AppAttestLocalStatus?, now: Date) -> Bool { + AppAttestStallRestartPolicy.unsupportedRestartEligible( + lastVerifiedAt: appAttestVerifiedMarker().lastVerified(), + relaunchesThroughLaunchd: appAttestRelaunchRoute() == .launchd, + profileExpired: status?.process?.preflight?.profileExpired, now: now) + } + + /// The restart trigger now, or nil when nothing justifies a restart (the + /// monitor then ends). An Apple stall wins over an unsupported state. + internal func appAttestRestartTrigger(heldSince: Date?, now: Date) -> AppAttestRestartTrigger? { + if let heldSince { + // Held but not yet stalled: keep watching as a stall below threshold. + return .stalled(seconds: AppleOperationStall.reportedSeconds(heldSince: heldSince, now: now) + ?? max(0, Int(now.timeIntervalSince(heldSince)))) + } + guard let since = appAttestUnsupportedSince else { return nil } + // The state can clear inside the process; Apple's live answer decides. + guard !appAttestSupportProbe() else { + logger.info("App Attest: isSupported is true again; no restart needed") + appAttestUnsupportedSince = nil + return nil + } + return .unsupported(seconds: max(0, Int(now.timeIntervalSince(since)))) + } + /// Returns whether monitoring should continue. private func evaluateAppAttestStallRestart() async -> Bool { - guard let client = appAttestShadowClient, !isShuttingDown, !Task.isCancelled, - let heldSince = await client.appleOperationHeldSince() else { - if appAttestStallLastSkip != nil { logger.info("App Attest: stalled Apple operation completed; no restart needed") } + let now = Date() + let heldSince = await appAttestShadowClient?.appleOperationHeldSince() + guard appAttestShadowClient != nil, !isShuttingDown, !Task.isCancelled, + let trigger = appAttestRestartTrigger(heldSince: heldSince, now: now) else { + if appAttestStallLastSkip != nil { logger.info("App Attest: restart condition cleared; no restart needed") } appAttestStallLastSkip = nil publishAppAttestStall(nil) appAttestStallMonitorTask = nil return false } - let now = Date() - guard let stalled = AppleOperationStall.reportedSeconds(heldSince: heldSince, now: now) else { return true } - publishAppAttestStall(stalled) + if case .stalled(let seconds) = trigger { + guard Double(seconds) > AppleOperationStall.threshold else { return true } + publishAppAttestStall(seconds) + } let marker = appAttestStallRestartMarker() let decision = AppAttestStallRestartPolicy.decide( - stalledSeconds: stalled, inferenceActive: hasInflightWork || isLoadingAny, + trigger: trigger, inferenceActive: hasInflightWork || isLoadingAny, lifecycleBusy: updatePhase != .idle || servingDrain.refusing || lifecycleDrainTask != nil, lastRestartAt: marker.lastRestart(), retryDeferred: appAttestStallRetryDeferred, now: now) switch decision { case .skip(let reason): if reason != appAttestStallLastSkip { - logger.warning("App Attest: Apple operation stalled for \(stalled)s; automatic restart deferred (\(reason.rawValue))") + logger.warning("App Attest: \(Self.describe(trigger)); automatic restart deferred (\(reason.rawValue))") } appAttestStallLastSkip = reason return true case .restart: - return await restartForStalledAppAttest(stalledSeconds: stalled, marker: marker) + return await restartForAppAttest(trigger, marker: marker) + } + } + + private static func describe(_ trigger: AppAttestRestartTrigger) -> String { + switch trigger { + case .stalled(let seconds): return "Apple operation stalled for \(seconds)s" + case .unsupported(let seconds): return "isSupported false for \(seconds)s" + } + } + + /// Whether the trigger still holds after the drain's last suspension point. + private func appAttestTriggerStillHolds(_ trigger: AppAttestRestartTrigger, now: Date) async -> Bool { + switch trigger { + case .stalled: + let heldSince = await appAttestShadowClient?.appleOperationHeldSince() + return AppAttestStallRestartPolicy.stillStalled(heldSince: heldSince, now: now) + case .unsupported: + // Never fall back to an in-place exec for this trigger. + return !appAttestSupportProbe() && appAttestRelaunchRoute() == .launchd } } @@ -67,29 +134,35 @@ extension ProviderLoop { writeDaemonState() } - private func restartForStalledAppAttest(stalledSeconds: Int, marker: AppAttestStallRestartMarker) async -> Bool { + private func restartForAppAttest(_ trigger: AppAttestRestartTrigger, marker: AppAttestStallRestartMarker) async -> Bool { let updater = SelfUpdater(coordinatorBaseURL: loopConfig.coordinatorURL) // The cross-process update lease excludes CLI stop/restart and updates. guard claimUpdateStart(updater: updater) else { appAttestStallLastSkip = .lifecycleBusy return true } - logger.warning("App Attest: Apple operation stalled for \(stalledSeconds)s; draining for a graceful provider restart to release DeviceCheck admission (at most once per \(Int(AppAttestStallRestartPolicy.minimumInterval / 3600))h)") + let purpose: String + switch trigger { + case .stalled: purpose = "release DeviceCheck admission" + case .unsupported: purpose = "let a new process launched by launchd read App Attest support again" + } + logger.warning("App Attest: \(Self.describe(trigger)); draining for a graceful provider restart to \(purpose) (at most once per \(Int(AppAttestStallRestartPolicy.minimumInterval / 3600))h)") beginUpdateDraining() - guard await waitForSafeDisconnect(timeout: Self.appAttestStallDrainTimeout, reason: "App Attest stall restart"), + guard await waitForSafeDisconnect(timeout: Self.appAttestStallDrainTimeout, reason: "App Attest restart"), !Task.isCancelled else { - logger.warning("App Attest: stall restart deferred \(Int(AppAttestStallRestartPolicy.drainRetryDelay / 60)) min; accepted work or coordinator acknowledgement is still pending") + logger.warning("App Attest: restart deferred \(Int(AppAttestStallRestartPolicy.drainRetryDelay / 60)) min; accepted work or coordinator acknowledgement is still pending") await abandonAppAttestStallRestart(after: .drainNotAcknowledged) return true } - // Apple's callback may have arrived, or a CLI stop, OS termination or - // scheduled shutdown may have taken over the drain, while we awaited. - // Nothing below suspends, so this is the last point to re-check both. - let heldSince = await appAttestShadowClient?.appleOperationHeldSince() + // Apple's callback may have arrived, isSupported may be true again, or + // a CLI stop, OS termination or scheduled shutdown may have taken over + // the drain, while we awaited. Nothing after the ownership read below + // suspends, so this is the last point to re-check both. + let stillHolds = await appAttestTriggerStillHolds(trigger, now: Date()) let ownsDrain = appAttestStallRestartOwnsDrain && !Task.isCancelled - switch AppAttestStallRestartPolicy.afterDrain(updateOwnsDrain: ownsDrain, heldSince: heldSince, now: Date()) { + switch AppAttestStallRestartPolicy.afterDrain(updateOwnsDrain: ownsDrain, stillBlocked: stillHolds) { case .lifecycleTookOver: - logger.info("App Attest: stall restart abandoned; a lifecycle drain or shutdown took over") + logger.info("App Attest: restart abandoned; a lifecycle drain or shutdown took over") appAttestStallMonitorTask = nil // Releases the update lease; lifecycle-owned admission stays closed. await resumeServingAfterUpdate() @@ -97,7 +170,8 @@ extension ProviderLoop { case .recovered: // App Attest recovered on its own: resume serving without spending // the six-hour marker or reloading models. - logger.info("App Attest: stalled Apple operation completed during drain; resuming without a restart") + logger.info("App Attest: restart condition cleared during drain; resuming without a restart") + if case .unsupported = trigger { appAttestUnsupportedSince = nil } appAttestStallLastSkip = nil appAttestStallMonitorTask = nil publishAppAttestStall(nil) @@ -116,14 +190,17 @@ extension ProviderLoop { return true } if case .failed(let reason) = prepareInstalledCandidateRestart(updater: updater) { - logger.warning("App Attest: stall restart not issued: \(reason)") + logger.warning("App Attest: restart not issued: \(reason)") await resumeServingAfterUpdate() return true } do { - try ProcessLifecycle.restartAfterUpdate(cause: .stallRestart) + switch trigger { + case .stalled: try ProcessLifecycle.restartAfterUpdate(cause: .stallRestart) + case .unsupported: try ProcessLifecycle.restartAfterUpdate(cause: .stallRestart, route: .launchd) + } } catch { - logger.warning("App Attest: stall restart failed: \(error)") + logger.warning("App Attest: restart failed: \(error)") try? updater.cancelPendingCandidateAttempt(operation: "app-attest-stall-restart-failure") await resumeServingAfterUpdate() return true @@ -154,4 +231,27 @@ extension ProviderLoop { AppAttestStallRestartMarker( directory: (daemonStateFileOverride ?? DaemonStateFile.path()).deletingLastPathComponent()) } + + internal func appAttestVerifiedMarker() -> AppAttestVerifiedMarker { + AppAttestVerifiedMarker( + directory: (daemonStateFileOverride ?? DaemonStateFile.path()).deletingLastPathComponent()) + } + + /// Records a coordinator-granted App Attest authorization, at most once per + /// `AppAttestVerifiedMarker.refreshInterval`. A failed write only disables + /// the unsupported restart; it never affects serving. + internal func recordAppAttestVerifiedIfGranted(_ authorization: ProviderAuthorizationStatus?, at receivedAt: Double) { + guard let authorization, authorization.hasCurrentAppAttestAuthorization(now: receivedAt) else { return } + let now = Date(timeIntervalSince1970: receivedAt) + if let last = appAttestVerifiedRecordedAt, + abs(now.timeIntervalSince(last)) < AppAttestVerifiedMarker.refreshInterval { return } + // Set first: leases renew every few seconds, so a failing write is + // retried, and logged, once per interval only. + appAttestVerifiedRecordedAt = now + do { + try appAttestVerifiedMarker().record(now) + } catch { + logger.warning("App Attest: cannot persist the verified marker: \(error)") + } + } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift index 258275d504..8423e39f44 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Trust.swift @@ -167,6 +167,7 @@ extension ProviderLoop { trustLevel: trustLevel, status: status, reason: reason, receivedAt: receivedAt, authorization: authorization) writeDaemonState() + recordAppAttestVerifiedIfGranted(authorization, at: receivedAt) } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index 3d8265a633..751928ab57 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -216,6 +216,15 @@ public actor ProviderLoop { /// attempt waits until this instant (monotonic; this process only, since a /// new process has no stalled call). internal var appAttestStallRetryAt: ContinuousClock.Instant? + /// When a `ready` in this process first answered `is_supported_false` on a + /// Mac that may restart for it; nil once a later `ready` answers otherwise. + internal var appAttestUnsupportedSince: Date? + /// Last write of `AppAttestVerifiedMarker` by this process. + internal var appAttestVerifiedRecordedAt: Date? + /// Seam for the launchd boundary: how a restart would reach its new process. + internal var appAttestRelaunchRoute: @Sendable () -> ProcessLifecycle.RelaunchRoute = { .current() } + /// Seam for Apple's live `DCAppAttestService.isSupported`. + internal var appAttestSupportProbe: @Sendable () -> Bool = { AppleAppAttestService.isSupportedNow() } internal let loopConfig: ProviderLoopConfig internal var ordinaryServingModelIDs: Set internal var autopilotSuccessorNeedsInventoryRefresh = false diff --git a/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift b/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift index dc0f8b01e0..eb0f529447 100644 --- a/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift +++ b/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift @@ -145,8 +145,7 @@ public enum ProcessLifecycle { } /// Replace this process image with the current executable and argv. - /// Used after startup auto-update so launchd keeps the same service - /// lifecycle while the provider begins serving with the new binary. + /// Only for a provider that launchd does not run (`RelaunchRoute.exec`). public static func execCurrentProcess() throws -> Never { #if canImport(Darwin) guard let executablePath = Bundle.main.executablePath else { @@ -188,31 +187,58 @@ public enum ProcessLifecycle { // MARK: - Launchd-Aware Restart - /// Restart the provider process after a background auto-update. + /// How a provider relaunch reaches its new process. + public enum RelaunchRoute: Sendable, Equatable { + /// `launchctl kickstart -k`: launchd stops this process and starts a + /// new one from the plist. + case launchd + /// `execv` in place: the same kernel process runs the new image. + case exec + + /// launchd only when its agent is loaded AND this process is that + /// agent's job. A foreground `start` beside a loaded agent keeps exec, + /// so it never hands its work to a different process. + public static func decide(agentLoaded: Bool, launchedByLaunchd: Bool) -> RelaunchRoute { + agentLoaded && launchedByLaunchd ? .launchd : .exec + } + + /// This process is the agent's job when `XPC_SERVICE_NAME` is its label + /// (an earlier in-place exec keeps it), or when launchd's own record of + /// the job names this exact process. + public static func current() -> RelaunchRoute { + let loaded = LaunchAgent.isLoaded() + let ownJob = loaded && (ProviderStartReason.launchedByLaunchd() + || ProcessIdentity.current().map { LaunchAgent.launchSnapshot()?.process == $0 } == true) + return decide(agentLoaded: loaded, launchedByLaunchd: ownJob) + } + } + + /// Restart the provider process after a self-update (startup or + /// background) or for App Attest recovery. /// - /// If the process is managed by launchd, delegates to - /// `LaunchAgent.restart()` (`launchctl kickstart -k`), which is a single - /// atomic launchd operation: it kills this instance and relaunches the - /// service from the same plist (picking up the freshly-installed binary). - /// launchd — not this process — performs the kill+relaunch, so it - /// completes even after we exit. Otherwise, falls back to - /// `execCurrentProcess()` (execv) which replaces the process image - /// in-place. + /// On `RelaunchRoute.launchd`, delegates to `LaunchAgent.restart()` + /// (`launchctl kickstart -k`), which is a single atomic launchd operation: + /// it kills this instance and relaunches the service from the same plist + /// (picking up the freshly-installed binary). launchd — not this process — + /// performs the kill+relaunch, so it completes even after we exit. On + /// `RelaunchRoute.exec`, `execCurrentProcess()` (execv) replaces the + /// process image in place. /// `cause` is recorded in the run marker so the next process reports /// `start_reason` (update vs App Attest stall restart). - public static func restartAfterUpdate(cause: ProviderRunMarker.ExitCause = .update) throws -> Never { + public static func restartAfterUpdate(cause: ProviderRunMarker.ExitCause = .update, + route: RelaunchRoute = .current()) throws -> Never { ProviderProcessRun.finish(cause: cause) do { - if LaunchAgent.isLoaded() { - // Launchd-managed: kickstart -k kills us and relaunches the - // service in place. Issue it, then exit so launchd is free to - // bring the new binary up cleanly (it may already have signalled - // us; the exit is the belt-and-suspenders path). + switch route { + case .launchd: + // kickstart -k kills us and relaunches the service in place. + // Issue it, then exit so launchd is free to bring the new + // binary up cleanly (it may already have signalled us; the + // exit is the belt-and-suspenders path). try LaunchAgent.restart() Thread.sleep(forTimeInterval: 2.0) exit(0) - } else { - // Not under launchd: replace process image with execv. + case .exec: try execCurrentProcess() } } catch { diff --git a/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift b/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift index c21ba8cdb2..29e9cb23f8 100644 --- a/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift +++ b/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift @@ -376,6 +376,8 @@ extension Start { await TelemetryClient.shared.shutdown() } + /// A provider that launchd runs relaunches through launchd, as the + /// background update does; a foreground provider keeps the in-place exec. private func runStartupAutoUpdate(coordinatorURL: String) async throws { if ProcessInfo.processInfo.environment["DARKBLOOM_NO_UPDATE_CHECK"] != nil { return @@ -391,7 +393,7 @@ extension Start { try updater.prepareCandidateLaunch( operation: "startup-update-exec" ) - try ProcessLifecycle.execCurrentProcess() + try ProcessLifecycle.restartAfterUpdate() } catch { try? updater.cancelPendingCandidateAttempt( operation: "startup-exec-failure") @@ -403,7 +405,7 @@ extension Start { try updater.prepareCandidateLaunch( operation: "startup-candidate-exec" ) - try ProcessLifecycle.execCurrentProcess() + try ProcessLifecycle.restartAfterUpdate() } catch { try? updater.cancelPendingCandidateAttempt( operation: "startup-exec-failure") diff --git a/provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift b/provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift index 6683f421b6..12e891ad49 100644 --- a/provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift +++ b/provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift @@ -314,4 +314,72 @@ final class AppAttestStallRestartPolicyTests: XCTestCase { let damaged = try XCTUnwrap(marker.lastRestart()) XCTAssertLessThan(abs(damaged.timeIntervalSinceNow), 60, "a damaged marker counts as a restart just now") } + + private func decide(_ trigger: AppAttestRestartTrigger?, inference: Bool = false, lifecycle: Bool = false, + deferred: Bool = false, last: Date? = nil) -> AppAttestStallRestartPolicy.Decision { + AppAttestStallRestartPolicy.decide(trigger: trigger, inferenceActive: inference, lifecycleBusy: lifecycle, + lastRestartAt: last, retryDeferred: deferred, now: now) + } + + func testUnsupportedRestartsOnlyAfterItsThresholdWhenIdle() { + let due = Int(AppAttestStallRestartPolicy.unsupportedThreshold) + XCTAssertEqual(decide(.unsupported(seconds: 0)), .skip(.unsupportedBriefly)) + XCTAssertEqual(decide(.unsupported(seconds: due - 1)), .skip(.unsupportedBriefly)) + XCTAssertEqual(decide(.unsupported(seconds: due)), .restart) + XCTAssertEqual(decide(.unsupported(seconds: due), inference: true), .skip(.inferenceActive)) + XCTAssertEqual(decide(.unsupported(seconds: due), lifecycle: true), .skip(.lifecycleBusy)) + XCTAssertEqual(decide(.unsupported(seconds: due), deferred: true), .skip(.retryDeferred)) + XCTAssertEqual(decide(nil), .skip(.notStalled)) + // The stalled-seconds entry point and the trigger entry point agree. + XCTAssertEqual(decide(.stalled(seconds: stalled)), decide(stalledSeconds: stalled)) + XCTAssertEqual(decide(.stalled(seconds: Int(AppleOperationStall.threshold))), .skip(.notStalled)) + } + + func testUnsupportedAndStallRestartsShareOneLimit() { + let due = Int(AppAttestStallRestartPolicy.unsupportedThreshold) + let interval = AppAttestStallRestartPolicy.minimumInterval + // A stall restart one hour ago blocks an unsupported restart, and the reverse: + // both write and read the same marker. + XCTAssertEqual(decide(.unsupported(seconds: due), last: now.addingTimeInterval(-3600)), .skip(.recentlyRestarted)) + XCTAssertEqual(decide(.stalled(seconds: stalled), last: now.addingTimeInterval(-3600)), .skip(.recentlyRestarted)) + XCTAssertEqual(decide(.unsupported(seconds: due), last: now.addingTimeInterval(-interval)), .restart) + XCTAssertEqual(decide(.unsupported(seconds: due), last: now.addingTimeInterval(3600)), .skip(.recentlyRestarted)) + } + + func testUnsupportedRecoveryDuringDrainCancelsTheRestart() { + XCTAssertEqual(AppAttestStallRestartPolicy.afterDrain(updateOwnsDrain: true, stillBlocked: true), .restart) + XCTAssertEqual(AppAttestStallRestartPolicy.afterDrain(updateOwnsDrain: true, stillBlocked: false), .recovered) + XCTAssertEqual(AppAttestStallRestartPolicy.afterDrain(updateOwnsDrain: false, stillBlocked: true), .lifecycleTookOver) + XCTAssertEqual(AppAttestStallRestartPolicy.afterDrain(updateOwnsDrain: false, stillBlocked: false), .lifecycleTookOver) + } + + func testUnsupportedRestartNeedsRecentVerificationLaunchdAndAValidProfile() { + func eligible(verified: Date?, launchd: Bool = true, expired: Bool? = false) -> Bool { + AppAttestStallRestartPolicy.unsupportedRestartEligible( + lastVerifiedAt: verified, relaunchesThroughLaunchd: launchd, profileExpired: expired, now: now) + } + let window = AppAttestStallRestartPolicy.verifiedWithin + XCTAssertTrue(eligible(verified: now.addingTimeInterval(-3600))) + XCTAssertTrue(eligible(verified: now.addingTimeInterval(-3600), expired: nil), "an unknown profile state does not block") + XCTAssertFalse(eligible(verified: nil), "a Mac never verified may not support App Attest at all") + XCTAssertFalse(eligible(verified: now.addingTimeInterval(-window))) + XCTAssertFalse(eligible(verified: now.addingTimeInterval(-3600), launchd: false), + "an in-place exec is never the remedy") + XCTAssertFalse(eligible(verified: now.addingTimeInterval(-3600), expired: true), + "a restart cannot renew an expired profile") + } + + func testVerifiedMarkerPersistsAndFailsClosedWhenDamaged() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + let marker = AppAttestVerifiedMarker(directory: directory) + XCTAssertNil(marker.lastVerified()) + try marker.record(now) + XCTAssertEqual(AppAttestVerifiedMarker(directory: directory).lastVerified(), now) + let mode = try FileManager.default.attributesOfItem(atPath: marker.url.path)[.posixPermissions] as? Int + XCTAssertEqual(mode, 0o600) + + try Data("not json".utf8).write(to: marker.url) + XCTAssertNil(marker.lastVerified(), "a damaged marker is no evidence, so no restart") + } } diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ProviderAuthorizationConnectionTests.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ProviderAuthorizationConnectionTests.swift index fb00d850ee..6e61e6ba49 100644 --- a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ProviderAuthorizationConnectionTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ProviderAuthorizationConnectionTests.swift @@ -16,8 +16,10 @@ import Testing provider: ProviderSettings(name: "authorization-test"), backend: BackendSettings(), coordinator: CoordinatorSettings())) let loop = try ProviderLoop(config: config, attestationSigner: nil) - let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: stateURL) } + // Its own directory: an App Attest grant also writes a marker beside the state file. + let stateDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let stateURL = stateDirectory.appendingPathComponent("state.json") + defer { try? FileManager.default.removeItem(at: stateDirectory) } await loop.installAuthorizationStateFileForTesting(stateURL) let authorization = ProviderAuthorizationStatus( appAttestAvailable: true, path: "app_attest", @@ -87,8 +89,9 @@ import Testing /// threshold passes, and clears the clock when the coordinator authorizes /// the connection. @Test func unauthorizedConnectionIsReportedAndReregisteredAfterTheThreshold() async throws { - let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: stateURL) } + let stateDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let stateURL = stateDirectory.appendingPathComponent("state.json") + defer { try? FileManager.default.removeItem(at: stateDirectory) } let loop = try await Self.makeLoop(stateURL: stateURL) let t0 = Date().timeIntervalSince1970 @@ -138,8 +141,9 @@ import Testing /// log that the coordinator is not routing it, or tell `status` it is /// excluded or needs macOS 27. @Test func aRegistrationRefusalAloneNeverReregisters() async throws { - let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: stateURL) } + let stateDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let stateURL = stateDirectory.appendingPathComponent("state.json") + defer { try? FileManager.default.removeItem(at: stateDirectory) } let logs = PublicLogLines() let loop = try await Self.makeLoop(stateURL: stateURL, logs: logs) @@ -173,8 +177,9 @@ import Testing /// An App Attest lease names its own expiry. Once it passes without a /// renewal the connection is refused, however old that status is. @Test func anExpiredLeaseIsJudgedWithoutAFreshStatus() async throws { - let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: stateURL) } + let stateDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let stateURL = stateDirectory.appendingPathComponent("state.json") + defer { try? FileManager.default.removeItem(at: stateDirectory) } let loop = try await Self.makeLoop(stateURL: stateURL) let t0 = Date().timeIntervalSince1970 @@ -199,8 +204,9 @@ import Testing /// routes the connection: the clock stops and the backoff resets. A /// refusal sent after that request counts again. @Test func aRoutedRequestOutweighsAnEarlierRefusal() async throws { - let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: stateURL) } + let stateDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let stateURL = stateDirectory.appendingPathComponent("state.json") + defer { try? FileManager.default.removeItem(at: stateDirectory) } let logs = PublicLogLines() let loop = try await Self.makeLoop(stateURL: stateURL, logs: logs) @@ -230,8 +236,9 @@ import Testing /// When the coordinator stops repeating a refusal, the provider stops /// counting it, and the log says routing is unconfirmed, not resumed. @Test func aRefusalTheCoordinatorStopsRepeatingIsLoggedAsUnconfirmed() async throws { - let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: stateURL) } + let stateDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let stateURL = stateDirectory.appendingPathComponent("state.json") + defer { try? FileManager.default.removeItem(at: stateDirectory) } let logs = PublicLogLines() let loop = try await Self.makeLoop(stateURL: stateURL, logs: logs) @@ -252,8 +259,9 @@ import Testing /// up to every 30 s. `status` must still say how long the connection has /// been down, not how long ago the last attempt failed. @Test func aFailingReconnectKeepsTheTimeTheConnectionWentDown() async throws { - let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: stateURL) } + let stateDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let stateURL = stateDirectory.appendingPathComponent("state.json") + defer { try? FileManager.default.removeItem(at: stateDirectory) } let loop = try await Self.makeLoop(stateURL: stateURL) let t0 = 1_000_000.0 @@ -284,8 +292,9 @@ import Testing /// Re-registering drains admission, which fails an accepted Autopilot /// command partway (after its victims unloaded, before its target loads). @Test func reregistrationWaitsForAnAcceptedAutopilotCommand() async throws { - let stateURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: stateURL) } + let stateDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let stateURL = stateDirectory.appendingPathComponent("state.json") + defer { try? FileManager.default.removeItem(at: stateDirectory) } let loop = try await Self.makeLoop(stateURL: stateURL) let t0 = Date().timeIntervalSince1970 diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift index 2cf1dc1f52..35f42efeb8 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift @@ -173,3 +173,14 @@ struct ProcessLifecycleTests { output: "disabled services = { \"provider\" => enabled \"watchdog\" => disabled }") #expect(modern == ["provider": true, "watchdog": false]) } + +/// A self-update or App Attest restart of a provider that launchd runs goes +/// through launchd; any other provider keeps the in-place exec. +@Test func relaunchRouteUsesLaunchdOnlyForTheLaunchdJobItself() { + #expect(ProcessLifecycle.RelaunchRoute.decide(agentLoaded: true, launchedByLaunchd: true) == .launchd) + // A foreground `start` beside a loaded agent must not hand its work to the agent. + #expect(ProcessLifecycle.RelaunchRoute.decide(agentLoaded: true, launchedByLaunchd: false) == .exec) + // launchd started this process, but its job was unloaded since: kickstart has no job. + #expect(ProcessLifecycle.RelaunchRoute.decide(agentLoaded: false, launchedByLaunchd: true) == .exec) + #expect(ProcessLifecycle.RelaunchRoute.decide(agentLoaded: false, launchedByLaunchd: false) == .exec) +} diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift index 9b63477c38..390b3de5c1 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift @@ -27,6 +27,11 @@ private func lifecycleClient(url: String, state: ProviderState) -> CoordinatorCl private extension ProviderLoop { func installAppAttestWorker(_ worker: any AppAttestWorkerExchangeClient) { appAttestWorkerClient = worker } + /// Fakes only the launchd boundary and Apple's live `isSupported`. + func setAppAttestRestartSeams(route: ProcessLifecycle.RelaunchRoute, supported: Bool) { + appAttestRelaunchRoute = { route } + appAttestSupportProbe = { supported } + } func holdLifecycleRequests(_ ids: Set) { acceptedLifecycleRequests.formUnion(ids) } func completeLifecycleRequest(_ id: String) { acceptedLifecycleRequests.remove(id) } func installCancellableLifecycleRequest(_ id: String) { @@ -286,3 +291,111 @@ struct ProviderLifecycleTests { #expect(barrier != nil) } } + +private func unsupportedReady(profileExpired: Bool? = false) -> AppAttestLocalStatus { + AppAttestLocalStatus(observedAt: 0, launchSession: .gui, availabilityReason: .isSupportedFalse, + process: AppAttestProcessDiagnostics(preflight: AppAttestPreflight(profileExpired: profileExpired))) +} + +private func appAttestGrant(expiresAt: Double, path: String = "app_attest") -> ProviderAuthorizationStatus { + ProviderAuthorizationStatus(appAttestAvailable: true, path: path, expiresAt: expiresAt, + sessionID: "connection", machineID: "machine") +} + +/// Whole seconds, so dates survive the JSON marker unchanged. +private func wholeSecondsNow() -> Date { Date(timeIntervalSince1970: Date().timeIntervalSince1970.rounded(.down)) } + +@Suite("App Attest unsupported restart") +struct AppAttestUnsupportedRestartTests { + @Test func unsupportedOnAVerifiedLaunchdMacBecomesATriggerUntilAppleAnswersSupported() async throws { + let (loop, root) = try await lifecycleLoop() + defer { try? FileManager.default.removeItem(at: root) } + await loop.setAppAttestRestartSeams(route: .launchd, supported: false) + let start = wholeSecondsNow() + // An earlier coordinator grant on this Mac is the evidence of verification. + await loop.handleTrustStatus(trustLevel: "self_signed", status: "online", reason: "", + authorization: appAttestGrant(expiresAt: start.timeIntervalSince1970 + 900), + receivedAt: start.timeIntervalSince1970) + #expect(AppAttestVerifiedMarker(directory: root).lastVerified() == start) + + await loop.noteAppAttestAvailability(unsupportedReady(), now: start) + #expect(await loop.appAttestUnsupportedSince == start) + // A later unsupported `ready` keeps the first observation. + await loop.noteAppAttestAvailability(unsupportedReady(), now: start.addingTimeInterval(60)) + #expect(await loop.appAttestUnsupportedSince == start) + + let due = AppAttestStallRestartPolicy.unsupportedThreshold + let trigger = await loop.appAttestRestartTrigger(heldSince: nil, now: start.addingTimeInterval(due)) + #expect(trigger == .unsupported(seconds: Int(due))) + #expect(AppAttestStallRestartPolicy.decide(trigger: trigger, inferenceActive: false, lifecycleBusy: false, + lastRestartAt: nil, retryDeferred: false, now: start.addingTimeInterval(due)) == .restart) + // An unanswered Apple call outranks it: that is the stall restart. + #expect(await loop.appAttestRestartTrigger(heldSince: start, now: start.addingTimeInterval(due)) + == .stalled(seconds: Int(due))) + + // Apple answers supported again inside the same process: no restart. + await loop.setAppAttestRestartSeams(route: .launchd, supported: true) + #expect(await loop.appAttestRestartTrigger(heldSince: nil, now: start.addingTimeInterval(due)) == nil) + #expect(await loop.appAttestUnsupportedSince == nil) + await loop.cancelAppAttestStallMonitor() + } + + @Test func unsupportedNeverArmsWithoutVerificationLaunchdOrAValidProfile() async throws { + let (loop, root) = try await lifecycleLoop() + defer { try? FileManager.default.removeItem(at: root) } + await loop.setAppAttestRestartSeams(route: .launchd, supported: false) + let start = wholeSecondsNow() + + // Never verified: this Mac may not support App Attest at all. + await loop.noteAppAttestAvailability(unsupportedReady(), now: start) + #expect(await loop.appAttestUnsupportedSince == nil) + #expect(await loop.appAttestRestartTrigger(heldSince: nil, now: start.addingTimeInterval(3600)) == nil) + + // A legacy path or an expired lease is not verification. + await loop.handleTrustStatus(trustLevel: "self_signed", status: "online", reason: "", + authorization: appAttestGrant(expiresAt: start.timeIntervalSince1970 + 900, path: "legacy"), + receivedAt: start.timeIntervalSince1970) + await loop.handleTrustStatus(trustLevel: "self_signed", status: "online", reason: "", + authorization: appAttestGrant(expiresAt: start.timeIntervalSince1970 - 1), + receivedAt: start.timeIntervalSince1970) + #expect(AppAttestVerifiedMarker(directory: root).lastVerified() == nil) + + try AppAttestVerifiedMarker(directory: root).record(start) + // A provider that launchd does not run would restart by exec: never for this state. + await loop.setAppAttestRestartSeams(route: .exec, supported: false) + await loop.noteAppAttestAvailability(unsupportedReady(), now: start) + #expect(await loop.appAttestUnsupportedSince == nil) + + // A restart cannot renew an expired provisioning profile. + await loop.setAppAttestRestartSeams(route: .launchd, supported: false) + await loop.noteAppAttestAvailability(unsupportedReady(profileExpired: true), now: start) + #expect(await loop.appAttestUnsupportedSince == nil) + + // Eligible, then a `ready` with any other answer clears it. + await loop.noteAppAttestAvailability(unsupportedReady(), now: start) + #expect(await loop.appAttestUnsupportedSince == start) + await loop.noteAppAttestAvailability(AppAttestLocalStatus(observedAt: 0, launchSession: .gui), now: start) + #expect(await loop.appAttestUnsupportedSince == nil) + await loop.cancelAppAttestStallMonitor() + } + + @Test func verifiedMarkerIsRewrittenAtMostOncePerInterval() async throws { + let (loop, root) = try await lifecycleLoop() + defer { try? FileManager.default.removeItem(at: root) } + let start = wholeSecondsNow() + func grant(at date: Date) async { + await loop.handleTrustStatus(trustLevel: "self_signed", status: "online", reason: "", + authorization: appAttestGrant(expiresAt: date.timeIntervalSince1970 + 900), + receivedAt: date.timeIntervalSince1970) + } + let marker = AppAttestVerifiedMarker(directory: root) + await grant(at: start) + #expect(marker.lastVerified() == start) + // Leases renew every few seconds; the marker does not. + await grant(at: start.addingTimeInterval(60)) + #expect(marker.lastVerified() == start) + let later = start.addingTimeInterval(AppAttestVerifiedMarker.refreshInterval) + await grant(at: later) + #expect(marker.lastVerified() == later) + } +} From a01955027f7d51f6328a05a7f4e0f30c4560d7a4 Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 21:26:28 -0600 Subject: [PATCH 0186/1441] docs(provider): state the overdue registration check exactly The protocol reference said the bounded wait applies when only in-flight work or a live lease deferred it during the whole wait. The code checks this at the overdue tick only. Say so. The inventoryRegistrationAllowed comment said "no transition". The check refuses every busy reason. Say so. Co-Authored-By: Claude Opus 5.5 --- docs/reference/protocol-messages.md | 4 ++-- .../Autopilot/ProviderLoop+AutopilotModelSet.swift | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/reference/protocol-messages.md b/docs/reference/protocol-messages.md index 97bfb2e37b..5c31531cbc 100644 --- a/docs/reference/protocol-messages.md +++ b/docs/reference/protocol-messages.md @@ -1428,8 +1428,8 @@ registration inventory, and sends **no** `models_update`, because that would mak it ordinary and publicly routable. It never loads or advertises the build; an Autopilot operation may load it. With consent but downloads off, such a request is refused `model_not_selected` and never takes the ordinary path. The provider then re-registers once when idle (no busy reason, -operation, live lease or other download), or after a bounded wait during which -only in-flight work or a live lease deferred it, +operation, live lease or other download), or, after a bounded wait, when only +in-flight work or a live lease defers it, so `register.autopilot_inventory` carries the build's `ModelInfo` ([Autopilot set](../architecture/model-autopilot.md#the-autopilot-model-set)). diff --git a/provider-swift/Sources/ProviderCore/Autopilot/ProviderLoop+AutopilotModelSet.swift b/provider-swift/Sources/ProviderCore/Autopilot/ProviderLoop+AutopilotModelSet.swift index 3dbeaf51ef..d0efe42639 100644 --- a/provider-swift/Sources/ProviderCore/Autopilot/ProviderLoop+AutopilotModelSet.swift +++ b/provider-swift/Sources/ProviderCore/Autopilot/ProviderLoop+AutopilotModelSet.swift @@ -140,8 +140,8 @@ extension ProviderLoop { } /// Rechecked after every hop: consent, a reported set, no operation, no - /// transition and the background verification finished. Before the wait - /// is overdue, also no live lease and no in-flight work. + /// busy reason and the background verification finished. Once the wait + /// is overdue, a live lease and in-flight work no longer count. private func inventoryRegistrationAllowed(overdue: Bool) -> Bool { !autopilotInventoryAwaitingRegistration.isEmpty && autopilotConsented && !autopilotNeedsInventoryRefresh && (overdue || !modelAutopilotEnabled) && autopilotCommand == nil From e857ad695aabb44692c4f4989d0140fef2cb80ca Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 21:26:55 -0600 Subject: [PATCH 0187/1441] fix(provider): keep a cluster member's registered set unknown A cluster member registers an empty models list by design. Recording it made the Models page warn about every selected model on a member Mac. The set now stays unknown for a member. Co-Authored-By: Claude Opus 5.5 --- docs/reference/desktop-control.md | 2 +- .../Coordinator/CoordinatorClient+Registration.swift | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/reference/desktop-control.md b/docs/reference/desktop-control.md index e51516bd5b..8e9de73dc7 100644 --- a/docs/reference/desktop-control.md +++ b/docs/reference/desktop-control.md @@ -239,7 +239,7 @@ carries for the model (`DesktopBackend.modelRegistration`). | `routable` | In the registration's `models`. The network sends it requests. | | `autopilot` | In `autopilot_inventory` only. Autopilot can load it. | | `none` | In neither. The network does not know this Mac has it. | -| `null` | Not known: the daemon is stopped, stale, Local only, not connected, or older. | +| `null` | Not known: the daemon is stopped, stale, Local only, not connected, a cluster member, or older. | The daemon writes the set to `registered_models` in its state file: the `register` sent on the live connection, plus each written `models_update`, diff --git a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Registration.swift b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Registration.swift index f4612051d4..9e42b57087 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Registration.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Registration.swift @@ -74,7 +74,9 @@ extension CoordinatorClient { } if case .register(let sent) = registration { state.registeredAutopilotInventoryIDs = Set((sent.autopilotInventory ?? []).map(\.id)) - state.registeredModelIDs = Set(sent.models.map(\.id)) + // A cluster member's `models` is empty by design; its routing is the + // pair's, so the set stays unknown rather than empty. + state.registeredModelIDs = config.executionRole == .solo ? Set(sent.models.map(\.id)) : nil } } From 2c595d4bac1b08e3027622b8779444970fdf22db Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 21:29:12 -0600 Subject: [PATCH 0188/1441] ci: run the provider macOS jobs on Blacksmith only The provider shards, the shard summary, the SDK lane and the cluster metadata checks no longer ask the Darkbloom route for a runner. They run on blacksmith-12vcpu-macos-27. On Darkbloom macOS sandboxes (43 shard jobs, 2026-10-31 to 11-02) the median shard took 17.3 min against 9.8 min on Blacksmith. The depth-1 checkout took up to 22 min, the build almost never found a cache, and five shards stopped in checkout until the 60-minute timeout. The Linux lanes keep their route. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 27 ++++++++++++------------- docs/developer/build.md | 13 ++++++++++-- docs/developer/test.md | 6 +++--- scripts/test-ci-component-paths.py | 6 +++--- scripts/test-darkbloom-route.py | 14 ++++++------- scripts/test-provider-ci-workflow.py | 30 ++++++++++++---------------- 6 files changed, 50 insertions(+), 46 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 84db42949a..856a2a0774 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,9 +26,12 @@ jobs: permissions: contents: read - # Chooses a Darkbloom Sandbox or the Blacksmith fallback for each read-only - # job below. It follows the classifier so only jobs that will run are + # Chooses a Darkbloom Sandbox or the Blacksmith fallback for the read-only + # Linux jobs below. It follows the classifier so only jobs that will run are # requested, and still routes the unconditional jobs if the classifier fails. + # The macOS jobs run on Blacksmith only. On Darkbloom macOS sandboxes the + # checkout took up to 22 minutes, most builds were cold, and some jobs hung in + # checkout until the 60-minute timeout (docs/developer/build.md). route: needs: changes if: ${{ !cancelled() }} @@ -38,10 +41,6 @@ jobs: lanes: | release-integrity linux_arm64 blacksmith-4vcpu-ubuntu-2404 docs linux_arm64 blacksmith-4vcpu-ubuntu-2404 - test-provider macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 5 || 0 }} - test-provider-summary macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} - test-provider-sdk macos_arm64 blacksmith-12vcpu-macos-27 ${{ (github.event_name == 'push' || needs.changes.outputs.sdk == 'true') && 1 || 0 }} - test-cluster-checks macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} release-integrity: name: Release Integrity @@ -131,9 +130,9 @@ jobs: # below. Provider Unit Tests Summary # checks that the shards together executed the full suite and reports coverage. name: Provider Unit Tests (shard ${{ matrix.shard }}) - needs: [changes, route] + needs: changes if: ${{ needs.changes.outputs.provider == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-provider'] }} + runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 strategy: # A failed shard does not cancel the other shards. @@ -341,9 +340,9 @@ jobs: test-provider-summary: # Checks the shards against the full suite list and reports coverage. name: Provider Unit Tests Summary - needs: [changes, route, test-provider] + needs: [changes, test-provider] if: ${{ !cancelled() && needs.changes.outputs.provider == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-provider-summary'] }} + runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 30 steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 @@ -505,9 +504,9 @@ jobs: # SDK-lane input changes (scripts/ci-component-paths.py SDK); every push to # dev or master runs it, and a failure there notifies without blocking. name: Provider SDK Tests - needs: [changes, route] + needs: changes if: ${{ github.event_name == 'push' || needs.changes.outputs.sdk == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-provider-sdk'] }} + runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 @@ -675,9 +674,9 @@ jobs: # metadata and argument checks) and runs it on the retained fixtures: no GPU, # no model load, no weights. Every runner runs even after another fails. name: Cluster Metadata Checks - needs: [changes, route] + needs: changes if: ${{ needs.changes.outputs.provider == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-cluster-checks'] }} + runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 diff --git a/docs/developer/build.md b/docs/developer/build.md index d94463d575..56d4a25a9e 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build The Provider And Landing -> Last updated: 2026-10-31 +> Last updated: 2026-11-03 Build the provider, its source-matched native resources, and the independent landing site from this repository. Backend, sidecar, console and admin builds @@ -234,7 +234,6 @@ checkout. Each routed job runs on `fromJSON(needs.route.outputs.routes)['' | Workflow | Routed jobs | Fallback | |---|---|---| | `ci.yml` | `release-integrity`, `docs` | `blacksmith-4vcpu-ubuntu-2404` | -| `ci.yml` | `test-provider` (one per shard), `test-provider-summary`, `test-provider-sdk`, `test-cluster-checks` | `blacksmith-12vcpu-macos-27` | | `docs-impact.yml` | `commit-signatures`, `docs-impact` | `blacksmith-4vcpu-ubuntu-2404` | | `landing.yml`, `desktop.yml`, `nightly-linear-package.yml` | `check`, `frontend`, `test` | `blacksmith-4vcpu-ubuntu-2404` | | `provider-release-cache.yml` | `warm`, pull requests only | `blacksmith-12vcpu-macos-27` | @@ -252,6 +251,16 @@ Release, signing, publication, model registration, review automation, labels. The component classifier and the `Provider Tests` gate run on `ubuntu-24.04`. +The macOS jobs of `ci.yml` (`test-provider`, `test-provider-summary`, +`test-provider-sdk` and `test-cluster-checks`) are not routed. They always run +on `blacksmith-12vcpu-macos-27`. In 43 provider shard jobs on Darkbloom macOS +sandboxes (2026-10-31 to 11-02), the median job took 17.3 min against 9.8 min +on Blacksmith (362 jobs). The depth-1 checkout took 146 s at the median and up +to 22 min, against 13 s. The sandboxes found almost no build cache, and +uploading it took about 150 s. Five jobs stopped in checkout until the +60-minute job timeout. `scripts/test-darkbloom-route.py` keeps these jobs on +the literal label. + Jobs on Darkbloom Sandboxes use GitHub's Actions cache, not Blacksmith's colocated cache, so their first runs start without cached build products. Darkbloom Linux sandboxes are ARM64; the Blacksmith Linux fallback is x64. The diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..9775e8cbed 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-10-31 +> Last updated: 2026-11-03 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -1367,8 +1367,8 @@ HTTPS plane with a throwaway certificate; the host needs Bash, Python, jq, curl and openssl. It covers the default-off switch, fork pull requests, exact label grants, HTTP errors, the single retry, timeouts, untrusted or plain-HTTP planes and hostile reply text. It also pins each routed job's fallback, timeout and -read-only permissions, and keeps release workflows on literal Blacksmith -runners. No check contacts the real plane. +read-only permissions, and keeps release workflows and the macOS jobs of +`ci.yml` on literal Blacksmith runners. No check contacts the real plane. Docs-impact tests retain provider, protocol, privacy, native capacity, cache, release/model publication and fixture mappings. Historical links need exact diff --git a/scripts/test-ci-component-paths.py b/scripts/test-ci-component-paths.py index aa82c47eee..cc6b292a33 100644 --- a/scripts/test-ci-component-paths.py +++ b/scripts/test-ci-component-paths.py @@ -239,17 +239,17 @@ def test_expensive_jobs_depend_on_successful_classifier(self): # Runner routing follows the classifier, so only selected lanes are requested. self.assertIn(" needs: changes\n", jobs["route"]) for lane, component in lanes.items(): - self.assertIn(" needs: [changes, route]\n", jobs[lane]) + self.assertIn(" needs: changes\n", jobs[lane]) self.assertIn(" if: ${{ needs.changes.outputs." + component + " == 'true' }}\n", jobs[lane]) self.assertNotIn("continue-on-error:", jobs[lane]) ci = workflow.job_blocks((ROOT / ".github/workflows/ci.yml").read_text()) # The SDK lane runs on every push and on pull requests that change its inputs. - self.assertIn(" needs: [changes, route]\n", ci["test-provider-sdk"]) + self.assertIn(" needs: changes\n", ci["test-provider-sdk"]) self.assertIn(" if: ${{ github.event_name == 'push' || needs.changes.outputs.sdk == 'true' }}\n", ci["test-provider-sdk"]) self.assertNotIn("continue-on-error:", ci["test-provider-sdk"]) # The summary runs after failed shards too, but only when the shards were selected. - self.assertIn(" needs: [changes, route, test-provider]\n", ci["test-provider-summary"]) + self.assertIn(" needs: [changes, test-provider]\n", ci["test-provider-summary"]) self.assertIn(" if: ${{ !cancelled() && needs.changes.outputs.provider == 'true' }}\n", ci["test-provider-summary"]) self.assertNotIn("continue-on-error:", ci["test-provider-summary"]) diff --git a/scripts/test-darkbloom-route.py b/scripts/test-darkbloom-route.py index 9773e5e606..06fa766d9f 100755 --- a/scripts/test-darkbloom-route.py +++ b/scripts/test-darkbloom-route.py @@ -39,19 +39,12 @@ "warm": MACOS_FALLBACK, "docs": LINUX_FALLBACK} GRANTED = {"release-integrity": LINUX, "test-provider": MACOS, "warm": MACOS, "docs": LINUX_FALLBACK} -PROVIDER = "${{ needs.changes.outputs.provider == 'true' && 1 || 0 }}" -PROVIDER_SHARDS = "${{ needs.changes.outputs.provider == 'true' && 5 || 0 }}" -SDK = "${{ (github.event_name == 'push' || needs.changes.outputs.sdk == 'true') && 1 || 0 }}" PULL_REQUEST_WARM = "${{ github.event_name == 'pull_request' && 2 || 0 }}" # Every routed job: (profile, fallback label, count expression or None for 1). ROUTED = { "ci.yml": { "release-integrity": ("linux_arm64", LINUX_FALLBACK, None), "docs": ("linux_arm64", LINUX_FALLBACK, None), - "test-provider": ("macos_arm64", MACOS_FALLBACK, PROVIDER_SHARDS), - "test-provider-summary": ("macos_arm64", MACOS_FALLBACK, PROVIDER), - "test-provider-sdk": ("macos_arm64", MACOS_FALLBACK, SDK), - "test-cluster-checks": ("macos_arm64", MACOS_FALLBACK, PROVIDER), }, "docs-impact.yml": { "commit-signatures": ("linux_arm64", LINUX_FALLBACK, None), @@ -66,6 +59,9 @@ UNROUTED = ("release-swift.yml", "release-provider.yml", "release-dev-branch.yml", "release-desktop.yml", "provider-signing-validation.yml", "register-model.yml", "threat-model-review.yml", "bedrock-smoke.yml", "claude.yml", "codex.yml") +# The CI macOS jobs never route: on Darkbloom macOS sandboxes their checkout and +# cold builds made them about twice as slow as on Blacksmith (build.md). +CI_MACOS_JOBS = ("test-provider", "test-provider-summary", "test-provider-sdk", "test-cluster-checks") # Master and dispatched warming feed release builds, so only PRs read the route. RUNS_ON = {"warm": "${{ github.event_name == 'pull_request' && " "fromJSON(needs.route.outputs.routes)['warm'] || 'blacksmith-12vcpu-macos-27' }}"} @@ -557,6 +553,10 @@ def test_release_and_credentialed_workflows_keep_literal_runners(self): self.assertRegex(job_field(job, "runs-on"), r"^(blacksmith-[a-z0-9-]+|ubuntu-24\.04)$") ci = jobs(self.texts["ci.yml"]) self.assertEqual(job_field(ci["cache-swift"], "runs-on"), MACOS_FALLBACK) + for name in CI_MACOS_JOBS: + with self.subTest(workflow="ci.yml", job=name): + self.assertEqual(job_field(ci[name], "runs-on"), MACOS_FALLBACK) + self.assertNotIn("route", needs(ci[name])) def test_classifier_gate_and_route_need_no_routed_runner(self): ci = jobs(self.texts["ci.yml"]) diff --git a/scripts/test-provider-ci-workflow.py b/scripts/test-provider-ci-workflow.py index c41a9aa722..05727be422 100644 --- a/scripts/test-provider-ci-workflow.py +++ b/scripts/test-provider-ci-workflow.py @@ -195,20 +195,16 @@ def test_lanes_are_independent_on_dedicated_supported_mac_runners(self): for job_id, lane in LANES.items(): with self.subTest(lane=lane): job = self.jobs[job_id] - # A Darkbloom macOS sandbox when granted, otherwise the same - # dedicated Blacksmith runner; requested only when the lane runs. - self.assertIn(" runs-on: ${{ fromJSON(needs.route.outputs.routes)['%s'] }}\n" % job_id, job) - # The provider lane asks for one runner per shard. The SDK lane - # runs on every push and on pull requests that change its inputs. - count = 5 if job_id == "test-provider" else 1 + # A dedicated Blacksmith Mac per job (per shard); the Darkbloom + # route never chooses a macOS runner for these lanes. + self.assertIn(" runs-on: blacksmith-12vcpu-macos-27\n", job) + self.assertNotIn(f" {job_id} ", self.jobs["route"]) + # The SDK lane runs on every push and on pull requests that + # change its inputs. condition = (SDK_CONDITION if job_id == "test-provider-sdk" else "needs.changes.outputs.provider == 'true'") - requested = f"({condition})" if "||" in condition else condition - self.assertIn(" %s macos_arm64 blacksmith-12vcpu-macos-27 " - "${{ %s && %d || 0 }}\n" % (job_id, requested, count), - self.jobs["route"]) self.assertIn(" timeout-minutes: 60\n", job) - self.assertIn(" needs: [changes, route]\n", job) + self.assertIn(" needs: changes\n", job) self.assertIn(" if: ${{ %s }}\n" % condition, job) if job_id == "test-provider": # Shards are independent: a failed shard never cancels another. @@ -294,9 +290,10 @@ def test_only_the_provider_lane_collects_and_reports_coverage(self): # build and writes the report; the gate requires it. summary = self.jobs["test-provider-summary"] self.assertIn(" name: Provider Unit Tests Summary\n", summary) - self.assertIn(" needs: [changes, route, test-provider]\n", summary) + self.assertIn(" needs: [changes, test-provider]\n", summary) self.assertIn(" if: ${{ !cancelled() && needs.changes.outputs.provider == 'true' }}\n", summary) - self.assertIn(" runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-provider-summary'] }}\n", summary) + self.assertIn(" runs-on: blacksmith-12vcpu-macos-27\n", summary) + self.assertNotIn(" test-provider-summary ", self.jobs["route"]) self.assertNotIn("continue-on-error:", summary) summary_steps = step_blocks(summary) summary_names = [field(step, "name", indent=6) for step in summary_steps] @@ -644,11 +641,10 @@ def test_audio_qualification_uses_real_codec_and_no_skip_gate(self): def test_cluster_metadata_runners_run_every_runner_and_fail_on_any(self): job = self.jobs["test-cluster-checks"] self.assertIn(" name: Cluster Metadata Checks\n", job) - self.assertIn(" needs: [changes, route]\n", job) + self.assertIn(" needs: changes\n", job) self.assertIn(" if: ${{ needs.changes.outputs.provider == 'true' }}\n", job) - self.assertIn(" runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-cluster-checks'] }}\n", job) - self.assertIn(" test-cluster-checks macos_arm64 blacksmith-12vcpu-macos-27 " - "${{ needs.changes.outputs.provider == 'true' && 1 || 0 }}\n", self.jobs["route"]) + self.assertIn(" runs-on: blacksmith-12vcpu-macos-27\n", job) + self.assertNotIn(" test-cluster-checks ", self.jobs["route"]) for forbidden in ("continue-on-error:", "secrets.", "DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST:"): self.assertNotIn(forbidden, job) steps = step_blocks(job) From ae4122f1e11b3c791173b70ef9331cdb6c460070 Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 21:32:48 -0600 Subject: [PATCH 0189/1441] ci: refactor pass: route comment, test comment and routing doc wording Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 7 ++----- docs/developer/build.md | 8 ++++---- scripts/test-darkbloom-route.py | 3 +-- 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 856a2a0774..f7d0d0516c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,11 +27,8 @@ jobs: contents: read # Chooses a Darkbloom Sandbox or the Blacksmith fallback for the read-only - # Linux jobs below. It follows the classifier so only jobs that will run are - # requested, and still routes the unconditional jobs if the classifier fails. - # The macOS jobs run on Blacksmith only. On Darkbloom macOS sandboxes the - # checkout took up to 22 minutes, most builds were cold, and some jobs hung in - # checkout until the 60-minute timeout (docs/developer/build.md). + # Linux jobs below. It waits for the classifier but still runs if it fails. + # The macOS jobs are not routed (docs/developer/build.md). route: needs: changes if: ${{ !cancelled() }} diff --git a/docs/developer/build.md b/docs/developer/build.md index 56d4a25a9e..5aab945daa 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -256,10 +256,10 @@ The macOS jobs of `ci.yml` (`test-provider`, `test-provider-summary`, on `blacksmith-12vcpu-macos-27`. In 43 provider shard jobs on Darkbloom macOS sandboxes (2026-10-31 to 11-02), the median job took 17.3 min against 9.8 min on Blacksmith (362 jobs). The depth-1 checkout took 146 s at the median and up -to 22 min, against 13 s. The sandboxes found almost no build cache, and -uploading it took about 150 s. Five jobs stopped in checkout until the -60-minute job timeout. `scripts/test-darkbloom-route.py` keeps these jobs on -the literal label. +to 22 min, against 13 s on Blacksmith. The sandboxes found almost no build +cache. Saving the cache took about 150 s. Five jobs stopped in checkout until +the 60-minute job timeout. `scripts/test-darkbloom-route.py` checks that these +jobs keep the literal label. Jobs on Darkbloom Sandboxes use GitHub's Actions cache, not Blacksmith's colocated cache, so their first runs start without cached build products. diff --git a/scripts/test-darkbloom-route.py b/scripts/test-darkbloom-route.py index 06fa766d9f..b082546650 100755 --- a/scripts/test-darkbloom-route.py +++ b/scripts/test-darkbloom-route.py @@ -59,8 +59,7 @@ UNROUTED = ("release-swift.yml", "release-provider.yml", "release-dev-branch.yml", "release-desktop.yml", "provider-signing-validation.yml", "register-model.yml", "threat-model-review.yml", "bedrock-smoke.yml", "claude.yml", "codex.yml") -# The CI macOS jobs never route: on Darkbloom macOS sandboxes their checkout and -# cold builds made them about twice as slow as on Blacksmith (build.md). +# The CI macOS jobs keep their literal Blacksmith label (build.md, CI Runner Routing). CI_MACOS_JOBS = ("test-provider", "test-provider-summary", "test-provider-sdk", "test-cluster-checks") # Master and dispatched warming feed release builds, so only PRs read the route. RUNS_ON = {"warm": "${{ github.event_name == 'pull_request' && " From c178d0edac975a8b3f9b1c7bc0d1000d7a5e44f8 Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 22:04:24 -0600 Subject: [PATCH 0190/1441] Pin libs/mlx-swift-lm to SDK main 747dd09c SDK PRs #370, #371, #382 and #377 merged into mlx-swift-lm main with merge commits. This moves the submodule from the PR head 86a5e4c4 to the SDK main merge 747dd09cfd2566e695b2c77a11bc8e0d2fdc0a44, which contains it. The provider PRs #1668, #1669, #1713 and #1722 now carry the same pin, so they no longer conflict on the submodule. Co-Authored-By: Claude Opus 5.5 --- libs/mlx-swift-lm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 86a5e4c425..747dd09cfd 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 86a5e4c4258628f2c0751286e0cccc8ec831644d +Subproject commit 747dd09cfd2566e695b2c77a11bc8e0d2fdc0a44 From 70e9a52ee5999712ae1cf2d97e983dd06654a3d5 Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 22:04:24 -0600 Subject: [PATCH 0191/1441] Pin libs/mlx-swift-lm to SDK main 747dd09c SDK PRs #370, #371, #382 and #377 merged into mlx-swift-lm main with merge commits. This moves the submodule from the PR head a4583d2a to the SDK main merge 747dd09cfd2566e695b2c77a11bc8e0d2fdc0a44, which contains it. The provider PRs #1668, #1669, #1713 and #1722 now carry the same pin, so they no longer conflict on the submodule. Co-Authored-By: Claude Opus 5.5 --- libs/mlx-swift-lm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index a4583d2ac1..747dd09cfd 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit a4583d2ac14a778989929d51464350d0adb61a32 +Subproject commit 747dd09cfd2566e695b2c77a11bc8e0d2fdc0a44 From 0e65e5d694cfae80d3090962179b879100aab7e3 Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 22:04:25 -0600 Subject: [PATCH 0192/1441] Pin libs/mlx-swift-lm to SDK main 747dd09c SDK PRs #370, #371, #382 and #377 merged into mlx-swift-lm main with merge commits. This moves the submodule from the PR head 63baac23 to the SDK main merge 747dd09cfd2566e695b2c77a11bc8e0d2fdc0a44, which contains it. The provider PRs #1668, #1669, #1713 and #1722 now carry the same pin, so they no longer conflict on the submodule. Co-Authored-By: Claude Opus 5.5 --- libs/mlx-swift-lm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 63baac23b1..747dd09cfd 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 63baac23b19997be1051994926a9b0decaff2455 +Subproject commit 747dd09cfd2566e695b2c77a11bc8e0d2fdc0a44 From 64629196944d73d4275159520bfa7506b4159586 Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 22:04:26 -0600 Subject: [PATCH 0193/1441] Pin libs/mlx-swift-lm to SDK main 747dd09c SDK PRs #370, #371, #382 and #377 merged into mlx-swift-lm main with merge commits. This moves the submodule from the PR head ad2ed74b to the SDK main merge 747dd09cfd2566e695b2c77a11bc8e0d2fdc0a44, which contains it. The provider PRs #1668, #1669, #1713 and #1722 now carry the same pin, so they no longer conflict on the submodule. Co-Authored-By: Claude Opus 5.5 --- libs/mlx-swift-lm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index ad2ed74b7d..747dd09cfd 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit ad2ed74b7dbd60fa7f679dd81c8996dba89bf415 +Subproject commit 747dd09cfd2566e695b2c77a11bc8e0d2fdc0a44 From 52079c01127c56d9a54da08a2541f09419da5824 Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 22:04:36 -0600 Subject: [PATCH 0194/1441] Keep the dev default for plain builds when this lands in dev This PR is based on master and merges into dev. master carries e9babca43 ("Keep master's prod default for plain builds (release snapshot only)"), which sets the plain-build default back to prod for the dev-to-master release snapshot. Its message asks that the next master-into-dev sync revert it, so that a plain build of dev keeps talking to the DevNet coordinator (431a93d4a). This PR is the first of the 0.10.7 provider PRs to merge into dev, so it carries that sync. This commit reverts e9babca43: Package.swift defaults to dev again and BuildEnvironmentTests expects the branch default, as on dev. Released binaries do not change: every release lane and CI set DARKBLOOM_RELEASE_ENVIRONMENT explicitly. Co-Authored-By: Claude Opus 5.5 --- provider-swift/Package.swift | 2 +- .../ProviderCoreTests/Config/BuildEnvironmentTests.swift | 9 ++++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/provider-swift/Package.swift b/provider-swift/Package.swift index c8be5b8a35..e04193d90d 100644 --- a/provider-swift/Package.swift +++ b/provider-swift/Package.swift @@ -8,7 +8,7 @@ import Foundation // DARKBLOOM_RELEASE_ENVIRONMENT. On the dev branch every other build is dev: // it talks to the DevNet coordinator. On master it is prod. let releaseEnvironment = ProcessInfo.processInfo.environment["DARKBLOOM_RELEASE_ENVIRONMENT"] - .flatMap { $0.isEmpty ? nil : $0 } ?? "prod" + .flatMap { $0.isEmpty ? nil : $0 } ?? "dev" precondition(["prod", "dev", "staging"].contains(releaseEnvironment), "DARKBLOOM_RELEASE_ENVIRONMENT must be prod, dev or staging") let buildEnvironmentSwiftSettings: [SwiftSetting] diff --git a/provider-swift/Tests/ProviderCoreTests/Config/BuildEnvironmentTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/BuildEnvironmentTests.swift index f9da9b1e1b..6841118e77 100644 --- a/provider-swift/Tests/ProviderCoreTests/Config/BuildEnvironmentTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Config/BuildEnvironmentTests.swift @@ -5,12 +5,11 @@ import Testing @Suite("Build environment defaults") struct BuildEnvironmentTests { - /// A plain build of master is a prod build (on the dev branch it is a dev build). DARKBLOOM_RELEASE_ENVIRONMENT, - /// read by Package.swift when the tests are built, selects another: CI builds prod, the identity the provider - /// suites pin. - @Test func plainBuildsTakeTheBranchDefault() throws { + /// A plain build of the dev branch is a dev build. DARKBLOOM_RELEASE_ENVIRONMENT, read by Package.swift when + /// the tests are built, selects another: CI builds prod, the identity the provider suites pin. + @Test func devBranchBuildsDefaultToDevNet() throws { let requested = ProcessInfo.processInfo.environment["DARKBLOOM_RELEASE_ENVIRONMENT"] - .flatMap { $0.isEmpty ? nil : $0 } ?? "prod" + .flatMap { $0.isEmpty ? nil : $0 } ?? "dev" let built = try #require(BuildEnvironment(rawValue: requested)) let coordinator = built.coordinatorWebSocketURL let hardware = HardwareInfo( From 6bba9acb6823226eda1cc641c16ac1a39bbd809f Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 22:16:32 -0600 Subject: [PATCH 0195/1441] ci: save PR caches only on a cold restore, drop cache-swift, run eight provider shards - provider-ci-build and Cluster Metadata Checks: a push saves its build; a pull request saves only when it restored nothing. Later PR pushes no longer add 1.7 GB and 0.56 GB entries that evict the base branch's entries. - Remove cache-swift (Swift Build + Cache). It saved a release build that only its own next run restored. Folded in from PR 1309 by Gajesh2007. - Provider Unit Tests: eight shards instead of five, with the suite times measured in run 41572867304 (the newest dev-base summary upload). No test, selector, gate condition or coverage step changes. The release qualification lane keeps five shards and its own cache namespaces. Co-Authored-By: Claude Opus 5.5 --- .github/actions/provider-ci-build/action.yml | 5 +- .github/workflows/ci.yml | 52 +- docs/developer/build.md | 7 +- docs/developer/test.md | 9 +- scripts/provider-test-shard-weights.json | 1260 +++++++++--------- scripts/test-ci-component-paths.py | 2 +- scripts/test-darkbloom-route.py | 1 - scripts/test-provider-ci-workflow.py | 26 +- 8 files changed, 672 insertions(+), 690 deletions(-) diff --git a/.github/actions/provider-ci-build/action.yml b/.github/actions/provider-ci-build/action.yml index 0adbe70dfe..10c8521932 100644 --- a/.github/actions/provider-ci-build/action.yml +++ b/.github/actions/provider-ci-build/action.yml @@ -77,8 +77,11 @@ runs: id: timestamps shell: bash run: python3 scripts/provider-release-cache.py snapshot-mtimes + # Pushes save their build. A pull request saves only when it restored + # nothing, so its later pushes do not each add a 1.7 GB entry that evicts + # the base branch's entry from the repository cache. - name: Save lane-specific Swift test build - if: ${{ !cancelled() && steps.timestamps.outcome == 'success' && steps.swift-cache.outputs.cache-hit != 'true' }} + if: ${{ !cancelled() && steps.timestamps.outcome == 'success' && steps.swift-cache.outputs.cache-hit != 'true' && (github.event_name != 'pull_request' || steps.swift-cache.outputs.cache-matched-key == '') }} uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 with: path: | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f7d0d0516c..29801cc104 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -135,7 +135,7 @@ jobs: # A failed shard does not cancel the other shards. fail-fast: false matrix: - shard: [1, 2, 3, 4, 5] + shard: [1, 2, 3, 4, 5, 6, 7, 8] steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: @@ -726,13 +726,15 @@ jobs: DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS: '12' DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT: ${{ runner.temp }}/cluster-native-metadata run: bash libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh + # Pushes save the cluster build; a pull request saves it only when it + # restored nothing (as the provider lane's Swift build). - name: Record source timestamps for the cluster build - if: ${{ !cancelled() && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' }} + if: ${{ !cancelled() && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' && (github.event_name != 'pull_request' || steps.cluster-build-cache.outputs.cache-matched-key == '') }} run: | python3 scripts/provider-release-cache.py snapshot-mtimes cp provider-swift/.build/provider-release-source-mtimes.json "$RUNNER_TEMP/cluster-native-metadata/" - name: Upload cluster metadata build cache - if: ${{ !cancelled() && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' }} + if: ${{ !cancelled() && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' && (github.event_name != 'pull_request' || steps.cluster-build-cache.outputs.cache-matched-key == '') }} uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 with: path: ${{ runner.temp }}/cluster-native-metadata @@ -777,47 +779,3 @@ jobs: esac test "$UNIT_RESULT" = "$expected" test "$SUMMARY_RESULT" = "$expected" - - cache-swift: - name: Swift Build + Cache - runs-on: blacksmith-12vcpu-macos-27 - if: github.event_name == 'push' - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - with: - submodules: recursive - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: '3.12.10' - - name: Select SDK 27 provider toolchain - run: ./scripts/prepare-provider-release-toolchain.sh - - name: Restore SwiftPM cache - uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 - with: - path: | - ~/Library/Caches/org.swift.swiftpm - ~/Library/org.swift.swiftpm - provider-swift/.build - libs/mlx-swift-lm/.build - key: spm-v4-blacksmith-macos27-native-${{ runner.os }}-${{ github.sha }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }} - restore-keys: | - spm-v4-blacksmith-macos27-native-${{ runner.os }}- - - name: Discard metallibs restored by the generic SwiftPM cache - run: | - for root in provider-swift/.build libs/mlx-swift-lm/.build; do - [ ! -d "$root" ] || find "$root" -type f -name mlx.metallib -delete - done - - name: Build provider-swift - working-directory: provider-swift - run: | - swift build -c release --product darkbloom - swift build -c release --product darkbloom-fan-helper - - name: Save SwiftPM cache - uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 - with: - path: | - ~/Library/Caches/org.swift.swiftpm - ~/Library/org.swift.swiftpm - provider-swift/.build - libs/mlx-swift-lm/.build - key: spm-v4-blacksmith-macos27-native-${{ runner.os }}-${{ github.sha }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }} diff --git a/docs/developer/build.md b/docs/developer/build.md index 5aab945daa..9eeb32af3d 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -246,10 +246,9 @@ fallback and the plane is not contacted. When it is on, the route job sends one most once after a transient failure. It uses a grant only when the grant repeats the exact Darkbloom labels for the job's profile. Errors, timeouts and malformed replies keep the fallback; the plane never fails the route job. -Release, signing, publication, model registration, review automation, -`cache-swift` and `master` or dispatched cache warming keep literal Blacksmith -labels. The component classifier and the `Provider Tests` gate run on -`ubuntu-24.04`. +Release, signing, publication, model registration, review automation and +`master` or dispatched cache warming keep literal Blacksmith labels. The +component classifier and the `Provider Tests` gate run on `ubuntu-24.04`. The macOS jobs of `ci.yml` (`test-provider`, `test-provider-summary`, `test-provider-sdk` and `test-cluster-checks`) are not routed. They always run diff --git a/docs/developer/test.md b/docs/developer/test.md index 9775e8cbed..09b0dfc62d 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -95,7 +95,7 @@ snapshots. Preserve its watchdog, cleanup and state isolation when using a focus selector. Use `scripts/run-nested-suite.sh` for documented nested Swift Testing cases and `scripts/run-exclusive-native-gpu-test.sh` for exclusive native work. -CI runs the provider suite in five shards (`Provider Unit Tests (shard K)`), one +CI runs the provider suite in eight shards (`Provider Unit Tests (shard K)`), one Mac each. `PROVIDER_TEST_SHARD=K/N` selects a shard in `scripts/run-provider-tests.sh`, and `scripts/provider-test-shards.py` chooses its suites: @@ -117,6 +117,13 @@ When the shards drift apart, replace the weights file with that artifact. A suite moves from the parallel class to the serial class when it fails or flakes in parallel; when in doubt, a suite stays serial. +The provider lanes and Cluster Metadata Checks restore their build cache by the +exact key first, then by the key prefix. A push to `dev` or `master` saves its +build. A pull request saves its build only when it restored nothing. Its later +pushes then restore the base branch's build again, and the repository cache +(10 GB) keeps the base branch's entries. CI has no separate push-only Swift +cache job. + The SDK has independent test products under `libs/mlx-swift-lm`. CI validates native memory ownership, cancellation, media decoding, paged KV and resource packaging there as well as provider behavior. `Provider SDK Tests` is not part diff --git a/scripts/provider-test-shard-weights.json b/scripts/provider-test-shard-weights.json index d3722085a0..58e70a2918 100644 --- a/scripts/provider-test-shard-weights.json +++ b/scripts/provider-test-shard-weights.json @@ -1,158 +1,160 @@ { -"DarkbloomCLITests.AccountCommandRunTests": 1.571, -"DarkbloomCLITests.AddonCommandTests": 0.031, +"DarkbloomCLITests.AccountCommandRunTests": 1.556, +"DarkbloomCLITests.AddonCommandTests": 0.014, "DarkbloomCLITests.AdvertisedModelSelectionTests": 0.001, -"DarkbloomCLITests.AppAttestQualificationCommandTests": 4.258, -"DarkbloomCLITests.AutoUpdateCommandTests": 0.236, -"DarkbloomCLITests.AutopilotCommandTests": 0.915, -"DarkbloomCLITests.AutopilotDownloadCommandTests": 0.442, -"DarkbloomCLITests.AutopilotInventoryTests": 0.015, -"DarkbloomCLITests.AutopilotReplacementTests": 0.297, -"DarkbloomCLITests.AutopilotStartupSelectionTests": 0.001, -"DarkbloomCLITests.BenchmarkArrivalPromptTests": 0.0, -"DarkbloomCLITests.BenchmarkKVQuantizationOptionsTests": 0.07, -"DarkbloomCLITests.BenchmarkNativeBlockModeTests": 0.031, +"DarkbloomCLITests.AppAttestQualificationCommandTests": 4.303, +"DarkbloomCLITests.AutoUpdateCommandTests": 0.165, +"DarkbloomCLITests.AutopilotCommandTests": 0.919, +"DarkbloomCLITests.AutopilotDownloadCommandTests": 0.333, +"DarkbloomCLITests.AutopilotInventoryTests": 0.019, +"DarkbloomCLITests.AutopilotReplacementTests": 0.169, +"DarkbloomCLITests.AutopilotStartupSelectionTests": 0.0, +"DarkbloomCLITests.BenchmarkArrivalPromptTests": 0.001, +"DarkbloomCLITests.BenchmarkKVQuantizationOptionsTests": 0.075, +"DarkbloomCLITests.BenchmarkNativeBlockModeTests": 0.037, "DarkbloomCLITests.BenchmarkParityExitTests": 0.001, "DarkbloomCLITests.BenchmarkRuntimeGenerationOptionsTests": 0.094, -"DarkbloomCLITests.BenchmarkSchedulerPrefillDecisionTests": 0.066, -"DarkbloomCLITests.BenchmarkSchedulerPrefillPromptTests": 0.073, -"DarkbloomCLITests.BenchmarkSweepExitTests": 0.027, -"DarkbloomCLITests.BenchmarkTeacherForcedOptionsTests": 0.05, -"DarkbloomCLITests.BetaCommandRunTests": 1.454, -"DarkbloomCLITests.BetaCommandTests": 1.044, -"DarkbloomCLITests.BootSecurityWarningTests": 0.011, -"DarkbloomCLITests.CLIDispatchTests": 0.55, -"DarkbloomCLITests.CacheCommandTests": 0.457, -"DarkbloomCLITests.CatalogPickerFlowTests": 0.045, -"DarkbloomCLITests.ClusterCommandTests": 0.017, -"DarkbloomCLITests.ClusterConsoleCommandTests": 0.153, -"DarkbloomCLITests.ClusterMemberSupervisorTests": 10.295, -"DarkbloomCLITests.ClusterRuntimeFactsCommandTests": 0.006, -"DarkbloomCLITests.ClusterServiceLoginAgentTests": 2.531, -"DarkbloomCLITests.ClusterWorkerOwnerCommandTests": 0.007, +"DarkbloomCLITests.BenchmarkSchedulerPrefillDecisionTests": 0.07, +"DarkbloomCLITests.BenchmarkSchedulerPrefillPromptTests": 0.081, +"DarkbloomCLITests.BenchmarkSweepExitTests": 0.031, +"DarkbloomCLITests.BenchmarkTeacherForcedOptionsTests": 0.048, +"DarkbloomCLITests.BetaCommandRunTests": 1.634, +"DarkbloomCLITests.BetaCommandTests": 1.121, +"DarkbloomCLITests.BootSecurityWarningTests": 0.014, +"DarkbloomCLITests.CLIDispatchTests": 0.576, +"DarkbloomCLITests.CacheCommandTests": 0.512, +"DarkbloomCLITests.CatalogPickerFlowTests": 0.047, +"DarkbloomCLITests.ClusterCommandTests": 0.014, +"DarkbloomCLITests.ClusterConsoleCommandTests": 0.181, +"DarkbloomCLITests.ClusterMemberSupervisorTests": 10.162, +"DarkbloomCLITests.ClusterRuntimeFactsCommandTests": 0.015, +"DarkbloomCLITests.ClusterServiceLoginAgentTests": 2.552, +"DarkbloomCLITests.ClusterWorkerOwnerCommandTests": 0.019, "DarkbloomCLITests.DesktopAccountCloudTests": 0.002, -"DarkbloomCLITests.DesktopAccountEarningsTests": 0.006, +"DarkbloomCLITests.DesktopAccountEarningsTests": 0.007, "DarkbloomCLITests.DesktopAccountIdentityTests": 0.001, -"DarkbloomCLITests.DesktopActionArgumentsTests": 0.227, +"DarkbloomCLITests.DesktopActionArgumentsTests": 0.229, "DarkbloomCLITests.DesktopActivityTests": 0.001, -"DarkbloomCLITests.DesktopAutopilotTests": 0.042, -"DarkbloomCLITests.DesktopControlTests": 0.012, +"DarkbloomCLITests.DesktopAutopilotTests": 0.026, +"DarkbloomCLITests.DesktopControlTests": 0.016, "DarkbloomCLITests.DesktopCoolingAuthorizationTests": 0.0, -"DarkbloomCLITests.DesktopCoolingCacheTests": 0.988, +"DarkbloomCLITests.DesktopCoolingCacheTests": 0.998, +"DarkbloomCLITests.DesktopDownloadProgressTests": 0.0, "DarkbloomCLITests.DesktopExecutableWatchTests": 0.003, -"DarkbloomCLITests.DesktopHTTPErrorTests": 0.003, -"DarkbloomCLITests.DesktopHardwareRouteTests": 0.594, -"DarkbloomCLITests.DesktopMacStatsTests": 0.005, -"DarkbloomCLITests.DesktopRuntimeProfileTests": 1.247, -"DarkbloomCLITests.DesktopServiceTests": 0.004, -"DarkbloomCLITests.DesktopUsageHistoryTests": 0.015, -"DarkbloomCLITests.DesktopWorkerTests": 4.884, +"DarkbloomCLITests.DesktopHTTPErrorTests": 0.002, +"DarkbloomCLITests.DesktopHardwareRouteTests": 0.603, +"DarkbloomCLITests.DesktopMacStatsTests": 0.012, +"DarkbloomCLITests.DesktopRuntimeProfileTests": 1.299, +"DarkbloomCLITests.DesktopServiceTests": 0.005, +"DarkbloomCLITests.DesktopUsageHistoryTests": 0.019, +"DarkbloomCLITests.DesktopWorkerTests": 4.87, "DarkbloomCLITests.DeviceCheckEvidenceTests": 0.003, -"DarkbloomCLITests.DeviceCheckExtractionBoundsTests": 0.162, -"DarkbloomCLITests.DeviceCheckProcessTests": 0.617, -"DarkbloomCLITests.DiagnosticProbeTests": 0.0, -"DarkbloomCLITests.DistributedStartCommandTests": 0.072, -"DarkbloomCLITests.DistributedStartSessionFactoryTests": 0.014, -"DarkbloomCLITests.DistributedStartSignalLatchTests": 0.012, -"DarkbloomCLITests.DistributedStartSignalsTests": 0.974, +"DarkbloomCLITests.DeviceCheckExtractionBoundsTests": 0.165, +"DarkbloomCLITests.DeviceCheckProcessTests": 0.628, +"DarkbloomCLITests.DiagnosticProbeTests": 0.001, +"DarkbloomCLITests.DistributedStartCommandTests": 0.078, +"DarkbloomCLITests.DistributedStartSessionFactoryTests": 0.012, +"DarkbloomCLITests.DistributedStartSignalLatchTests": 0.016, +"DarkbloomCLITests.DistributedStartSignalsTests": 0.983, "DarkbloomCLITests.DoctorAttestationTests": 0.001, -"DarkbloomCLITests.DoctorCaptureTests": 7.308, -"DarkbloomCLITests.DoctorChecksTests": 0.42, -"DarkbloomCLITests.DoctorClearBackendGuardFailureTests": 0.005, -"DarkbloomCLITests.DoctorClearBackendGuardTests": 0.013, -"DarkbloomCLITests.DoctorCommandRunTests": 4.456, -"DarkbloomCLITests.DoctorOperatorDiagnosisTests": 6.767, -"DarkbloomCLITests.EnrollCommandTests": 0.002, -"DarkbloomCLITests.FanActivityLeaseTests": 0.02, -"DarkbloomCLITests.FanCommandArgumentTests": 0.019, -"DarkbloomCLITests.FanCommandTests": 0.005, -"DarkbloomCLITests.FanHelperClientTests": 0.003, -"DarkbloomCLITests.FanProcessRunnerTests": 1.034, +"DarkbloomCLITests.DoctorCaptureTests": 7.384, +"DarkbloomCLITests.DoctorChecksTests": 0.424, +"DarkbloomCLITests.DoctorClearBackendGuardFailureTests": 0.003, +"DarkbloomCLITests.DoctorClearBackendGuardTests": 0.003, +"DarkbloomCLITests.DoctorCommandRunTests": 4.69, +"DarkbloomCLITests.DoctorOperatorDiagnosisTests": 6.967, +"DarkbloomCLITests.EnrollCommandTests": 0.003, +"DarkbloomCLITests.FanActivityLeaseTests": 0.026, +"DarkbloomCLITests.FanCommandArgumentTests": 0.032, +"DarkbloomCLITests.FanCommandTests": 0.004, +"DarkbloomCLITests.FanHelperClientTests": 0.005, +"DarkbloomCLITests.FanProcessRunnerTests": 1.03, "DarkbloomCLITests.FanServiceDisableTests": 0.197, -"DarkbloomCLITests.FanServiceEnableTests": 0.32, -"DarkbloomCLITests.FanServiceInstallStepTests": 0.054, -"DarkbloomCLITests.FanStatusOutputTests": 0.003, +"DarkbloomCLITests.FanServiceEnableTests": 0.321, +"DarkbloomCLITests.FanServiceInstallStepTests": 0.063, +"DarkbloomCLITests.FanStatusOutputTests": 0.002, "DarkbloomCLITests.GLMWiredLimitAdviceTests": 0.001, -"DarkbloomCLITests.IdleCommandTests": 0.402, -"DarkbloomCLITests.InstallerCoordinatorBindingTests": 0.36, +"DarkbloomCLITests.IdleCommandTests": 0.411, +"DarkbloomCLITests.InstallerCoordinatorBindingTests": 0.386, "DarkbloomCLITests.KVBackendGuardDiagnosticsTests": 0.001, "DarkbloomCLITests.KVBackendPostureTests": 0.003, -"DarkbloomCLITests.LifecycleRecoveryPublicationTests": 0.008, -"DarkbloomCLITests.LifecycleRecoveryRollbackTests": 0.843, -"DarkbloomCLITests.LocalEndpointCommandTests": 0.255, +"DarkbloomCLITests.LifecycleRecoveryPublicationTests": 0.015, +"DarkbloomCLITests.LifecycleRecoveryRollbackTests": 0.991, +"DarkbloomCLITests.LocalEndpointCommandTests": 0.276, "DarkbloomCLITests.LocalStartupPreloadGateTests": 0.277, "DarkbloomCLITests.LogoutCommandTests": 0.095, "DarkbloomCLITests.LogsCommandArgvTests": 0.0, "DarkbloomCLITests.LogsCommandOptionsTests": 0.007, -"DarkbloomCLITests.MacOSUpgradeNoticeTests": 1.059, -"DarkbloomCLITests.MiMoImageOnboardingCommandTests": 0.014, -"DarkbloomCLITests.ModelPickerInputEndTests": 2.271, +"DarkbloomCLITests.MacOSUpgradeNoticeTests": 1.161, +"DarkbloomCLITests.MiMoImageOnboardingCommandTests": 0.017, +"DarkbloomCLITests.ModelPickerInputEndTests": 2.301, "DarkbloomCLITests.ModelPickerTerminalTests": 0.092, -"DarkbloomCLITests.ModelsCommandRunTests": 3.187, -"DarkbloomCLITests.ModelsLocationCommandTests": 2.861, +"DarkbloomCLITests.ModelsCommandRunTests": 3.14, +"DarkbloomCLITests.ModelsLocationCommandTests": 2.867, "DarkbloomCLITests.PickerCatalogRowTests": 0.003, +"DarkbloomCLITests.PickerDownloadOutputTests": 0.322, "DarkbloomCLITests.PickerEntryTests": 0.004, -"DarkbloomCLITests.PickerServingSetBudgetTests": 0.05, -"DarkbloomCLITests.RegistrationWeightHashTests": 0.01, +"DarkbloomCLITests.PickerServingSetBudgetTests": 0.051, +"DarkbloomCLITests.RegistrationWeightHashTests": 0.012, "DarkbloomCLITests.ReportAppAttestEvidenceTests": 0.005, -"DarkbloomCLITests.ReportCommandRunTests": 0.521, +"DarkbloomCLITests.ReportCommandRunTests": 0.597, "DarkbloomCLITests.ReportCommandTests": 0.002, -"DarkbloomCLITests.ReportConfigPathTests": 0.001, -"DarkbloomCLITests.ReportPayloadTests": 0.02, +"DarkbloomCLITests.ReportConfigPathTests": 0.004, +"DarkbloomCLITests.ReportPayloadTests": 0.022, "DarkbloomCLITests.RestartCommandTests": 0.004, -"DarkbloomCLITests.RootCommandOutputTests": 0.5, +"DarkbloomCLITests.RootCommandOutputTests": 0.509, "DarkbloomCLITests.RuntimeSmokeKVOptionsTests": 0.002, -"DarkbloomCLITests.RuntimeSnapshotConfigTests": 0.308, -"DarkbloomCLITests.SandboxAddonTests": 5.478, -"DarkbloomCLITests.SandboxEligibilityTests": 0.023, -"DarkbloomCLITests.SandboxSetupTests": 2.034, -"DarkbloomCLITests.SandboxStatusTests": 0.008, -"DarkbloomCLITests.ScheduleCommandTests": 1.391, -"DarkbloomCLITests.ScheduledWindowSelectionTests": 0.156, +"DarkbloomCLITests.RuntimeSnapshotConfigTests": 0.334, +"DarkbloomCLITests.SandboxAddonTests": 5.545, +"DarkbloomCLITests.SandboxEligibilityTests": 0.025, +"DarkbloomCLITests.SandboxSetupTests": 2.135, +"DarkbloomCLITests.SandboxStatusTests": 0.01, +"DarkbloomCLITests.ScheduleCommandTests": 1.411, +"DarkbloomCLITests.ScheduledWindowSelectionTests": 0.164, "DarkbloomCLITests.ScheduledWindowTimingTests": 0.003, -"DarkbloomCLITests.ServiceDrainTests": 0.277, -"DarkbloomCLITests.ServiceDrainWaitTests": 0.804, -"DarkbloomCLITests.StartCommandOptionsTests": 0.092, -"DarkbloomCLITests.StartCommandTests": 0.006, -"DarkbloomCLITests.StartLaunchdGuardTests": 0.786, -"DarkbloomCLITests.StartServingGuardTests": 1.103, -"DarkbloomCLITests.StatusCommandRunTests": 2.793, +"DarkbloomCLITests.ServiceDrainTests": 0.275, +"DarkbloomCLITests.ServiceDrainWaitTests": 0.815, +"DarkbloomCLITests.StartCommandOptionsTests": 0.086, +"DarkbloomCLITests.StartCommandTests": 0.007, +"DarkbloomCLITests.StartLaunchdGuardTests": 0.784, +"DarkbloomCLITests.StartServingGuardTests": 1.109, +"DarkbloomCLITests.StatusCommandRunTests": 2.659, "DarkbloomCLITests.StatusDaemonHealthLineTests": 0.01, "DarkbloomCLITests.StatusLifecycleDrainLineTests": 0.0, -"DarkbloomCLITests.StatusResidencyTests": 1.009, -"DarkbloomCLITests.SwitchCommandTests": 0.376, -"DarkbloomCLITests.UnenrollChoiceTests": 0.025, -"DarkbloomCLITests.UnenrollKeepServingTests": 0.007, -"DarkbloomCLITests.UpdateCheckCommandTests": 1.187, -"DarkbloomCLITests.WatchdogCommandTests": 0.016, +"DarkbloomCLITests.StatusResidencyTests": 0.979, +"DarkbloomCLITests.SwitchCommandTests": 0.382, +"DarkbloomCLITests.UnenrollChoiceTests": 0.026, +"DarkbloomCLITests.UnenrollKeepServingTests": 0.006, +"DarkbloomCLITests.UpdateCheckCommandTests": 1.07, +"DarkbloomCLITests.WatchdogCommandTests": 0.012, "DarkbloomCLITests.WatchdogRecordRecoveryOutcomeTests": 0.002, "DarkbloomCLITests.WatchdogRecoveryOutcomeDetailTests": 0.002, -"DarkbloomCLITests.WatchdogSignalTrapTests": 0.643, -"DarkbloomFanCoreTests.FanControllerTests": 1.306, -"DarkbloomFanCoreTests.FanHardwareTests": 0.326, -"DarkbloomFanCoreTests.FanPolicyTests": 0.09, -"DarkbloomFanCoreTests.SMCCodecTests": 0.192, -"DarkbloomFanHelperTests.FanDaemonTests": 0.32, -"DarkbloomFanHelperTests.FanStartupDiscoveryTests": 0.462, -"DarkbloomFanServiceTests.FanServiceTests": 0.346, -"DarkbloomHardwareLoadTests.CPUTopologyResolverTests": 0.224, -"DarkbloomHardwareLoadTests.CounterLivenessTests": 0.096, -"DarkbloomHardwareLoadTests.HardwareLoadMonitorTests": 0.818, -"DarkbloomHardwareLoadTests.IOReportMathTests": 0.261, -"DarkbloomHardwareLoadTests.LiveHardwareTests": 1.106, -"DarkbloomHardwareLoadTests.ProviderGPUShareTests": 0.19, -"DarkbloomHardwareLoadTests.ReaderParsingTests": 0.189, +"DarkbloomCLITests.WatchdogSignalTrapTests": 0.614, +"DarkbloomFanCoreTests.FanControllerTests": 0.626, +"DarkbloomFanCoreTests.FanHardwareTests": 0.248, +"DarkbloomFanCoreTests.FanPolicyTests": 0.193, +"DarkbloomFanCoreTests.SMCCodecTests": 0.178, +"DarkbloomFanHelperTests.FanDaemonTests": 0.272, +"DarkbloomFanHelperTests.FanStartupDiscoveryTests": 0.387, +"DarkbloomFanServiceTests.FanServiceTests": 0.288, +"DarkbloomHardwareLoadTests.CPUTopologyResolverTests": 0.221, +"DarkbloomHardwareLoadTests.CounterLivenessTests": 0.084, +"DarkbloomHardwareLoadTests.HardwareLoadMonitorTests": 0.926, +"DarkbloomHardwareLoadTests.IOReportMathTests": 0.249, +"DarkbloomHardwareLoadTests.LiveHardwareTests": 1.21, +"DarkbloomHardwareLoadTests.ProviderGPUShareTests": 0.152, +"DarkbloomHardwareLoadTests.ReaderParsingTests": 0.226, "DarkbloomPublishTests.HashCommandTests": 0.014, -"GPTOSSOptimizationTests.CBv2Gemma4ScheduledPrefillTests": 4.401, -"GPTOSSOptimizationTests.CBv2ModelGPTOSSForwardTests": 1.576, -"GPTOSSOptimizationTests.CBv2ModelGemma4ForwardTests": 4.81, -"GPTOSSOptimizationTests.CBv2ModelLayerKindTests": 0.054, -"GPTOSSOptimizationTests.GPTOSSCompiledExpertsTests": 3.163, -"GPTOSSOptimizationTests.GPTOSSGateUpFusionTests": 1.836, -"GPTOSSOptimizationTests.GPTOSSPrefillOutputTests": 11.16, +"GPTOSSOptimizationTests.CBv2Gemma4ScheduledPrefillTests": 4.162, +"GPTOSSOptimizationTests.CBv2ModelGPTOSSForwardTests": 4.11, +"GPTOSSOptimizationTests.CBv2ModelGemma4ForwardTests": 4.8, +"GPTOSSOptimizationTests.CBv2ModelLayerKindTests": 0.05, +"GPTOSSOptimizationTests.GPTOSSCompiledExpertsTests": 1.655, +"GPTOSSOptimizationTests.GPTOSSGateUpFusionTests": 3.414, +"GPTOSSOptimizationTests.GPTOSSPrefillOutputTests": 12.533, "GPTOSSOptimizationTests.GPTOSSRealCheckpointParityTests": 0.0, -"GPTOSSOptimizationTests.IncrementalCheckpointMaterializationTests": 0.039, -"GPTOSSOptimizationTests.QuantizedSwitchLinearConstantCastTests": 1.028, +"GPTOSSOptimizationTests.IncrementalCheckpointMaterializationTests": 0.033, +"GPTOSSOptimizationTests.QuantizedSwitchLinearConstantCastTests": 1.078, "ProviderAppAttestTests.AppAttestEntitlementPolicyTests": 0.003, "ProviderAppAttestTests.AppAttestShadowTests": 0.055, "ProviderAppAttestTests.AppAttestStallRestartPolicyTests": 0.004, @@ -165,12 +167,12 @@ "ProviderAppAttestTests.WorkerProcessTests": 3.88, "ProviderAppAttestTests.WorkerRuntimeDiagnosticsTests": 0.001, "ProviderAppAttestTests.WorkerTransportTests": 0.068, -"ProviderCoreFoundationTests.CacheDirectoryResolutionTests": 0.756, +"ProviderCoreFoundationTests.CacheDirectoryResolutionTests": 0.694, "ProviderCoreFoundationTests.DiffusionGemmaMediaPolicyTests": 0.007, "ProviderCoreFoundationTests.EmptyFileTest": 0.003, "ProviderCoreFoundationTests.EnumerationOrderInvarianceTest": 0.014, "ProviderCoreFoundationTests.FlintDiscoveryTests": 0.033, -"ProviderCoreFoundationTests.GLM5NextDiscoveryLoadFootprintTests": 1.081, +"ProviderCoreFoundationTests.GLM5NextDiscoveryLoadFootprintTests": 1.067, "ProviderCoreFoundationTests.GoldenVectorTest": 0.003, "ProviderCoreFoundationTests.HarmonySanitizationTests": 0.002, "ProviderCoreFoundationTests.HashAllowlistTests": 0.025, @@ -183,10 +185,10 @@ "ProviderCoreFoundationTests.ModelScannerSnapshotSymlinkTests": 0.033, "ProviderCoreFoundationTests.NemotronSuperDistributionManifestTests": 0.177, "ProviderCoreFoundationTests.NemotronSuperMediaPolicyTests": 0.001, -"ProviderCoreFoundationTests.NemotronTemplateFiltersTests": 0.2, +"ProviderCoreFoundationTests.NemotronTemplateFiltersTests": 0.195, "ProviderCoreFoundationTests.PageCacheTests": 0.066, -"ProviderCoreFoundationTests.PromptContractIdentityTests": 0.201, -"ProviderCoreFoundationTests.PromptRenderDateTests": 0.05, +"ProviderCoreFoundationTests.PromptContractIdentityTests": 0.196, +"ProviderCoreFoundationTests.PromptRenderDateTests": 0.097, "ProviderCoreFoundationTests.Qwen4MediaPolicyTests": 0.011, "ProviderCoreFoundationTests.RoleClassificationTests": 0.0, "ProviderCoreFoundationTests.StaleHashRecomputeTest": 0.013, @@ -196,284 +198,288 @@ "ProviderCoreFoundationTests.WeightHasherConcurrencyTests": 0.112, "ProviderCoreFoundationTests.WeightHasherMemoryTests": 0.07, "ProviderCoreFoundationTests.WeightHasherStreamParityTests": 0.538, -"ProviderCoreTests.APNsPushHistoryTests": 0.028, +"ProviderCoreTests.APNsPushHistoryTests": 0.027, "ProviderCoreTests.AddonHoldDrainOwnershipTests": 0.0, -"ProviderCoreTests.AddonHoldLoopTests": 2.092, -"ProviderCoreTests.AddonHoldServeLoopTests": 1.176, +"ProviderCoreTests.AddonHoldLoopTests": 2.094, +"ProviderCoreTests.AddonHoldServeLoopTests": 1.636, "ProviderCoreTests.AddonHoldStoreTests": 0.031, -"ProviderCoreTests.AddonIPCServerTests": 1.101, -"ProviderCoreTests.AddonIPCTests": 0.002, +"ProviderCoreTests.AddonIPCServerTests": 1.155, +"ProviderCoreTests.AddonIPCTests": 0.003, "ProviderCoreTests.AddonPeerPolicyTests": 0.001, "ProviderCoreTests.AdmissionRateEstimatorTests": 0.006, "ProviderCoreTests.AdvertisedModelStoreTests": 0.0, "ProviderCoreTests.AppAttestDeepDiagnosisTests": 0.004, -"ProviderCoreTests.AppAttestLocalDiagnosisTests": 0.003, -"ProviderCoreTests.AppAttestProcessProbeTests": 0.431, -"ProviderCoreTests.AppAttestResumeTests": 0.038, -"ProviderCoreTests.AppAttestResumeTransportTests": 0.86, -"ProviderCoreTests.AppAttestShadowReplyTests": 4.219, -"ProviderCoreTests.AppAttestUpdateLifecycleTests": 2.982, -"ProviderCoreTests.ArrivalInvarianceMeasurementTests": 0.551, -"ProviderCoreTests.AttentionMetadataProductionOwnerTests": 2.763, -"ProviderCoreTests.AudioInputRejectionTests": 0.02, -"ProviderCoreTests.AutoUpdateClaimTests": 0.064, -"ProviderCoreTests.AutoUpdateControllerTests": 0.002, -"ProviderCoreTests.AutoUpdateCycleTests": 0.409, +"ProviderCoreTests.AppAttestLocalDiagnosisTests": 0.006, +"ProviderCoreTests.AppAttestProcessProbeTests": 0.432, +"ProviderCoreTests.AppAttestResumeTests": 0.036, +"ProviderCoreTests.AppAttestResumeTransportTests": 1.11, +"ProviderCoreTests.AppAttestShadowReplyTests": 4.484, +"ProviderCoreTests.AppAttestUpdateLifecycleTests": 3.125, +"ProviderCoreTests.ArrivalInvarianceMeasurementTests": 0.554, +"ProviderCoreTests.AttentionMetadataProductionOwnerTests": 5.039, +"ProviderCoreTests.AudioInputRejectionTests": 0.024, +"ProviderCoreTests.AutoUpdateClaimTests": 0.072, +"ProviderCoreTests.AutoUpdateControllerTests": 0.003, +"ProviderCoreTests.AutoUpdateCycleTests": 0.433, "ProviderCoreTests.AutoUpdateJitterSequencingTests": 0.0, "ProviderCoreTests.AutoUpdateLifecycleOverlapTests": 0.0, -"ProviderCoreTests.AutoUpdateMonitorStartTests": 0.005, -"ProviderCoreTests.AutopilotAdoptionTests": 0.063, +"ProviderCoreTests.AutoUpdateMonitorStartTests": 0.002, +"ProviderCoreTests.AutopilotAdoptionTests": 0.119, "ProviderCoreTests.AutopilotBuildEligibilityTests": 0.001, -"ProviderCoreTests.AutopilotBusyReasonTests": 0.145, -"ProviderCoreTests.AutopilotDownloadLedgerTests": 0.006, +"ProviderCoreTests.AutopilotBusyReasonTests": 0.335, +"ProviderCoreTests.AutopilotDownloadLedgerTests": 0.015, "ProviderCoreTests.AutopilotDownloadPrefetcherTests": 0.001, -"ProviderCoreTests.AutopilotDownloadTests": 0.977, -"ProviderCoreTests.AutopilotInventoryTests": 0.023, +"ProviderCoreTests.AutopilotDownloadTests": 1.319, +"ProviderCoreTests.AutopilotInventoryTests": 0.048, "ProviderCoreTests.AutopilotModelSetTests": 0.001, "ProviderCoreTests.AutopilotModelSwitchOwnershipTests": 0.003, "ProviderCoreTests.AutopilotPlacementHoldTests": 0.04, -"ProviderCoreTests.AutopilotSnapshotCodingTests": 0.016, +"ProviderCoreTests.AutopilotSnapshotCodingTests": 0.009, "ProviderCoreTests.AutopilotStartInventoryTests": 0.002, -"ProviderCoreTests.AutopilotStartupPreferencesTests": 0.031, -"ProviderCoreTests.AutopilotStartupTests": 0.024, -"ProviderCoreTests.BackendParityHarnessProbeTests": 0.004, +"ProviderCoreTests.AutopilotStartupPreferencesTests": 0.036, +"ProviderCoreTests.AutopilotStartupTests": 0.02, +"ProviderCoreTests.BackendParityHarnessProbeTests": 0.003, "ProviderCoreTests.BackendParityReportTests": 0.011, "ProviderCoreTests.BenchmarkCheckpointPartitionTests": 0.0, -"ProviderCoreTests.BenchmarkEntryPointRefusalTests": 0.009, -"ProviderCoreTests.BenchmarkProductionGrantTests": 0.003, +"ProviderCoreTests.BenchmarkEntryPointRefusalTests": 0.01, +"ProviderCoreTests.BenchmarkProductionGrantTests": 0.004, "ProviderCoreTests.BenchmarkProductionInputTests": 0.013, -"ProviderCoreTests.BenchmarkSessionDonationDemandTests": 0.015, +"ProviderCoreTests.BenchmarkSessionDonationDemandTests": 0.014, "ProviderCoreTests.BetaFeaturesTests": 0.002, -"ProviderCoreTests.Bonsai9BContextTests": 0.006, +"ProviderCoreTests.Bonsai9BContextTests": 0.005, "ProviderCoreTests.Bonsai9BMTPPolicyTests": 0.003, -"ProviderCoreTests.Bonsai9BRequestPolicyTests": 0.002, -"ProviderCoreTests.BonsaiDemandedShortCheckpointTests": 0.045, +"ProviderCoreTests.Bonsai9BRequestPolicyTests": 0.004, +"ProviderCoreTests.BonsaiDemandedShortCheckpointTests": 0.023, "ProviderCoreTests.BonsaiEncryptedCheckpointLiveTests": 0.0, "ProviderCoreTests.BootSecurityTests": 0.0, "ProviderCoreTests.BuildEnvironmentTests": 0.001, -"ProviderCoreTests.CacheDirectoryPermissionsTests": 0.023, +"ProviderCoreTests.CacheDirectoryPermissionsTests": 0.03, "ProviderCoreTests.CachePromptParityTests": 0.01, -"ProviderCoreTests.CacheSettingsTests": 0.002, +"ProviderCoreTests.CacheSettingsTests": 0.003, "ProviderCoreTests.CacheStorageEnvironmentTests": 0.005, -"ProviderCoreTests.CacheVolumeTests": 0.026, -"ProviderCoreTests.CancelledSettlementLifecycleTests": 0.001, +"ProviderCoreTests.CacheVolumeTests": 0.021, +"ProviderCoreTests.CancelledSettlementLifecycleTests": 0.002, "ProviderCoreTests.ChatRequestExtraFieldsTests": 0.002, -"ProviderCoreTests.ChatTemplateLoopRewritesTests": 4.248, +"ProviderCoreTests.ChatTemplateLoopRewritesTests": 5.332, "ProviderCoreTests.ChunkBatcherLifecycleTests": 0.003, -"ProviderCoreTests.ChunkSenderTests": 0.902, +"ProviderCoreTests.ChunkSenderTests": 0.903, "ProviderCoreTests.ClusterAPIDecorationTests": 0.002, -"ProviderCoreTests.ClusterAPIParityTests": 3.063, -"ProviderCoreTests.ClusterApprovalAnyNumericsClassTests": 0.001, -"ProviderCoreTests.ClusterApprovalFetchTests": 0.9, -"ProviderCoreTests.ClusterApprovalLifetimeTests": 0.475, -"ProviderCoreTests.ClusterApprovalServiceStartTests": 7.353, -"ProviderCoreTests.ClusterApprovalSyncTests": 3.901, -"ProviderCoreTests.ClusterApprovalWatchTests": 5.005, +"ProviderCoreTests.ClusterAPIParityTests": 3.181, +"ProviderCoreTests.ClusterApprovalAnyNumericsClassTests": 0.002, +"ProviderCoreTests.ClusterApprovalFetchTests": 0.993, +"ProviderCoreTests.ClusterApprovalLifetimeTests": 0.453, +"ProviderCoreTests.ClusterApprovalServiceStartTests": 11.878, +"ProviderCoreTests.ClusterApprovalSyncTests": 5.91, +"ProviderCoreTests.ClusterApprovalWatchTests": 5.82, "ProviderCoreTests.ClusterCacheOwnershipTests": 0.001, -"ProviderCoreTests.ClusterChipAgnosticGrantTests": 0.003, -"ProviderCoreTests.ClusterConfigurationTests": 0.004, +"ProviderCoreTests.ClusterChipAgnosticGrantTests": 0.005, +"ProviderCoreTests.ClusterConfigurationTests": 0.005, "ProviderCoreTests.ClusterDerivedTimeBudgetTests": 0.001, -"ProviderCoreTests.ClusterGLMManifestPinTests": 2.443, -"ProviderCoreTests.ClusterInstalledReferenceTests": 0.009, -"ProviderCoreTests.ClusterLeaderFailoverFinishTests": 1.57, -"ProviderCoreTests.ClusterLinkControlHostTests": 0.007, +"ProviderCoreTests.ClusterGLMManifestPinTests": 2.616, +"ProviderCoreTests.ClusterInstalledReferenceTests": 0.011, +"ProviderCoreTests.ClusterLeaderFailoverFinishTests": 1.645, +"ProviderCoreTests.ClusterLinkControlHostTests": 0.005, "ProviderCoreTests.ClusterLocalServingTests": 0.001, -"ProviderCoreTests.ClusterMemberLoopTests": 0.017, -"ProviderCoreTests.ClusterMemberNegotiationTests": 0.951, -"ProviderCoreTests.ClusterMemberRegistrationTests": 10.115, -"ProviderCoreTests.ClusterMemberServeLoopTests": 22.626, -"ProviderCoreTests.ClusterMemberSupervisionTests": 0.003, -"ProviderCoreTests.ClusterMembershipTests": 0.003, -"ProviderCoreTests.ClusterNativeMemberAttachmentTests": 0.029, -"ProviderCoreTests.ClusterObservabilityTests": 0.015, -"ProviderCoreTests.ClusterOnboardingPeerLabelTests": 0.171, -"ProviderCoreTests.ClusterOwnerCommittedBootstrapTests": 1.714, -"ProviderCoreTests.ClusterOwnerServingTests": 0.004, -"ProviderCoreTests.ClusterPairApprovalTests": 0.02, +"ProviderCoreTests.ClusterMemberLoopTests": 0.015, +"ProviderCoreTests.ClusterMemberNegotiationTests": 0.969, +"ProviderCoreTests.ClusterMemberRegistrationTests": 10.122, +"ProviderCoreTests.ClusterMemberServeLoopTests": 21.62, +"ProviderCoreTests.ClusterMemberSupervisionTests": 0.002, +"ProviderCoreTests.ClusterMembershipTests": 0.004, +"ProviderCoreTests.ClusterModelApprovalTests": 0.007, +"ProviderCoreTests.ClusterNativeMemberAttachmentTests": 0.028, +"ProviderCoreTests.ClusterObservabilityTests": 0.018, +"ProviderCoreTests.ClusterOnboardingPeerLabelTests": 0.093, +"ProviderCoreTests.ClusterOwnerCommittedBootstrapTests": 1.707, +"ProviderCoreTests.ClusterOwnerServingTests": 0.031, +"ProviderCoreTests.ClusterPairApprovalTests": 0.009, "ProviderCoreTests.ClusterPairMediaRegistrationTests": 0.001, -"ProviderCoreTests.ClusterPairServingDecisionsTests": 0.003, -"ProviderCoreTests.ClusterPairServingTests": 0.58, +"ProviderCoreTests.ClusterPairServingDecisionsTests": 0.006, +"ProviderCoreTests.ClusterPairServingTests": 0.602, "ProviderCoreTests.ClusterPairSlotOwnerLanesTests": 0.0, -"ProviderCoreTests.ClusterPairSlotServeTests": 1.32, -"ProviderCoreTests.ClusterPairSlotTests": 1.387, -"ProviderCoreTests.ClusterPairingProviderTests": 1.451, -"ProviderCoreTests.ClusterPrefixCacheSettingsTests": 0.011, -"ProviderCoreTests.ClusterPrefixSSDKeyMaterialTests": 0.202, -"ProviderCoreTests.ClusterRosterMemberTests": 0.014, -"ProviderCoreTests.ClusterRuntimeApprovalFactsTests": 0.525, -"ProviderCoreTests.ClusterServiceAgentTests": 0.028, -"ProviderCoreTests.ClusterServiceDescriptorTests": 0.903, -"ProviderCoreTests.ClusterServicePowerAssertionTests": 0.006, -"ProviderCoreTests.ClusterServiceRecoveryTests": 7.49, -"ProviderCoreTests.ClusterSetupProbeRequestTests": 0.003, -"ProviderCoreTests.ClusterStatusSpeculationTests": 0.003, -"ProviderCoreTests.ClusterStoreManifestRepairTests": 3.471, +"ProviderCoreTests.ClusterPairSlotServeTests": 1.455, +"ProviderCoreTests.ClusterPairSlotTests": 1.41, +"ProviderCoreTests.ClusterPairingProviderTests": 1.516, +"ProviderCoreTests.ClusterPrefixCacheSettingsTests": 0.012, +"ProviderCoreTests.ClusterPrefixSSDKeyMaterialTests": 0.208, +"ProviderCoreTests.ClusterRosterMemberTests": 0.041, +"ProviderCoreTests.ClusterRuntimeApprovalFactsTests": 3.322, +"ProviderCoreTests.ClusterServiceAgentTests": 0.019, +"ProviderCoreTests.ClusterServiceDescriptorTests": 0.895, +"ProviderCoreTests.ClusterServicePowerAssertionTests": 0.005, +"ProviderCoreTests.ClusterServiceRecoveryTests": 7.638, +"ProviderCoreTests.ClusterSetupProbeRequestTests": 0.006, +"ProviderCoreTests.ClusterStatusSpeculationTests": 0.002, +"ProviderCoreTests.ClusterStoreManifestRepairTests": 3.661, +"ProviderCoreTests.ClusterTransferReportsTests": 0.0, "ProviderCoreTests.CompletePrefixCacheCapabilityTests": 0.001, -"ProviderCoreTests.ConfigValidationTests": 0.005, -"ProviderCoreTests.CoordinatorAdvertiseTests": 0.0, -"ProviderCoreTests.CoordinatorHandshakeDeadlineTests": 3.234, -"ProviderCoreTests.CoordinatorIntegrationTests": 2.389, -"ProviderCoreTests.CoordinatorLifecycleBarrierTests": 0.148, -"ProviderCoreTests.CoordinatorModelSwitchTests": 0.437, -"ProviderCoreTests.CoordinatorWireVectorTests": 0.026, +"ProviderCoreTests.ConfigValidationTests": 0.006, +"ProviderCoreTests.CoordinatorAdvertiseTests": 0.001, +"ProviderCoreTests.CoordinatorHandshakeDeadlineTests": 3.471, +"ProviderCoreTests.CoordinatorIntegrationTests": 10.106, +"ProviderCoreTests.CoordinatorLifecycleBarrierTests": 0.141, +"ProviderCoreTests.CoordinatorModelSwitchTests": 0.438, +"ProviderCoreTests.CoordinatorReconnectPolicyTests": 0.001, +"ProviderCoreTests.CoordinatorWireVectorTests": 0.019, "ProviderCoreTests.CrashLoopGuardPredicateTests": 0.0, "ProviderCoreTests.CrashLoopGuardRecoveryWiringTests": 0.282, -"ProviderCoreTests.CrashLoopGuardTripTests": 0.005, -"ProviderCoreTests.DaemonStateServedCountTests": 0.006, +"ProviderCoreTests.CrashLoopGuardTripTests": 0.009, +"ProviderCoreTests.DaemonStateServedCountTests": 0.003, "ProviderCoreTests.DarkbloomMDMRemovalTests": 0.002, -"ProviderCoreTests.DeadlineDecisionBridgeTests": 0.012, -"ProviderCoreTests.DeadlineDecisionProfileTests": 0.002, +"ProviderCoreTests.DeadlineDecisionBridgeTests": 0.016, +"ProviderCoreTests.DeadlineDecisionProfileTests": 0.001, "ProviderCoreTests.DecodeBandwidthModelTests": 0.001, -"ProviderCoreTests.DecodeInterleaveDeadlineAdmissionTests": 0.044, -"ProviderCoreTests.DesiredModelsForPostureTests": 0.003, -"ProviderCoreTests.DeviceCodeLoginTests": 4.267, -"ProviderCoreTests.DiffusionBenchmarkRouteProbeTests": 0.001, -"ProviderCoreTests.DiffusionBenchmarkTests": 0.002, -"ProviderCoreTests.DiffusionCheckpointEnvelopeTests": 0.091, -"ProviderCoreTests.DiffusionGemmaBenchmarkRowTests": 0.001, +"ProviderCoreTests.DecodeInterleaveDeadlineAdmissionTests": 0.335, +"ProviderCoreTests.DesiredModelsForPostureTests": 0.004, +"ProviderCoreTests.DeviceCodeLoginTests": 4.029, +"ProviderCoreTests.DiffusionBenchmarkRouteProbeTests": 0.002, +"ProviderCoreTests.DiffusionBenchmarkTests": 0.001, +"ProviderCoreTests.DiffusionCheckpointEnvelopeTests": 0.089, +"ProviderCoreTests.DiffusionGemmaBenchmarkRowTests": 0.002, "ProviderCoreTests.DiffusionGemmaConcurrencyLiveTests": 0.001, "ProviderCoreTests.DiffusionGemmaEncryptedHandlerLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaFourCallDiagnosticLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaFourCallFixtureTests": 0.001, "ProviderCoreTests.DiffusionGemmaMediaLiveTests": 0.0, -"ProviderCoreTests.DiffusionGemmaMediaNormalizationTests": 0.089, +"ProviderCoreTests.DiffusionGemmaMediaNormalizationTests": 0.044, "ProviderCoreTests.DiffusionGemmaMediaPrefixLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaNamedToolDiagnosticLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaPrefixLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaPromptParityLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaProtocolLiveTests": 0.0, -"ProviderCoreTests.DiffusionGemmaProviderBridgeTests": 45.968, +"ProviderCoreTests.DiffusionGemmaProviderBridgeTests": 48.52, "ProviderCoreTests.DiffusionGemmaProviderLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaRawCaseLiveTests": 0.0, -"ProviderCoreTests.DiffusionGemmaReasoningControlTests": 0.001, -"ProviderCoreTests.DiffusionGemmaReasoningEmissionTests": 0.049, +"ProviderCoreTests.DiffusionGemmaReasoningControlTests": 0.002, +"ProviderCoreTests.DiffusionGemmaReasoningEmissionTests": 0.05, "ProviderCoreTests.DiffusionGemmaStandaloneLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaStopLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaTokenizerParityLiveTests": 0.0, "ProviderCoreTests.DiffusionLongContextLiveTests": 0.0, -"ProviderCoreTests.DiffusionToolResultMediaTests": 0.128, +"ProviderCoreTests.DiffusionToolResultMediaTests": 0.127, "ProviderCoreTests.DiffusionVisibleThroughputLiveTests": 0.001, -"ProviderCoreTests.DistributedAutomaticBatchPlannerTests": 0.508, -"ProviderCoreTests.DistributedCBv2CleanStopTests": 0.055, -"ProviderCoreTests.DistributedCBv2DeadlineTests": 0.002, -"ProviderCoreTests.DistributedCBv2EngineTests": 0.008, -"ProviderCoreTests.DistributedHTTPCleanStopTests": 1.08, -"ProviderCoreTests.DistributedHTTPCompletionTests": 2.324, -"ProviderCoreTests.DistributedHTTPDeliveryLifecycleTests": 1.95, -"ProviderCoreTests.DistributedHTTPDisconnectTests": 1.63, -"ProviderCoreTests.DistributedHTTPFrameWakeupTests": 0.275, -"ProviderCoreTests.DistributedHTTPOriginTests": 0.221, +"ProviderCoreTests.DistributedAutomaticBatchPlannerTests": 0.458, +"ProviderCoreTests.DistributedCBv2CleanStopTests": 0.059, +"ProviderCoreTests.DistributedCBv2DeadlineTests": 0.003, +"ProviderCoreTests.DistributedCBv2EngineTests": 0.006, +"ProviderCoreTests.DistributedHTTPCleanStopTests": 1.072, +"ProviderCoreTests.DistributedHTTPCompletionTests": 2.364, +"ProviderCoreTests.DistributedHTTPDeliveryLifecycleTests": 1.83, +"ProviderCoreTests.DistributedHTTPDisconnectTests": 1.631, +"ProviderCoreTests.DistributedHTTPFrameWakeupTests": 0.297, +"ProviderCoreTests.DistributedHTTPOriginTests": 0.235, "ProviderCoreTests.DistributedHTTPRetirementTests": 0.013, -"ProviderCoreTests.DistributedHTTPTerminalIntegrationTests": 0.923, -"ProviderCoreTests.DistributedHTTPVisibleContentTests": 0.421, +"ProviderCoreTests.DistributedHTTPTerminalIntegrationTests": 0.937, +"ProviderCoreTests.DistributedHTTPVisibleContentTests": 0.439, "ProviderCoreTests.DistributedInstalledCancellationTests": 0.001, -"ProviderCoreTests.DistributedInstalledFilesTests": 0.004, -"ProviderCoreTests.DistributedInstalledKVQuantizationTests": 0.008, +"ProviderCoreTests.DistributedInstalledFilesTests": 0.005, +"ProviderCoreTests.DistributedInstalledKVQuantizationTests": 0.007, "ProviderCoreTests.DistributedInstalledLanesTests": 0.001, -"ProviderCoreTests.DistributedLogprobAdmissionTests": 0.002, +"ProviderCoreTests.DistributedLogprobAdmissionTests": 0.004, "ProviderCoreTests.DistributedMiMoImageRefusalTests": 0.0, "ProviderCoreTests.DistributedPrefixPartitionTests": 0.003, -"ProviderCoreTests.DistributedQwenMediaHostMemoryTests": 0.002, -"ProviderCoreTests.DistributedQwenMediaIngressTests": 1.199, -"ProviderCoreTests.DistributedQwenMediaLifetimeTests": 0.003, -"ProviderCoreTests.DistributedRequestObservationSinkTests": 0.006, -"ProviderCoreTests.DistributedRequestObservationTests": 0.007, -"ProviderCoreTests.DistributedRequestOriginDeadlineTests": 0.002, +"ProviderCoreTests.DistributedQwenMediaHostMemoryTests": 0.003, +"ProviderCoreTests.DistributedQwenMediaIngressTests": 1.252, +"ProviderCoreTests.DistributedQwenMediaLifetimeTests": 0.002, +"ProviderCoreTests.DistributedRequestObservationSinkTests": 0.007, +"ProviderCoreTests.DistributedRequestObservationTests": 0.004, +"ProviderCoreTests.DistributedRequestOriginDeadlineTests": 0.003, "ProviderCoreTests.DistributedRequestQueueTests": 0.0, -"ProviderCoreTests.DistributedServingEligibilityTests": 0.044, +"ProviderCoreTests.DistributedServingEligibilityTests": 0.004, +"ProviderCoreTests.DistributedStopStringScopeTests": 0.002, "ProviderCoreTests.EmbeddedQwen38RuntimeRequirementsTests": 0.0, -"ProviderCoreTests.EngineDeadlineRetirementBridgeTests": 0.008, +"ProviderCoreTests.EngineDeadlineRetirementBridgeTests": 0.009, "ProviderCoreTests.EngineEarlyPerformanceTests": 0.002, -"ProviderCoreTests.EngineMeasurementOrderingTests": 0.142, +"ProviderCoreTests.EngineMeasurementOrderingTests": 0.159, "ProviderCoreTests.EnginePerformanceHeartbeatTests": 0.048, -"ProviderCoreTests.EngineProfileCancelTests": 0.009, +"ProviderCoreTests.EngineProfileCancelTests": 0.01, "ProviderCoreTests.EngineProfileMappingTests": 0.0, -"ProviderCoreTests.EngineTransferredRetirementWorkTests": 1.591, -"ProviderCoreTests.EngineV2BenchmarkMTPAcceptanceTests": 1.563, -"ProviderCoreTests.EngineV2BenchmarkMTPVerificationTests": 3.354, -"ProviderCoreTests.EngineV2BridgeCheckpointTargetTests": 0.004, +"ProviderCoreTests.EngineTransferredRetirementWorkTests": 1.554, +"ProviderCoreTests.EngineV2BenchmarkMTPAcceptanceTests": 1.413, +"ProviderCoreTests.EngineV2BenchmarkMTPVerificationTests": 3.601, +"ProviderCoreTests.EngineV2BridgeCheckpointTargetTests": 0.002, "ProviderCoreTests.EngineV2BridgeMultimodalTests": 0.005, -"ProviderCoreTests.EngineV2BridgePagedKVTests": 0.005, -"ProviderCoreTests.EngineV2BridgePumpReceiptTests": 1.461, -"ProviderCoreTests.EngineV2CancellationTests": 0.003, -"ProviderCoreTests.EngineV2CapacityTests": 0.005, -"ProviderCoreTests.EngineV2CoResidencyLiveTests": 0.0, -"ProviderCoreTests.EngineV2ContiguousAdmissionTests": 1.286, -"ProviderCoreTests.EngineV2DiffusionMediaChunkBoundTests": 0.002, -"ProviderCoreTests.EngineV2DiffusionPrefixPrecisionTests": 0.064, +"ProviderCoreTests.EngineV2BridgePagedKVTests": 0.004, +"ProviderCoreTests.EngineV2BridgePumpReceiptTests": 0.158, +"ProviderCoreTests.EngineV2CancellationTests": 0.001, +"ProviderCoreTests.EngineV2CapacityTests": 0.011, +"ProviderCoreTests.EngineV2CoResidencyLiveTests": 0.001, +"ProviderCoreTests.EngineV2ContiguousAdmissionTests": 1.592, +"ProviderCoreTests.EngineV2DiffusionMediaChunkBoundTests": 0.004, +"ProviderCoreTests.EngineV2DiffusionPrefixPrecisionTests": 0.062, "ProviderCoreTests.EngineV2ErrorMappingTests": 0.002, -"ProviderCoreTests.EngineV2EventFramingTests": 0.006, +"ProviderCoreTests.EngineV2EventFramingTests": 0.007, "ProviderCoreTests.EngineV2FP32PagedRateTests": 0.001, -"ProviderCoreTests.EngineV2FailLoudFactoryTests": 0.005, -"ProviderCoreTests.EngineV2FirstTokenDeadlineAdmissionTests": 0.039, -"ProviderCoreTests.EngineV2HardeningTests": 0.002, -"ProviderCoreTests.EngineV2HybridPrefixIdentityTests": 0.178, +"ProviderCoreTests.EngineV2FailLoudFactoryTests": 0.008, +"ProviderCoreTests.EngineV2FirstTokenDeadlineAdmissionTests": 0.04, +"ProviderCoreTests.EngineV2HardeningTests": 0.001, +"ProviderCoreTests.EngineV2HybridPrefixIdentityTests": 0.184, "ProviderCoreTests.EngineV2KVBackendFallbackHeartbeatTests": 0.003, -"ProviderCoreTests.EngineV2KVBackendGateTests": 21.901, -"ProviderCoreTests.EngineV2KVBackendPolicyTests": 0.004, -"ProviderCoreTests.EngineV2KVQuantizationPolicyTests": 0.002, -"ProviderCoreTests.EngineV2LivenessRecoveryTests": 0.045, +"ProviderCoreTests.EngineV2KVBackendGateTests": 20.974, +"ProviderCoreTests.EngineV2KVBackendPolicyTests": 0.003, +"ProviderCoreTests.EngineV2KVQuantizationPolicyTests": 0.001, +"ProviderCoreTests.EngineV2LivenessRecoveryTests": 0.04, "ProviderCoreTests.EngineV2LivenessVerdictTests": 0.002, -"ProviderCoreTests.EngineV2LogprobsChannelCapTests": 0.002, -"ProviderCoreTests.EngineV2LogprobsPassthroughTests": 0.123, -"ProviderCoreTests.EngineV2LookupReceiptCoverageTests": 0.017, +"ProviderCoreTests.EngineV2LogprobsChannelCapTests": 0.003, +"ProviderCoreTests.EngineV2LogprobsPassthroughTests": 0.127, +"ProviderCoreTests.EngineV2LookupReceiptCoverageTests": 0.009, "ProviderCoreTests.EngineV2MTPAdmissionChargesTests": 0.001, "ProviderCoreTests.EngineV2MTPProductionAdmissionTests": 0.01, -"ProviderCoreTests.EngineV2MatchedStopSequenceTests": 0.001, -"ProviderCoreTests.EngineV2MemoryConcurrencyTests": 0.022, +"ProviderCoreTests.EngineV2MatchedStopSequenceTests": 0.002, +"ProviderCoreTests.EngineV2MemoryConcurrencyTests": 0.023, "ProviderCoreTests.EngineV2NativeBlockTimingTests": 0.0, "ProviderCoreTests.EngineV2PagedParityLiveTests": 0.001, -"ProviderCoreTests.EngineV2PagedPoolDTypeEnvTests": 0.729, -"ProviderCoreTests.EngineV2PrefillGeometryEngineTests": 4.069, -"ProviderCoreTests.EngineV2PrefillGeometryTests": 0.041, -"ProviderCoreTests.EngineV2PrefillSamplingTests": 0.025, -"ProviderCoreTests.EngineV2PrefixCacheUsageTests": 0.003, -"ProviderCoreTests.EngineV2RequestRoutingTests": 0.037, +"ProviderCoreTests.EngineV2PagedPoolDTypeEnvTests": 0.93, +"ProviderCoreTests.EngineV2PrefillGeometryEngineTests": 2.831, +"ProviderCoreTests.EngineV2PrefillGeometryTests": 0.052, +"ProviderCoreTests.EngineV2PrefillSamplingTests": 0.035, +"ProviderCoreTests.EngineV2PrefixCacheUsageTests": 0.004, +"ProviderCoreTests.EngineV2RequestRoutingTests": 0.034, "ProviderCoreTests.EngineV2ResliceTests": 0.001, -"ProviderCoreTests.EngineV2ResliceUnwindTests": 0.016, -"ProviderCoreTests.EngineV2ReslicingWiringTests": 0.136, -"ProviderCoreTests.EngineV2RuntimeGuardTests": 0.026, +"ProviderCoreTests.EngineV2ResliceUnwindTests": 0.008, +"ProviderCoreTests.EngineV2ReslicingWiringTests": 0.132, +"ProviderCoreTests.EngineV2RuntimeGuardTests": 0.035, "ProviderCoreTests.EngineV2SSDPrefixCacheLiveTests": 0.0, -"ProviderCoreTests.EngineV2SamplingDefaultsTests": 0.003, -"ProviderCoreTests.EngineV2SeededSamplingTests": 0.316, +"ProviderCoreTests.EngineV2SamplingDefaultsTests": 0.004, +"ProviderCoreTests.EngineV2SeededSamplingTests": 0.29, "ProviderCoreTests.EngineV2ServiceabilityPolicyTests": 0.003, -"ProviderCoreTests.EngineV2ServiceableGrantTests": 2.334, -"ProviderCoreTests.EngineV2ServiceableLoadTests": 1.403, -"ProviderCoreTests.EngineV2SharedBudgetTests": 0.276, -"ProviderCoreTests.EngineV2ShutdownTests": 0.0, -"ProviderCoreTests.EngineV2SlotBuildTests": 0.022, -"ProviderCoreTests.EngineV2SupportedSetGateTests": 0.013, +"ProviderCoreTests.EngineV2ServiceableGrantTests": 1.419, +"ProviderCoreTests.EngineV2ServiceableLoadTests": 0.072, +"ProviderCoreTests.EngineV2SharedBudgetTests": 0.303, +"ProviderCoreTests.EngineV2ShutdownTests": 0.001, +"ProviderCoreTests.EngineV2SlotBuildTests": 0.026, +"ProviderCoreTests.EngineV2SupportedSetGateTests": 0.018, "ProviderCoreTests.EngineV2TranslationTests": 0.002, "ProviderCoreTests.EngineV2VisionMLXFaultTests": 0.001, -"ProviderCoreTests.EngineV2VisionPixelRunTests": 0.002, -"ProviderCoreTests.EngineV2VisionRoutingTests": 0.053, -"ProviderCoreTests.EngineV2VisionSpanCarvingTests": 0.005, +"ProviderCoreTests.EngineV2VisionPixelRunTests": 0.005, +"ProviderCoreTests.EngineV2VisionRoutingTests": 0.057, +"ProviderCoreTests.EngineV2VisionSpanCarvingTests": 0.003, "ProviderCoreTests.EnrollmentTests": 0.023, -"ProviderCoreTests.EvalProbeTests": 0.005, -"ProviderCoreTests.FirstContentDeadlineTests": 0.032, +"ProviderCoreTests.EvalProbeTests": 0.007, +"ProviderCoreTests.FirstContentDeadlineTests": 0.042, "ProviderCoreTests.FlashNextEncryptedHandlerLiveTests": 0.0, "ProviderCoreTests.FlashNextQuietCancellationReloadLiveTests": 0.0, "ProviderCoreTests.FlashNextReclaimDiagnostics": 0.0, -"ProviderCoreTests.FlintAnswerStopServingTests": 0.976, -"ProviderCoreTests.FlintAnswerStopTests": 1.824, -"ProviderCoreTests.FlintContextAdmissionTests": 1.27, +"ProviderCoreTests.FlintAnswerStopServingTests": 0.931, +"ProviderCoreTests.FlintAnswerStopTests": 1.847, +"ProviderCoreTests.FlintContextAdmissionTests": 1.24, "ProviderCoreTests.FlintLiveTests": 0.0, -"ProviderCoreTests.FlintNativeProtocolFactoryTests": 0.802, -"ProviderCoreTests.FlintNativeProtocolTests": 0.51, +"ProviderCoreTests.FlintNativeProtocolFactoryTests": 0.862, +"ProviderCoreTests.FlintNativeProtocolTests": 0.509, "ProviderCoreTests.FlintOpenRouterLiveTests": 0.0, -"ProviderCoreTests.FlintPagedOnlyBackendTests": 0.816, -"ProviderCoreTests.FlintPolicyTests": 0.175, +"ProviderCoreTests.FlintPagedOnlyBackendTests": 0.521, +"ProviderCoreTests.FlintPolicyTests": 0.188, "ProviderCoreTests.FlintR2InstallTests": 0.0, -"ProviderCoreTests.FlintReasoningVisibilityTests": 2.36, +"ProviderCoreTests.FlintReasoningVisibilityTests": 2.321, "ProviderCoreTests.FlintRelayLogprobsLiveTests": 0.0, -"ProviderCoreTests.FlintResponseFormatConstraintTests": 0.356, +"ProviderCoreTests.FlintResponseFormatConstraintTests": 0.338, "ProviderCoreTests.FlintResponseFormatOutputTests": 0.004, -"ProviderCoreTests.FlintResponseFormatPolicyTests": 0.413, +"ProviderCoreTests.FlintResponseFormatPolicyTests": 0.433, "ProviderCoreTests.FlintTemplateReplayTests": 0.049, -"ProviderCoreTests.FlintToolChoicePromptPolicyTests": 0.009, +"ProviderCoreTests.FlintToolChoicePromptPolicyTests": 0.018, "ProviderCoreTests.FrozenReplayRealModelTests": 0.0, -"ProviderCoreTests.GLM5NextCalibrationAuthorizerTests": 0.018, -"ProviderCoreTests.GLM5NextCalibrationBindingWireTests": 0.003, +"ProviderCoreTests.GLM5NextCalibrationAuthorizerTests": 0.019, +"ProviderCoreTests.GLM5NextCalibrationBindingWireTests": 0.004, "ProviderCoreTests.GLM5NextCalibrationBootstrapDeadlineTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationDispatchDigestTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationDispatchResultTests": 0.0, @@ -482,32 +488,32 @@ "ProviderCoreTests.GLM5NextCalibrationInstalledOwnerTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationInstalledPairTests": 0.018, "ProviderCoreTests.GLM5NextCalibrationInstalledQuoteCompletedTests": 0.0, -"ProviderCoreTests.GLM5NextCalibrationLaunchTests": 0.016, -"ProviderCoreTests.GLM5NextCalibrationNativeCodecTests": 0.002, -"ProviderCoreTests.GLM5NextCalibrationNativeDocumentsTests": 0.075, +"ProviderCoreTests.GLM5NextCalibrationLaunchTests": 0.019, +"ProviderCoreTests.GLM5NextCalibrationNativeCodecTests": 0.003, +"ProviderCoreTests.GLM5NextCalibrationNativeDocumentsTests": 0.08, "ProviderCoreTests.GLM5NextCalibrationNativeStartTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationPairedControlTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationPeerQuoteTests": 0.0, -"ProviderCoreTests.GLM5NextCalibrationPublicQuoteValidationTests": 0.007, +"ProviderCoreTests.GLM5NextCalibrationPublicQuoteValidationTests": 0.008, "ProviderCoreTests.GLM5NextCalibrationQuoteAuthorizerTests": 0.046, -"ProviderCoreTests.GLM5NextCalibrationQuoteLaunchTests": 0.005, -"ProviderCoreTests.GLM5NextCalibrationQuoteOutputTests": 0.102, -"ProviderCoreTests.GLM5NextCalibrationQuoteOwnershipTests": 0.526, -"ProviderCoreTests.GLM5NextCalibrationQuoteProcessTests": 3.569, +"ProviderCoreTests.GLM5NextCalibrationQuoteLaunchTests": 0.006, +"ProviderCoreTests.GLM5NextCalibrationQuoteOutputTests": 0.103, +"ProviderCoreTests.GLM5NextCalibrationQuoteOwnershipTests": 0.568, +"ProviderCoreTests.GLM5NextCalibrationQuoteProcessTests": 3.624, "ProviderCoreTests.GLM5NextCalibrationReportTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationResultPublicationTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationTerminalStatusRaceTests": 0.0, -"ProviderCoreTests.GLM5NextCoordinatorServingTests": 0.062, -"ProviderCoreTests.GLM5NextDiscoveryTests": 0.295, -"ProviderCoreTests.GLM5NextEncryptedCheckpointTests": 30.571, +"ProviderCoreTests.GLM5NextCoordinatorServingTests": 0.063, +"ProviderCoreTests.GLM5NextDiscoveryTests": 0.296, +"ProviderCoreTests.GLM5NextEncryptedCheckpointTests": 30.805, "ProviderCoreTests.GLM5NextHardwareGateTests": 0.0, -"ProviderCoreTests.GLM5NextLocalQualificationTests": 0.099, +"ProviderCoreTests.GLM5NextLocalQualificationTests": 0.105, "ProviderCoreTests.GLM5NextLogprobsTests": 0.0, "ProviderCoreTests.GLM5NextManagedKernelTests": 0.0, -"ProviderCoreTests.GLM5NextManagedMetadataTests": 1.293, -"ProviderCoreTests.GLM5NextMediaRoutingTests": 15.889, -"ProviderCoreTests.GLM5NextOpenRouterCapabilityTests": 1.028, -"ProviderCoreTests.GLM5NextPromptPolicyTests": 0.945, +"ProviderCoreTests.GLM5NextManagedMetadataTests": 1.317, +"ProviderCoreTests.GLM5NextMediaRoutingTests": 15.836, +"ProviderCoreTests.GLM5NextOpenRouterCapabilityTests": 1.072, +"ProviderCoreTests.GLM5NextPromptPolicyTests": 0.892, "ProviderCoreTests.GLM5NextProtectedFactoryTests": 0.0, "ProviderCoreTests.GLM5NextProviderLoopTests": 0.0, "ProviderCoreTests.GLM5NextRealArtifactQualificationTests": 0.0, @@ -515,25 +521,25 @@ "ProviderCoreTests.GLM5NextRealLogprobsQualificationTests": 0.0, "ProviderCoreTests.GLM5NextRealTeacherLogitsTests": 0.0, "ProviderCoreTests.GLM5NextRealTimingMatrixTests": 0.0, -"ProviderCoreTests.GLM5NextReasoningVisibilityTests": 0.065, -"ProviderCoreTests.GLM5NextRelayLogprobsTests": 0.117, +"ProviderCoreTests.GLM5NextReasoningVisibilityTests": 0.071, +"ProviderCoreTests.GLM5NextRelayLogprobsTests": 0.114, "ProviderCoreTests.GLM5NextResidencyIntegrationTests": 0.0, "ProviderCoreTests.GLM5NextStandaloneLoadPolicyTests": 0.0, -"ProviderCoreTests.GLM5NextWiredLimitTests": 0.001, +"ProviderCoreTests.GLM5NextWiredLimitTests": 0.002, "ProviderCoreTests.GLM5NextWiredResidencyTests": 0.001, -"ProviderCoreTests.GLM5ToolFailureTests": 0.098, -"ProviderCoreTests.GLMClusterImageReasoningTests": 0.009, -"ProviderCoreTests.GLMClusterTensorParallelMediaTests": 0.04, +"ProviderCoreTests.GLM5ToolFailureTests": 0.1, +"ProviderCoreTests.GLMClusterImageReasoningTests": 0.012, +"ProviderCoreTests.GLMClusterTensorParallelMediaTests": 0.042, "ProviderCoreTests.GLMImageAdmissionTests": 0.001, -"ProviderCoreTests.GLMPairForcedOutputTests": 0.057, -"ProviderCoreTests.GLMSlotParityTests": 0.219, +"ProviderCoreTests.GLMPairForcedOutputTests": 0.059, +"ProviderCoreTests.GLMSlotParityTests": 0.216, "ProviderCoreTests.GPTOSSCheckpointRestartLiveTests": 0.0, -"ProviderCoreTests.GPTOSSDefaultPrefixCacheWiringTests": 0.088, -"ProviderCoreTests.GPTOSSHarmonyTemplateFixesTests": 0.003, +"ProviderCoreTests.GPTOSSDefaultPrefixCacheWiringTests": 1.52, +"ProviderCoreTests.GPTOSSHarmonyTemplateFixesTests": 0.004, "ProviderCoreTests.GPTOSSMixedPrefixCacheLiveTests": 0.0, -"ProviderCoreTests.GPUEnforcementTests": 0.314, -"ProviderCoreTests.Gemma4ServedTemplateRenderTests": 0.205, -"ProviderCoreTests.Gemma4ToolCallArgumentsTests": 0.001, +"ProviderCoreTests.GPUEnforcementTests": 0.286, +"ProviderCoreTests.Gemma4ServedTemplateRenderTests": 0.202, +"ProviderCoreTests.Gemma4ToolCallArgumentsTests": 0.002, "ProviderCoreTests.Gemma4ToolSchemaEnforcementTests": 0.001, "ProviderCoreTests.Gemma4TurnStructureTests": 0.003, "ProviderCoreTests.GemmaMTPPerformanceLiveTests": 0.0, @@ -544,7 +550,7 @@ "ProviderCoreTests.GemmaOptimizationReportingTests": 0.001, "ProviderCoreTests.GemmaQATCheckpointRestartLiveTests": 0.0, "ProviderCoreTests.GemmaToolCallLiveTests": 0.0, -"ProviderCoreTests.GemmaToolConstraintTests": 0.452, +"ProviderCoreTests.GemmaToolConstraintTests": 0.46, "ProviderCoreTests.GemmaVLMEngineV2LiveTests": 0.0, "ProviderCoreTests.GemmaVLMSharedTowerMemoryLiveTests": 0.0, "ProviderCoreTests.GemmaVLMVideoEngineV2LiveTests": 0.0, @@ -552,68 +558,68 @@ "ProviderCoreTests.GlobalKVCacheBudgetAuditTests": 0.003, "ProviderCoreTests.HardwareDetectorTests": 0.0, "ProviderCoreTests.HeartbeatClusterSessionTests": 0.001, -"ProviderCoreTests.HeartbeatIdlePolicyTests": 0.001, -"ProviderCoreTests.HuggingFaceDownloadTests": 0.06, -"ProviderCoreTests.IdleCalibrationCoordinatorTests": 0.06, +"ProviderCoreTests.HeartbeatIdlePolicyTests": 0.0, +"ProviderCoreTests.HuggingFaceDownloadTests": 0.068, +"ProviderCoreTests.IdleCalibrationCoordinatorTests": 0.067, "ProviderCoreTests.IdleTimeoutPolicyTests": 0.0, -"ProviderCoreTests.InboundChatRequestDecodeTests": 0.008, -"ProviderCoreTests.InboundDecodeTests": 0.006, +"ProviderCoreTests.InboundChatRequestDecodeTests": 0.01, +"ProviderCoreTests.InboundDecodeTests": 0.005, "ProviderCoreTests.InferenceLiveTests": 0.0, -"ProviderCoreTests.InferenceRefusalLoggingTests": 0.066, -"ProviderCoreTests.InlineDeclarationProbeTests": 0.052, +"ProviderCoreTests.InferenceRefusalLoggingTests": 0.073, +"ProviderCoreTests.InlineDeclarationProbeTests": 0.06, "ProviderCoreTests.JinjaSanitizationLiveTests": 0.0, "ProviderCoreTests.JinjaSanitizationTests": 0.008, -"ProviderCoreTests.KVBackendGuardStoreTests": 0.007, +"ProviderCoreTests.KVBackendGuardStoreTests": 0.006, "ProviderCoreTests.KVCheckpointPostureTests": 0.0, -"ProviderCoreTests.KVPoolIdleSweepTests": 0.123, +"ProviderCoreTests.KVPoolIdleSweepTests": 0.118, "ProviderCoreTests.KVPoolReclaimerNativeGateTests": 0.001, -"ProviderCoreTests.KVPoolReclaimerTests": 0.008, -"ProviderCoreTests.KVPoolSweepWiringTests": 0.23, -"ProviderCoreTests.KVQuantizationConfigTests": 0.003, -"ProviderCoreTests.KernelTests": 1.668, -"ProviderCoreTests.LaunchAgentDrainAllowanceTests": 0.002, +"ProviderCoreTests.KVPoolReclaimerTests": 0.011, +"ProviderCoreTests.KVPoolSweepWiringTests": 0.217, +"ProviderCoreTests.KVQuantizationConfigTests": 0.004, +"ProviderCoreTests.KernelTests": 1.616, +"ProviderCoreTests.LaunchAgentDrainAllowanceTests": 0.001, "ProviderCoreTests.LaunchAgentDrainIntegrationTests": 0.0, "ProviderCoreTests.LaunchAgentEnvironmentTests": 0.003, -"ProviderCoreTests.LaunchAgentLifecycleTests": 0.014, +"ProviderCoreTests.LaunchAgentLifecycleTests": 0.015, "ProviderCoreTests.LaunchAgentPathsAndErrorsTests": 0.003, -"ProviderCoreTests.LaunchAgentRemovalTests": 0.022, +"ProviderCoreTests.LaunchAgentRemovalTests": 0.023, "ProviderCoreTests.LaunchAgentRestartTests": 0.0, -"ProviderCoreTests.LaunchAgentServicePlistTests": 0.002, -"ProviderCoreTests.LifecycleMailboxTests": 0.029, -"ProviderCoreTests.LiveInferenceMetallibSourceTests": 0.022, -"ProviderCoreTests.LoadedModelsPersistenceWiringTests": 0.009, -"ProviderCoreTests.LoadedModelsStoreTests": 0.002, -"ProviderCoreTests.LocalChatRequestTests": 0.007, -"ProviderCoreTests.LocalContentPartRefusalTests": 0.008, +"ProviderCoreTests.LaunchAgentServicePlistTests": 0.003, +"ProviderCoreTests.LifecycleMailboxTests": 0.032, +"ProviderCoreTests.LiveInferenceMetallibSourceTests": 0.018, +"ProviderCoreTests.LoadedModelsPersistenceWiringTests": 0.025, +"ProviderCoreTests.LoadedModelsStoreTests": 0.004, +"ProviderCoreTests.LocalChatRequestTests": 0.006, +"ProviderCoreTests.LocalContentPartRefusalTests": 0.006, "ProviderCoreTests.LocalDisconnectTests": 0.003, -"ProviderCoreTests.LocalDrainHTTPTests": 0.01, +"ProviderCoreTests.LocalDrainHTTPTests": 0.009, "ProviderCoreTests.LocalEndpointFileTests": 0.003, "ProviderCoreTests.LocalOpenAIObjectCompatibilityTests": 0.002, "ProviderCoreTests.LocalOutputTokenLimitTests": 0.005, -"ProviderCoreTests.LocalResponseConversationTests": 0.014, -"ProviderCoreTests.LocalResponseTrackerTests": 0.013, +"ProviderCoreTests.LocalResponseConversationTests": 0.012, +"ProviderCoreTests.LocalResponseTrackerTests": 0.014, "ProviderCoreTests.LocalServingPostureTests": 0.001, "ProviderCoreTests.LocalStreamingFailureTests": 0.003, "ProviderCoreTests.MDMEnrollmentTests": 0.001, "ProviderCoreTests.MDMTrustDiagnosisTests": 0.001, "ProviderCoreTests.MLXMemoryGuardConfigureOnceTests": 0.001, -"ProviderCoreTests.MTPAcceptanceConfigTests": 0.001, -"ProviderCoreTests.MTPBenchmarkTests": 0.194, +"ProviderCoreTests.MTPAcceptanceConfigTests": 0.002, +"ProviderCoreTests.MTPBenchmarkTests": 0.166, "ProviderCoreTests.MTPBetaFeatureTests": 0.0, "ProviderCoreTests.MTPConfigKeyTests": 0.004, "ProviderCoreTests.MTPIdleUpgradeTests": 0.001, -"ProviderCoreTests.MTPPostureTelemetryTests": 1.029, -"ProviderCoreTests.MTPResliceFallbackTests": 0.046, +"ProviderCoreTests.MTPPostureTelemetryTests": 1.117, +"ProviderCoreTests.MTPResliceFallbackTests": 0.097, "ProviderCoreTests.MTPStagingReservationsTests": 0.0, "ProviderCoreTests.MTPSupportedModelsTests": 0.0, -"ProviderCoreTests.MediaKindClassificationTests": 0.002, +"ProviderCoreTests.MediaKindClassificationTests": 0.003, "ProviderCoreTests.MediaToolMetadataTests": 0.002, -"ProviderCoreTests.MetallibHashTests": 0.007, +"ProviderCoreTests.MetallibHashTests": 0.009, "ProviderCoreTests.MiMoCompleteCheckpointIdentityTests": 0.002, -"ProviderCoreTests.MiMoImageHTTPIngressTests": 1.235, -"ProviderCoreTests.MiMoImageOnboardingSelectionTests": 0.107, -"ProviderCoreTests.MiMoInstalledEncryptedLinkPolicyTests": 0.269, -"ProviderCoreTests.MiMoInstalledImagePolicyTests": 0.213, +"ProviderCoreTests.MiMoImageHTTPIngressTests": 1.184, +"ProviderCoreTests.MiMoImageOnboardingSelectionTests": 0.112, +"ProviderCoreTests.MiMoInstalledEncryptedLinkPolicyTests": 0.289, +"ProviderCoreTests.MiMoInstalledImagePolicyTests": 0.218, "ProviderCoreTests.MiMoMediaDecodeMemoryTests": 0.818, "ProviderCoreTests.MiMoMemoryAdmissionTests": 0.001, "ProviderCoreTests.MiMoTestPrerequisitesTests": 0.001, @@ -650,164 +656,166 @@ "ProviderCoreTests.MiMoV26TemplateFixTests": 0.009, "ProviderCoreTests.MiMoV26WiredDeviceContextTests": 0.001, "ProviderCoreTests.MiMoV26WiredResidencyTests": 0.046, -"ProviderCoreTests.ModelArtifactPublicationTests": 0.025, -"ProviderCoreTests.ModelArtifactReceiptTests": 0.571, -"ProviderCoreTests.ModelArtifactWriteLeaseTests": 0.004, +"ProviderCoreTests.ModelArtifactPublicationTests": 0.024, +"ProviderCoreTests.ModelArtifactReceiptTests": 0.626, +"ProviderCoreTests.ModelArtifactWriteLeaseTests": 0.003, "ProviderCoreTests.ModelAutopilotHistoryTests": 0.002, -"ProviderCoreTests.ModelAutopilotOperationOwnershipTests": 0.012, -"ProviderCoreTests.ModelAutopilotRuntimeTests": 0.322, -"ProviderCoreTests.ModelAutopilotShadowTests": 0.028, +"ProviderCoreTests.ModelAutopilotOperationOwnershipTests": 0.019, +"ProviderCoreTests.ModelAutopilotRuntimeTests": 0.32, +"ProviderCoreTests.ModelAutopilotShadowTests": 0.027, "ProviderCoreTests.ModelAutopilotTests": 0.003, -"ProviderCoreTests.ModelAutopilotUnloadTests": 0.117, +"ProviderCoreTests.ModelAutopilotUnloadTests": 0.196, "ProviderCoreTests.ModelBenchmarkDispatchTests": 0.003, "ProviderCoreTests.ModelBenchmarkReportTests": 0.001, -"ProviderCoreTests.ModelCacheConfigurationTests": 0.002, +"ProviderCoreTests.ModelCacheConfigurationTests": 0.003, "ProviderCoreTests.ModelCalibrationPolicyTests": 0.001, -"ProviderCoreTests.ModelCalibrationTests": 5.721, -"ProviderCoreTests.ModelCatalogTests": 2.463, +"ProviderCoreTests.ModelCalibrationTests": 6.22, +"ProviderCoreTests.ModelCatalogTests": 2.472, "ProviderCoreTests.ModelCheckpointConversationLiveTests": 0.0, -"ProviderCoreTests.ModelCheckpointDonationControlTests": 0.003, -"ProviderCoreTests.ModelCheckpointObservationLifetimeTests": 0.098, +"ProviderCoreTests.ModelCheckpointDonationControlTests": 0.005, +"ProviderCoreTests.ModelCheckpointObservationLifetimeTests": 0.11, "ProviderCoreTests.ModelCheckpointRestoreContentionLiveTests": 0.0, "ProviderCoreTests.ModelCheckpointStorageLiveTests": 0.0, -"ProviderCoreTests.ModelCheckpointStorageSpecificationTests": 0.005, -"ProviderCoreTests.ModelDownloadCacheTests": 0.005, -"ProviderCoreTests.ModelDownloadProgressTests": 0.305, -"ProviderCoreTests.ModelLoadEvictionAndAdmissionTests": 0.554, -"ProviderCoreTests.ModelLoadRefusalTests": 0.123, -"ProviderCoreTests.ModelPrefetchCoordinatorTests": 0.275, -"ProviderCoreTests.ModelPrefetchDownloaderTests": 0.759, -"ProviderCoreTests.ModelPrefixBenchmarkAdjacentForkTests": 0.014, -"ProviderCoreTests.ModelPrefixBenchmarkCleanupTests": 0.002, +"ProviderCoreTests.ModelCheckpointStorageSpecificationTests": 0.004, +"ProviderCoreTests.ModelDownloadCacheTests": 0.006, +"ProviderCoreTests.ModelDownloadProgressDownloaderTests": 4.492, +"ProviderCoreTests.ModelDownloadProgressTests": 0.17, +"ProviderCoreTests.ModelLoadEvictionAndAdmissionTests": 1.106, +"ProviderCoreTests.ModelLoadRefusalTests": 0.121, +"ProviderCoreTests.ModelPrefetchCoordinatorTests": 0.272, +"ProviderCoreTests.ModelPrefetchDownloaderTests": 0.854, +"ProviderCoreTests.ModelPrefixBenchmarkAdjacentForkTests": 0.009, +"ProviderCoreTests.ModelPrefixBenchmarkCleanupTests": 0.001, "ProviderCoreTests.ModelPrefixBenchmarkDiagnosticsTests": 0.001, "ProviderCoreTests.ModelPrefixBenchmarkLiveTests": 0.0, -"ProviderCoreTests.ModelPrefixBenchmarkMTPObservationTests": 0.001, +"ProviderCoreTests.ModelPrefixBenchmarkMTPObservationTests": 0.002, "ProviderCoreTests.ModelPrefixBenchmarkOutputTimingTests": 0.0, "ProviderCoreTests.ModelPrefixBenchmarkQuiescenceTimingTests": 0.001, -"ProviderCoreTests.ModelPrefixBenchmarkTerminalTests": 0.002, -"ProviderCoreTests.ModelRequirementLineTests": 0.0, -"ProviderCoreTests.ModelRevisionActivationTests": 0.043, -"ProviderCoreTests.ModelRevisionPreparationTests": 0.083, -"ProviderCoreTests.ModelRevisionPublicationTests": 0.078, -"ProviderCoreTests.ModelScannerArchitectureTests": 0.006, +"ProviderCoreTests.ModelPrefixBenchmarkTerminalTests": 0.001, +"ProviderCoreTests.ModelRequirementLineTests": 0.001, +"ProviderCoreTests.ModelRevisionActivationTests": 0.05, +"ProviderCoreTests.ModelRevisionPreparationTests": 0.091, +"ProviderCoreTests.ModelRevisionPublicationTests": 0.07, +"ProviderCoreTests.ModelScannerArchitectureTests": 0.005, "ProviderCoreTests.ModelScannerMemoryFilterTests": 0.004, -"ProviderCoreTests.ModelSelectionDownloadTests": 0.029, -"ProviderCoreTests.ModelSlotBookkeepingTests": 0.079, +"ProviderCoreTests.ModelSelectionDownloadTests": 0.031, +"ProviderCoreTests.ModelSlotBookkeepingTests": 0.031, "ProviderCoreTests.MultimodalErrorMappingTests": 0.0, "ProviderCoreTests.NativeBlockRetirementBridgeTests": 0.115, -"ProviderCoreTests.NativeChannelSplitterTests": 0.017, -"ProviderCoreTests.NativeCheckpointQuantizationTests": 0.078, -"ProviderCoreTests.NativeDiffusionCheckpointKeysTests": 0.004, -"ProviderCoreTests.NativeDiffusionCheckpointStoreTests": 2.136, +"ProviderCoreTests.NativeChannelSplitterTests": 0.023, +"ProviderCoreTests.NativeCheckpointQuantizationTests": 0.093, +"ProviderCoreTests.NativeDiffusionCheckpointKeysTests": 0.003, +"ProviderCoreTests.NativeDiffusionCheckpointStoreTests": 0.865, "ProviderCoreTests.NativeLocalConsumerOwnershipTests": 0.014, -"ProviderCoreTests.NativeMediaToolPreparationTests": 0.002, +"ProviderCoreTests.NativeMediaToolPreparationTests": 0.001, "ProviderCoreTests.NativeMediaToolsCapabilityTests": 0.001, "ProviderCoreTests.NativeMemoryReclamationTests": 0.0, "ProviderCoreTests.NativeMemoryRetirementWindowTests": 0.0, -"ProviderCoreTests.NativeModelToolChoiceTests": 0.003, +"ProviderCoreTests.NativeModelToolChoiceTests": 0.002, "ProviderCoreTests.NativeOutputControlRefusalTests": 0.0, -"ProviderCoreTests.NativePairMemberContractTests": 0.026, -"ProviderCoreTests.NativePairMemberControlTests": 0.163, -"ProviderCoreTests.NativePairMemberInstallTests": 0.006, -"ProviderCoreTests.NativePairMemberInvocationTests": 0.944, -"ProviderCoreTests.NativePairMemberServingTests": 2.699, -"ProviderCoreTests.NativePairMessageTests": 0.002, -"ProviderCoreTests.NativePairSessionHeartbeatTests": 0.314, -"ProviderCoreTests.NativeServeQualificationTests": 0.007, -"ProviderCoreTests.NativeServeRunLifetimeTests": 0.002, -"ProviderCoreTests.NativeToolCapabilityAdvertisementTests": 0.001, -"ProviderCoreTests.NativeToolStreamRouterTests": 0.027, +"ProviderCoreTests.NativePairMemberContractTests": 0.032, +"ProviderCoreTests.NativePairMemberControlTests": 0.178, +"ProviderCoreTests.NativePairMemberInstallTests": 0.01, +"ProviderCoreTests.NativePairMemberInvocationTests": 0.962, +"ProviderCoreTests.NativePairMemberServingTests": 2.897, +"ProviderCoreTests.NativePairMessageTests": 0.001, +"ProviderCoreTests.NativePairSessionHeartbeatTests": 0.394, +"ProviderCoreTests.NativeServeQualificationTests": 0.006, +"ProviderCoreTests.NativeServeRunLifetimeTests": 0.004, +"ProviderCoreTests.NativeToolCapabilityAdvertisementTests": 0.002, +"ProviderCoreTests.NativeToolStreamRouterTests": 0.02, "ProviderCoreTests.NativeWorkerServeQualificationTests": 0.002, "ProviderCoreTests.Nemotron35ArchitectureTests": 0.001, -"ProviderCoreTests.NemotronDemandedShortCheckpointTests": 0.032, +"ProviderCoreTests.NemotronDemandedShortCheckpointTests": 0.029, "ProviderCoreTests.NemotronMTPDeclarationTests": 0.0, -"ProviderCoreTests.NemotronPagingPrefixIntegrationTests": 1.153, -"ProviderCoreTests.NemotronStandaloneAdmissionTests": 0.013, -"ProviderCoreTests.NemotronSuperDurablePrefixCacheTests": 7.075, -"ProviderCoreTests.NemotronSuperImageDecodeTests": 1.288, -"ProviderCoreTests.NemotronSuperImageFormatHTTPTests": 9.064, -"ProviderCoreTests.NemotronSuperImageGoldenTests": 16.856, +"ProviderCoreTests.NemotronPagingPrefixIntegrationTests": 15.772, +"ProviderCoreTests.NemotronStandaloneAdmissionTests": 0.01, +"ProviderCoreTests.NemotronSuperDurablePrefixCacheTests": 5.702, +"ProviderCoreTests.NemotronSuperImageDecodeTests": 1.258, +"ProviderCoreTests.NemotronSuperImageFormatHTTPTests": 7.671, +"ProviderCoreTests.NemotronSuperImageGoldenTests": 16.983, "ProviderCoreTests.NemotronSuperImageHTTPRelayTests": 0.001, -"ProviderCoreTests.NemotronSuperImagePlanTests": 1.516, -"ProviderCoreTests.NemotronSuperJPEGContainerTests": 0.013, -"ProviderCoreTests.NemotronSuperLoadAdmissionTests": 0.001, -"ProviderCoreTests.NemotronSuperLocalBindingTests": 1.035, -"ProviderCoreTests.NemotronSuperLocalHTTPAdmissionTests": 3.767, -"ProviderCoreTests.NemotronSuperLocalHTTPTests": 5.747, -"ProviderCoreTests.NemotronSuperLocalImageBindingTests": 0.578, -"ProviderCoreTests.NemotronSuperLocalMTPBatchedTests": 5.012, -"ProviderCoreTests.NemotronSuperLocalMTPTests": 5.983, +"ProviderCoreTests.NemotronSuperImagePlanTests": 1.13, +"ProviderCoreTests.NemotronSuperJPEGContainerTests": 0.012, +"ProviderCoreTests.NemotronSuperLoadAdmissionTests": 0.002, +"ProviderCoreTests.NemotronSuperLocalBindingTests": 3.053, +"ProviderCoreTests.NemotronSuperLocalHTTPAdmissionTests": 7.535, +"ProviderCoreTests.NemotronSuperLocalHTTPTests": 3.352, +"ProviderCoreTests.NemotronSuperLocalImageBindingTests": 0.664, +"ProviderCoreTests.NemotronSuperLocalMTPBatchedTests": 5.659, +"ProviderCoreTests.NemotronSuperLocalMTPTests": 6.49, "ProviderCoreTests.NemotronSuperLocalOutputTests": 0.055, -"ProviderCoreTests.NemotronSuperLocalOwnerTests": 0.859, -"ProviderCoreTests.NemotronSuperLocalPagedTests": 2.575, -"ProviderCoreTests.NemotronSuperLocalPrefillTests": 1.838, -"ProviderCoreTests.NemotronSuperLocalPrefixCacheTests": 4.068, +"ProviderCoreTests.NemotronSuperLocalOwnerTests": 1.325, +"ProviderCoreTests.NemotronSuperLocalPagedTests": 2.634, +"ProviderCoreTests.NemotronSuperLocalPrefillTests": 3.447, +"ProviderCoreTests.NemotronSuperLocalPrefixCacheTests": 5.213, "ProviderCoreTests.NemotronSuperLongContextLiveTests": 0.0, -"ProviderCoreTests.NemotronSuperLongContextTests": 0.201, -"ProviderCoreTests.NemotronSuperManagedSlotTests": 26.641, -"ProviderCoreTests.NemotronSuperMediaChargeTests": 1.672, +"ProviderCoreTests.NemotronSuperLongContextTests": 0.581, +"ProviderCoreTests.NemotronSuperManagedSlotTests": 26.678, +"ProviderCoreTests.NemotronSuperMediaChargeTests": 1.521, "ProviderCoreTests.NemotronSuperMemoryLiveTests": 0.0, -"ProviderCoreTests.NemotronSuperOpenRouterCapabilityTests": 0.472, -"ProviderCoreTests.NemotronSuperOpenRouterVideoTests": 57.04, -"ProviderCoreTests.NemotronSuperPNGTextTests": 0.059, +"ProviderCoreTests.NemotronSuperOpenRouterCapabilityTests": 0.477, +"ProviderCoreTests.NemotronSuperOpenRouterVideoTests": 51.872, +"ProviderCoreTests.NemotronSuperPNGTextTests": 0.058, "ProviderCoreTests.NemotronSuperPagedLiveTests": 0.0, -"ProviderCoreTests.NemotronSuperPrefixCacheEvidenceTests": 4.038, +"ProviderCoreTests.NemotronSuperPrefixCacheEvidenceTests": 1.091, "ProviderCoreTests.NemotronSuperPromptContractTests": 0.433, "ProviderCoreTests.NemotronSuperPromptGoldenTests": 0.651, "ProviderCoreTests.NemotronSuperRecurrentAdmissionTests": 0.001, -"ProviderCoreTests.NemotronSuperServingPolicyTests": 0.259, -"ProviderCoreTests.NemotronSuperVideoBindingTests": 9.267, -"ProviderCoreTests.NemotronSuperVideoDecodeTests": 2.481, -"ProviderCoreTests.NemotronSuperVideoGoldenTests": 9.044, +"ProviderCoreTests.NemotronSuperServingPolicyTests": 0.258, +"ProviderCoreTests.NemotronSuperVideoBindingTests": 10.119, +"ProviderCoreTests.NemotronSuperVideoDecodeTests": 2.353, +"ProviderCoreTests.NemotronSuperVideoGoldenTests": 8.707, "ProviderCoreTests.NemotronTemplateParityLiveTests": 0.001, -"ProviderCoreTests.ObservedRateDeadlineAdmissionTests": 0.01, -"ProviderCoreTests.OuterPrefixCacheReceiptTests": 0.004, +"ProviderCoreTests.NetworkFrameworkCloseCodeTests": 0.012, +"ProviderCoreTests.ObservedRateDeadlineAdmissionTests": 0.009, +"ProviderCoreTests.OuterPrefixCacheReceiptTests": 0.005, "ProviderCoreTests.PackagedRetainedGemmaSmokeTests": 0.001, "ProviderCoreTests.PagedFootprintTelemetryTests": 0.001, -"ProviderCoreTests.PagedKernelPreflightTests": 4.907, +"ProviderCoreTests.PagedKernelPreflightTests": 4.99, "ProviderCoreTests.PagedStorageTelemetryTests": 0.001, "ProviderCoreTests.PagedTeacherForcedAgreementTests": 0.0, "ProviderCoreTests.PerformanceHeartbeatMaterialityTests": 0.0, "ProviderCoreTests.PersistentEnclaveKeyErrorTests": 0.0, -"ProviderCoreTests.PlannedProviderDisconnectTests": 2.217, +"ProviderCoreTests.PlannedProviderDisconnectTests": 2.407, "ProviderCoreTests.PrefillDeadlineProductionConfigTests": 0.005, "ProviderCoreTests.PrefillEvidenceRecoveryStateTests": 0.0, -"ProviderCoreTests.PrefillEvidenceRecoveryTests": 0.587, -"ProviderCoreTests.PrefixCacheCheckpointIdentityTests": 0.014, +"ProviderCoreTests.PrefillEvidenceRecoveryTests": 0.669, +"ProviderCoreTests.PrefixCacheCheckpointIdentityTests": 0.016, "ProviderCoreTests.PrefixCacheDiagnosisTests": 0.0, -"ProviderCoreTests.PrefixCacheEvidenceSequencerTests": 0.032, -"ProviderCoreTests.PrefixCacheLoadHashTests": 0.017, -"ProviderCoreTests.PrefixCachePolicyTests": 0.008, -"ProviderCoreTests.PrefixCacheReceiptTests": 0.065, -"ProviderCoreTests.ProcessLifecycleTests": 0.006, +"ProviderCoreTests.PrefixCacheEvidenceSequencerTests": 0.029, +"ProviderCoreTests.PrefixCacheLoadHashTests": 0.018, +"ProviderCoreTests.PrefixCachePolicyTests": 0.007, +"ProviderCoreTests.PrefixCacheReceiptTests": 0.064, +"ProviderCoreTests.ProcessLifecycleTests": 0.008, "ProviderCoreTests.ProcessMemoryNativeIntegrationTests": 0.719, "ProviderCoreTests.ProcessMemoryTelemetryTests": 0.001, -"ProviderCoreTests.ProductionModelCalibrationTests": 49.866, +"ProviderCoreTests.ProductionModelCalibrationTests": 51.267, "ProviderCoreTests.ProductionPromptParityTests": 0.0, "ProviderCoreTests.PromptDateRenderingTests": 0.003, -"ProviderCoreTests.PromptTokenCacheTests": 1.05, -"ProviderCoreTests.ProviderAuthorizationConnectionTests": 0.003, +"ProviderCoreTests.PromptTokenCacheTests": 1.088, +"ProviderCoreTests.ProviderAuthorizationConnectionTests": 0.004, "ProviderCoreTests.ProviderAuthorizationProtocolTests": 0.001, -"ProviderCoreTests.ProviderAuthorizationReadinessTests": 0.002, +"ProviderCoreTests.ProviderAuthorizationReadinessTests": 0.003, "ProviderCoreTests.ProviderAutoRestartConfigTests": 0.001, -"ProviderCoreTests.ProviderBusyWireTests": 0.001, -"ProviderCoreTests.ProviderCancelledPrefixCacheTests": 0.216, +"ProviderCoreTests.ProviderBusyWireTests": 0.002, +"ProviderCoreTests.ProviderCancelledPrefixCacheTests": 0.282, "ProviderCoreTests.ProviderCapabilityLabelsTests": 0.0, -"ProviderCoreTests.ProviderConfigParseGrowthTests": 0.008, +"ProviderCoreTests.ProviderConfigParseGrowthTests": 0.007, "ProviderCoreTests.ProviderLaunchSnapshotTests": 0.0, -"ProviderCoreTests.ProviderLifecycleTests": 2.39, -"ProviderCoreTests.ProviderLogoutTests": 0.762, -"ProviderCoreTests.ProviderLoopCalibrationTests": 2.876, -"ProviderCoreTests.ProviderLoopMTPUpgradeTests": 0.156, +"ProviderCoreTests.ProviderLifecycleTests": 2.447, +"ProviderCoreTests.ProviderLogoutTests": 0.773, +"ProviderCoreTests.ProviderLoopCalibrationTests": 3.038, +"ProviderCoreTests.ProviderLoopMTPUpgradeTests": 0.144, "ProviderCoreTests.ProviderLoopNativeMiMoLifetimeTests": 1.618, -"ProviderCoreTests.ProviderLoopPrefetchTests": 0.82, -"ProviderCoreTests.ProviderMTPFactoryTests": 0.031, -"ProviderCoreTests.ProviderModelSwitchTests": 1.737, -"ProviderCoreTests.ProviderRunMarkerTests": 0.016, -"ProviderCoreTests.ProviderRuntimeCapabilityTests": 0.005, -"ProviderCoreTests.ProviderSignalTests": 3.004, +"ProviderCoreTests.ProviderLoopPrefetchTests": 0.864, +"ProviderCoreTests.ProviderMTPFactoryTests": 0.027, +"ProviderCoreTests.ProviderModelSwitchTests": 1.689, +"ProviderCoreTests.ProviderRunMarkerTests": 0.015, +"ProviderCoreTests.ProviderRuntimeCapabilityTests": 0.006, +"ProviderCoreTests.ProviderSignalTests": 3.083, "ProviderCoreTests.ProviderStopSignalsTests": 0.0, -"ProviderCoreTests.QMVWideMetalTests": 1.172, +"ProviderCoreTests.QMVWideMetalTests": 0.996, "ProviderCoreTests.Qwen35AdjacentCheckpointLiveTests": 0.0, "ProviderCoreTests.Qwen35CBv2FixedRequestAccountingTests": 0.001, "ProviderCoreTests.Qwen35CheckpointRetentionLiveTests": 0.0, @@ -817,215 +825,217 @@ "ProviderCoreTests.Qwen38ProductionCanaryTests": 0.0, "ProviderCoreTests.Qwen4CanonicalMediaPositionsTests": 0.002, "ProviderCoreTests.Qwen4DefaultProfilePerformanceTests": 0.001, -"ProviderCoreTests.Qwen4EmbeddedMTPTests": 0.011, +"ProviderCoreTests.Qwen4EmbeddedMTPTests": 0.013, "ProviderCoreTests.Qwen4ExecutionPolicyTests": 0.0, -"ProviderCoreTests.Qwen4ExpLoadFootprintTests": 0.025, -"ProviderCoreTests.Qwen4ExpMmapFootprintTests": 0.01, -"ProviderCoreTests.Qwen4FactorySelectionTests": 0.003, +"ProviderCoreTests.Qwen4ExpLoadFootprintTests": 0.009, +"ProviderCoreTests.Qwen4ExpMmapFootprintTests": 0.015, +"ProviderCoreTests.Qwen4FactorySelectionTests": 0.002, "ProviderCoreTests.Qwen4FixedDepthPerformanceProbeTests": 0.001, "ProviderCoreTests.Qwen4LayerSubmissionSafetyProbeTests": 0.001, "ProviderCoreTests.Qwen4LayerSubmissionStateProbeTests": 0.0, -"ProviderCoreTests.Qwen4NativeMediaPrefixPositionsTests": 0.348, +"ProviderCoreTests.Qwen4NativeMediaPrefixPositionsTests": 0.272, "ProviderCoreTests.Qwen4NativeToolConstraintTests": 0.005, -"ProviderCoreTests.Qwen4OwnedVLMRoutingTests": 0.006, -"ProviderCoreTests.Qwen4PagingPrefixIntegrationTests": 18.894, +"ProviderCoreTests.Qwen4OwnedVLMRoutingTests": 0.008, +"ProviderCoreTests.Qwen4PagingPrefixIntegrationTests": 18.933, "ProviderCoreTests.Qwen4ReasoningControlTests": 0.0, -"ProviderCoreTests.Qwen4ReasoningEffortValidationTests": 0.003, -"ProviderCoreTests.Qwen4ReclaimAdmissionTests": 0.126, +"ProviderCoreTests.Qwen4ReasoningEffortValidationTests": 0.004, +"ProviderCoreTests.Qwen4ReclaimAdmissionTests": 0.133, "ProviderCoreTests.Qwen4SparseParallelProbeTests": 0.001, -"ProviderCoreTests.Qwen4StandaloneAdmissionTests": 0.039, -"ProviderCoreTests.Qwen4SupportPolicyTests": 0.007, +"ProviderCoreTests.Qwen4StandaloneAdmissionTests": 0.027, +"ProviderCoreTests.Qwen4SupportPolicyTests": 0.01, "ProviderCoreTests.Qwen4ToolChoicePromptPolicyTests": 0.002, -"ProviderCoreTests.Qwen4ToolFramingVocabularyTests": 0.001, -"ProviderCoreTests.QwenJSONAnswerConstraintTests": 4.207, -"ProviderCoreTests.QwenJSONAnswerOutputTests": 0.006, -"ProviderCoreTests.QwenJSONAnswerPolicyTests": 0.581, +"ProviderCoreTests.Qwen4ToolFramingVocabularyTests": 0.002, +"ProviderCoreTests.QwenJSONAnswerConstraintTests": 4.233, +"ProviderCoreTests.QwenJSONAnswerOutputTests": 0.003, +"ProviderCoreTests.QwenJSONAnswerPolicyTests": 0.606, "ProviderCoreTests.QwenJSONAnswerRealTokenizerTests": 0.0, -"ProviderCoreTests.QwenJSONAnswerServingTests": 0.548, +"ProviderCoreTests.QwenJSONAnswerServingTests": 0.555, "ProviderCoreTests.QwenPerImageVisionEquivalenceTests": 0.0, -"ProviderCoreTests.QwenVLMTargetExtractionTests": 2.961, +"ProviderCoreTests.QwenVLMTargetExtractionTests": 2.747, "ProviderCoreTests.ReasoningEffortLiveTests": 0.0, "ProviderCoreTests.ReasoningParserSelectionTests": 0.0, -"ProviderCoreTests.ReasoningPromptProbeTests": 0.004, +"ProviderCoreTests.ReasoningPromptProbeTests": 0.003, "ProviderCoreTests.ReleaseCoResidencyLiveTests": 0.0, -"ProviderCoreTests.RequestProfileBuilderTests": 0.054, -"ProviderCoreTests.ReserveRaisePreflightTests": 1.11, -"ProviderCoreTests.ResidentPrefixCacheEvidenceTests": 0.021, +"ProviderCoreTests.RequestProfileBuilderTests": 0.046, +"ProviderCoreTests.ReserveRaisePreflightTests": 1.089, +"ProviderCoreTests.ResidentPrefixCacheEvidenceTests": 0.02, "ProviderCoreTests.RetirementGateTests": 0.001, -"ProviderCoreTests.RuntimeConcurrencyBenchmarkTests": 0.051, -"ProviderCoreTests.RuntimeGenerationBenchmarkTests": 0.001, +"ProviderCoreTests.RuntimeConcurrencyBenchmarkTests": 0.053, +"ProviderCoreTests.RuntimeGenerationBenchmarkTests": 0.002, "ProviderCoreTests.RuntimeMetallibTemporaryDirectoryTests": 0.004, "ProviderCoreTests.SDPAPartialPrecisionTests": 1.324, -"ProviderCoreTests.SSDBlockIndexTests": 0.0, -"ProviderCoreTests.SSDBlockStoreTests": 0.064, -"ProviderCoreTests.SSDBlockStreamingTests": 0.021, -"ProviderCoreTests.SSDCacheEpochStoreRecoveryTests": 0.288, -"ProviderCoreTests.SSDCacheEpochStoreTests": 0.281, +"ProviderCoreTests.SSDBlockIndexTests": 0.763, +"ProviderCoreTests.SSDBlockStoreTests": 0.063, +"ProviderCoreTests.SSDBlockStreamingTests": 0.027, +"ProviderCoreTests.SSDCacheEpochStoreRecoveryTests": 0.289, +"ProviderCoreTests.SSDCacheEpochStoreTests": 0.309, "ProviderCoreTests.SSDCheckpointCPUAcceptanceTests": 0.314, -"ProviderCoreTests.SSDCheckpointCommitRetirementTests": 0.043, -"ProviderCoreTests.SSDCheckpointDeltaTests": 0.496, -"ProviderCoreTests.SSDCheckpointDemandAdmissionTests": 0.041, +"ProviderCoreTests.SSDCheckpointCommitRetirementTests": 0.044, +"ProviderCoreTests.SSDCheckpointDeltaTests": 0.504, +"ProviderCoreTests.SSDCheckpointDemandAdmissionTests": 0.04, "ProviderCoreTests.SSDCheckpointDemandTests": 0.011, "ProviderCoreTests.SSDCheckpointDonationHashBenchmarkTests": 0.0, "ProviderCoreTests.SSDCheckpointDonationHashTests": 0.019, "ProviderCoreTests.SSDCheckpointFileCoordinatorPathTests": 0.004, -"ProviderCoreTests.SSDCheckpointFileCoordinatorTests": 0.01, -"ProviderCoreTests.SSDCheckpointFleetWritePriorityTests": 0.107, +"ProviderCoreTests.SSDCheckpointFileCoordinatorTests": 0.194, +"ProviderCoreTests.SSDCheckpointFleetWritePriorityTests": 0.113, "ProviderCoreTests.SSDCheckpointLookupTests": 0.0, -"ProviderCoreTests.SSDCheckpointMaintenanceEpochTests": 0.068, -"ProviderCoreTests.SSDCheckpointPublicationCPUTests": 0.016, -"ProviderCoreTests.SSDCheckpointPublicationTests": 0.014, -"ProviderCoreTests.SSDCheckpointReadBudgetTests": 0.005, -"ProviderCoreTests.SSDCheckpointRecencyCoordinationTests": 0.01, -"ProviderCoreTests.SSDCheckpointRemovalRaceTests": 0.334, -"ProviderCoreTests.SSDCheckpointStageCostTests": 0.026, -"ProviderCoreTests.SSDCheckpointStageReservationTests": 0.005, -"ProviderCoreTests.SSDCheckpointWriteRecoveryTests": 0.153, +"ProviderCoreTests.SSDCheckpointMaintenanceEpochTests": 0.058, +"ProviderCoreTests.SSDCheckpointPublicationCPUTests": 0.015, +"ProviderCoreTests.SSDCheckpointPublicationTests": 0.015, +"ProviderCoreTests.SSDCheckpointReadBudgetTests": 0.006, +"ProviderCoreTests.SSDCheckpointRecencyCoordinationTests": 0.013, +"ProviderCoreTests.SSDCheckpointRemovalRaceTests": 0.162, +"ProviderCoreTests.SSDCheckpointStageCostTests": 0.025, +"ProviderCoreTests.SSDCheckpointStageReservationTests": 0.007, +"ProviderCoreTests.SSDCheckpointWriteRecoveryTests": 0.148, +"ProviderCoreTests.SSDClosedStoreEvictionTests": 1.257, "ProviderCoreTests.SSDCompleteCheckpointStageCapTests": 0.001, -"ProviderCoreTests.SSDCompleteDonationTelemetryTests": 0.031, -"ProviderCoreTests.SSDDebugCacheKeyFileTests": 0.037, -"ProviderCoreTests.SSDEpochContinuityTests": 0.065, -"ProviderCoreTests.SSDHybridCheckpointCoordinationTests": 0.085, -"ProviderCoreTests.SSDHybridCheckpointDuplicateTests": 0.159, -"ProviderCoreTests.SSDHybridCheckpointRecencyTests": 0.036, -"ProviderCoreTests.SSDHybridCheckpointStoreFactoryFailureTests": 0.014, -"ProviderCoreTests.SSDHybridCheckpointStoreTests": 0.114, -"ProviderCoreTests.SSDHybridMediaIdentityTests": 0.013, +"ProviderCoreTests.SSDCompleteDonationTelemetryTests": 0.033, +"ProviderCoreTests.SSDDebugCacheKeyFileTests": 0.035, +"ProviderCoreTests.SSDEpochContinuityTests": 0.061, +"ProviderCoreTests.SSDHybridCheckpointCoordinationTests": 0.123, +"ProviderCoreTests.SSDHybridCheckpointDuplicateTests": 0.16, +"ProviderCoreTests.SSDHybridCheckpointRecencyTests": 0.071, +"ProviderCoreTests.SSDHybridCheckpointStoreFactoryFailureTests": 0.02, +"ProviderCoreTests.SSDHybridCheckpointStoreTests": 0.119, +"ProviderCoreTests.SSDHybridMediaIdentityTests": 0.014, "ProviderCoreTests.SSDLookupKeysTests": 0.0, "ProviderCoreTests.SSDNativeCheckpointOracleTests": 1.07, -"ProviderCoreTests.SSDNativePrefixBuilderTests": 0.013, -"ProviderCoreTests.SSDNoFollowIOSpecialFileTests": 0.554, -"ProviderCoreTests.SSDOwnedEntryRetirementTests": 0.014, -"ProviderCoreTests.SSDPersistentTestKeyNamespaceTests": 0.006, -"ProviderCoreTests.SSDPrefixCacheDonationGateTests": 0.472, -"ProviderCoreTests.SSDPrefixCacheDonationOutcomeTests": 0.223, -"ProviderCoreTests.SSDPrefixCacheFactoryConstructionTests": 0.067, +"ProviderCoreTests.SSDNativePrefixBuilderTests": 0.014, +"ProviderCoreTests.SSDNoFollowIOSpecialFileTests": 0.495, +"ProviderCoreTests.SSDOwnedEntryRetirementTests": 0.112, +"ProviderCoreTests.SSDPersistentTestKeyNamespaceTests": 0.007, +"ProviderCoreTests.SSDPrefixCacheDonationGateTests": 0.48, +"ProviderCoreTests.SSDPrefixCacheDonationOutcomeTests": 0.053, +"ProviderCoreTests.SSDPrefixCacheFactoryConstructionTests": 0.059, "ProviderCoreTests.SSDPrefixCacheFactoryMaintenanceTests": 0.024, "ProviderCoreTests.SSDPrefixCacheFactoryPathTests": 0.001, -"ProviderCoreTests.SSDPrefixCacheFactoryRefusalTests": 0.002, -"ProviderCoreTests.SSDPrefixCacheLifecycleTests": 1.781, -"ProviderCoreTests.SSDPrefixCacheMetadataPlanningTests": 0.001, +"ProviderCoreTests.SSDPrefixCacheFactoryRefusalTests": 0.003, +"ProviderCoreTests.SSDPrefixCacheLifecycleTests": 1.681, +"ProviderCoreTests.SSDPrefixCacheMetadataPlanningTests": 0.002, "ProviderCoreTests.SSDPrefixCacheModeTests": 0.001, -"ProviderCoreTests.SSDPrefixCacheReadyReceiptTests": 0.249, -"ProviderCoreTests.SSDPrefixCacheReservationTests": 0.753, -"ProviderCoreTests.SSDPrefixCacheTelemetryTests": 0.005, -"ProviderCoreTests.SSDReadyWriteBarrierTests": 0.054, +"ProviderCoreTests.SSDPrefixCacheReadyReceiptTests": 0.21, +"ProviderCoreTests.SSDPrefixCacheReservationTests": 0.799, +"ProviderCoreTests.SSDPrefixCacheTelemetryTests": 0.004, +"ProviderCoreTests.SSDReadyWriteBarrierTests": 0.056, "ProviderCoreTests.SSDRootIsolationTests": 0.0, -"ProviderCoreTests.SSDSharedProcessCheckpointTests": 0.061, -"ProviderCoreTests.SSDShorterCheckpointRestoreTests": 0.852, +"ProviderCoreTests.SSDSharedProcessCheckpointTests": 0.048, +"ProviderCoreTests.SSDShorterCheckpointRestoreTests": 0.832, "ProviderCoreTests.SSDShorterNativeBlockRestoreTests": 2.004, -"ProviderCoreTests.SSDShorterRestoreClockTests": 0.051, +"ProviderCoreTests.SSDShorterRestoreClockTests": 0.047, "ProviderCoreTests.SSDTestDirectoryTests": 0.002, -"ProviderCoreTests.SSDTrackedNativeRetryTests": 0.012, -"ProviderCoreTests.SSDWholeRootMaintenanceTests": 0.219, -"ProviderCoreTests.SSDWholeRootTelemetryConcurrencyTests": 0.011, -"ProviderCoreTests.SSDWindowSidecarTests": 0.701, -"ProviderCoreTests.SSDWriteBudgetTests": 0.382, -"ProviderCoreTests.SSDWriteEnduranceTests": 1.959, -"ProviderCoreTests.ScheduleTests": 0.011, +"ProviderCoreTests.SSDTrackedNativeRetryTests": 0.015, +"ProviderCoreTests.SSDWholeRootMaintenanceTests": 0.283, +"ProviderCoreTests.SSDWholeRootTelemetryConcurrencyTests": 0.012, +"ProviderCoreTests.SSDWindowSidecarTests": 0.796, +"ProviderCoreTests.SSDWriteBehindLedgerChargeTests": 0.121, +"ProviderCoreTests.SSDWriteBudgetTests": 0.278, +"ProviderCoreTests.SSDWriteEnduranceTests": 1.874, +"ProviderCoreTests.ScheduleTests": 0.009, "ProviderCoreTests.SchedulerPrefillBenchmarkTests": 0.0, -"ProviderCoreTests.SchedulerPrefillDecisionBenchmarkTests": 0.056, +"ProviderCoreTests.SchedulerPrefillDecisionBenchmarkTests": 0.06, "ProviderCoreTests.SchedulerPrefillDecisionEvaluatorTests": 0.14, -"ProviderCoreTests.SchedulerPrefillDecisionKVProvenanceTests": 0.0, -"ProviderCoreTests.SchedulerPrefillDecisionLiveRunnerTests": 0.093, +"ProviderCoreTests.SchedulerPrefillDecisionKVProvenanceTests": 0.001, +"ProviderCoreTests.SchedulerPrefillDecisionLiveRunnerTests": 0.095, "ProviderCoreTests.SchedulerPrefillDecisionLiveTests": 0.0, -"ProviderCoreTests.SchedulerPrefillDecisionMetadataTests": 0.104, +"ProviderCoreTests.SchedulerPrefillDecisionMetadataTests": 0.186, "ProviderCoreTests.SchedulerPrefillPromptTests": 0.003, -"ProviderCoreTests.SecurityCommandRunnerTests": 0.225, +"ProviderCoreTests.SecurityCommandRunnerTests": 0.229, "ProviderCoreTests.SegmentedProductionGrantTests": 0.032, "ProviderCoreTests.SelfUpdaterInstallRootTests": 0.002, -"ProviderCoreTests.SelfUpdaterTests": 40.446, -"ProviderCoreTests.SequenceStateMachineTests": 0.001, +"ProviderCoreTests.SelfUpdaterTests": 41.12, +"ProviderCoreTests.SequenceStateMachineTests": 0.0, "ProviderCoreTests.ServeLoopAppAttestInteropTests": 0.0, -"ProviderCoreTests.ServeLoopAppAttestTests": 1.873, -"ProviderCoreTests.ServeLoopColdLoadTests": 2.907, -"ProviderCoreTests.ServeLoopConnectionTests": 6.481, -"ProviderCoreTests.ServeLoopDispatchTests": 1.586, -"ProviderCoreTests.ServiceReservationHandlerTests": 0.006, -"ProviderCoreTests.ServiceReservationInboundTests": 0.002, +"ProviderCoreTests.ServeLoopAppAttestTests": 2.151, +"ProviderCoreTests.ServeLoopColdLoadTests": 2.788, +"ProviderCoreTests.ServeLoopConnectionTests": 6.565, +"ProviderCoreTests.ServeLoopDispatchTests": 1.483, +"ProviderCoreTests.ServiceReservationHandlerTests": 0.007, +"ProviderCoreTests.ServiceReservationInboundTests": 0.003, "ProviderCoreTests.ServiceReservationLifetimeTests": 0.001, "ProviderCoreTests.ServiceReservationRequestProtocolTests": 0.0, -"ProviderCoreTests.ServingReadinessTests": 0.002, +"ProviderCoreTests.ServingReadinessTests": 0.006, "ProviderCoreTests.SignedReleaseIdentityTests": 0.003, "ProviderCoreTests.SingleProbeInlineDecisionTests": 0.001, "ProviderCoreTests.SlotSizingDriftTests": 0.002, -"ProviderCoreTests.SpecDecArtifactFunnelTests": 0.051, +"ProviderCoreTests.SpecDecArtifactFunnelTests": 0.05, "ProviderCoreTests.SpecDecHuggingFaceTests": 3.213, "ProviderCoreTests.SpecDecLoadGateTests": 0.001, -"ProviderCoreTests.SpecDecResolverTests": 5.31, +"ProviderCoreTests.SpecDecResolverTests": 5.566, "ProviderCoreTests.SpecDecSizingSnapshotTests": 0.001, -"ProviderCoreTests.SpecDecSlotTeardownTests": 0.004, -"ProviderCoreTests.StandaloneEvictionOwnershipTests": 0.003, -"ProviderCoreTests.StandaloneLifecycleControlTests": 0.777, -"ProviderCoreTests.StandaloneMTPUpgradeTests": 0.145, -"ProviderCoreTests.StandaloneServerDrainTests": 0.751, -"ProviderCoreTests.StandaloneServerModelAdmissionTests": 2.034, +"ProviderCoreTests.SpecDecSlotTeardownTests": 0.005, +"ProviderCoreTests.StandaloneEvictionOwnershipTests": 0.004, +"ProviderCoreTests.StandaloneLifecycleControlTests": 0.806, +"ProviderCoreTests.StandaloneMTPUpgradeTests": 0.14, +"ProviderCoreTests.StandaloneServerDrainTests": 0.695, +"ProviderCoreTests.StandaloneServerModelAdmissionTests": 2.043, "ProviderCoreTests.StartupPerformanceEvidenceTests": 0.004, -"ProviderCoreTests.StartupPreloadGateTests": 1.212, -"ProviderCoreTests.StartupPreloadNoEvictTests": 0.048, -"ProviderCoreTests.StartupPreloadPlanTests": 0.019, -"ProviderCoreTests.StartupPreloadPostRegistrationRetirementTests": 0.76, -"ProviderCoreTests.StartupPreloaderTests": 0.002, +"ProviderCoreTests.StartupPreloadGateTests": 1.292, +"ProviderCoreTests.StartupPreloadNoEvictTests": 0.042, +"ProviderCoreTests.StartupPreloadPlanTests": 0.036, +"ProviderCoreTests.StartupPreloadPostRegistrationRetirementTests": 0.734, +"ProviderCoreTests.StartupPreloaderTests": 0.003, "ProviderCoreTests.StartupSelfTestDecodeLiveTests": 0.0, -"ProviderCoreTests.StreamedToolCallTests": 0.033, -"ProviderCoreTests.StreamingFileDownloadDelegateTests": 0.042, -"ProviderCoreTests.StructuredForcedToolAdmissionTests": 0.046, -"ProviderCoreTests.SwiftJinjaCompatibilityTests": 0.004, -"ProviderCoreTests.SwiftJinjaLoopContextTests": 0.004, -"ProviderCoreTests.TeacherForcedBenchmarkTests": 0.005, +"ProviderCoreTests.StreamedToolCallTests": 0.034, +"ProviderCoreTests.StreamingFileDownloadDelegateTests": 0.023, +"ProviderCoreTests.StructuredForcedToolAdmissionTests": 0.044, +"ProviderCoreTests.SwiftJinjaCompatibilityTests": 0.008, +"ProviderCoreTests.SwiftJinjaLoopContextTests": 0.005, +"ProviderCoreTests.TeacherForcedBenchmarkTests": 0.004, "ProviderCoreTests.TelemetryClientTests": 0.0, -"ProviderCoreTests.TelemetryOverflowQueueTests": 0.002, +"ProviderCoreTests.TelemetryOverflowQueueTests": 0.004, "ProviderCoreTests.TelemetrySymmetryTests": 0.001, "ProviderCoreTests.ThinkStreamingLatencyTests": 0.001, -"ProviderCoreTests.ThroughputSweepDecodeTimingTests": 0.002, -"ProviderCoreTests.ThroughputSweepDecodeWarmupTests": 0.001, +"ProviderCoreTests.ThroughputSweepDecodeTimingTests": 0.001, +"ProviderCoreTests.ThroughputSweepDecodeWarmupTests": 0.002, "ProviderCoreTests.ThroughputSweepMedianTests": 0.002, -"ProviderCoreTests.ThroughputSweepNotesTests": 0.004, +"ProviderCoreTests.ThroughputSweepNotesTests": 0.006, "ProviderCoreTests.ThroughputSweepReportTests": 0.002, "ProviderCoreTests.ThroughputSweepRowAggregationTests": 0.0, "ProviderCoreTests.ThroughputSweepTilingTests": 0.0, -"ProviderCoreTests.TinyModelLoadTests": 4.015, +"ProviderCoreTests.TinyModelLoadTests": 3.176, "ProviderCoreTests.ToolCallTemplateArgumentsTests": 0.0, "ProviderCoreTests.ToolChoicePromptPolicyTests": 0.002, "ProviderCoreTests.ToolChoiceViolationErrorTests": 0.001, -"ProviderCoreTests.ToolSchemaNormalizationCorpusTests": 0.003, -"ProviderCoreTests.ToolSchemaNormalizationTests": 0.003, -"ProviderCoreTests.TransitionWatchdogSupervisionTests": 2.092, +"ProviderCoreTests.ToolSchemaNormalizationCorpusTests": 0.002, +"ProviderCoreTests.ToolSchemaNormalizationTests": 0.004, +"ProviderCoreTests.TransitionWatchdogSupervisionTests": 2.226, "ProviderCoreTests.TransitionWatchdogTests": 0.001, "ProviderCoreTests.UnauthorizedConnectionRecoveryTests": 0.001, -"ProviderCoreTests.UnauthorizedConnectionSupervisionTests": 0.067, -"ProviderCoreTests.UnevictableResidentReportTests": 0.078, -"ProviderCoreTests.UnitTests": 4.311, -"ProviderCoreTests.UnreclaimableLoadMemoryTests": 0.102, -"ProviderCoreTests.UnsupportedContentPartIngressTests": 0.004, +"ProviderCoreTests.UnauthorizedConnectionSupervisionTests": 0.061, +"ProviderCoreTests.UnevictableResidentReportTests": 0.08, +"ProviderCoreTests.UnitTests": 4.398, +"ProviderCoreTests.UnreclaimableLoadMemoryTests": 0.105, +"ProviderCoreTests.UnsupportedContentPartIngressTests": 0.003, "ProviderCoreTests.UpdateBannerTests": 0.001, "ProviderCoreTests.UpdateDrainAwarenessTests": 0.074, -"ProviderCoreTests.UpdateJitterTests": 0.001, -"ProviderCoreTests.UpdateProcessLockTests": 1.037, -"ProviderCoreTests.UpdateRecoveryStateTests": 0.001, -"ProviderCoreTests.VerifiedWeightHashStoreTests": 0.024, -"ProviderCoreTests.VisionTowerBudgetArithmeticTests": 0.0, +"ProviderCoreTests.UpdateJitterTests": 0.003, +"ProviderCoreTests.UpdateProcessLockTests": 1.035, +"ProviderCoreTests.UpdateRecoveryStateTests": 0.002, +"ProviderCoreTests.VerifiedWeightHashStoreTests": 0.01, +"ProviderCoreTests.VisionTowerBudgetArithmeticTests": 0.001, "ProviderCoreTests.VisionTowerBudgetIncidentTests": 0.001, "ProviderCoreTests.VisionTowerHeadFactorTests": 0.0, "ProviderCoreTests.WatchdogAgentPlistTests": 0.0, "ProviderCoreTests.WatchdogCrashLoopCountTests": 0.001, -"ProviderCoreTests.WatchdogCrashLoopNextStateTests": 0.003, -"ProviderCoreTests.WatchdogDecisionTests": 0.0, +"ProviderCoreTests.WatchdogCrashLoopNextStateTests": 0.005, +"ProviderCoreTests.WatchdogDecisionTests": 0.001, "ProviderCoreTests.WatchdogEffectiveDownSinceTests": 0.0, -"ProviderCoreTests.WatchdogLaunchAdapterTests": 0.167, +"ProviderCoreTests.WatchdogLaunchAdapterTests": 0.172, "ProviderCoreTests.WatchdogNextStateTests": 0.0, "ProviderCoreTests.WatchdogProbeParseTests": 0.001, -"ProviderCoreTests.WatchdogProviderIdentityTests": 0.004, +"ProviderCoreTests.WatchdogProviderIdentityTests": 0.002, "ProviderCoreTests.WatchdogRearmActionTests": 0.0, -"ProviderCoreTests.WatchdogRecoveryIntegrationTests": 10.995, -"ProviderCoreTests.WatchdogSchedulerTests": 0.061, +"ProviderCoreTests.WatchdogRecoveryIntegrationTests": 11.164, +"ProviderCoreTests.WatchdogSchedulerTests": 0.042, "ProviderCoreTests.WatchdogStateTests": 0.001, "ProviderCoreTests.WedgeMonitorTests": 0.001, -"ProviderCoreTests.WeightHashCacheEligibilityTests": 0.019, -"ProviderCoreTests.WholeMacServiceHeartbeatTests": 0.017, -"ProviderCoreTests.WholeMacServiceReservationTests": 0.046, +"ProviderCoreTests.WeightHashCacheEligibilityTests": 0.027, +"ProviderCoreTests.WholeMacServiceHeartbeatTests": 0.014, +"ProviderCoreTests.WholeMacServiceReservationTests": 0.044, "ServingQualificationTests.FlintHTTPBenchmarkTests": 0.0, -"ServingQualificationTests.ServingPromptCountArtifactTests": 0.004, +"ServingQualificationTests.ServingPromptCountArtifactTests": 0.003, "ServingQualificationTests.ServingPromptCountQualificationTests": 0.0, "ServingQualificationTests.ServingQualificationCollectorTests": 0.0, "ServingQualificationTests.ServingQualificationCompetingModelsTests": 0.0, diff --git a/scripts/test-ci-component-paths.py b/scripts/test-ci-component-paths.py index cc6b292a33..cbcb1fffb1 100644 --- a/scripts/test-ci-component-paths.py +++ b/scripts/test-ci-component-paths.py @@ -256,7 +256,7 @@ def test_expensive_jobs_depend_on_successful_classifier(self): for policy in ("release-integrity", "docs"): self.assertNotIn(" if:", ci[policy]) self.assertIn("python3 scripts/test-ci-component-paths.py", ci["release-integrity"]) - self.assertIn("if: github.event_name == 'push'", ci["cache-swift"]) + self.assertNotIn("cache-swift", ci) def test_detector_has_full_history_no_credentials_or_api_truncation(self): text = (ROOT / ".github/workflows/component-changes.yml").read_text() diff --git a/scripts/test-darkbloom-route.py b/scripts/test-darkbloom-route.py index b082546650..67a141ec2d 100755 --- a/scripts/test-darkbloom-route.py +++ b/scripts/test-darkbloom-route.py @@ -551,7 +551,6 @@ def test_release_and_credentialed_workflows_keep_literal_runners(self): with self.subTest(workflow=filename, job=name): self.assertRegex(job_field(job, "runs-on"), r"^(blacksmith-[a-z0-9-]+|ubuntu-24\.04)$") ci = jobs(self.texts["ci.yml"]) - self.assertEqual(job_field(ci["cache-swift"], "runs-on"), MACOS_FALLBACK) for name in CI_MACOS_JOBS: with self.subTest(workflow="ci.yml", job=name): self.assertEqual(job_field(ci[name], "runs-on"), MACOS_FALLBACK) diff --git a/scripts/test-provider-ci-workflow.py b/scripts/test-provider-ci-workflow.py index 05727be422..e49d1d310a 100644 --- a/scripts/test-provider-ci-workflow.py +++ b/scripts/test-provider-ci-workflow.py @@ -209,7 +209,7 @@ def test_lanes_are_independent_on_dedicated_supported_mac_runners(self): if job_id == "test-provider": # Shards are independent: a failed shard never cancels another. self.assertIn(" strategy:\n # A failed shard does not cancel the other shards.\n" - " fail-fast: false\n matrix:\n shard: [1, 2, 3, 4, 5]\n", job) + " fail-fast: false\n matrix:\n shard: [1, 2, 3, 4, 5, 6, 7, 8]\n", job) else: self.assertNotRegex(job, re.compile(r"^ strategy:", re.MULTILINE), msg=job) self.assertNotIn("continue-on-error:", job) @@ -691,6 +691,10 @@ def test_cluster_metadata_runners_run_every_runner_and_fail_on_any(self): self.assertIn(component, key) for step in (steps[record], steps[upload]): self.assertIn("steps.capability-checks.outcome == 'success'", field(step, "if")) + # A pull request saves only when it restored nothing; pushes save. + self.assertIn("steps.cluster-build-cache.outputs.cache-hit != 'true' && (github.event_name != " + "'pull_request' || steps.cluster-build-cache.outputs.cache-matched-key == '')", + field(step, "if")) support = (ROOT / "libs/darkbloom-cluster/Tests/Support/native-metadata.sh").read_text() self.assertIn('task_jobs="${DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS:-4}"', support) self.assertIn('--jobs "$task_jobs"', support) @@ -705,15 +709,10 @@ def test_parity_has_no_backend_caches_or_credentials(self): for forbidden in ("coordinator/", "cargo ", "rust-key", "secrets.", "darkbloom-platform"): self.assertNotIn(forbidden, self.jobs["test-provider"]) - def test_push_only_release_build_no_longer_warms_sdk_debug_tests(self): - job = self.jobs["cache-swift"] - self.assertIn(" if: github.event_name == 'push'", job) - runs = [run_command(step) for step in step_blocks(job) if field(step, "run")] - self.assertIn("swift build -c release --product darkbloom\n" - "swift build -c release --product darkbloom-fan-helper", runs) - self.assertNotIn("swift build --build-tests", job) - self.assertNotIn("working-directory: libs/mlx-swift-lm", job) - self.assertIn("actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57", job) + def test_obsolete_self_consuming_cache_warmer_is_absent(self): + # cache-swift saved a release build that only its own next run restored. + self.assertNotIn("cache-swift", self.jobs) + self.assertNotIn("spm-v4-blacksmith-macos27-native-", WORKFLOW.read_text()) def test_offline_workflow_test_runs_in_release_integrity(self): self.assertIn("python3 provider-swift/Tests/test_protocol_fixture_resources.py", self.jobs["release-integrity"]) @@ -763,6 +762,13 @@ def test_composite_cache_keys_retain_swift_and_metal_without_backend_work(self): self.assertNotIn("rust-key:", action) self.assertNotIn("rust-cache-hit:", action) self.assertEqual(sum("actions/cache/save@" in step for step in steps), 2) + # Pushes save the Swift build. A pull request saves it only when it + # restored nothing, so its later pushes do not evict the base entry. + swift_save = next(step for step in steps if field(step, "name", indent=4) == "Save lane-specific Swift test build") + self.assertEqual(field(swift_save, "if", indent=6), + "${{ !cancelled() && steps.timestamps.outcome == 'success' && " + "steps.swift-cache.outputs.cache-hit != 'true' && (github.event_name != 'pull_request' " + "|| steps.swift-cache.outputs.cache-matched-key == '') }}") if __name__ == "__main__": From 71e0d51ec60b8b536a3ea02a0cf12ce1c809f74d Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 22:19:04 -0600 Subject: [PATCH 0196/1441] ci: refactor pass: summary build comment, cache comment and cache doc Co-Authored-By: Claude Opus 5.5 --- .github/actions/provider-ci-build/action.yml | 4 ++-- .github/workflows/ci.yml | 5 +++-- docs/developer/test.md | 10 +++++----- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/.github/actions/provider-ci-build/action.yml b/.github/actions/provider-ci-build/action.yml index 10c8521932..d7df50ed39 100644 --- a/.github/actions/provider-ci-build/action.yml +++ b/.github/actions/provider-ci-build/action.yml @@ -78,8 +78,8 @@ runs: shell: bash run: python3 scripts/provider-release-cache.py snapshot-mtimes # Pushes save their build. A pull request saves only when it restored - # nothing, so its later pushes do not each add a 1.7 GB entry that evicts - # the base branch's entry from the repository cache. + # nothing, so its later pushes do not each add an entry that evicts the + # base branch's entry from the repository cache. - name: Save lane-specific Swift test build if: ${{ !cancelled() && steps.timestamps.outcome == 'success' && steps.swift-cache.outputs.cache-hit != 'true' && (github.event_name != 'pull_request' || steps.swift-cache.outputs.cache-matched-key == '') }} uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 29801cc104..8844c68967 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -345,8 +345,9 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: submodules: recursive - # The shards saved this build; restoring it gives the binaries that - # `swift test list` and llvm-cov read. + # This restores the shards' build, or on a pull request the base + # branch's build, and rebuilds it from the same sources and flags. + # `swift test list` and llvm-cov read its binaries. - name: Build provider CI prerequisites id: provider-ci-build uses: ./.github/actions/provider-ci-build diff --git a/docs/developer/test.md b/docs/developer/test.md index 09b0dfc62d..8d1e2acf01 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -118,11 +118,11 @@ suite moves from the parallel class to the serial class when it fails or flakes in parallel; when in doubt, a suite stays serial. The provider lanes and Cluster Metadata Checks restore their build cache by the -exact key first, then by the key prefix. A push to `dev` or `master` saves its -build. A pull request saves its build only when it restored nothing. Its later -pushes then restore the base branch's build again, and the repository cache -(10 GB) keeps the base branch's entries. CI has no separate push-only Swift -cache job. +exact key first, then by the key prefix. A push to `dev`, `main` or `master` +saves its build. A pull request saves its build only when it restored nothing. +Its later pushes then restore that entry or the base branch's entry and add no +new entry, so they do not evict the base branch's entries. CI has no separate +push-only Swift cache job. The SDK has independent test products under `libs/mlx-swift-lm`. CI validates native memory ownership, cancellation, media decoding, paged KV and resource From 4f36f565ed1bee2e06e839672ed764daeb5dce51 Mon Sep 17 00:00:00 2001 From: David Tai Date: Mon, 2 Nov 2026 22:58:31 -0600 Subject: [PATCH 0197/1441] refactor(provider): apply the refactor pass to the App Attest restart Findings from the independent refactor pass on PR 1731: - One unsupported restart per verified episode. The restart now also needs a coordinator verification after the last automatic App Attest restart, so a restart that did not help does not repeat every 6 h. - Remove the unused decide(stalledSeconds:) and afterDrain(heldSince:) forms. Adapt their tests to the remaining forms; no assertion removed. - Share one timestamp-file type between the stall-restart marker and the verified marker. The stall marker keeps its fallback to the file time; the file format does not change. - Decide the relaunch route from launchd's record of the provider job only (LaunchAgent.isCurrentProcessJob). XPC_SERVICE_NAME alone is not enough, because a child such as a cluster member inherits it. Start reuses the same check for its launch-managed test. - Never arm the restart in a cluster member. - Run launchctl only after the cheaper eligibility checks pass. - Log a lost launchd route after the drain as its own abandon branch. - Add seams for the restart boundary and the leased install, and test the real monitor, lease, drain and marker through to the launchd restart, and the recovery during the drain. - Docs and changelog match the new rules. Co-Authored-By: Claude Opus 5.5 --- changelog.d/app-attest-unsupported-restart.md | 4 +- docs/provider/attestation.md | 5 +- docs/provider/cli-reference.md | 6 +- docs/reference/app-attest-shadow.md | 2 +- .../AppAttestStallRestart.swift | 114 ++++++++-------- .../ProviderLoop+AppAttestStall.swift | 32 +++-- .../Sources/ProviderCore/ProviderLoop.swift | 6 + .../Service/ProcessLifecycle.swift | 18 +-- .../Service/ProviderLaunchSnapshot.swift | 13 ++ .../darkbloom/Start/StartCommand+Modes.swift | 2 +- .../StalledOperationAndRotationTests.swift | 42 ++++-- .../Service/ProcessLifecycleTests.swift | 19 ++- .../Service/ProviderLifecycleTests.swift | 124 +++++++++++++++++- 13 files changed, 272 insertions(+), 115 deletions(-) diff --git a/changelog.d/app-attest-unsupported-restart.md b/changelog.d/app-attest-unsupported-restart.md index 3aa50187af..20767a0a6d 100644 --- a/changelog.d/app-attest-unsupported-restart.md +++ b/changelog.d/app-attest-unsupported-restart.md @@ -1,5 +1,5 @@ ### App Attest recovers by itself after a self-update -- A provider that launchd runs now relaunches through launchd after a startup self-update, as it already did after a background update. Only a provider that launchd does not run, such as `darkbloom start --foreground` in a terminal, replaces itself in place. A background update or App Attest restart in such a provider no longer starts the LaunchAgent instead. -- When App Attest reports `is_supported_false` on a Mac that the coordinator verified for App Attest in the last 7 days, the provider restarts once through launchd. It waits until the state lasts 5 minutes and the provider is idle, and it checks Apple's answer again after the drain. This restart and the stall restart share one limit: one automatic App Attest restart per 6 hours. +- A provider that launchd runs as its provider job now relaunches through launchd after a startup self-update, as it already did after a background update. Only a provider that launchd does not run, such as `darkbloom start --foreground` in a terminal, replaces itself in place. A background update or App Attest restart in such a provider no longer starts the LaunchAgent instead. +- When App Attest reports `is_supported_false` on a Mac that the coordinator verified for App Attest in the last 7 days, the provider restarts once through launchd. It waits until the state lasts 5 minutes and the provider is idle, and it checks Apple's answer again after the drain. If the new process still reports unsupported, it does not restart again until the coordinator verifies the Mac again. This restart and the stall restart share one limit: one automatic App Attest restart per 6 hours. Cluster members never restart for it. - The provider keeps the time of its last App Attest authorization in `app-attest-verified.json` beside the daemon state file. diff --git a/docs/provider/attestation.md b/docs/provider/attestation.md index 7d7a514cb8..8759fb0ca9 100644 --- a/docs/provider/attestation.md +++ b/docs/provider/attestation.md @@ -103,8 +103,9 @@ After a self-update, some macOS 27 Macs report App Attest as unsupported (`is_supported_false`) although it worked before. If the coordinator granted this Mac App Attest in the last 7 days and launchd runs the provider, the provider restarts once through launchd when the state lasts 5 minutes and the -provider is idle. This restart shares the stall restart's limit of one per 6 -hours. The log line starts with `App Attest: isSupported is false`. See the +provider is idle. It restarts once per verified episode: if the new process +still reports unsupported, it waits until the coordinator verifies the Mac +again. This restart shares the stall restart's limit of one per 6 hours. The log line starts with `App Attest: isSupported is false`. See the [thresholds and limits](../reference/app-attest-shadow.md#bounds-and-credential-lifecycle). The separate [supervised worker candidate](../architecture/security/identity-binding.md#supervised-app-attest-worker-candidate) diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 4a2b6fb3db..51cba2344e 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -434,9 +434,9 @@ drains it instead of ending the process at once. `SIGHUP` is not a stop signal in two cases: the provider's launchd job does not take it, so it has whatever action launchd started the job with, and a start that arrived with `SIGHUP` ignored, for example under `nohup`, keeps ignoring it. A provider that -re-executes itself in place for a self-update (one that launchd does not run; -launchd relaunches its own provider) carries the same choice into the -new process (`ProviderStopSignals` in +re-executes itself in place for a self-update (one that is not the provider +LaunchAgent's own job; launchd relaunches that job) carries the same choice +into the new process (`ProviderStopSignals` in `provider-swift/Sources/ProviderCore/Service/ProviderStopSignals.swift`). The signal deadline is configurable with [`DARKBLOOM_DRAIN_TIMEOUT_SECONDS`](../reference/configuration.md#provider-drain-deadline). diff --git a/docs/reference/app-attest-shadow.md b/docs/reference/app-attest-shadow.md index dc62177c6f..22239e451b 100644 --- a/docs/reference/app-attest-shadow.md +++ b/docs/reference/app-attest-shadow.md @@ -127,7 +127,7 @@ provider-local Apple callback, retry, key-budget and socket fences remain separa | Session recovery | Generic or server-unavailable Apple API failures retry after one minute, then five minutes, then at most the normal ten-minute assertion interval. Other transient coordinator/storage failures retain the one-minute, five-minute, then hourly backoff. Every attempt gets a new session/nonce and reloads durable acceptance/counters. Successful assertions reset backoff. An Apple API error is an unknown prospective verdict and grants no permission; verified crypto/policy rejections remain terminal, and cancellation stops retries. Persistent generic errors still need native domain/code diagnostics from a signed upgraded client. [Dead-key rotation](#dead-key-rotation) and the [invalid-key enrollment backoff](#invalid-key-enrollment-backoff) replace this delay in their specific cases. Code: [coordinator/internal/appattest/recovery/recovery_policy.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/internal/appattest/recovery/recovery_policy.go) (`ExchangeRetryDelay`), [coordinator/internal/appattest/recovery/driver.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/internal/appattest/recovery/driver.go) (`Driver.Run`); session wiring in [coordinator/appattest/service/retry.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/appattest/service/retry.go) (`run`). | | First-risk-receipt wait | A valid first assertion with no verified risk receipt yet, including an initial `renewal_required` receipt, stays unknown. Without an existing authorization record, a fresh assertion retries after one minute, five minutes, then at the normal ten-minute cadence while Apple's receipt renewal runs independently. Only complete fresh evidence can authorize serving. Code: [coordinator/appattest/service/authorization_identity.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/appattest/service/authorization_identity.go) and `retry.go`. | | Apple callbacks | 25-second waiter deadline. The actual uncancellable Apple operation retains admission until its callback arrives; retries receive `busy` in the meantime. A token fences duplicate late callbacks from unlocking a newer operation. A pre-cancelled call does not acquire admission. The gate records when it was acquired: once held longer than `AppleOperationStall.threshold` (15 min), `ready` replies return `busy` with `operation_stalled_seconds`, and the provider restarts itself through the background-update path (update lease, drain, `waitForSafeDisconnect`, `ProcessLifecycle.restartAfterUpdate`) only when no inference is in flight or loading and no update or lifecycle drain is running, at most once per `AppAttestStallRestartPolicy.minimumInterval` (6 h, persisted in `app-attest-stall-restart.json` beside the daemon state file before the restart is issued). An attempt that drains but cannot restart reopens serving and waits before draining again in the same process: `AppAttestStallRestartPolicy.drainRetryDelay` (15 min) when accepted work or the coordinator's drain acknowledgement did not finish in time, and a full `minimumInterval` when the marker cannot be written, since no restart may be issued without it. After the drain, and after its last suspension point, it checks again (`AppAttestStallRestartPolicy.afterDrain`): if Apple's callback released the gate, or a CLI stop, OS termination or scheduled shutdown took over the drain, it releases the update lease without restarting, and a lifecycle-owned drain stays closed. Code: `AppleOperationGate.swift`, `AppleAppAttestService.swift`, `AppleOperationStall.swift` and `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | -| `isSupported` false after verification | When a `ready` answers `is_supported_false` (macOS 27 or later), the provider restarts once through launchd if all of these hold: the coordinator granted this Mac an App Attest authorization within `AppAttestStallRestartPolicy.verifiedWithin` (7 days; the time is kept in `app-attest-verified.json` beside the daemon state file, rewritten at most once per hour); launchd runs this provider (`ProcessLifecycle.RelaunchRoute`: its agent is loaded and `XPC_SERVICE_NAME` is its label); and the embedded provisioning profile has not expired. The live `DCAppAttestService.isSupported` must stay false for `AppAttestStallRestartPolicy.unsupportedThreshold` (5 min) and again after the drain. The restart uses the stall restart's monitor, idle checks, drain, `app-attest-stall-restart.json` limit (one automatic App Attest restart per 6 h, for both causes) and `start_reason` `stall_restart`. It never uses an in-place exec. Code: `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | +| `isSupported` false after verification | When a `ready` answers `is_supported_false` (macOS 27 or later), the provider restarts once through launchd if all of these hold: the coordinator granted this Mac an App Attest authorization within `AppAttestStallRestartPolicy.verifiedWithin` (7 days) and after the last automatic App Attest restart (the time is kept in `app-attest-verified.json` beside the daemon state file, rewritten at most once per hour), so one unsupported episode gets one restart; the embedded provisioning profile has not expired; this is not a cluster member; and launchd runs this provider (`ProcessLifecycle.RelaunchRoute`: launchd's record of the loaded provider job names this exact process, which an in-place exec keeps). The live `DCAppAttestService.isSupported` must stay false for `AppAttestStallRestartPolicy.unsupportedThreshold` (5 min) and again after the drain. The restart uses the stall restart's monitor, idle checks, drain, `app-attest-stall-restart.json` limit (one automatic App Attest restart per 6 h, for both causes) and `start_reason` `stall_restart`. It never uses an in-place exec. Code: `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | | Coordinator-driven rotation (client side) | An `attest` for a key this client already attested, with no cached proof, clears the key ID and replies `key_unregistered` without calling Apple. The next `prepare` generates a replacement within the per-key one-hour cooldown and the shared five-per-hour generation budget. Released 0.9.8 and 0.9.9 clients behave the same way. Code: `provider-swift/Sources/ProviderAppAttest/AppAttestShadowClient.swift`; pinned by `provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift`. | | Attestation retries | At most three attempts, 2/8-second waits, only for service unavailable. `ShadowEnrollmentAttempt` persists the original key/hash, status, session and timestamp across later coordinator retries and reconnects (the provider serves protocol 3 only; an attempt recorded under an earlier protocol is retired), as [Apple requires](https://developer.apple.com/documentation/devicecheck/dcerror-swift.struct/code/serverunavailable). Successful recovery uses the original stored server transaction; a subsequent serving assertion always signs fresh status/challenge/endpoint. Expired or malformed retry state retires under existing generation limits. | | Failed one-time enrollment | Non-service-unavailable Apple failures retire the enrollment key identifier under the existing generation limits. The app persists `attestationStartedAt` before calling Apple; an interrupted attempt without a saved proof is retired on the next prepare. Cached successful proofs remain recoverable. Generic assertion failures do not make the client rotate an accepted key on its own; an explicit invalid-key response can retire it, and the coordinator can request [dead-key rotation](#dead-key-rotation). Code: `provider-swift/Sources/ProviderAppAttest/EnrollmentKeyLifecycle.swift` and `AppAttestShadowClient.swift`. | diff --git a/provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift b/provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift index 54cdda642d..66154d3f1d 100644 --- a/provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift +++ b/provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift @@ -68,12 +68,6 @@ public enum AppAttestStallRestartPolicy { /// A marker from the future (clock moved backwards) also counts as recent /// unless it is more than one interval away. `retryDeferred` is this /// process's in-memory deferral after a failed attempt. - public static func decide(stalledSeconds: Int?, inferenceActive: Bool, lifecycleBusy: Bool, - lastRestartAt: Date?, retryDeferred: Bool, now: Date) -> Decision { - decide(trigger: stalledSeconds.map { .stalled(seconds: $0) }, inferenceActive: inferenceActive, - lifecycleBusy: lifecycleBusy, lastRestartAt: lastRestartAt, retryDeferred: retryDeferred, now: now) - } - public static func decide(trigger: AppAttestRestartTrigger?, inferenceActive: Bool, lifecycleBusy: Bool, lastRestartAt: Date?, retryDeferred: Bool, now: Date) -> Decision { switch trigger { @@ -111,10 +105,6 @@ public enum AppAttestStallRestartPolicy { /// Decided after the drain's last suspension point. Losing ownership of /// the drain wins over everything else: the process is being stopped. - public static func afterDrain(updateOwnsDrain: Bool, heldSince: Date?, now: Date) -> AfterDrain { - afterDrain(updateOwnsDrain: updateOwnsDrain, stillBlocked: stillStalled(heldSince: heldSince, now: now)) - } - /// `stillBlocked`: the trigger still holds after the drain (the Apple call /// is still unanswered, or `isSupported` is still false). public static func afterDrain(updateOwnsDrain: Bool, stillBlocked: Bool) -> AfterDrain { @@ -122,53 +112,71 @@ public enum AppAttestStallRestartPolicy { return stillBlocked ? .restart : .recovered } - /// Whether `isSupported == false` may lead to a restart at all. The - /// coordinator must have verified App Attest on this Mac within - /// `verifiedWithin`; launchd must start the new process (an in-place exec - /// is a suspected cause of this state, so it is never the remedy); and the provisioning - /// profile must not have expired, because a restart cannot renew it. - public static func unsupportedRestartEligible(lastVerifiedAt: Date?, relaunchesThroughLaunchd: Bool, - profileExpired: Bool?, now: Date) -> Bool { - guard relaunchesThroughLaunchd, profileExpired != true, let lastVerifiedAt else { return false } - return abs(now.timeIntervalSince(lastVerifiedAt)) < verifiedWithin + /// Whether `isSupported == false` may lead to a restart at all: + /// - the coordinator verified App Attest on this Mac within `verifiedWithin`, + /// and after the last automatic App Attest restart. So one unsupported + /// episode gets one restart; a restart that did not help waits for a new + /// verification instead of repeating every interval; + /// - the provisioning profile has not expired (a restart cannot renew it); + /// - launchd starts the new process. Fleet data shows the state almost + /// never in a process that launchd started; whether an in-place exec + /// causes it is not known, so exec is not used for this restart. + /// `relaunchesThroughLaunchd` runs `launchctl`, so it is evaluated last. + public static func unsupportedRestartEligible(lastVerifiedAt: Date?, lastRestartAt: Date?, + profileExpired: Bool?, now: Date, + relaunchesThroughLaunchd: @autoclosure () -> Bool) -> Bool { + guard profileExpired != true, let lastVerifiedAt, + abs(now.timeIntervalSince(lastVerifiedAt)) < verifiedWithin else { return false } + if let lastRestartAt, lastVerifiedAt <= lastRestartAt { return false } + return relaunchesThroughLaunchd() } } -/// Persisted time of the last automatic stall restart. Written before the -/// restart is issued so a failed or looping restart cannot exceed the limit. -public struct AppAttestStallRestartMarker: Sendable { - public static let fileName = "app-attest-stall-restart.json" - public let url: URL - - public init(directory: URL) { - url = directory.appendingPathComponent(Self.fileName) - } - - private struct Record: Codable { - let restartedAt: Double - enum CodingKeys: String, CodingKey { case restartedAt = "restarted_at" } - } +/// One owner-only (0600) JSON file holding a single Unix-seconds timestamp. +struct AppAttestTimestampFile: Sendable { + let url: URL + let key: String - /// An unreadable marker falls back to its modification time, so damage - /// cannot lift the limit early. - public func lastRestart() -> Date? { + /// Nil when the file is missing. A file that cannot be decoded gives its + /// modification time when `damagedAsModified`, else nil. + func read(damagedAsModified: Bool) -> Date? { guard FileManager.default.fileExists(atPath: url.path) else { return nil } if let data = try? Data(contentsOf: url), - let record = try? JSONDecoder().decode(Record.self, from: data), record.restartedAt.isFinite { - return Date(timeIntervalSince1970: record.restartedAt) + let object = try? JSONDecoder().decode([String: Double].self, from: data), + let seconds = object[key], seconds.isFinite { + return Date(timeIntervalSince1970: seconds) } + guard damagedAsModified else { return nil } return (try? FileManager.default.attributesOfItem(atPath: url.path))?[.modificationDate] as? Date } - public func record(_ date: Date) throws { + func write(_ date: Date) throws { try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) - let data = try JSONEncoder().encode(Record(restartedAt: date.timeIntervalSince1970)) - try data.write(to: url, options: .atomic) + try JSONEncoder().encode([key: date.timeIntervalSince1970]).write(to: url, options: .atomic) try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) } } +/// Persisted time of the last automatic App Attest restart (stall or +/// unsupported). Written before the restart is issued so a failed or looping +/// restart cannot exceed the limit. +public struct AppAttestStallRestartMarker: Sendable { + public static let fileName = "app-attest-stall-restart.json" + private let file: AppAttestTimestampFile + public var url: URL { file.url } + + public init(directory: URL) { + file = AppAttestTimestampFile(url: directory.appendingPathComponent(Self.fileName), key: "restarted_at") + } + + /// An unreadable marker falls back to its modification time, so damage + /// cannot lift the limit early. + public func lastRestart() -> Date? { file.read(damagedAsModified: true) } + + public func record(_ date: Date) throws { try file.write(date) } +} + /// Persisted time when the coordinator last granted this Mac an App Attest /// authorization. It only enables the restart for `isSupported == false`; it /// never authorizes serving. @@ -176,29 +184,15 @@ public struct AppAttestVerifiedMarker: Sendable { public static let fileName = "app-attest-verified.json" /// The running provider rewrites the marker at most this often. public static let refreshInterval: TimeInterval = 3600 - public let url: URL + private let file: AppAttestTimestampFile + public var url: URL { file.url } public init(directory: URL) { - url = directory.appendingPathComponent(Self.fileName) - } - - private struct Record: Codable { - let verifiedAt: Double - enum CodingKeys: String, CodingKey { case verifiedAt = "verified_at" } + file = AppAttestTimestampFile(url: directory.appendingPathComponent(Self.fileName), key: "verified_at") } /// Nil when the marker is missing or unreadable: no evidence, no restart. - public func lastVerified() -> Date? { - guard let data = try? Data(contentsOf: url), - let record = try? JSONDecoder().decode(Record.self, from: data), record.verifiedAt.isFinite else { return nil } - return Date(timeIntervalSince1970: record.verifiedAt) - } + public func lastVerified() -> Date? { file.read(damagedAsModified: false) } - public func record(_ date: Date) throws { - try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), - withIntermediateDirectories: true) - let data = try JSONEncoder().encode(Record(verifiedAt: date.timeIntervalSince1970)) - try data.write(to: url, options: .atomic) - try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) - } + public func record(_ date: Date) throws { try file.write(date) } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift index a645eca8d6..246424a72b 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift @@ -19,7 +19,8 @@ extension ProviderLoop { /// when an unanswered Apple call can be holding admission. One monitor per /// process; it ends as soon as Apple's callback releases the gate. internal func startAppAttestStallMonitorIfNeeded() { - guard serveUsesHostServices, !usesAppAttestWorker, + // A cluster member never relaunches its binary unattended. + guard serveUsesHostServices, !isClusterMember, !usesAppAttestWorker, appAttestStallMonitorTask == nil, !isShuttingDown else { return } appAttestStallMonitorTask = Task { [weak self] in while !Task.isCancelled { @@ -37,7 +38,7 @@ extension ProviderLoop { /// Called with each `ready` this process answers. Starts the monitor when /// `isSupported` is false on a Mac that may restart for it. internal func noteAppAttestAvailability(_ status: AppAttestLocalStatus?, now: Date = Date()) { - guard serveUsesHostServices, !usesAppAttestWorker, status?.availabilityReason == .isSupportedFalse, + guard serveUsesHostServices, !isClusterMember, !usesAppAttestWorker, status?.availabilityReason == .isSupportedFalse, appAttestUnsupportedRestartEligible(status, now: now) else { appAttestUnsupportedSince = nil return @@ -52,8 +53,9 @@ extension ProviderLoop { private func appAttestUnsupportedRestartEligible(_ status: AppAttestLocalStatus?, now: Date) -> Bool { AppAttestStallRestartPolicy.unsupportedRestartEligible( lastVerifiedAt: appAttestVerifiedMarker().lastVerified(), - relaunchesThroughLaunchd: appAttestRelaunchRoute() == .launchd, - profileExpired: status?.process?.preflight?.profileExpired, now: now) + lastRestartAt: appAttestStallRestartMarker().lastRestart(), + profileExpired: status?.process?.preflight?.profileExpired, now: now, + relaunchesThroughLaunchd: appAttestRelaunchRoute() == .launchd) } /// The restart trigger now, or nil when nothing justifies a restart (the @@ -121,8 +123,7 @@ extension ProviderLoop { let heldSince = await appAttestShadowClient?.appleOperationHeldSince() return AppAttestStallRestartPolicy.stillStalled(heldSince: heldSince, now: now) case .unsupported: - // Never fall back to an in-place exec for this trigger. - return !appAttestSupportProbe() && appAttestRelaunchRoute() == .launchd + return !appAttestSupportProbe() } } @@ -135,7 +136,7 @@ extension ProviderLoop { } private func restartForAppAttest(_ trigger: AppAttestRestartTrigger, marker: AppAttestStallRestartMarker) async -> Bool { - let updater = SelfUpdater(coordinatorBaseURL: loopConfig.coordinatorURL) + let updater = appAttestRestartUpdater ?? SelfUpdater(coordinatorBaseURL: loopConfig.coordinatorURL) // The cross-process update lease excludes CLI stop/restart and updates. guard claimUpdateStart(updater: updater) else { appAttestStallLastSkip = .lifecycleBusy @@ -159,6 +160,15 @@ extension ProviderLoop { // the drain, while we awaited. Nothing after the ownership read below // suspends, so this is the last point to re-check both. let stillHolds = await appAttestTriggerStillHolds(trigger, now: Date()) + let route = appAttestRelaunchRoute() + // The unsupported restart never falls back to an in-place exec. + if case .unsupported = trigger, stillHolds, route != .launchd { + logger.warning("App Attest: restart abandoned; launchd no longer runs this provider") + appAttestUnsupportedSince = nil + appAttestStallMonitorTask = nil + await resumeServingAfterUpdate() + return false + } let ownsDrain = appAttestStallRestartOwnsDrain && !Task.isCancelled switch AppAttestStallRestartPolicy.afterDrain(updateOwnsDrain: ownsDrain, stillBlocked: stillHolds) { case .lifecycleTookOver: @@ -195,16 +205,16 @@ extension ProviderLoop { return true } do { - switch trigger { - case .stalled: try ProcessLifecycle.restartAfterUpdate(cause: .stallRestart) - case .unsupported: try ProcessLifecycle.restartAfterUpdate(cause: .stallRestart, route: .launchd) - } + try appAttestRestart(.stallRestart, route) } catch { logger.warning("App Attest: restart failed: \(error)") try? updater.cancelPendingCandidateAttempt(operation: "app-attest-stall-restart-failure") await resumeServingAfterUpdate() return true } + // Reached only when a test seam returns instead of relaunching. + appAttestStallMonitorTask = nil + return false } /// An attempt that closed admission but will not restart: reopen serving diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index 751928ab57..1ccc3dc479 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -225,6 +225,12 @@ public actor ProviderLoop { internal var appAttestRelaunchRoute: @Sendable () -> ProcessLifecycle.RelaunchRoute = { .current() } /// Seam for Apple's live `DCAppAttestService.isSupported`. internal var appAttestSupportProbe: @Sendable () -> Bool = { AppleAppAttestService.isSupportedNow() } + /// Seam for the App Attest restart itself (launchd kickstart or exec). + /// Production relaunches for real; tests replace only this boundary. + internal typealias AppAttestRestart = @Sendable (ProviderRunMarker.ExitCause, ProcessLifecycle.RelaunchRoute) throws -> Void + internal var appAttestRestart: AppAttestRestart = { try ProcessLifecycle.restartAfterUpdate(cause: $0, route: $1) } + /// Seam for the install the App Attest restart leases; nil is the running install. + internal var appAttestRestartUpdater: SelfUpdater? internal let loopConfig: ProviderLoopConfig internal var ordinaryServingModelIDs: Set internal var autopilotSuccessorNeedsInventoryRefresh = false diff --git a/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift b/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift index eb0f529447..89a7ef2426 100644 --- a/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift +++ b/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift @@ -195,21 +195,11 @@ public enum ProcessLifecycle { /// `execv` in place: the same kernel process runs the new image. case exec - /// launchd only when its agent is loaded AND this process is that - /// agent's job. A foreground `start` beside a loaded agent keeps exec, - /// so it never hands its work to a different process. - public static func decide(agentLoaded: Bool, launchedByLaunchd: Bool) -> RelaunchRoute { - agentLoaded && launchedByLaunchd ? .launchd : .exec - } - - /// This process is the agent's job when `XPC_SERVICE_NAME` is its label - /// (an earlier in-place exec keeps it), or when launchd's own record of - /// the job names this exact process. + /// launchd only when this process is the provider agent's job. A + /// foreground `start` beside a loaded agent, or a cluster member, keeps + /// exec, so it never hands its work to a different process. public static func current() -> RelaunchRoute { - let loaded = LaunchAgent.isLoaded() - let ownJob = loaded && (ProviderStartReason.launchedByLaunchd() - || ProcessIdentity.current().map { LaunchAgent.launchSnapshot()?.process == $0 } == true) - return decide(agentLoaded: loaded, launchedByLaunchd: ownJob) + LaunchAgent.isCurrentProcessJob() ? .launchd : .exec } } diff --git a/provider-swift/Sources/ProviderCore/Service/ProviderLaunchSnapshot.swift b/provider-swift/Sources/ProviderCore/Service/ProviderLaunchSnapshot.swift index f4c84dc795..3dd4e55453 100644 --- a/provider-swift/Sources/ProviderCore/Service/ProviderLaunchSnapshot.swift +++ b/provider-swift/Sources/ProviderCore/Service/ProviderLaunchSnapshot.swift @@ -26,6 +26,19 @@ public struct ProviderLaunchSnapshot: Codable, Sendable, Equatable { } extension LaunchAgent { + /// launchd's record of the loaded provider job names this exact process. + /// An in-place exec keeps the process identity, so it still matches. + /// Environment such as `XPC_SERVICE_NAME` is not enough: child processes + /// inherit it. + public static func isCurrentProcessJob() -> Bool { + isJob(launchSnapshot()?.process, current: ProcessIdentity.current()) + } + + static func isJob(_ jobProcess: ProcessIdentity?, current: ProcessIdentity?) -> Bool { + guard let jobProcess, let current else { return false } + return jobProcess == current + } + public static func launchSnapshot() -> ProviderLaunchSnapshot? { let output = LaunchctlControl.printOutput(label: label) guard output.succeeded else { return nil } diff --git a/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift b/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift index 29e9cb23f8..583bffc3c5 100644 --- a/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift +++ b/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift @@ -184,7 +184,7 @@ extension Start { ) async throws { warnBootSecurity(snapshot: bootSecuritySnapshot, coordinatorEnforced: true) - let launchManaged = ProcessIdentity.current().map { LaunchAgent.launchSnapshot()?.process == $0 } ?? false + let launchManaged = LaunchAgent.isCurrentProcessJob() let usePinnedSelection = Self.usesPinnedModelSelection(configPath: snapshot.configPath, launchManaged: launchManaged) let selectedModels = advertisedModels( from: snapshot.models, diff --git a/provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift b/provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift index 12e891ad49..f4f0c413ee 100644 --- a/provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift +++ b/provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift @@ -242,7 +242,7 @@ final class AppAttestStallRestartPolicyTests: XCTestCase { private func decide(stalledSeconds: Int?, inference: Bool = false, lifecycle: Bool = false, deferred: Bool = false, last: Date? = nil) -> AppAttestStallRestartPolicy.Decision { - AppAttestStallRestartPolicy.decide(stalledSeconds: stalledSeconds, inferenceActive: inference, + AppAttestStallRestartPolicy.decide(trigger: stalledSeconds.map { .stalled(seconds: $0) }, inferenceActive: inference, lifecycleBusy: lifecycle, lastRestartAt: last, retryDeferred: deferred, now: now) } @@ -290,14 +290,20 @@ final class AppAttestStallRestartPolicyTests: XCTestCase { XCTAssertTrue(AppAttestStallRestartPolicy.stillStalled(heldSince: now.addingTimeInterval(-threshold - 120), now: now)) } + private func afterDrain(updateOwnsDrain: Bool, heldSince: Date?) -> AppAttestStallRestartPolicy.AfterDrain { + AppAttestStallRestartPolicy.afterDrain( + updateOwnsDrain: updateOwnsDrain, + stillBlocked: AppAttestStallRestartPolicy.stillStalled(heldSince: heldSince, now: now)) + } + func testLifecycleTakeoverDuringDrainCancelsTheRestart() { let stuck = now.addingTimeInterval(-AppleOperationStall.threshold - 120) - XCTAssertEqual(AppAttestStallRestartPolicy.afterDrain(updateOwnsDrain: true, heldSince: stuck, now: now), .restart) - XCTAssertEqual(AppAttestStallRestartPolicy.afterDrain(updateOwnsDrain: true, heldSince: nil, now: now), .recovered) + XCTAssertEqual(afterDrain(updateOwnsDrain: true, heldSince: stuck), .restart) + XCTAssertEqual(afterDrain(updateOwnsDrain: true, heldSince: nil), .recovered) // A stop or shutdown that took over the drain wins even while the // Apple call is still stuck: the provider must not be relaunched. - XCTAssertEqual(AppAttestStallRestartPolicy.afterDrain(updateOwnsDrain: false, heldSince: stuck, now: now), .lifecycleTookOver) - XCTAssertEqual(AppAttestStallRestartPolicy.afterDrain(updateOwnsDrain: false, heldSince: nil, now: now), .lifecycleTookOver) + XCTAssertEqual(afterDrain(updateOwnsDrain: false, heldSince: stuck), .lifecycleTookOver) + XCTAssertEqual(afterDrain(updateOwnsDrain: false, heldSince: nil), .lifecycleTookOver) } func testMarkerPersistsAcrossInstancesAndFailsClosedWhenDamaged() throws { @@ -330,8 +336,7 @@ final class AppAttestStallRestartPolicyTests: XCTestCase { XCTAssertEqual(decide(.unsupported(seconds: due), lifecycle: true), .skip(.lifecycleBusy)) XCTAssertEqual(decide(.unsupported(seconds: due), deferred: true), .skip(.retryDeferred)) XCTAssertEqual(decide(nil), .skip(.notStalled)) - // The stalled-seconds entry point and the trigger entry point agree. - XCTAssertEqual(decide(.stalled(seconds: stalled)), decide(stalledSeconds: stalled)) + XCTAssertEqual(decide(.stalled(seconds: stalled)), .restart) XCTAssertEqual(decide(.stalled(seconds: Int(AppleOperationStall.threshold))), .skip(.notStalled)) } @@ -354,9 +359,10 @@ final class AppAttestStallRestartPolicyTests: XCTestCase { } func testUnsupportedRestartNeedsRecentVerificationLaunchdAndAValidProfile() { - func eligible(verified: Date?, launchd: Bool = true, expired: Bool? = false) -> Bool { + func eligible(verified: Date?, restarted: Date? = nil, launchd: Bool = true, expired: Bool? = false) -> Bool { AppAttestStallRestartPolicy.unsupportedRestartEligible( - lastVerifiedAt: verified, relaunchesThroughLaunchd: launchd, profileExpired: expired, now: now) + lastVerifiedAt: verified, lastRestartAt: restarted, profileExpired: expired, now: now, + relaunchesThroughLaunchd: launchd) } let window = AppAttestStallRestartPolicy.verifiedWithin XCTAssertTrue(eligible(verified: now.addingTimeInterval(-3600))) @@ -367,6 +373,24 @@ final class AppAttestStallRestartPolicyTests: XCTestCase { "an in-place exec is never the remedy") XCTAssertFalse(eligible(verified: now.addingTimeInterval(-3600), expired: true), "a restart cannot renew an expired profile") + // One restart per verified episode: a restart that did not help waits + // for a new verification instead of repeating every interval. + XCTAssertFalse(eligible(verified: now.addingTimeInterval(-7200), restarted: now.addingTimeInterval(-3600))) + XCTAssertFalse(eligible(verified: now.addingTimeInterval(-3600), restarted: now.addingTimeInterval(-3600))) + XCTAssertTrue(eligible(verified: now.addingTimeInterval(-60), restarted: now.addingTimeInterval(-3600))) + } + + func testUnsupportedEligibilityAsksLaunchdOnlyWhenEverythingElsePasses() { + var asked = 0 + func launchd() -> Bool { asked += 1; return true } + _ = AppAttestStallRestartPolicy.unsupportedRestartEligible( + lastVerifiedAt: nil, lastRestartAt: nil, profileExpired: false, now: now, relaunchesThroughLaunchd: launchd()) + _ = AppAttestStallRestartPolicy.unsupportedRestartEligible( + lastVerifiedAt: now, lastRestartAt: nil, profileExpired: true, now: now, relaunchesThroughLaunchd: launchd()) + XCTAssertEqual(asked, 0, "a Mac that cannot restart for this state runs no launchctl") + XCTAssertTrue(AppAttestStallRestartPolicy.unsupportedRestartEligible( + lastVerifiedAt: now, lastRestartAt: nil, profileExpired: false, now: now, relaunchesThroughLaunchd: launchd())) + XCTAssertEqual(asked, 1) } func testVerifiedMarkerPersistsAndFailsClosedWhenDamaged() throws { diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift index 35f42efeb8..64301ef2c4 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift @@ -175,12 +175,17 @@ struct ProcessLifecycleTests { } /// A self-update or App Attest restart of a provider that launchd runs goes -/// through launchd; any other provider keeps the in-place exec. +/// through launchd; any other provider keeps the in-place exec. The route +/// follows launchd's record of the job, which names one exact process. @Test func relaunchRouteUsesLaunchdOnlyForTheLaunchdJobItself() { - #expect(ProcessLifecycle.RelaunchRoute.decide(agentLoaded: true, launchedByLaunchd: true) == .launchd) - // A foreground `start` beside a loaded agent must not hand its work to the agent. - #expect(ProcessLifecycle.RelaunchRoute.decide(agentLoaded: true, launchedByLaunchd: false) == .exec) - // launchd started this process, but its job was unloaded since: kickstart has no job. - #expect(ProcessLifecycle.RelaunchRoute.decide(agentLoaded: false, launchedByLaunchd: true) == .exec) - #expect(ProcessLifecycle.RelaunchRoute.decide(agentLoaded: false, launchedByLaunchd: false) == .exec) + let current = ProcessIdentity(pid: 4242, startTimeMicros: 1_000_000) + #expect(LaunchAgent.isJob(current, current: current)) + // A foreground `start` beside a loaded agent, or a child of the job (a + // cluster member inherits XPC_SERVICE_NAME), must not hand its work to the agent. + #expect(!LaunchAgent.isJob(ProcessIdentity(pid: 4243, startTimeMicros: 1_000_000), current: current)) + // Same PID, another process: PID reuse never counts. + #expect(!LaunchAgent.isJob(ProcessIdentity(pid: 4242, startTimeMicros: 2_000_000), current: current)) + // No loaded job (launchctl print fails) or no readable identity. + #expect(!LaunchAgent.isJob(nil, current: current)) + #expect(!LaunchAgent.isJob(current, current: nil)) } diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift index 390b3de5c1..ef8a182de6 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift @@ -9,11 +9,12 @@ private func lifecycleHardware() -> HardwareInfo { cpuCores: CpuCores(total: 16, performance: 12, efficiency: 4), gpuCores: 40, memoryBandwidthGbs: 546) } -private func lifecycleLoop() async throws -> (ProviderLoop, URL) { +private func lifecycleLoop(role: ProviderExecutionRole = .solo) async throws -> (ProviderLoop, URL) { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) let loop = try ProviderLoop(config: ProviderLoopConfig(coordinatorURL: "ws://127.0.0.1:0/unused", - hardware: lifecycleHardware(), models: [], config: ProviderConfig(provider: ProviderSettings(name: "lifecycle-test"))), attestationSigner: nil) + hardware: lifecycleHardware(), models: [], config: ProviderConfig(provider: ProviderSettings(name: "lifecycle-test")), + executionRole: role), attestationSigner: nil) await loop.setDaemonStateFileForTesting(root.appendingPathComponent("state.json")) return (loop, root) } @@ -27,10 +28,21 @@ private func lifecycleClient(url: String, state: ProviderState) -> CoordinatorCl private extension ProviderLoop { func installAppAttestWorker(_ worker: any AppAttestWorkerExchangeClient) { appAttestWorkerClient = worker } - /// Fakes only the launchd boundary and Apple's live `isSupported`. - func setAppAttestRestartSeams(route: ProcessLifecycle.RelaunchRoute, supported: Bool) { + /// Fakes only the launchd/exec boundary and Apple's live `isSupported`. + /// A restart that reaches the boundary is recorded, never issued. + func setAppAttestRestartSeams(route: ProcessLifecycle.RelaunchRoute, supported: @escaping @Sendable () -> Bool, + restarts: AppAttestRestartLog = AppAttestRestartLog(), updater: SelfUpdater? = nil) { appAttestRelaunchRoute = { route } - appAttestSupportProbe = { supported } + appAttestSupportProbe = supported + appAttestRestart = { restarts.append($0, $1) } + appAttestRestartUpdater = updater + } + func setAppAttestRestartSeams(route: ProcessLifecycle.RelaunchRoute, supported: Bool) { + setAppAttestRestartSeams(route: route, supported: { supported }) + } + func installIdleAppAttestClient() { + appAttestShadowClient = AppAttestShadowClient(scope: loopConfig.coordinatorURL, service: IdleAppAttestService(), + storage: EmptyShadowKeys()) } func holdLifecycleRequests(_ ids: Set) { acceptedLifecycleRequests.formUnion(ids) } func completeLifecycleRequest(_ id: String) { acceptedLifecycleRequests.remove(id) } @@ -292,6 +304,38 @@ struct ProviderLifecycleTests { } } +private final class AppAttestRestartLog: @unchecked Sendable { + private let lock = NSLock() + private var entries: [(ProviderRunMarker.ExitCause, ProcessLifecycle.RelaunchRoute)] = [] + func append(_ cause: ProviderRunMarker.ExitCause, _ route: ProcessLifecycle.RelaunchRoute) { + lock.withLock { entries.append((cause, route)) } + } + var routes: [ProcessLifecycle.RelaunchRoute] { lock.withLock { entries.map(\.1) } } + var causes: [ProviderRunMarker.ExitCause] { lock.withLock { entries.map(\.0) } } +} + +/// Apple boundary with no outstanding call; availability comes from the probe seam. +private actor IdleAppAttestService: AppAttestService { + func checkAvailability(environment: String) {} + func generateKey() -> String { "" } + func attestKey(_ id: String, hash: Data) -> Data { Data() } + func generateAssertion(_ id: String, hash: Data) -> Data { Data() } + func operationHeldSince() -> Date? { nil } +} + +private struct EmptyShadowKeys: ShadowKeyStorage { + func load(scope: String) -> ShadowKeyRecord? { nil } + func save(_ record: ShadowKeyRecord, scope: String) {} +} + +private func waitFor(_ condition: () async -> Bool) async -> Bool { + for _ in 0..<500 { + if await condition() { return true } + try? await Task.sleep(nanoseconds: 10_000_000) + } + return false +} + private func unsupportedReady(profileExpired: Bool? = false) -> AppAttestLocalStatus { AppAttestLocalStatus(observedAt: 0, launchSession: .gui, availabilityReason: .isSupportedFalse, process: AppAttestProcessDiagnostics(preflight: AppAttestPreflight(profileExpired: profileExpired))) @@ -398,4 +442,74 @@ struct AppAttestUnsupportedRestartTests { await grant(at: later) #expect(marker.lastVerified() == later) } + + /// The real monitor, policy, lease, drain and marker run; only the + /// launchd/exec boundary and Apple's `isSupported` are fakes. + @Test func unsupportedRestartDrainsSpendsTheSharedMarkerAndUsesLaunchdOnce() async throws { + let (loop, root) = try await lifecycleLoop() + defer { try? FileManager.default.removeItem(at: root) } + let install = try UpdateRecoveryFixture() + defer { install.cleanup() } + let restarts = AppAttestRestartLog() + await loop.setAppAttestRestartSeams(route: .launchd, supported: { false }, restarts: restarts, + updater: install.updater(baseURL: URL(string: "http://127.0.0.1:9")!)) + await loop.installIdleAppAttestClient() + let now = Date() + try AppAttestVerifiedMarker(directory: root).record(now.addingTimeInterval(-3600)) + let marker = AppAttestStallRestartMarker(directory: root) + #expect(marker.lastRestart() == nil) + + // First seen longer ago than the threshold: the monitor's first tick is due. + await loop.noteAppAttestAvailability( + unsupportedReady(), now: now.addingTimeInterval(-AppAttestStallRestartPolicy.unsupportedThreshold - 60)) + #expect(await waitFor { restarts.routes.count == 1 }) + #expect(restarts.routes == [.launchd]) + #expect(restarts.causes == [.stallRestart]) + let spent = try #require(marker.lastRestart(), "the shared marker is written before the restart") + + // One restart per verified episode: the same state does not arm again + // until the coordinator verifies this Mac after the restart. + await loop.noteAppAttestAvailability(unsupportedReady(), now: spent) + #expect(await loop.appAttestUnsupportedSince == nil) + await loop.cancelAppAttestStallMonitor() + } + + @Test func unsupportedThatClearsDuringTheDrainResumesWithoutARestart() async throws { + let (loop, root) = try await lifecycleLoop() + defer { try? FileManager.default.removeItem(at: root) } + let install = try UpdateRecoveryFixture() + defer { install.cleanup() } + let restarts = AppAttestRestartLog() + // Unsupported when the monitor decides; supported again after the drain. + let probes = RecoveryRestartCounter() + await loop.setAppAttestRestartSeams(route: .launchd, supported: { probes.increment() > 1 }, restarts: restarts, + updater: install.updater(baseURL: URL(string: "http://127.0.0.1:9")!)) + await loop.installIdleAppAttestClient() + let now = Date() + try AppAttestVerifiedMarker(directory: root).record(now.addingTimeInterval(-3600)) + + await loop.noteAppAttestAvailability( + unsupportedReady(), now: now.addingTimeInterval(-AppAttestStallRestartPolicy.unsupportedThreshold - 60)) + #expect(await waitFor { await loop.appAttestUnsupportedSince == nil }) + #expect(await waitFor { + let phase = await loop.updatePhase + let refusing = await loop.servingDrain.refusing + return phase == .idle && !refusing + }) + #expect(probes.value == 2) + #expect(restarts.routes.isEmpty) + #expect(AppAttestStallRestartMarker(directory: root).lastRestart() == nil, + "a state that cleared on its own does not spend the limit") + await loop.cancelAppAttestStallMonitor() + } + + @Test func clusterMemberNeverArmsTheUnsupportedRestart() async throws { + let (loop, root) = try await lifecycleLoop(role: .clusterMember) + defer { try? FileManager.default.removeItem(at: root) } + await loop.setAppAttestRestartSeams(route: .launchd, supported: false) + try AppAttestVerifiedMarker(directory: root).record(Date().addingTimeInterval(-3600)) + await loop.noteAppAttestAvailability(unsupportedReady(), now: Date()) + #expect(await loop.appAttestUnsupportedSince == nil) + #expect(await loop.appAttestStallMonitorTask == nil) + } } From 901367d11b5eac70f54cd1b54f9d87d9904c9445 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 2 Nov 2026 21:08:00 -0800 Subject: [PATCH 0198/1441] feat(cluster): simpler two-Mac setup with lists, stated permissions and a fixed leader The 2026-11-02 onboarding review of a customer's first two-Mac setup found `darkbloom cluster` too verbose, keyed on letters, out of sync with macOS's prompts, and leading from the Mac that joined. This change: - Four steps (Connect, Pair, Choose a model, Start), one line per event, and the next action as the last line of every screen. - Every choice is a list moved with the arrow keys and taken with enter, as `darkbloom start` picks models: the pairing code, the model, a missing model's copy or download (a short copy included), the two-cables choice and the leader's menu. q cancels a list or a wait; arrow keys pressed during a wait are ignored. Plain consoles number the list, byte-identical on a terminal and a pipe. - The model list holds only models approved for clusters (`ClusterPublicModels.declared`) that the pair can serve. - The Mac the cluster is set up on leads: every plan, including the cluster service's automatic re-plans, puts it at rank 0 (`ClusterControlDerivation.planLeader`), so a 0.10.6 pair that leads from the joined Mac moves back at its next re-plan; before a plan exists, derivation prefers it. - macOS approvals are named up front and asked at stated moments: the cable's port in Connect (with sudo in the terminal where macOS can show no window, as over SSH, instead of a script to run by hand) and Darkbloom's Local Network access right after pairing, waited for until allowed, with what to click on which Mac. - Both Macs still confirm the pairing code (each must before it trusts the other's key), and the screens say so. - The member's `darkbloom cluster` is read-only; both Macs say whether their window may close; the Start step says whether the pair serves through Darkbloom. - `darkbloom doctor` includes the cluster's checks on a paired Mac. Tested: ClusterOnboardingChecks 666/0, ClusterControlChecks 229/0, ClusterPlacementChecks 237, ClusterSupervisionChecks 146, ClusterLinkChecks 2453, ClusterDiagnosticsChecks and ClusterInstalledSessionChecks pass; `swift build --build-tests` is clean and the doctor tests pass 13/13; docs-check, docs-impact and the changelog check pass. ClusterConsoleChecks fails to compile identically on master (pre-existing). Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-onboarding-simple.md | 17 + docs/architecture/inference.md | 50 +- docs/provider/cli-reference.md | 12 +- docs/provider/two-mac-cluster.md | 159 ++- .../Config/ClusterConfiguration.swift | 2 +- .../ClusterSetupWizardLiveOperations.swift | 11 +- .../Onboarding/ClusterControlLeadership.swift | 33 +- .../ClusterLocalNetworkAccess.swift | 163 +++ .../Onboarding/ClusterOnboardingFlow.swift | 880 ++++++++----- .../Onboarding/ClusterOnboardingLive.swift | 92 +- .../ClusterOnboardingTerminal.swift | 193 ++- .../Onboarding/ClusterService.swift | 3 + .../Onboarding/ClusterServiceControl.swift | 3 +- .../darkbloom/DoctorClusterChecks.swift | 25 + .../Sources/darkbloom/DoctorCommand.swift | 2 + .../ClusterControlChecks/ControlChecks.swift | 40 + .../OnboardingChecks.swift | 1143 ++++++++++------- .../DoctorClusterChecksTests.swift | 28 + 18 files changed, 1930 insertions(+), 926 deletions(-) create mode 100644 changelog.d/cluster-onboarding-simple.md create mode 100644 provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift create mode 100644 provider-swift/Sources/darkbloom/DoctorClusterChecks.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/DoctorClusterChecksTests.swift diff --git a/changelog.d/cluster-onboarding-simple.md b/changelog.d/cluster-onboarding-simple.md new file mode 100644 index 0000000000..e8f7cb403f --- /dev/null +++ b/changelog.d/cluster-onboarding-simple.md @@ -0,0 +1,17 @@ +### Simpler two-Mac cluster setup + +- `darkbloom cluster` setup is shorter and asks with lists: four steps (Connect, Pair, Choose a model, Start), one line + for each thing that happened, and every choice (the pairing code, the model, a missing model's copy, the leader's + menu) is a list moved with ↑↓ and taken with enter, as `darkbloom start` picks models; plain transcripts number the + list and take one key. The last line of each screen is the one thing to do next. +- The model list shows only the models approved for clusters (GLM-5.3-Flash and Qwen3.8 27B) that the two Macs can + serve, and a named model that is not approved is refused. +- The Mac you set up on leads and keeps leading: every plan puts rank 0 (the API and the coordinator's registration) + on it, and before a plan exists it is the leader on identical Macs too. +- macOS's permissions are asked at stated moments on each Mac, with what to click: the cable's port and this + terminal's Local Network access in Connect, Darkbloom's Local Network access right after the code is confirmed. + Where macOS cannot show its password window (an SSH session), the setup runs the port's commands with sudo in that + terminal instead of sending you to run a script. +- On the Mac that follows, `darkbloom cluster` shows the status and where to manage the cluster, with nothing to + choose; both Macs say whether their window can be closed. +- `darkbloom doctor` includes the cluster's checks on a Mac paired for a cluster. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 9d40490161..082cec2fb3 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-11-01 +> Last updated: 2026-11-03 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -222,8 +222,8 @@ and `libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementBa ## Cluster setup presentation -`ClusterOnboardingDriver` presents connection, pairing, model choice, startup -and a test response as five stages. Completion requires the test response to +`ClusterOnboardingDriver` presents connection, pairing, model choice and +startup (with its test response) as four steps. Completion requires the test response to succeed; a failed response retains the saved setup for a later retry. After the test response succeeds, the control leader registers the pair with the coordinator when the coordinator serves a cluster approval for this pair @@ -261,6 +261,38 @@ served is left out when another offers the same digests under the same name, and an artifact this build serves is never called unsupported for a copy the worker does not take (`ClusterSetupPlanning.copyNotTaken`). +Every choice goes through one console call (`ClusterOnboardingConsole.choose`): +on a color terminal a list moved with ↑↓ and taken with enter that folds to the +chosen line (`ClusterOnboardingTerminal.pick`), elsewhere numbered lines and one +key read the same way on every console (`ClusterOnboardingChoice.match`), so the +plain transcript stays byte for byte the same on a terminal and a pipe. The +setup's list holds only models the owner approved for clusters +(`ClusterOnboardingModelChoice.validated`, `listed`; `OnboardingLive.approved` +against `ClusterPublicModels.declared`); an older leader's choices carry no +such field and are listed as they come. A member's `darkbloom cluster` shows +the status and where to manage the cluster, with no list +(`ClusterOnboardingDriver.member`); the leader's is a list of the control +operations (`ClusterOnboardingDriver.menu`). + +The Mac the cluster was set up on leads. `LiveContext.plan` makes the Mac that +plans (the control leader) every plan's rank 0, so the derived leadership +(rank 0 of the adopted plan) stays there, and before a plan exists derivation +prefers it among the members present (`ClusterControlDerivation.derive`, +`preferred`; `ClusterControlNode.preferredLeader`, from the pairing's leader +pin). A Mac that is away never leads, so failover is unchanged. + +macOS's permissions are asked at stated moments +(`ClusterOnboardingDriver.allowLocalNetwork`): the command probes Local Network +access in the Connect step (`ClusterLocalNetworkAccess.probe`: one datagram to +the cable's subnet broadcast, refused with `EHOSTUNREACH` until allowed), and +the cluster service probes as it starts, right after pairing, keeping each +outcome for the onboarding (`ClusterLocalNetworkAccess.startServiceProbe`, +`serviceState`). Where macOS shows no approval window for the cable's port, the +link setup's owner-only script runs with sudo in the same terminal +(`ClusterOnboardingLinkResult.manualScript`, +`ClusterLocalNetworkAccess.runLinkScriptWithSudo`), with the terminal in its +ordinary mode while sudo reads the password (`ClusterOnboardingConsole.suspended`). + A DevNet build is installed as `Darkbloom Dev.app`, and its CLI is `darkbloom-dev`. A saved setup accepts a space in its installed paths (`ClusterConfigurationSyntax.installedPath`). The orphan sweep, the teardown @@ -2924,11 +2956,8 @@ 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`); -the coordinator decides each public placement. +cluster that serves through Darkbloom, the coordinator decides each public +placement ([serving a pair](../reference/cluster-control-protocol.md#serving-a-pair)). ### Two-Mac cluster stages (experimental) @@ -2998,7 +3027,8 @@ answer with the same worker build (`ClusterOnboardingUpdate.oneBuild`): the [pair's coordinated update](../provider/cluster-always-on.md#the-pairs-coordinated-update) restarts the two Macs seconds apart, and a plan made while one still runs the other build would fail and wait 600 s. A model change of -a serving cluster (`m`, or `darkbloom cluster local `) plans the same way: +a serving cluster (**Change model** in the leader's menu, `ClusterOnboardingDriver.menu`, +or `darkbloom cluster local `) plans the same way: its list was priced while the running parts held their memory, where tensor parallel may not fit now, so once both parts stopped and both Macs gave the memory back (`OnboardingLive.awaitReleased`) it plans again and adopts the @@ -3705,7 +3735,7 @@ says the gain. Predictions are still made and reported. A first placement, befor any load measured the link, plans tensor parallel on the keyed reduction a forced plan assumes (`tensorParallelAssumesUnmeasuredLink`, labelled as assumed), so a new pair's first setup is tensor parallel too: every plan made by `ClusterPlacementFlow.decide` -(the onboarding, `m`, the re-plan after a Darkbloom update or after two load +(the onboarding, **Change model**, the re-plan after a Darkbloom update or after two load refusals) is a first placement in this sense. Since tensor parallel's place no longer depends on the link's speed, the first load's keyed probe changes no choice, and nothing has to re-plan a pair after it. A pair still serves a diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index f49c4dbf83..b5f8224bb7 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1,6 +1,6 @@ # Provider CLI reference -> Last updated: 2026-11-02 +> Last updated: 2026-11-03 Reference for the `darkbloom` command-line tool: every subcommand and flag, the files and identifiers it creates, the `provider.toml` keys it reads with their @@ -587,7 +587,8 @@ darkbloom cluster local [] [--bind
] Runs the onboarding asking for local-only serving (`ClusterOnboardingRequest`), saved in the leader's setup record (`ClusterOnboardingLeadership.localOnly`, -`localBind`) until `p` in `darkbloom cluster` serves through Darkbloom again. +`localBind`) until **Serve through Darkbloom** in `darkbloom cluster` serves +through Darkbloom again. The leader part then starts with `--no-coordinator`. Needs a terminal; exit 1 otherwise. On the Mac that joins a waiting leader it pairs, says to run it on the leader and ends (exit 0) like `darkbloom cluster` @@ -1459,6 +1460,13 @@ The report header prints `Build` (`prod` or `dev`, fixed at compile time), `darkbloom doctor` is read-only except for the subprocess calls used by public ProviderCore checks and the explicit `--clear-backend-guard` action (`provider-swift/Sources/darkbloom/DoctorCommand.swift`, `runClearBackendGuard`). +On a Mac paired for a two-Mac cluster, the detailed checks also list the +checks `darkbloom cluster doctor` runs (installed metadata, trust files, the +Thunderbolt RDMA link, the saved setup), each named `cluster `; a failed +one fails the run and points to `darkbloom cluster doctor` for its details. A +Mac that is not paired gets none of them, and its link is not inspected +(`provider-swift/Sources/darkbloom/DoctorClusterChecks.swift`, +`buildClusterDoctorChecks`). The operator report begins with a readiness summary and the first concrete action. A failed model-fit check names the live usable memory, the required load budget and their shortfall; it tells the operator to free memory, rerun diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index ec48574988..0f5151f2dd 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-11-01 +> Last updated: 2026-11-03 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 @@ -26,19 +26,52 @@ Remote Login, no IP address and no network setting is typed anywhere. ## The steps, once -Run `darkbloom cluster` on each Mac, pick a model, done. Start on either Mac: it -drives the onboarding screens, chooses the model, sends the other Mac its setup -over the cable and starts it; you never go back to the other Mac. Which Mac -handles commands afterwards is worked out by the cluster itself (see +Run `darkbloom cluster` on each Mac, pick a model, done. The Mac you start on +leads the cluster and keeps leading: it chooses the model, sends the other Mac +its setup over the cable and starts it, and it holds rank 0, where requests +enter and which the coordinator registers (and pays) for the pair. Every plan +puts rank 0 on it (`LiveContext.plan`), and before a plan exists the cluster's +leader is derived as that Mac (`ClusterControlDerivation.derive`, `preferred`). +The other Mac follows; you never go back to it (see [If a Mac goes away](#if-a-mac-goes-away)). -The screen follows five stages: **Connect**, **Pair**, **Choose**, **Start** and -**Test**. The model list names the choice that Enter selects and explains why -any unavailable model cannot be selected. +The screen follows four steps: **Connect**, **Pair**, **Choose a model** and +**Start**, one line for each thing that happened. Every choice is a list you +move through with ↑ and ↓ and take with enter, as `darkbloom start` picks +models: the answer to the pairing code, the model, how a missing model gets +onto the Macs and, later, what to do with a running cluster. Where the screen +has no color (`NO_COLOR`, `TERM=dumb`, a pipe), the same list is numbered and +one key answers it: a number, enter for the first line, or a letter only one +line starts with (`y` for "Yes, pair"). The model list shows only models +approved for clusters (`ClusterPublicModels.declared`: GLM-5.3-Flash and +Qwen3.8 27B) that these two Macs can serve; any other model is left out, and a +model named on the command line that is not approved is refused. + +macOS asks for its permissions at two stated moments on each Mac, while you are +at that Mac, and the screen says what each prompt is and what to click: + +- **Connect:** the cable's port, once (your password), and Local Network access + for the program macOS attributes this command to: the terminal app, or sshd + in an SSH session. A probe that sends one datagram on the cable is what makes + macOS ask (`ClusterLocalNetworkAccess.probe`), and the setup waits for Allow. +- **Right after the code is confirmed:** Local Network access for Darkbloom, + which this Mac's cluster service asks for as it starts + (`ClusterLocalNetworkAccess.startServiceProbe`); the setup waits for Allow. + +When macOS cannot show its password window (an SSH session with no desktop), +the setup runs the same commands with `sudo` in that terminal: you type this +Mac's password into sudo, not into Darkbloom, and the setup goes on. Only when +sudo fails does it name the script to run yourself. + +The Mac that joins ends once paired: it says it follows the other Mac, whether +its window can close (a signed Darkbloom.app keeps serving; a development build +serves only while the window stays open), and, last, to continue on the other +Mac. The leader ends the same way: what serves, whether the windows can close, +and, last, the command to manage it. On a color terminal with a UTF-8 locale and at least 40 columns, setup opens -with the Darkbloom mark, which blooms in pixel by pixel. Each stage's heading -carries a step meter (`●●○○○`). Long work (checking the cable, reading both Macs, +with the Darkbloom mark, which blooms in pixel by pixel. Each step's heading +carries a step meter (`●●○○`). Long work (checking the cable, reading both Macs, planning, loading the model, waiting for the first tokens) shows a live line with a turning petal; the next line of the transcript replaces it. `DARKBLOOM_NO_ANIMATION=1` or `CI` keeps the mark and meter but stops the motion. @@ -51,8 +84,15 @@ recovery steps stay in scrollback, and no credential is printed: the API key lin names `darkbloom local`, which shows it. Setup reports completion only after the test response succeeds. If that request -fails, the saved setup remains available: run `darkbloom cluster`, check its -status, and press `t` to retry the response. +fails, the saved setup remains available: run `darkbloom cluster` on the leader, +check its status, and choose **Test a response** to try again. + +`darkbloom cluster` run again shows the cluster's status and, on the leader, a +list: **Test a response**, **Change model** (**Choose a model and serve** when +stopped), **Serve locally only** or **Serve through Darkbloom**, **Stop +serving**, **Check both Macs released their memory** and **Quit**. On the +other Mac it shows the status and where to manage the cluster, with nothing to +choose: its part runs by itself. The planner picks tensor parallel or pipeline for your Macs by itself. Phase split is off. A model whose artifact ships a speculative (MTP) head can also @@ -88,8 +128,8 @@ coordinator never carries it. So, with the default `[backend] mtp_mode` of With `mtp_mode = "on"`, `darkbloom cluster` keeps the assistant too. That pair is then not offered to the coordinator: its plan says "not offered for public traffic", and it serves on the leader's local API. A serving cluster switched -with `l` or `p` keeps the setup it has; press `m` to plan the model again for -the new way of serving. Public speculative decoding for Qwen pairs needs +with **Serve locally only** or **Serve through Darkbloom** keeps the setup it +has; choose **Change model** to plan the model again for the new way of serving. Public speculative decoding for Qwen pairs needs qualification evidence of its own, which no record holds yet. Rules: [Qwen27 TP assistant policy](../reference/configuration.md#qwen27-tp-assistant-policy). @@ -105,11 +145,11 @@ format instruction only, as on one Mac | # | Where | What you do | What it asks | |---|---|---|---| -| 1 | the first Mac | Run `darkbloom cluster`. It checks the Thunderbolt cable ("Cable found.", "Cable ready."). Nobody waits on the cable yet, so it says **"On your other Mac, run `darkbloom cluster`."** and waits (q cancels). With two cables it asks which one to use. | one macOS administrator approval when the selected port needs configuration ("Darkbloom needs network access for the cluster cable") | -| 2 | the other Mac | Run `darkbloom cluster`. The same checks; then it finds the waiting Mac on the cable by itself (no address, no host name). Both screens show the same six-digit code. | its own approval if needed; `y` on each Mac when the codes match | -| 3 | — | The other Mac says **"Paired with the other Mac (). Continue on the other Mac."** Its cluster service now runs; nothing else is ever asked there, also when it was started with `darkbloom cluster local` (it then says to run that on the Mac that leads). macOS may ask once to allow Darkbloom on the local network: allow it. | the Local Network prompt, once | -| 4 | the leader | It shows both Macs' hardware, tagged "(this Mac)" and "(the other Mac)", and every model the pair can serve (held by both Macs, by one of them, or in Darkbloom's catalog), one line each: size, how it is split, each Mac's share ("this Mac 50% / the other Mac 50%") and the expected speed. A model a Mac holds twice (a catalog download beside the cluster's own copy) is listed once. A model that has tensor parallel but is split otherwise says why on a short second line (for example "tensor parallel: slower here" or "tensor parallel: link unmeasured"). Models that fit in the Macs' free memory now come first. Choose the model (enter takes the first). A model the other Mac lacks says how it gets there ("copy ... over the Thunderbolt cable (6.1 GB)"). | enter to copy (a copy predicted under 30 s at the speed measured on these Macs starts by itself, `n` within 3 s stops it) | -| 5 | — | Choosing is starting: "Starting on both Macs in 3 s; press n to stop here." The leader saves the setup, sends it to the other Mac over the cable, starts both Macs, waits until both are loaded and answers one test request. | nothing | +| 1 | the first Mac | Run `darkbloom cluster`. It checks the Thunderbolt cable ("Cable found.", "Cable ready.") and Local Network access. Nobody waits on the cable yet, so this Mac leads; its last line is **"Now run `darkbloom cluster` on the other Mac."**, and it waits (q cancels). With two cables it asks which one to use. | the cable's port, once (your password; sudo in this terminal where macOS shows no window), and Local Network access for the terminal app | +| 2 | the other Mac | Run `darkbloom cluster`. The same checks; then it finds the waiting Mac on the cable by itself (no address, no host name). Both screens show the same six-digit code. | the same two permissions; **Yes, pair** on each Mac when the codes match | +| 3 | — | The other Mac says **"Paired with the other Mac (). It leads; this Mac follows it."** Its cluster service now runs, and macOS asks once to let Darkbloom find devices on your local network (Allow). Nothing else is ever asked there, also when it was started with `darkbloom cluster local` (it then says to run that on the Mac that leads); its last line says to continue on the other Mac. | Local Network access for Darkbloom, once | +| 4 | the leader | It shows both Macs in one line ("This Mac: … · the other Mac: …") and every model approved for clusters that the pair can serve (held by both Macs, by one of them, or in Darkbloom's catalog), one line each: size, how it is split, each Mac's share ("this Mac 50% / the other Mac 50%") and the expected speed. A model a Mac holds twice (a catalog download beside the cluster's own copy) is listed once. A model that has tensor parallel but is split otherwise says why at the end of its line (for example "tensor parallel: slower here", "tensor parallel: not measured yet" or "tensor parallel: link unmeasured"). Models that fit in the Macs' free memory now come first; one that does not ends with "does not fit now". Choose the model with ↑↓ and enter (enter takes the first). A model the other Mac lacks says how it gets there ("copy ... over the Thunderbolt cable (6.1 GB)"). | the copy first in a list (a copy predicted under 30 s at the speed measured on these Macs starts by itself, `n` within 3 s stops it) | +| 5 | — | Choosing is starting: the leader saves the setup, sends it to the other Mac over the cable, starts both Macs, waits until both are loaded and answers one test request, each said in one line. | nothing | When it serves, the screen says how in one line, for example: @@ -214,17 +254,17 @@ What `darkbloom cluster` status says in each mode: Approval sources, checks and saved fields: [coordinator-paired member](../reference/configuration.md#coordinator-paired-member). -Counting every key: `y` on the other Mac, and `y` and enter on the leader -(three keys), plus at most one macOS approval per Mac. +Counting every key: enter for **Yes, pair** on each Mac and enter for the first +model on the leader (three keys), plus the macOS prompts [above](#the-steps-once). Running `darkbloom cluster` again on either Mac opens with the same Darkbloom -mark, beside "Darkbloom cluster" and what can be done there ("Status / Test / -Change model / Stop"), and shows the same menu: the -cluster's state (the deployment line first), a test request (`t`), another -model (`m`), stopping (`s`) and a check that both Macs released their memory -(`v`). When it is stopped, `m` chooses a model and serves again. On a Mac that -does not handle commands, each choice is sent over the cable to the Mac that -does, and its answer is shown as it is. +mark, beside "Darkbloom cluster" and the part this Mac plays ("This Mac leads +the cluster", or "This Mac follows the other Mac (…)"), then shows the +cluster's state (the deployment line first) and, on the leader, the list +[above](#the-steps-once). The other Mac ends with where to manage the cluster +("To test, change the model or stop: run `darkbloom cluster` on the other Mac +(…)."), or, when the cable moved to a port not set up yet, offers to set it up +([below](#when-something-is-in-the-way)). If both Macs start waiting at the same moment, the pairing's own rule picks one to keep waiting (it leads) and the other says so and joins it. @@ -270,8 +310,9 @@ Mac or reach it over a tailnet (encrypted). With the macOS firewall on, macOS may ask once to let Darkbloom accept incoming connections. The choice is kept: after a restart or reboot both Macs serve locally only -again, until you switch back. In `darkbloom cluster`, `p` serves through -Darkbloom again and `l` serves locally only; on a serving cluster the leading +again, until you switch back. In `darkbloom cluster` on the leader, **Serve +through Darkbloom** serves through Darkbloom again and **Serve locally only** +serves locally only; on a serving cluster the leading Mac's part restarts that way and the screen waits for it. The model list still reads Darkbloom's catalog when the network is up (to download a model neither Mac has); with no network, it lists the models already on the Macs. Only @@ -321,9 +362,9 @@ require a pipeline layer cut. An unsupported model or rank count falls back to pipeline when eligible and fitting, without requesting a link measurement. Where tensor parallel fits both Macs' memory as they are now, it is chosen, also on a new pair whose link no load has measured yet. A pipeline is chosen -when only a pipeline fits now, and stays until the pair is planned again (`m` -in `darkbloom cluster`, or after a Darkbloom update). Changing the model of a -serving cluster (`m`, or `darkbloom cluster local `) plans again once both +when only a pipeline fits now, and stays until the pair is planned again (**Change +model** in `darkbloom cluster`, or after a Darkbloom update). Changing the model of a +serving cluster (**Change model**, or `darkbloom cluster local `) plans again once both Macs have stopped their parts and given back their memory, so the memory the running model held does not turn tensor parallel into a pipeline. Every load records the encrypted link's cost for later predictions; plans use the median of the @@ -358,8 +399,8 @@ under the near-tie rule) do two things only: counts for nothing. The coordinator's parity qualification still decides each public placement. -A model or mode with no passing record is served for you, and the plan and the -onboarding say in one line: "not yet qualified for public traffic". +A model or mode with no passing record is served for you, and the plan says in +one line: "not yet qualified for public traffic". Time budgets (startup, first token, stop) are derived from the setup and the installed artifact, not from a per-model table: @@ -432,8 +473,9 @@ The cluster keeps itself running. When one Mac goes away (turned off, asleep, cable out), the other keeps its part ready for 10 minutes; if the Mac comes back in that time, the cluster re-forms with nothing to do. After that, a Mac that can hold the model alone serves it alone until the other Mac is back, and -`darkbloom cluster` on it says so. Commands typed on either Mac keep working: -they are handled by whichever Mac runs the cluster now. +`darkbloom cluster` on it says so. When the Mac you set up on is back, it leads +again (it holds rank 0). Manage the cluster on the Mac that leads; on the other +Mac, `darkbloom cluster` shows the status and names the Mac to use. ## How the split is chosen @@ -590,9 +632,10 @@ drained for an update yet: its update waits while it serves (the log says - **No macOS prompt can be shown** (for example with no one logged in to the desktop): the check writes the exact commands the prompt would run to an owner-only - script and prints one line to run once as an administrator: - `sudo sh ~/.darkbloom/cluster-device/link-fix.sh`; then run - `darkbloom cluster` again. A port an administrator already isolated this way + script, and the setup runs it with `sudo` in the same terminal (type this + Mac's password into sudo). Only when that fails does it print the line to run + once as an administrator, `sudo sh ~/.darkbloom/cluster-device/link-fix.sh`; + then run `darkbloom cluster` again. A port an administrator already isolated this way is recognised and recorded (no change, no prompt). - **Internet Sharing shares to the cluster port itself**: the check says so and stops before any prompt. Turn the cluster port off under System Settings → @@ -600,7 +643,7 @@ drained for an update yet: its update waits while it serves (the log says `darkbloom cluster` again. - **The cable moved to another Thunderbolt port**: an already configured port is reused without another configuration prompt. For a port not yet configured, - run `darkbloom cluster` and press `f` when offered; macOS asks for administrator + run `darkbloom cluster` and choose **Set up the cable's port** when offered; macOS asks for administrator approval to configure that port. Recovery RDMA enablement and Local Network privacy permission remain separate steps. - **The Macs were paired again** while their cluster services ran @@ -612,23 +655,28 @@ drained for an update yet: its update waits while it serves (the log says restart its service, since one an earlier release started keeps the earlier pairing: on that Mac, run `darkbloom cluster stop`, then `darkbloom cluster`. - **A part keeps ending the same way**: after three identical ends the screen - says it and offers `d`; both Macs keep trying by themselves. + says it and offers **Save a diagnostics file to send to Darkbloom**; both Macs + keep trying by themselves. - **The leader cannot reach the other Mac**: make sure the other Mac is on and logged in; it rejoins by itself. If you denied the Local Network prompt there, allow Darkbloom in System Settings → Privacy & Security → Local Network, then run `darkbloom cluster` again. -- **A model is not offered**: the reason is shown beside it, for example "Not - yet qualified on this pair of Macs" (a pair serves a model only where its - cross-cable check passed). A copy the cluster worker does not take, of a - model a pair serves, says so ("supported on a cluster, but this Mac's cluster - worker does not take this copy of it"); the model is listed once when another - copy can be served. -- **A model does not fit now**: it is listed after the ones that fit, with what - frees the memory ("Quit apps on the other Mac (…) first"); the fit is checked - again right before the start. +- **A model is not offered**: the list leaves out every model that is not + approved for clusters or that these Macs cannot serve, with no reason beside + it. A model named on the command line says why ("… is not approved for + clusters yet.", or "… is not offered on these Macs: "). When no + approved model can run, the screen says so and gives each reason once, after + the models it holds back, for example "supported on a cluster, but this Mac's + cluster worker does not take this copy of it"; a model is listed once when + another copy of it can be served. +- **A model does not fit now**: it is listed after the ones that fit, its line + ending "does not fit now". The fit is checked again right before the start; a + model that still does not fit is not started, and the screen says what frees + the memory ("Quit apps on the other Mac (…) first."). - **The start does not finish**: the screen shows each Mac's last error and - offers `d` to save a diagnostics file in your home folder (no keys, addresses or - names in it; nothing is written if any would remain). + offers **Save a diagnostics file to send to Darkbloom**, which writes one to + your home folder (no keys, addresses or names in it; nothing is written if any + would remain). ## Undo @@ -662,8 +710,7 @@ and they must match. yet: on two different Macs it is planned 1:1, so the slower Mac sets the pace ([how the split is chosen](#how-the-split-is-chosen)). - A member cannot yet download a catalog model itself (the leader downloads and - copies), and a model change typed on a Mac that does not lead cannot copy a - model (run it on the leader). + copies). ## Developer notes @@ -685,7 +732,7 @@ Nothing here is needed to use the cluster. For background serving, install the same signed `Darkbloom.app` on each Mac and approve Local Network access on each when macOS asks. The setup installs a login agent associated with that app. After leaving both setup terminals, reopen -`darkbloom cluster` on either Mac and test a response. An ad-hoc development +`darkbloom cluster` on the leader and test a response. An ad-hoc development service can lose outbound access when its originating session closes; use the signed app instead of extending lease timeouts. See [background service permissions](cluster-always-on.md#permissions-asked-once). diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift b/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift index eb481decf4..9dd00dfe12 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift @@ -110,7 +110,7 @@ public struct ClusterConfiguration: Codable, Sendable, Equatable { /// approval runs this rule before any part stops (`ClusterApprovalAttachment.attachment`). Short enough to reach /// the leader whole through the other Mac's refusal (`ClusterSetupFailure` keeps 240 characters). static let tensorAssistantServesLocally = "Qwen's speculative assistant serves local clusters only (not qualified for " - + "public traffic); with mtp_mode \"auto\", press m in `darkbloom cluster` to plan without it" + + "public traffic); with mtp_mode \"auto\", choose Change model in `darkbloom cluster` to drop it" func validate(capability: ClusterRuntimeCapability, rawCapabilitySHA256: String) throws { func require(_ value: Bool, _ message: String) throws { diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift index 5fab33f75f..13e8ba5bfa 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift @@ -650,9 +650,18 @@ final class LiveContext: @unchecked Sendable { if let peerID = description.members.first(where: { $0.id != memberID })?.id { ClusterMemberProfiles.record([memberID: localProfile, peerID: peerProfile], homeDirectory: home) } + // The Mac the cluster was set up on leads every plan (rank 0: the API, the coordinator's head and the pair's + // earnings), on whichever Mac plans: the onboarding plans there, and the cluster service re-plans on the + // control leader, so a pair the joined Mac led moves back at its next plan (2026-11-02 onboarding review: a + // plan whose rank 0 was the other Mac handed leadership to the Mac that joined). The wizard's own steps lead + // from this Mac. + let setUp = (try? store.readRecord())?.leadership.map { ClusterSetupMemberFacts.memberID(pin: $0.leaderPin) } let decided = ClusterSetupPlanning.decide(readings: readings, description: description, localMemberID: memberID, localProfile: localProfile, peerProfile: peerProfile, peerModels: peer.models, measurements: measurements(), - leader: settings.derivedPlacement ? .some(nil) : .none, served: ClusterServedSpeedHistory.entries(homeDirectory: home) + (peer.served ?? []), + leader: settings.derivedPlacement + ? ClusterControlDerivation.planLeader(setUp: setUp, members: description.members.map(\.id), localID: memberID) + : memberID, + served: ClusterServedSpeedHistory.entries(homeDirectory: home) + (peer.served ?? []), link: description.members.count == 2 ? ClusterLinkProbeHistory.costs(homeDirectory: home, members: description.members.map(\.id)) ?? .unmeasured : .unmeasured, shareProbes: ClusterShareProbeHistory.read(ClusterShareProbeHistory.defaultFile(homeDirectory: home)), diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterControlLeadership.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterControlLeadership.swift index e6e38242ad..4c3633cc0c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterControlLeadership.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterControlLeadership.swift @@ -97,13 +97,21 @@ public enum ClusterControlDerivation { } /// The leader for these members, of which `present` answer now. `rankOrder` is the adopted plan's - /// member order (rank 0 first), nil before a plan. - public static func derive(members: [ClusterControlMember], present: Set, rankOrder: [String]?) -> Choice? { + /// member order (rank 0 first), nil before a plan. `preferred`: the Mac the cluster was set up on, which + /// leads whenever it is present and no plan's rank 0 decides (2026-11-02 onboarding review: on two + /// identical Macs the tie went to the lower key identity, and the Mac that joined became the leader). + /// The planner makes that Mac rank 0 as well, so the two rules agree; a Mac that is away never leads. + public static func derive(members: [ClusterControlMember], present: Set, rankOrder: [String]?, + preferred: String? = nil) -> Choice? { let candidates = members.filter { present.contains($0.memberID) } guard !candidates.isEmpty else { return nil } if let first = rankOrder?.first, present.contains(first), candidates.contains(where: { $0.memberID == first }) { return .init(memberID: first, reason: "rank 0 of the adopted plan: requests enter there and the coordinator registers it as the head") } + if let preferred, candidates.contains(where: { $0.memberID == preferred }) { + return .init(memberID: preferred, reason: rankOrder == nil ? "the Mac the cluster was set up on" + : "rank 0 is absent; the Mac the cluster was set up on is present") + } let best = candidates.min { a, b in let aloneA = a.holdsModelAlone == true, aloneB = b.holdsModelAlone == true if aloneA != aloneB { return aloneA } @@ -114,6 +122,14 @@ public enum ClusterControlDerivation { let why = best.holdsModelAlone == true ? "holds the chosen model alone" : "the most memory and GPU cores present" return .init(memberID: best.memberID, reason: rankOrder == nil ? why : "rank 0 is absent; of the members present, \(why)") } + + /// The member a plan puts at rank 0: `setUp`, the Mac the cluster was set up on, whichever Mac plans, so a + /// re-plan on the Mac that joined (a memory refusal, an update) hands rank 0 back to it; `localID` (the Mac + /// planning) when `setUp` is not one of the plan's members (no onboarding record, or one of an earlier pairing). + public static func planLeader(setUp: String?, members: [String], localID: String) -> String { + guard let setUp, members.contains(setUp) else { return localID } + return setUp + } } /// What one Mac's cluster service does about control, from its own observations only. @@ -160,6 +176,8 @@ public struct ClusterControlNode: Sendable, Equatable { public private(set) var claim: ClusterControlClaim public private(set) var members: [String: ClusterControlMember] public var rankOrder: [String]? + /// The Mac the cluster was set up on (`ClusterControlDerivation.derive`'s `preferred`). + public let preferredLeader: String? /// On a member: whether the leader's last lease said the cluster runs. public private(set) var leaderRunsCluster = false /// The leader: when each member last accepted this claim. A member: when the leader (or its awaited successor) last renewed. @@ -186,8 +204,9 @@ public struct ClusterControlNode: Sendable, Equatable { /// `claim` as persisted, or nil before the first one (term 0: derived among the known members). public init(localID: String, members: [ClusterControlMember], claim: ClusterControlClaim?, rankOrder: [String]?, now: Double, ttl: Double, - soloGrace: Double = ClusterControlNode.defaultSoloGraceSeconds) { + soloGrace: Double = ClusterControlNode.defaultSoloGraceSeconds, preferredLeader: String? = nil) { self.localID = localID + self.preferredLeader = preferredLeader self.soloGrace = soloGrace self.members = Dictionary(members.map { ($0.memberID, $0) }, uniquingKeysWith: { _, b in b }) self.rankOrder = rankOrder @@ -197,7 +216,7 @@ public struct ClusterControlNode: Sendable, Equatable { resolved = claim } else { let ids = Set(members.map(\.memberID) + [localID]) - let choice = ClusterControlDerivation.derive(members: members, present: ids, rankOrder: rankOrder) + let choice = ClusterControlDerivation.derive(members: members, present: ids, rankOrder: rankOrder, preferred: preferredLeader) resolved = ClusterControlClaim(term: 0, leaderID: choice?.memberID ?? localID, members: Array(ids), reason: choice?.reason ?? "the only member known") } @@ -320,7 +339,8 @@ public struct ClusterControlNode: Sendable, Equatable { // Leadership moves by derivation once a plan exists (before it, the Mac that drives the onboarding keeps // the screens and the claim; a failover's survivor keeps it until the plan's rank 0 is back). if let plan = rankOrder, !plan.isEmpty, - let choice = ClusterControlDerivation.derive(members: Array(members.values), present: present(now: now), rankOrder: plan), + let choice = ClusterControlDerivation.derive(members: Array(members.values), present: present(now: now), rankOrder: plan, + preferred: preferredLeader), choice.memberID != localID, confirmed.contains(choice.memberID) { let offer = ClusterControlClaim(term: claim.term + 1, leaderID: choice.memberID, members: claim.members, reason: choice.reason) pendingHandOver = offer @@ -336,7 +356,8 @@ public struct ClusterControlNode: Sendable, Equatable { heard[previous] = nil leaderRunsCluster = false let remaining = Set(claim.members).subtracting(expired).union([localID]) - guard let choice = ClusterControlDerivation.derive(members: Array(members.values), present: remaining, rankOrder: rankOrder) + guard let choice = ClusterControlDerivation.derive(members: Array(members.values), present: remaining, rankOrder: rankOrder, + preferred: preferredLeader) else { return [] } if choice.memberID == localID { claim = ClusterControlClaim(term: claim.term + 1, leaderID: localID, members: claim.members, diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift new file mode 100644 index 0000000000..d243e1b44b --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift @@ -0,0 +1,163 @@ +import Foundation +import Darwin + +/// Local Network privacy (macOS 15 and later) for the cluster: macOS asks once per program before the program may +/// reach other devices on the local network, the Thunderbolt cable included, and refuses the program's packets +/// (`EHOSTUNREACH`) until the person allows it. Left alone, each prompt appears whenever that program's first traffic +/// happens to flow, often while the person is at the other Mac (2026-11-02 onboarding review: "approve prompts for +/// network access are out of sync"). The onboarding asks at stated moments instead: +/// +/// - this command probes in Connect. macOS lets command-line tools run from Terminal or over SSH through by +/// themselves (Apple's TN3179), so this asks nothing unless the probe finds the cable blocked anyway; macOS then +/// names the program it attributes the command to (the terminal app, or sshd-keygen-wrapper in an SSH session); +/// - this Mac's cluster service probes as it starts (once paired): a launchd agent is not let through by itself, so +/// macOS asks about Darkbloom then, and the service keeps each outcome in a file the onboarding reads while it +/// waits for the answer. +/// +/// A probe is one datagram to the cable's subnet broadcast address, sent from the cable's interface to the discard +/// port: nothing on the other Mac reads it. +public enum ClusterLocalNetworkAccess { + /// Whether a datagram on `interface` (the cable's) is let through now. Nil `interface`: the one Thunderbolt + /// interface with an IPv4 address, as pairing finds it. + public static func probe(interface: String? = nil) -> ClusterOnboardingLocalNetwork { + guard let name = interface ?? (try? ClusterPairCommandLine.resolveInterface(ClusterPairCommandRequest(), peer: nil)), + let target = broadcastAddress(interface: name) else { return .unknown } + let index = if_nametoindex(name) + guard index != 0 else { return .unknown } + let socket = Darwin.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) + guard socket >= 0 else { return .unknown } + defer { Darwin.close(socket) } + var on: Int32 = 1 + var bound = index + guard setsockopt(socket, SOL_SOCKET, SO_BROADCAST, &on, socklen_t(MemoryLayout.size)) == 0, + setsockopt(socket, IPPROTO_IP, IP_BOUND_IF, &bound, socklen_t(MemoryLayout.size)) == 0 else { return .unknown } + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + address.sin_port = in_port_t(9).bigEndian + address.sin_addr = target + let payload = Array("darkbloom local network check".utf8) + let sent = withUnsafePointer(to: &address) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { + Darwin.sendto(socket, payload, payload.count, 0, $0, socklen_t(MemoryLayout.size)) + } + } + if sent == payload.count { return .allowed } + return blocked(errno) ? .blocked : .unknown + } + + /// The errors macOS gives a program it has not let onto the local network. + static func blocked(_ error: Int32) -> Bool { error == EHOSTUNREACH || error == EPERM } + + /// The interface's IPv4 broadcast address (address | ~mask), or nil when it has no IPv4 address. + static func broadcastAddress(interface: String) -> in_addr? { + var list: UnsafeMutablePointer? + guard getifaddrs(&list) == 0, let first = list else { return nil } + defer { freeifaddrs(list) } + for entry in sequence(first: first, next: { $0.pointee.ifa_next }) { + let item = entry.pointee + guard String(cString: item.ifa_name) == interface, let address = item.ifa_addr, let mask = item.ifa_netmask, + address.pointee.sa_family == sa_family_t(AF_INET) else { continue } + let host = address.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { $0.pointee.sin_addr.s_addr } + let net = mask.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { $0.pointee.sin_addr.s_addr } + return in_addr(s_addr: host | ~net) + } + return nil + } + + /// This command runs in an SSH session: macOS shows its windows on the Mac's own screen, not in this terminal. + public static func overSSH(environment: [String: String] = ProcessInfo.processInfo.environment) -> Bool { + environment["SSH_CONNECTION"] != nil || environment["SSH_TTY"] != nil + } + + /// The app macOS names when it asks about a command run in this terminal: sshd-keygen-wrapper (the program macOS + /// attributes an SSH session to) over SSH, else the terminal app (`TERM_PROGRAM`), else plain words. + public static func commandApp(environment: [String: String] = ProcessInfo.processInfo.environment) -> String { + if overSSH(environment: environment) { return "sshd-keygen-wrapper" } + switch environment["TERM_PROGRAM"] { + case "Apple_Terminal": return "Terminal" + case "iTerm.app": return "iTerm" + case "vscode": return "Visual Studio Code" + case "WarpTerminal": return "Warp" + case "ghostty": return "Ghostty" + case let name? where !name.isEmpty && name.count <= 40 && ClusterOnboardingDeployment.shownPlainly(name): return name + default: return "your terminal app" + } + } + + // MARK: - The cluster service's own probe + + /// What the service last saw, for the onboarding to read. + struct Report: Codable, Equatable { + var state: ClusterOnboardingLocalNetwork + /// The service process that probed: a report of an earlier run never speaks for this one. + var pid: Int32 + } + + /// How long the service keeps probing while refused, and how often. + static let serviceProbeSeconds: Double = 900 + static let serviceProbeInterval: useconds_t = 2_000_000 + + static func reportFile() -> URL? { + (try? ClusterService.paths())?.pid.deletingLastPathComponent().appendingPathComponent("local-network.json") + } + + /// The service's side, from its start: probes at once (the probe that makes macOS ask about Darkbloom), then every + /// 2 s while refused, for up to 15 minutes, keeping each outcome for the onboarding; stops once allowed. Off the + /// service's thread; says each change in the service log. + public static func startServiceProbe(say: @escaping @Sendable (String) -> Void) { + Thread.detachNewThread { + let started = Date() + var last: ClusterOnboardingLocalNetwork? + while Date().timeIntervalSince(started) < serviceProbeSeconds { + let state = probe() + if state != last { + write(Report(state: state, pid: getpid())) + if state != .unknown { say("local network access for this service: \(state.rawValue)") } + last = state + } + if state == .allowed { return } + usleep(serviceProbeInterval) + } + } + } + + static func write(_ report: Report) { + guard let file = reportFile(), let data = try? JSONEncoder().encode(report) else { return } + try? data.write(to: file, options: [.atomic]) + chmod(file.path, 0o600) + } + + /// The running service's last outcome: unknown when it wrote none yet (a service of an older build never does). + public static func serviceState() -> ClusterOnboardingLocalNetwork { + guard let paths = try? ClusterService.paths(), let file = reportFile(), + let pidText = try? String(contentsOf: paths.pid, encoding: .utf8), + let pid = Int32(pidText.trimmingCharacters(in: .whitespacesAndNewlines)), + let data = try? Data(contentsOf: file), data.count <= 4_096, + let report = try? JSONDecoder().decode(Report.self, from: data), report.pid == pid else { return .unknown } + return report.state + } + + // MARK: - The cable's port, where macOS cannot show its prompt + + /// Runs Darkbloom's own link setup script (`~/.darkbloom/cluster-device/link-fix.sh`, written owner-only by the + /// link setup) with sudo, attached to this terminal: sudo asks for the password itself; Darkbloom never reads it. + /// Any other path, or a file that is not this user's private regular file, is refused. True when it exited 0. + public static func runLinkScriptWithSudo(_ shown: String, paths: ClusterUserPaths) -> Bool { + let home = paths.homeDirectory.path + let path = shown.hasPrefix("~/") ? home + shown.dropFirst(1) : shown + let expected = paths.deviceDirectory.appendingPathComponent("link-fix.sh").path + var metadata = stat() + guard path == expected, lstat(path, &metadata) == 0, (metadata.st_mode & S_IFMT) == S_IFREG, + metadata.st_uid == getuid(), metadata.st_mode & 0o022 == 0 else { return false } + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/sudo") + process.arguments = ["/bin/sh", path] + process.standardInput = FileHandle.standardInput + process.standardOutput = FileHandle.standardOutput + process.standardError = FileHandle.standardError + do { try process.run() } catch { return false } + process.waitUntilExit() + return process.terminationStatus == 0 + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift index 39a521c20b..f5b162e138 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift @@ -3,17 +3,20 @@ import Foundation // Leader-first onboarding (owner spec 2026-10-12, `darkbloom cluster`): // // Mac 1: `darkbloom cluster` -> checks (RDMA, cable, isolation behind ONE -// macOS approval, GID) -> nobody waits on the cable, so this Mac becomes the -// leader-to-be, answers discovery on the cable and says "On your other Mac, -// run `darkbloom cluster`." -> waits (q cancels). +// macOS approval, or sudo in this terminal where none can show, GID) and +// this command's Local Network access -> nobody waits on the cable, so this +// Mac leads, answers discovery on the cable and says "Now run `darkbloom +// cluster` on the other Mac." -> waits (q cancels). // Mac 2: `darkbloom cluster` -> its own checks -> finds the waiting leader -// on the cable by itself -> the same code on both screens, y on each -> -// "Paired with the other Mac (). Continue on the other Mac." -> its -// cluster service runs, and nothing else is asked there. -// Mac 1 (the leader, where onboarding started): both Macs' hardware, the -// model choice, the planner's placement (which Mac decodes is derived, not -// the leader), the setup synced to the member over the link control -// channel, the member started remotely, serving, one test request. +// on the cable by itself -> the same code on both screens, "Yes, pair" on +// each -> "Paired with the other Mac (). It leads; this Mac follows +// it." -> its cluster service runs (macOS asks about Darkbloom's Local +// Network access), and nothing else is asked there. +// Mac 1 (the leader, where onboarding started): its service's Local Network +// access, both Macs in one line, the choice among the models approved for +// clusters, the planner's placement (this Mac is rank 0), the setup synced +// to the member over the link control channel, the member started +// remotely, serving, one test request. // // Everything here is pure (Foundation and Darwin only): the operations are // closures, so a check drives the whole flow on a pseudo-terminal with @@ -146,7 +149,7 @@ public struct ClusterOnboardingResume: Sendable, Equatable { public var modelName: String? /// How the cluster serves (kept across restarts, as the leader saved it). public var scope: ClusterServingScope = .publicServing - /// On a member: the derived control leader's name (commands typed here run there). + /// On a member: the derived control leader's name (the Mac the cluster is managed on). public var leaderName: String? /// Why derivation picked the leader, and its term. public var leaderReason: String? @@ -207,14 +210,6 @@ public struct ClusterOnboardingMachine: Codable, Sendable, Equatable { self.name = name; self.memoryGB = memoryGB; self.gpuCores = gpuCores; self.leads = leads; self.models = models self.memberID = memberID; self.here = here ?? leads } - - /// The machine's line, tagged "(this Mac)" on the screen's own Mac and, in a pair (`inPair`), "(the other Mac)" - /// on the other one: two Macs of one kind share the hardware name. - public func line(inPair: Bool) -> String { - let gpu = gpuCores.map { " · \($0)-core GPU" } ?? "" - let mac = here ? " (\(ClusterOnboardingMacName.this))" : inPair ? " (\(ClusterOnboardingMacName.other))" : "" - return " \(name) · \(memoryGB) GB\(gpu) · \(models) model\(models == 1 ? "" : "s") · \(leads ? "leads" : "member")\(mac)" - } } /// One model the leader may choose, with the planner's placement in words. @@ -231,23 +226,31 @@ public struct ClusterOnboardingModelChoice: Codable, Sendable, Equatable { public var fitRemedy: String? /// The model's id (`title` is its catalog display name when the catalog gave one); nil from an older build. public var modelID: String? - /// Whether public traffic may reach it yet, in one line; said once it is chosen, and only when the cluster serves - /// through Darkbloom. Nil from an older build (which put the line in `lines`). + /// Whether public traffic may reach it yet, in one line, for an older member's screen, which says it once the model + /// is chosen (this build's list does not). Nil from an older build (which put the line in `lines`). public var publicTraffic: String? /// Why the planner's split is not tensor parallel, in a few words ("tensor parallel: slower here"), for a model /// with a tensor-parallel plan that the planner did not give one. Nil when the split is tensor parallel, when the /// model has no such plan (no line for it), and from an older build. public var tensorParallelNote: String? + /// The owner approved this model for clusters (`ClusterPublicModels`): the setup lists only such models + /// (2026-11-02 onboarding review: "only allow ones that are allowed to cluster serve and validated"). Nil from + /// an older leader, which does not say: its list is shown as it came. + public var validated: Bool? public init(title: String, lines: [String], blocker: String?, provision: ClusterOnboardingProvisionOffer? = nil, fitRemedy: String? = nil, - modelID: String? = nil, publicTraffic: String? = nil, tensorParallelNote: String? = nil) { + modelID: String? = nil, publicTraffic: String? = nil, tensorParallelNote: String? = nil, validated: Bool? = nil) { self.title = title; self.lines = lines; self.blocker = blocker; self.provision = provision; self.fitRemedy = fitRemedy self.modelID = modelID; self.publicTraffic = publicTraffic; self.tensorParallelNote = tensorParallelNote + self.validated = validated } + /// Offered on the setup's list: it can be served on these Macs and is not known to be unapproved. + public var listed: Bool { blocker == nil && validated != false } + /// The list's one line: the title (with the model's id when another choice shows the same title), the first of /// its lines (size and how it is split, or how it gets onto the Macs) and, at its end, the tensor-parallel note - /// when there is one it can say. The rest is said once it is chosen. + /// when there is one it can say. public func listLine(sameTitleElsewhere: Bool) -> String { let name = sameTitleElsewhere ? "\(title) (\(modelID ?? title))" : title let line = lines.first.map { "\(name) — \($0)" } ?? name @@ -366,9 +369,9 @@ public struct ClusterOnboardingProvisionOffer: Codable, Sendable, Equatable { public var leaderDownloads: Bool /// Why it cannot start (not enough free disk on a Mac), nil when it can. public var blocker: String? - /// The predicted time of a copy over the cable short enough to start without asking (derived from the copy rate - /// measured on these Macs and the bytes to move; `ClusterModelProvisioning.quickCopySeconds`): it starts with a - /// stated line and n still stops it. Nil: asked for (a long copy, a download, or no rate measured yet). + /// The predicted time of a short copy over the cable (derived from the copy rate measured on these Macs and the + /// bytes to move; `ClusterModelProvisioning.quickCopySeconds`): the list's copy item says it. Nil: a long copy, a + /// download, or no rate measured yet. public var quickSeconds: Double? public init(lines: [String], downloadAlternative: Bool, leaderDownloads: Bool, blocker: String? = nil, quickSeconds: Double? = nil) { @@ -480,7 +483,32 @@ public struct ClusterOnboardingLinkResult: Sendable, Equatable { public var exitCode: Int32 /// More than one cable port is active and none is set up yet: the ports to choose from ("en5", "en6"). public var ports: [String] - public init(ready: Bool, exitCode: Int32, ports: [String] = []) { self.ready = ready; self.exitCode = exitCode; self.ports = ports } + /// macOS could not show its approval prompt here (an SSH session with no desktop): the owner-only script of the + /// port's setup commands, which the onboarding runs with sudo in this terminal instead of sending the person to + /// run it by hand. Nil otherwise. + public var manualScript: String? + public init(ready: Bool, exitCode: Int32, ports: [String] = [], manualScript: String? = nil) { + self.ready = ready; self.exitCode = exitCode; self.ports = ports; self.manualScript = manualScript + } +} + +/// Whether macOS lets a program reach the cable's network (Local Network privacy), from a probe that sends one +/// datagram there: macOS shows its prompt the first time a program does, and refuses the program's traffic until the +/// person allows it. +public enum ClusterOnboardingLocalNetwork: String, Codable, Sendable, Equatable { + case allowed + /// Not allowed yet: macOS's prompt is up, or the person denied it. + case blocked + /// Nothing could be probed or read (no cable address yet, or a service that does not report it). + case unknown +} + +/// Who macOS names in its Local Network prompt: each is asked once per Mac. +public enum ClusterOnboardingLocalNetworkSubject: Sendable, Equatable { + /// This command, as macOS attributes it: the terminal app it runs in, or sshd in an SSH session. + case thisCommand + /// This Mac's cluster service (Darkbloom), which carries the cluster's traffic once the onboarding ends. + case service } public struct ClusterOnboardingReady: Codable, Sendable, Equatable { @@ -591,10 +619,10 @@ public struct ClusterOnboardingOperations: Sendable { /// Finds a Mac waiting on the cable and joins it, or waits there as the leader-to-be. Records the role. public var pair: @Sendable (_ events: @escaping @Sendable (ClusterOnboardingPairEvent) -> Void) -> ClusterOnboardingPairResult public var answerCode: @Sendable (_ accept: Bool) -> Void - /// Starts this Mac's cluster service unless it runs; its line for the screen. - public var ensureService: @Sendable () -> Result + /// Starts this Mac's cluster service unless it runs (a failure's lines say why it did not). + public var ensureService: @Sendable () -> Result /// Every Mac of the cluster, the leader first, read over the link control channel. - public var reachMembers: @Sendable (_ say: @escaping @Sendable (String) -> Void) -> Result<[ClusterOnboardingMachine], ClusterOnboardingFailure> + public var reachMembers: @Sendable () -> Result<[ClusterOnboardingMachine], ClusterOnboardingFailure> public var planModels: @Sendable () -> Result<[ClusterOnboardingModelChoice], ClusterOnboardingFailure> /// Saves this Mac's setup for the choice and syncs every member's to it over the link. public var adopt: @Sendable (_ index: Int) -> Result<[String], ClusterOnboardingFailure> @@ -628,13 +656,26 @@ public struct ClusterOnboardingOperations: Sendable { /// After the Test stage passed: registers the pair with the coordinator as a cluster member when the coordinator /// serves a cluster approval for this pair's installed app and model; its lines (none: nothing changed). public var register: @Sendable () -> Result<[String], ClusterOnboardingFailure> + /// Local Network access on this Mac for `subject`: this command probed now, or the cluster service as it last + /// reported its own probe. The first probe is what makes macOS ask. + public var localNetwork: @Sendable (_ subject: ClusterOnboardingLocalNetworkSubject) -> ClusterOnboardingLocalNetwork + /// The app macOS names when it asks about this command: the terminal app, or sshd in an SSH session. + public var commandApp: @Sendable () -> String + /// Runs the owner-only link `script` with sudo in this terminal, where macOS could not show its own prompt: the + /// person types this Mac's password into sudo, never into Darkbloom. True when it exited 0. + public var runAsAdministrator: @Sendable (_ script: String) -> Bool + /// This Mac's cluster service keeps running once this window closes (a login agent of the signed app). False for a + /// development build, whose service lives only as long as the session that started it. + public var serviceOutlivesWindow: @Sendable () -> Bool + /// This command runs over SSH: macOS shows its prompts on this Mac's own screen, not in this terminal. + public var remote: @Sendable () -> Bool public init(resume: @escaping @Sendable () -> ClusterOnboardingResume, checkLink: @escaping @Sendable (@escaping @Sendable (String) -> Void) -> ClusterOnboardingLinkResult, pair: @escaping @Sendable (@escaping @Sendable (ClusterOnboardingPairEvent) -> Void) -> ClusterOnboardingPairResult, answerCode: @escaping @Sendable (Bool) -> Void, - ensureService: @escaping @Sendable () -> Result, - reachMembers: @escaping @Sendable (@escaping @Sendable (String) -> Void) -> Result<[ClusterOnboardingMachine], ClusterOnboardingFailure>, + ensureService: @escaping @Sendable () -> Result, + reachMembers: @escaping @Sendable () -> Result<[ClusterOnboardingMachine], ClusterOnboardingFailure>, planModels: @escaping @Sendable () -> Result<[ClusterOnboardingModelChoice], ClusterOnboardingFailure>, adopt: @escaping @Sendable (Int) -> Result<[String], ClusterOnboardingFailure>, serve: @escaping @Sendable () -> Result<[String], ClusterOnboardingFailure>, @@ -652,13 +693,20 @@ public struct ClusterOnboardingOperations: Sendable { developerNotice: @escaping @Sendable () -> String? = { nil }, setScope: @escaping @Sendable (ClusterServingScope) -> Result<[String], ClusterOnboardingFailure> = { _ in .failure(.init("This build cannot change how the cluster serves.")) }, - register: @escaping @Sendable () -> Result<[String], ClusterOnboardingFailure> = { .success([]) }) { + register: @escaping @Sendable () -> Result<[String], ClusterOnboardingFailure> = { .success([]) }, + localNetwork: @escaping @Sendable (ClusterOnboardingLocalNetworkSubject) -> ClusterOnboardingLocalNetwork = { _ in .allowed }, + commandApp: @escaping @Sendable () -> String = { "Terminal" }, + runAsAdministrator: @escaping @Sendable (String) -> Bool = { _ in false }, + serviceOutlivesWindow: @escaping @Sendable () -> Bool = { true }, + remote: @escaping @Sendable () -> Bool = { false }) { self.resume = resume; self.checkLink = checkLink; self.pair = pair; self.answerCode = answerCode self.ensureService = ensureService; self.reachMembers = reachMembers; self.planModels = planModels self.adopt = adopt; self.serve = serve; self.waitReady = waitReady; self.testRequest = testRequest self.status = status; self.stop = stop; self.provision = provision; self.verifyTeardown = verifyTeardown self.useLinkPort = useLinkPort; self.recheckFit = recheckFit; self.afterRestart = afterRestart; self.saveDiagnostics = saveDiagnostics self.developerNotice = developerNotice; self.setScope = setScope; self.register = register + self.localNetwork = localNetwork; self.commandApp = commandApp; self.runAsAdministrator = runAsAdministrator + self.serviceOutlivesWindow = serviceOutlivesWindow; self.remote = remote } } @@ -673,44 +721,62 @@ public struct ClusterOnboardingPairing: Sendable, Equatable { /// The role this run is heading for; nil until it listens or dials. public private(set) var role: ClusterOnboardingRole? private var announcedWait = false - /// The code is on screen and waits for y or n. + /// The other Mac has answered the code. + private var peerAnswered = false + /// The code is on screen and waits for its answer (`codeAnswers`). public private(set) var asking: String? public init() {} - public static let otherMacLine = "On your other Mac, run `darkbloom cluster`." + /// The one thing to do on the other Mac while this one waits: said last, so it is the line the person reads. + public static let otherMacLine = "Now run `darkbloom cluster` on the other Mac." + + /// The question under the code, and its two answers (a menu: arrows and enter, or 1 and 2). Each Mac answers for + /// itself: a "yes" passed on from the other Mac could come from a Mac in between. + public static let codeQuestion = "Does the other Mac show the same code? Answer on both Macs." + public static let codeAnswers = ["Yes, pair", "No"] + /// Said once this Mac answered yes and the other Mac has not answered yet: the next thing to do, kept on screen + /// (a plain console shows no live line). + public static let otherMacAnswerLine = "Now choose \u{201C}Yes, pair\u{201D} on the other Mac too." + + /// What the live line says while the pairing runs: the action again while this Mac waits for the other one. + public var working: String? { + switch phase { + case .searching: return "Looking for the other Mac on the cable" + case .waiting: return "Waiting for the other Mac (run `darkbloom cluster` there; q cancels)" + case .joining: return "Exchanging keys with the other Mac" + case .confirmed: return "Waiting for the other Mac to confirm the code" + case .confirming, .done: return nil + } + } public mutating func handle(_ event: ClusterOnboardingPairEvent) -> [String] { switch event { case .searching: phase = .searching - return ["Looking for a Mac waiting on the cable…"] + return [] case .waitingAsLeader: phase = .waiting role = .leader guard !announcedWait else { return [] } announcedWait = true - return ["No other Mac is waiting on the cable, so this Mac will lead the cluster.", - "", - " " + Self.otherMacLine, - "", - "Waiting for it here (up to 10 minutes; press q to cancel)…"] + return ["This Mac leads. It waits up to 10 minutes for the other Mac (q cancels).", Self.otherMacLine] case .joining: let yielded = role == .leader phase = .joining role = .member return [yielded ? "The other Mac started waiting at the same moment and leads; this Mac joins it." - : "Found a Mac waiting on the cable: this Mac joins its cluster."] + : "Found the other Mac on the cable: it leads, and this Mac joins it."] case .connected: - return ["Connected over the cable; exchanging keys…"] + return [] case .code(let code, let peer): let shown = Self.spaced(code) phase = .confirming(shown) asking = shown - return ["", "The other Mac: " + (peer.first ?? "a Mac on the cable")] + peer.dropFirst().map { " " + $0 } - + ["", "Code: \(shown) (the same code is on the other Mac's screen)", - "Does the other Mac show \(shown)? Press y if it does, n if it does not."] + return ["The other Mac: " + (peer.first ?? "a Mac on the cable")] + peer.dropFirst().map { " " + $0 } + + ["Code: \(shown)", Self.codeQuestion] case .peerDecided(let accepted): + peerAnswered = true return [accepted ? "The other Mac confirmed the code." : "The other Mac declined the code."] case .note(let text): return [text] @@ -722,7 +788,8 @@ public struct ClusterOnboardingPairing: Sendable, Equatable { guard asking != nil else { return [] } asking = nil phase = .confirmed - return [accept ? "Confirmed here; waiting for the other Mac…" : "Declined here: nothing is paired."] + guard accept else { return ["Declined here: nothing is paired."] } + return peerAnswered ? [] : [Self.otherMacAnswerLine] } public mutating func finished(_ result: ClusterOnboardingPairResult) -> [String] { @@ -733,8 +800,8 @@ public struct ClusterOnboardingPairing: Sendable, Equatable { self.role = role let other = ClusterOnboardingMacName.other(named: peerName) switch role { - case .member: return ["", "Paired with \(other). Continue on \(ClusterOnboardingMacName.other)."] - case .leader: return ["", "Paired with \(other). This Mac leads the cluster."] + case .member: return ["\(ClusterOnboardingDriver.done) Paired with \(other). It leads; this Mac follows it."] + case .leader: return ["\(ClusterOnboardingDriver.done) Paired with \(other). This Mac leads."] } case .failed(let lines): return ["Not paired."] + lines + ["Run `darkbloom cluster` again to try again."] @@ -761,10 +828,15 @@ public protocol ClusterOnboardingConsole: AnyObject { /// A copy's or download's live report (`ClusterOnboardingProgress.live`): redrawn in place where `working` /// lines show; otherwise said only when `logged`. func progress(_ text: (_ width: Int?) -> String, logged: Bool) - /// One key, or nil when `milliseconds` passed with none. "\r" is enter. + /// One key, or nil when `milliseconds` passed with none. "\r" is enter; a lone escape is "\u{1B}"; a key that + /// sends a sequence (an arrow) reads as none, so it never stops a wait. func key(milliseconds: Int) -> Character? - /// A line typed after `prompt` (echoed as typed), or nil when the input closed. - func line(prompt: String) -> String? + /// One of `options` (their order), as `darkbloom start` picks models: ↑↓ and enter where the console can redraw, + /// else a number, enter for `selected`, or an option's first letter. Nil when the person cancelled (q or escape), + /// the input closed, or `abandon` turned true while it waited (asked between keys). + func choose(_ options: [String], selected: Int, abandon: () -> Bool) -> Int? + /// Runs `body` with the terminal in its ordinary mode, nothing live on screen (sudo asks for a password there). + func suspended(_ body: () -> T) -> T /// The input is closed: nothing more can be asked. var closed: Bool { get } } @@ -776,9 +848,29 @@ public extension ClusterOnboardingConsole { func working(_ text: String) {} func settle() {} func progress(_ text: (_ width: Int?) -> String, logged: Bool) { if logged { say(" " + text(nil)) } } + func suspended(_ body: () -> T) -> T { body() } + + func choose(_ options: [String], selected: Int = 0) -> Int? { choose(options, selected: selected, abandon: { false }) } +} + +/// How a typed answer picks one of a list's options, the same on every console: enter takes the default, a number +/// its line, and a letter the one option whose first word starts with it ("y" for "Yes, pair"). +public enum ClusterOnboardingChoice { + public static func match(_ typed: String, options: [String], selected: Int) -> Int? { + let text = typed.trimmingCharacters(in: .whitespaces).lowercased() + if text.isEmpty { return selected } + if let number = Int(text) { return options.indices.contains(number - 1) ? number - 1 : nil } + let starting = options.indices.filter { options[$0].lowercased().hasPrefix(text) } + return starting.count == 1 ? starting[0] : nil + } } /// Runs the onboarding on a console with the operations given; returns the exit status. +/// +/// The screens follow the 2026-11-02 onboarding review: four steps (Connect, Pair, Choose, Start), one line per +/// thing that happened, every macOS permission asked at a stated moment while the person is at that Mac (the cable's +/// approval and this terminal's Local Network access in Connect, Darkbloom's own once paired), choices from a list +/// with ↑↓ and enter as `darkbloom start` picks models, and the one thing to do next as the last line. public enum ClusterOnboardingDriver { public static func run(_ operations: ClusterOnboardingOperations, console: ClusterOnboardingConsole, request: ClusterOnboardingRequest = .init()) -> Int32 { @@ -795,30 +887,72 @@ public enum ClusterOnboardingDriver { } switch resume.role { case .member: - console.banner(resumeTitle, resumeSubtitle) + console.banner(title, followerSubtitle(resume)) return member(resume, operations, console, request: request) case .leader: - console.banner(resumeTitle, resumeSubtitle) + console.banner(title, leaderSubtitle) return leader(resume, operations, console, justPaired: false, request: request) case nil: return onboard(operations, console, request: request) } } - /// The opening on a Mac that is already in a cluster (`darkbloom cluster` run again, on the leader or a member): - /// the same mark as the setup, with what can be done from here. - public static let resumeTitle = "Darkbloom cluster" - public static let resumeSubtitle = "Status / Test / Change model / Stop" + /// The setup's opening, and the opening on a Mac that is already in a cluster (`darkbloom cluster` run again): + /// the same mark, with the part this Mac plays. + public static let title = "Darkbloom cluster" + public static let setupSubtitle = "Two Macs, one model: connect, pair, choose, start" + public static let leaderSubtitle = "This Mac leads the cluster" + static func followerSubtitle(_ resume: ClusterOnboardingResume) -> String { + "This Mac follows " + ClusterOnboardingMacName.other(named: resume.leaderName ?? resume.peerName) + } - /// macOS asks once, the first time Darkbloom's service talks over the cable. Said before it can appear. - public static let localNetworkLine = "macOS may ask once to allow Darkbloom on the local network. Allow it." + /// A step that is done, at the start of its line. + public static let done = "\u{2713}" - /// The Mac that joined ends its onboarding once paired; the last thing it says. - public static let joinedLine = "Nothing else to do on this Mac: the other Mac chooses the model and starts this Mac's part." + /// What macOS asks, and where to answer it, for the program it names. `remote` (over SSH): the prompt is on this + /// Mac's own screen, not in this terminal. + public static func localNetworkLine(_ app: String, remote: Bool = false) -> String { + "macOS asks\(onScreen(remote)) to let \(app) find devices on your local network: click Allow." + } + + /// The same where the probe could not tell whether macOS will ask (nothing to wait for). + public static func localNetworkMaybeLine(_ app: String, remote: Bool = false) -> String { + "If macOS asks\(onScreen(remote)) to let \(app) find devices on your local network, click Allow." + } + + private static func onScreen(_ remote: Bool) -> String { + remote ? " on this Mac's own screen (use Screen Sharing if it has no display)" : "" + } + + /// Said once paired: both cluster services ask at the same moment, one on each Mac. + public static let otherMacAllowLine = "The other Mac may ask too: click Allow there as well." + + /// Connect's first line: every approval the setup asks for on this Mac, and when (2026-11-02 review: "bundle all + /// of the permissions ahead of time"). + public static func approvalsLine(remote: Bool) -> String { + remote ? "Up to two approvals on this Mac: the cable's port (now, with sudo in this terminal) and Local Network for Darkbloom (once paired, on this Mac's own screen)." + : "Up to two macOS approvals on this Mac: the cable's port (now) and Local Network for Darkbloom (once paired)." + } + + /// The Mac that joined ends its onboarding once paired; the last thing it says (the one thing to do next). + public static let joinedLine = "Continue on the other Mac: it chooses the model and starts this Mac's part." + + /// The same, for a Mac that joined when it was asked for `darkbloom cluster local`. + public static let joinedLocalContinueLine = "Continue on the other Mac with `darkbloom cluster local`: it chooses the model and starts this Mac's part." /// Said on the Mac that joined when it was asked for `darkbloom cluster local` (a model too, perhaps): nothing of it /// runs here, because the Mac that leads chooses how the cluster serves and its model. - public static let joinedLocalLine = "`darkbloom cluster local` takes effect on the Mac that leads, not on this one: " - + "run it on the other Mac to serve locally only or to name the model." + public static let joinedLocalLine = "`darkbloom cluster local` takes effect on the Mac that leads: run it on the other Mac." + + /// Whether the window may close: a login agent keeps serving; a development build's session service does not. + public static let closeWindowLine = "You can close this window." + public static let keepWindowLine = "Keep this window open: this development build serves only while it stays open." + + /// How long the setup waits for a service that was just started to report its own probe (a service that never + /// reports is an older build: nothing to wait for). A Local Network prompt itself is waited for until it is + /// answered or q: the person may be at the other Mac, answering its own. + static let serviceReportSeconds: Double = 10 + /// After this long still refused, the screen also says where the setting is (the prompt was answered before). + static let settingsHintSeconds: Double = 15 /// Runs the cable checks with each line shown as it is made (the approval line comes before the macOS prompt). static func checkLink(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> ClusterOnboardingLinkResult { @@ -834,201 +968,291 @@ public enum ClusterOnboardingDriver { } } + /// Asks macOS for Local Network access for `subject` now, while the person is at this Mac, instead of whenever the + /// first traffic happens to flow (2026-11-02: the prompts came out of sync, on the other Mac's turn). Says nothing + /// when it is allowed already; otherwise the prompt to answer, then waits for the probe to pass, for as long as the + /// person takes (they may be at the other Mac, answering its prompt) or until q. A service whose probe tells + /// nothing gets the prompt's line as an "if". False (with where to turn it on) when the person stopped waiting. + static func allowLocalNetwork(_ subject: ClusterOnboardingLocalNetworkSubject, _ operations: ClusterOnboardingOperations, + _ console: ClusterOnboardingConsole) -> Bool { + let app = subject == .service ? "Darkbloom" : operations.commandApp() + let remote = operations.remote() + var state = operations.localNetwork(subject) + if state == .unknown, subject == .service { + let deadline = Date().addingTimeInterval(serviceReportSeconds) + while state == .unknown, Date() < deadline { + console.working("Checking local network access") + usleep(250_000) + state = operations.localNetwork(subject) + } + console.settle() + } + switch state { + case .allowed: return true + case .unknown: + // This command cannot be probed before the cable has an address, and macOS lets it through by itself + // (TN3179); the service is a launchd agent, which macOS asks about. + if subject == .service { console.say(" " + localNetworkMaybeLine(app, remote: remote) + " " + otherMacAllowLine) } + return true + case .blocked: break + } + console.say(" " + localNetworkLine(app, remote: remote) + (subject == .service ? " " + otherMacAllowLine : "")) + let started = Date() + var hinted = false + while !console.closed { + if !hinted, Date().timeIntervalSince(started) >= settingsHintSeconds { + hinted = true + console.settle() + console.say(" No prompt? Turn on \(app) in System Settings → Privacy & Security → Local Network.") + } + console.working("Waiting for Allow (q cancels)") + if let key = console.key(milliseconds: 1_000), key == "q" || key == "Q" || key == "\u{1B}" { break } + state = operations.localNetwork(subject) + if state == .allowed { + console.settle() + console.say(" \(done) Local network allowed for \(app).") + return true + } + } + console.settle() + console.say(" Local network access is still off for \(app) on this Mac.") + console.say("Turn it on in System Settings → Privacy & Security → Local Network, then run `darkbloom cluster` again.") + return false + } + + /// Starts this Mac's cluster service (its login agent) unless it runs; says only what went wrong. + static func startService(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> Bool { + switch operations.ensureService() { + case .success: return true + case .failure(let failure): + for line in failure.lines { console.say(line) } + return false + } + } + /// No pairing yet: checks, then find a waiting leader or become one. static func onboard(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, request: ClusterOnboardingRequest = .init()) -> Int32 { - console.banner("Darkbloom cluster setup", "Connect / Pair / Choose / Start / Test") - console.heading("1 / 5 Connect the Macs") - console.say("Checking this Mac's Thunderbolt cable…") + console.banner(title, setupSubtitle) + console.heading("1 / 4 Connect") + console.say(" " + approvalsLine(remote: operations.remote())) var link = checkLink(operations, console) if !link.ready, link.ports.count > 1 { // Two cables (two links to the other Mac, or one to a third Mac): the person says which one to use here. - let listed = link.ports.enumerated().map { "\($0.offset + 1)) \($0.element)" }.joined(separator: " ") - var chosen: String? - while chosen == nil { - guard let typed = console.line(prompt: "\(link.ports.count == 2 ? "Two" : "\(link.ports.count)") cables found: \(listed) [enter = 1]: ") else { - console.say("The input closed: nothing was changed.") - return 1 - } - let text = typed.trimmingCharacters(in: .whitespaces) - if text.isEmpty { chosen = link.ports[0] } - else if let number = Int(text), link.ports.indices.contains(number - 1) { chosen = link.ports[number - 1] } - else if link.ports.contains(text) { chosen = text } - else { console.say("Type a number from 1 to \(link.ports.count), or press enter for 1.") } + console.say(" \(link.ports.count == 2 ? "Two" : "\(link.ports.count)") cables are connected. Which one goes to the other Mac?") + guard let index = console.choose(link.ports, selected: 0) else { + console.say("Nothing was changed.") + return 1 + } + operations.useLinkPort(link.ports[index]) + link = checkLink(operations, console) + } + if !link.ready, let script = link.manualScript, !console.closed { + // macOS could not show its approval window (an SSH session with no desktop): the same commands with sudo + // right here, instead of a script for the person to find and run by hand (2026-11-02, `link-fix.sh`). + guard setUpPortWithSudo(script, operations, console) else { + console.say("The cable's port was not set up. Run `darkbloom cluster` again, or run: sudo sh \(script)") + return 1 } - operations.useLinkPort(chosen!) - console.say("Using \(chosen!) for the cluster.") link = checkLink(operations, console) } guard link.ready else { console.say("The cable is not ready yet, so pairing waits. Run `darkbloom cluster` again when the step above is done.") return max(link.exitCode, 1) } - console.heading("2 / 5 Pair securely") + guard allowLocalNetwork(.thisCommand, operations, console) else { return 1 } + console.heading("2 / 4 Pair") let events = ClusterOnboardingMailbox() let outcome = ClusterOnboardingMailbox() Thread.detachNewThread { outcome.post(operations.pair { events.post($0) }) } var pairing = ClusterOnboardingPairing() var result: ClusterOnboardingPairResult? + func show() { for event in events.take() { for line in pairing.handle(event) { console.say(" " + line) } } } while result == nil { - for event in events.take() { for line in pairing.handle(event) { console.say(line) } } + show() if let finished = outcome.take().first { // Whatever the pairing said last comes before its result. - for event in events.take() { for line in pairing.handle(event) { console.say(line) } } + show() result = finished break } + if pairing.asking != nil { + // The code on screen: a choice, which ends by itself when the pairing does (the other Mac declined). + console.settle() + let answer = console.choose(ClusterOnboardingPairing.codeAnswers, selected: 0, abandon: { outcome.hasItems }) + if answer == nil { + if outcome.hasItems { continue } + if console.closed { console.say("The input closed: nothing was paired."); return 1 } + } + let accept = answer == 0 + // What the other Mac said while the list was up comes first: its answer decides what this one says. + show() + for line in pairing.answered(accept) { console.say(" " + line) } + operations.answerCode(accept) + continue + } + if let working = pairing.working { console.working(working) } guard let key = console.key(milliseconds: 100) else { if console.closed { console.say("The input closed: nothing was paired."); return 1 } continue } - let lower = Character(key.lowercased()) - if pairing.asking != nil, lower == "y" || lower == "n" { - for line in pairing.answered(lower == "y") { console.say(line) } - operations.answerCode(lower == "y") - } else if lower == "q" || key == "\u{1B}", pairing.asking == nil, pairing.phase != .confirmed { + if key == "q" || key == "Q" || key == "\u{1B}", pairing.phase != .confirmed { + console.settle() console.say("Cancelled: nothing was paired. Run `darkbloom cluster` again to start over.") return 130 } } - for line in pairing.finished(result!) { console.say(line) } + console.settle() + for line in pairing.finished(result!) { console.say(" " + line) } guard case .paired(let role, let peerName) = result! else { return 1 } switch role { case .member: - switch operations.ensureService() { - case .success(let line): console.say(line) - case .failure(let failure): - for line in failure.lines { console.say(line) } + guard startService(operations, console) else { console.say("Run `darkbloom cluster` here again to start it; the pairing is kept.") return 1 } - console.say(localNetworkLine) - // Nothing else is asked on the Mac that joined (step 3), `darkbloom cluster local` included: the Mac that - // leads is on its own model list by now (2026-10-25: both Macs showed the list, and the one that joined - // would have chosen through the other's). - if request.scope != nil || request.model != nil { console.say(joinedLocalLine) } - console.say(joinedLine) + guard allowLocalNetwork(.service, operations, console) else { return 1 } + // Nothing else is asked on the Mac that joined, `darkbloom cluster local` included: the Mac that leads is on + // its own model list by now (2026-10-25: both Macs showed the list). Its last line is the one thing to do + // on the other Mac, `local` included. + console.say("") + if let restart = operations.afterRestart() { console.say(restart) } + console.say("Done on this Mac. " + (operations.serviceOutlivesWindow() ? closeWindowLine : keepWindowLine)) + console.say(request.scope?.isLocalOnly == true ? joinedLocalContinueLine : joinedLine) return 0 case .leader: return leader(.init(role: .leader, peerName: peerName), operations, console, justPaired: true, request: request) } } - /// A member: `darkbloom cluster` works here too. Every command runs on the derived control leader, forwarded over - /// the link control channel, and its answer is shown here. + /// A member: its part runs by itself and the cluster is managed on the Mac that leads, so it shows the cluster as + /// it is and says where to manage it (2026-11-02: "why does the member have the choices to change model, test …"). static func member(_ resume: ClusterOnboardingResume, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, request: ClusterOnboardingRequest = .init()) -> Int32 { - // A member of a pair is led by the other Mac. + guard startService(operations, console) else { return 1 } + for line in operations.status() { console.say(" " + line) } let leader = ClusterOnboardingMacName.other(named: resume.leaderName ?? resume.peerName) - console.say("This Mac is a member of the cluster led by \(leader).") - switch operations.ensureService() { - case .success(let line): console.say(line) - case .failure(let failure): - for line in failure.lines { console.say(line) } + if let port = resume.unsetCablePort { + // The cable moved to a port that was never set up: the one thing that is this Mac's to do. + console.say("") + console.say(unsetPortLine(port)) + guard console.choose([fixPortItem, "Quit"], selected: 0) == 0 else { return 0 } + return fixPort(operations, console) + } + console.say("") + if request.scope != nil || request.model != nil { + console.say(joinedLocalLine) return 1 } - console.say("Commands typed here run on \(ClusterOnboardingMacName.other) over the cable.") - return menu(resume, operations, console, request: request) + console.say("This Mac's part runs by itself: nothing to do here.") + console.say("To test, change the model or stop: run `darkbloom cluster` on \(leader).") + return 0 } /// The leader: the model and options, the sync, the start, serving. static func leader(_ resume: ClusterOnboardingResume, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, justPaired: Bool, request: ClusterOnboardingRequest = .init()) -> Int32 { - switch operations.ensureService() { - case .success(let line): console.say(line) - case .failure(let failure): - for line in failure.lines { console.say(line) } - return 1 - } - if justPaired { console.say(localNetworkLine) } - // Serving, or stopped after a model was chosen: the same menu as on a member (a stopped leader is offered `v`, - // whether both Macs released their memory, as well as `m`). Only a leader that never chose a model goes - // straight to the choice. + guard startService(operations, console) else { return 1 } + if justPaired { guard allowLocalNetwork(.service, operations, console) else { return 1 } } + // Serving, or stopped after a model was chosen: the menu. Only a leader that never chose a model goes straight + // to the choice. if !justPaired, resume.serving || resume.modelName != nil { - console.say("This Mac leads the cluster.") return menu(resume, operations, console, request: request) } return chooseAndServe(operations, console, scope: request.scope ?? resume.scope, saveScope: request.scope != nil, - model: request.model) + model: request.model, privateImage: request.privateImageQualification) } - /// Status, then one key: the same on every member (a member's commands are forwarded to the leader). - /// `darkbloom cluster local` comes here asking for local-only serving: a cluster that is not serving (or asked for - /// a model by name) goes to the choice and starts that way; a serving cluster switches and serves again. + /// One thing the leader's menu does. + enum MenuItem { case fixPort, test, model, scope, stop, verify, quit } + + /// The status, then one choice from a list. `darkbloom cluster local` comes here asking for local-only serving: a + /// cluster that is not serving (or asked for a model by name) goes to the choice and starts that way; a serving + /// cluster switches and serves again. static func menu(_ resume: ClusterOnboardingResume, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, request: ClusterOnboardingRequest = .init()) -> Int32 { if let wanted = request.scope { if request.model != nil || !resume.serving { return chooseAndServe(operations, console, scope: wanted, saveScope: true, model: request.model, - leads: resume.role != .member) + privateImage: request.privateImageQualification) } if wanted != resume.scope { return changeScope(to: wanted, resume, operations, console) } } - console.heading("Cluster status") for line in operations.status() { console.say(" " + line) } - // A cable moved to a port that was never set up: the one thing to do first (2026-10-16, Thunderbolt 1). + var items = [(MenuItem, String)]() if let port = resume.unsetCablePort { - console.say("The cable is on \(port), which is not set up for the cluster, so the Macs cannot reach each other.") - console.say("Press f to set it up (macOS asks for your password once).") + // A cable moved to a port that was never set up: the one thing to do first (2026-10-16, Thunderbolt 1). + console.say(unsetPortLine(port)) + items.append((.fixPort, fixPortItem)) } - if resume.serving { - console.say("Enter Leave setup unchanged") - console.say("t Test a response m Change model s Stop serving") - } else { - console.say("Not serving. Press m to choose a model and serve; enter to leave.") - } - console.say("v Check both Macs released their memory") - // The other way to serve, one key: `l` serves locally only, `p` through Darkbloom again (kept until changed). - console.say(resume.scope.isLocalOnly ? "This cluster serves locally only (no coordinator); press p to serve through Darkbloom instead." - : "Press l to serve locally only (no coordinator).") - while true { - guard let key = console.key(milliseconds: 60_000) else { - if console.closed { return 0 } - continue + if resume.serving { items.append((.test, "Test a response")) } + items.append((.model, resume.serving ? "Change model" : "Choose a model and serve")) + items.append((.scope, resume.scope.isLocalOnly ? "Serve through Darkbloom" : "Serve locally only (no coordinator)")) + if resume.serving { items.append((.stop, "Stop serving")) } + items.append((.verify, "Check both Macs released their memory")) + items.append((.quit, "Quit")) + console.say("") + guard let index = console.choose(items.map(\.1), selected: 0) else { return 0 } + switch items[index].0 { + case .quit: return 0 + case .test: return test(operations, console) ? 0 : 1 + case .model: return chooseAndServe(operations, console, scope: resume.scope, privateImage: request.privateImageQualification) + case .scope: + return changeScope(to: resume.scope.isLocalOnly ? .publicServing : .localOnly(bind: ClusterServingScope.localOnlyDefaultBind), + resume, operations, console) + case .stop: + switch busy(console, "Stopping both Macs", operations.stop) { + case .success(let lines): + for line in lines { console.say(line) } + return 0 + case .failure(let failure): + for line in failure.lines { console.say(line) } + return 1 } - switch key { - case "\r", "\n", "q", "Q": return 0 - case "l" where !resume.scope.isLocalOnly, "L" where !resume.scope.isLocalOnly: - return changeScope(to: .localOnly(bind: ClusterServingScope.localOnlyDefaultBind), resume, operations, console) - case "p" where resume.scope.isLocalOnly, "P" where resume.scope.isLocalOnly: - return changeScope(to: .publicServing, resume, operations, console) - case "t" where resume.serving, "T" where resume.serving: return test(operations, console) ? 0 : 1 - case "s" where resume.serving, "S" where resume.serving: - switch operations.stop() { - case .success(let lines): - for line in lines { console.say(line) } - return 0 - case .failure(let failure): - for line in failure.lines { console.say(line) } - return 1 - } - case "v", "V": - switch operations.verifyTeardown() { - case .success(let lines): - for line in lines { console.say(" " + line) } - return 0 - case .failure(let failure): - for line in failure.lines { console.say(line) } - return 1 - } - case "m", "M": return chooseAndServe(operations, console, scope: resume.scope, leads: resume.role != .member) - case "f" where resume.unsetCablePort != nil, "F" where resume.unsetCablePort != nil: - let result = checkLink(operations, console) - console.say(result.ready ? "The cable's port is set up; the cluster re-forms by itself in a moment." - : "The port is not set up yet; run `darkbloom cluster` again to try once more.") - return result.ready ? 0 : 1 - default: continue + case .verify: + switch busy(console, "Asking both Macs", operations.verifyTeardown) { + case .success(let lines): + for line in lines { console.say(" " + line) } + return 0 + case .failure(let failure): + for line in failure.lines { console.say(line) } + return 1 } + case .fixPort: return fixPort(operations, console) } } + /// The cable moved to a port that was never set up, and the one item that sets it up. + static func unsetPortLine(_ port: String) -> String { + "The cable is on \(port), which is not set up for the cluster, so the Macs cannot reach each other." + } + static let fixPortItem = "Set up the cable's port (macOS asks for your password)" + + /// Sets up the port the cable moved to (macOS asks once), and says how it went. + static func fixPort(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> Int32 { + var result = checkLink(operations, console) + if !result.ready, let script = result.manualScript, !console.closed, setUpPortWithSudo(script, operations, console) { + result = checkLink(operations, console) + } + console.say(result.ready ? "The cable's port is set up; the cluster re-forms by itself in a moment." + : "The port is not set up yet; run `darkbloom cluster` again to try once more.") + return result.ready ? 0 : 1 + } + + /// Where macOS could not show its approval window: the port's setup `script` runs with sudo in this terminal, the + /// person typing this Mac's password into sudo. True when it exited 0. + static func setUpPortWithSudo(_ script: String, _ operations: ClusterOnboardingOperations, + _ console: ClusterOnboardingConsole) -> Bool { + console.say(" macOS could not show its password window here. Type this Mac's password for sudo to set up the cable's port:") + return console.suspended { operations.runAsAdministrator(script) } + } + /// Saves the other way to serve on the control leader. A serving cluster starts its leading part again that way /// (the setup and the model stay), so the screen waits for it as it does after a start. static func changeScope(to wanted: ClusterServingScope, _ resume: ClusterOnboardingResume, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> Int32 { - console.say(wanted.isLocalOnly ? "Serving locally only from now on (no coordinator)…" : "Serving through Darkbloom from now on…") - switch operations.setScope(wanted) { - case .success(let lines): for line in lines { console.say(" " + line) } + switch busy(console, wanted.isLocalOnly ? "Switching to local only" : "Switching to serving through Darkbloom", { operations.setScope(wanted) }) { + case .success: break case .failure(let failure): for line in failure.lines { console.say(" " + line) } console.say("Nothing was changed.") @@ -1036,109 +1260,105 @@ public enum ClusterOnboardingDriver { } console.say(wanted.line + ".") guard resume.serving else { - console.say("Not serving now: the next start serves this way. Press m in `darkbloom cluster` to choose a model.") + console.say("Not serving now: the next start serves this way.") return 0 } return awaitReady(title: resume.modelName ?? "the model", operations, console) != nil ? 0 : 1 } - /// How long the start waits for n after the model is chosen (the choice is the start). - static let startSeconds = 3 - /// Each reason once, where it first appears. static func reasonsInOrder(_ reasons: [String]) -> [String] { var seen = Set() return reasons.filter { seen.insert($0).inserted } } - /// The choice, then the start. `scope` is how it will serve (what the screen says); `saveScope` saves it on the - /// control leader first (`darkbloom cluster local`); `model` names the choice so the list is not asked. `leads`: - /// this Mac leads; on a member every step runs on the other Mac, which sends this Mac its setup. + /// Both Macs in one line: "This Mac: Apple M5 Ultra, 256 GB · the other Mac: Apple M3 Ultra, 256 GB". + static func machinesLine(_ machines: [ClusterOnboardingMachine]) -> String { + let pair = machines.count == 2 + return ClusterOnboardingMacName.sentence(machines.map { machine in + "\(machine.here ? ClusterOnboardingMacName.this : pair ? ClusterOnboardingMacName.other : "a member"): \(machine.name)" + }.joined(separator: " · ")) + } + + /// The choice, then the start. `scope` is how it will serve; `saveScope` saves it on the control leader first + /// (`darkbloom cluster local`); `model` names the choice so the list is not asked; `privateImage`: a private image + /// candidate, which never takes public traffic. static func chooseAndServe(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, scope: ClusterServingScope = .publicServing, saveScope: Bool = false, model: String? = nil, - leads: Bool = true) -> Int32 { - console.heading("3 / 5 Choose a model") - console.say("Reading both Macs over the cable…") - let notes = ClusterOnboardingMailbox() - let reached = busy(console, "Reading both Macs") { operations.reachMembers { notes.post($0) } } - for line in notes.take() { console.say(" " + line) } - let machines: [ClusterOnboardingMachine] - switch reached { - case .success(let value): machines = value - case .failure(let failure): - for line in failure.lines { console.say(line) } - console.say("Run `darkbloom cluster` here again once the other Mac is on; nothing was changed.") - return 1 + privateImage: Bool = false) -> Int32 { + console.heading("3 / 4 Choose a model") + var reached: [ClusterOnboardingMachine]? + while reached == nil { + switch busy(console, "Reading both Macs over the cable", operations.reachMembers) { + case .success(let value): reached = value + case .failure(let failure): + for line in failure.lines { console.say(line) } + // Once paired, the other Mac's service may still wait for its Allow (both Macs ask at the same moment). + guard console.choose(["Try again", "Stop here"], selected: 0) == 0 else { + console.say("Run `darkbloom cluster` here again once the other Mac is on; nothing was changed.") + return 1 + } + } } - console.say("The cluster:") - for machine in machines { console.say(machine.line(inPair: machines.count == 2)) } - console.say("") - console.say("Working out the fastest way to split each model across both Macs…") + let machines = reached! + console.say(" " + machinesLine(machines)) if let notice = operations.developerNotice() { console.say(notice) } let choices: [ClusterOnboardingModelChoice] - switch busy(console, "Planning on both Macs' memory", operations.planModels) { + switch busy(console, "Planning each model for both Macs", operations.planModels) { case .success(let value): choices = value case .failure(let failure): for line in failure.lines { console.say(line) } return 1 } - // The choices that fit now come first, so enter (= 1) is one that fits. - let offered = choices.indices.filter { choices[$0].blocker == nil } - let open = offered.filter { choices[$0].fitRemedy == nil } + offered.filter { choices[$0].fitRemedy != nil } - // One line per model (owner, 2026-10-15: shorter screens), ending with a few words when the model has tensor - // parallel and the planner split it otherwise (why not); a second only when it does not fit now. What moves - // and the planner's full reasons are said once a model is chosen. - let titles = choices.map(\.title) - for (number, index) in open.enumerated() { - let shared = titles.filter { $0 == choices[index].title }.count > 1 - console.say(" \(number + 1). " + choices[index].listLine(sameTitleElsewhere: shared)) - if let remedy = choices[index].fitRemedy { console.say(" does not fit now: " + remedy) } - } - let blocked = choices.indices.filter { choices[$0].blocker != nil } - if !blocked.isEmpty { - console.say(" Not offered:") - // One line per reason, the models it holds back named before it, in the order the planner listed them. - for reason in Self.reasonsInOrder(blocked.compactMap { choices[$0].blocker }) { - let titles = blocked.filter { choices[$0].blocker == reason }.map { choices[$0].title } - console.say(" \(titles.joined(separator: ", ")): \(reason)") - } - } + // Only models the owner approved for clusters that these Macs can serve, those that fit now first, so enter + // picks one that fits (2026-11-02: the list showed the whole catalog). + let listed = choices.indices.filter { choices[$0].listed } + let open = listed.filter { choices[$0].fitRemedy == nil } + listed.filter { choices[$0].fitRemedy != nil } guard !open.isEmpty else { - console.say("No model can be served by these Macs now; the reasons are above.") + console.say("No model approved for clusters can run on these two Macs now.") + // One line per reason, the approved models it holds back named before it. + let held = choices.indices.filter { choices[$0].validated != false && choices[$0].blocker != nil } + for reason in reasonsInOrder(held.compactMap { choices[$0].blocker }) { + let titles = held.filter { choices[$0].blocker == reason }.map { choices[$0].title } + console.say(" \(titles.joined(separator: ", ")): \(reason)") + } return 1 } var chosen: Int? if let model { - // Named on the command line: matched to a model id or title, without the list's question. + // Named on the command line: matched to a model id or title, without the list. let named = { (index: Int) in [choices[index].modelID, choices[index].title].contains { $0?.caseInsensitiveCompare(model) == .orderedSame } } if let index = open.first(where: named) { chosen = index - console.say("Chosen: \(choices[index].title).") - } else if let index = blocked.first(where: named) { - console.say("\(choices[index].title) is not offered on these Macs: \(choices[index].blocker!)") + } else if let index = choices.indices.first(where: named) { + console.say(choices[index].validated == false ? "\(choices[index].title) is not approved for clusters yet." + : "\(choices[index].title) is not offered on these Macs: \(choices[index].blocker ?? "it cannot be served here").") return 1 } else { - console.say("No model on the list is named \(model); choose one by its number.") + console.say("No model on the list is named \(model).") } } if chosen == nil { - console.say("") - console.say("Enter selects \(choices[open[0]].title). Choose another model by number.") - } - while chosen == nil { - guard let typed = console.line(prompt: "Choose a model [1-\(open.count), enter = 1]: ") else { return 1 } - let text = typed.trimmingCharacters(in: .whitespaces) - if text.isEmpty { chosen = open[0]; break } - if let number = Int(text), (1...open.count).contains(number) { chosen = open[number - 1]; break } - console.say("Type a number from 1 to \(open.count), or press enter for 1.") + let titles = choices.map(\.title) + let lines = open.map { index -> String in + let shared = titles.filter { $0 == choices[index].title }.count > 1 + let line = choices[index].listLine(sameTitleElsewhere: shared) + return choices[index].fitRemedy == nil ? line : line + " · does not fit now" + } + guard let picked = console.choose(lines, selected: 0) else { + console.say("Nothing was changed. Run `darkbloom cluster` again to choose.") + return 0 + } + chosen = open[picked] } var choice = choices[chosen!] - // The chosen model's other lines: the planner's reason, and whether public traffic may reach it (not when the - // cluster serves locally only). - for line in choice.lines.dropFirst() { console.say(" " + line) } - if !scope.isLocalOnly, let line = choice.publicTraffic { console.say(" " + line) } + // Whether public traffic may reach it, said at the choice (not when the cluster serves locally only): whether + // the pair can earn with it, and that a private image candidate never takes public traffic. + if !scope.isLocalOnly, let line = choice.publicTraffic { + console.say(" " + ClusterOnboardingMacName.sentence(line) + (line.hasSuffix(".") ? "" : ".")) + } if let offer = choice.provision { switch provision(offer, title: choice.title, index: chosen!, operations, console) { case .stopped: return 0 @@ -1146,8 +1366,7 @@ public enum ClusterOnboardingDriver { case .done: // A model this Mac downloaded is planned from its own files now. if offer.leaderDownloads { - console.say("Planning \(choice.title) now that it is on this Mac…") - guard case .success(let again) = operations.planModels(), + guard case .success(let again) = busy(console, "Planning \(choice.title)", operations.planModels), let index = again.firstIndex(where: { ($0.modelID ?? $0.title) == (choice.modelID ?? choice.title) }) else { console.say("\(choice.title) could not be planned after the download. Run `darkbloom cluster` here again.") return 1 @@ -1158,7 +1377,6 @@ public enum ClusterOnboardingDriver { } choice = again[index] chosen = index - for line in choice.lines { console.say(" " + line) } if let more = choice.provision { switch provision(more, title: choice.title, index: index, operations, console) { case .stopped: return 0 @@ -1169,37 +1387,16 @@ public enum ClusterOnboardingDriver { } } } - console.heading("4 / 5 Start the model") - console.say(scope.isLocalOnly - ? "Options: always on (each Mac starts its part again by itself); \(scope.line.prefix(1).lowercased() + scope.line.dropFirst())." - : "Options: always on (each Mac starts its part again by itself); serves your own requests through Darkbloom, " - + "and public requests where Darkbloom has qualified this model and split.") - // The choice is the start: a moment to stop it, no second question. - console.say("Starting \(choice.title) on both Macs in \(startSeconds) s; press n to stop here.") - let deadline = Date().addingTimeInterval(Double(startSeconds)) - wait: while Date() < deadline { - guard let key = console.key(milliseconds: max(1, Int(deadline.timeIntervalSinceNow * 1000))) else { - if console.closed { break wait } - continue - } - switch key { - case "\r", "\n", "y", "Y": break wait - case "n", "N", "q", "Q": - console.say("Nothing was changed. Run `darkbloom cluster` here again to choose.") - return 0 - default: continue - } - } + console.heading("4 / 4 Start") // Memory moves while the person reads: the fit is checked again right before anything starts. if let remedy = operations.recheckFit(chosen!) { console.say("\(choice.title) does not fit in the Macs' free memory now: \(remedy)") console.say("Nothing was changed. Run `darkbloom cluster` here again after that.") return 1 } - console.say(leads ? "Saving the setup and sending it to the other Mac over the cable…" - : "Saving the setup on the other Mac, which sends it to this Mac over the cable…") - switch operations.adopt(chosen!) { - case .success(let lines): for line in lines { console.say(" " + line) } + let index = chosen! + switch busy(console, "Sending the setup to the other Mac", { operations.adopt(index) }) { + case .success: break case .failure(let failure): for line in failure.lines { console.say(" " + line) } return 1 @@ -1207,33 +1404,45 @@ public enum ClusterOnboardingDriver { // After the adopt (which stopped a running model first), so the scope never restarts the old model. if saveScope { switch operations.setScope(scope) { - case .success(let lines): for line in lines { console.say(" " + line) } + case .success: break case .failure(let failure): for line in failure.lines { console.say(" " + line) } return 1 } } - switch operations.serve() { - case .success(let lines): for line in lines { console.say(" " + line) } + switch busy(console, "Starting both Macs", operations.serve) { + case .success: break case .failure(let failure): for line in failure.lines { console.say(" " + line) } return 1 } - console.say("Starting both Macs' parts and loading the model…") + console.say(" \(done) Setup sent to the other Mac.") guard let ready = awaitReady(title: choice.title, operations, console) else { return 1 } // A pair offered for pairing has no local API to test: its requests come through Darkbloom. if ready.offered != nil { console.say(ClusterOnboardingReady.offeredTestLine) } - let tested = ready.offered != nil || test(operations, console, setup: true) + let tested = ready.offered != nil || test(operations, console) if tested, ready.offered == nil, !scope.isLocalOnly { register(title: choice.title, operations, console) } console.say("") - if tested { - console.say("Done. Run `darkbloom cluster` on any of these Macs to see it, change the model or stop it.") - } else { + guard tested else { console.say("Setup saved, but the test request failed.") - console.say("Run `darkbloom cluster` to check status and retry the test with t.") + console.say("Run `darkbloom cluster` to see the status and test again.") + return 1 } - console.say("Nothing else is needed on the other Mac." + (operations.afterRestart().map { " " + $0 } ?? "")) - return tested ? 0 : 1 + if !privateImage, let line = servesLine(scope: scope, ready: ready) { console.say(line) } + if let restart = operations.afterRestart() { console.say(restart) } + console.say("Done. " + (operations.serviceOutlivesWindow() ? "You can close this window here and on the other Mac." + : "Keep this window and the other Mac's open: this development build serves only while they stay open.")) + console.say("To test, change the model or stop: run `darkbloom cluster` on this Mac.") + return 0 + } + + /// The setup's word on how the pair serves, where nothing above said it: serving locally (local only, or a + /// coordinator without cluster support) already has its notice under the API line. + public static let earnsLine = "Serving through Darkbloom: the pair earns for the public requests it serves." + static func servesLine(scope: ClusterServingScope, ready: ClusterOnboardingReady) -> String? { + guard !scope.isLocalOnly else { return nil } + if let notice = ready.notice, !notice.hasPrefix(ClusterOnboardingReady.registeredNotice) { return nil } + return earnsLine } /// After the Test stage: registers the pair with the coordinator when it serves a cluster approval for this pair, @@ -1260,17 +1469,18 @@ public enum ClusterOnboardingDriver { let finished = ClusterOnboardingMailbox>() Thread.detachNewThread { finished.post(operations.waitReady { progress.post($0) }) } var ready: Result? + // The parts' progress ("1 of 2 parts ready") is the live line only: the screen keeps the result. + var latest: String? while ready == nil { - for line in progress.take() { console.say(" " + line) } + if let line = progress.take().last { latest = line } if let value = finished.take().first { ready = value; break } - console.working("Loading \(title) on both Macs") + console.working("Loading \(title) on both Macs" + (latest.map { " (\($0))" } ?? "")) _ = console.key(milliseconds: 120) } console.settle() - for line in progress.take() { console.say(" " + line) } switch ready! { case .success(let where_): - for line in where_.lines(model: title) { console.say(line + ".") } + for line in where_.lines(model: title) { console.say(" " + line + ".") } return where_ case .failure(let failure): for line in failure.lines { console.say(line) } @@ -1280,84 +1490,37 @@ public enum ClusterOnboardingDriver { } } - /// One key to save a diagnostics file (redacted) after a start that did not finish. + /// One choice to save a diagnostics file (redacted) after a start that did not finish. static func offerDiagnostics(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) { - console.say("Press d to save a diagnostics file to send to Darkbloom, enter to leave.") - while true { - guard let key = console.key(milliseconds: 60_000) else { - if console.closed { return } - continue - } - switch key { - case "d", "D": - switch operations.saveDiagnostics() { - case .success(let lines): for line in lines { console.say(" " + line) } - case .failure(let failure): for line in failure.lines { console.say(" " + line) } - } - return - case "\r", "\n", "q", "Q", "n", "N": return - default: continue - } + guard console.choose(["Save a diagnostics file to send to Darkbloom", "Leave"], selected: 0) == 0 else { return } + switch operations.saveDiagnostics() { + case .success(let lines): for line in lines { console.say(" " + line) } + case .failure(let failure): for line in failure.lines { console.say(" " + line) } } } enum ProvisionOutcome { case done, stopped, failed } - /// Says what has to move for the chosen model, asks once (enter = the recommended way), and moves it with progress. + /// Says what has to move for the chosen model, asks once (the recommended way first), and moves it with progress. static func provision(_ offer: ClusterOnboardingProvisionOffer, title: String, index: Int, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> ProvisionOutcome { - console.say("") - console.say(offer.leaderDownloads ? "\(title) is not on this Mac yet. No download by hand is needed:" - : "\(title) is not on every Mac yet. No download by hand is needed:") - for line in offer.lines { console.say(" " + line) } + console.say(" " + (offer.leaderDownloads ? "\(title) is not on this Mac yet:" : "\(title) is not on every Mac yet:")) + for line in offer.lines { console.say(" " + line) } if let blocker = offer.blocker { console.say("It cannot start: \(blocker). Free some space and run `darkbloom cluster` here again.") return .failed } - var download = false - if let seconds = offer.quickSeconds { - // A short copy is not asked for: said, with a moment to stop it (or take the catalog instead). - let alternative = offer.downloadAlternative ? ", d to download it from Darkbloom's catalog instead" : "" - console.say("Copying it over the Thunderbolt cable now (\(Self.duration(seconds)) at the speed measured on these Macs); press n in the next 3 s to stop here\(alternative).") - let deadline = Date().addingTimeInterval(3) - wait: while Date() < deadline { - guard let key = console.key(milliseconds: max(1, Int(deadline.timeIntervalSinceNow * 1000))) else { - if console.closed { return .stopped } - continue - } - switch key { - case "\r", "\n", "c", "C": break wait - case "d" where offer.downloadAlternative, "D" where offer.downloadAlternative: download = true; break wait - case "n", "N", "q", "Q": - console.say("Nothing was copied or downloaded. Run `darkbloom cluster` here again to choose.") - return .stopped - default: continue - } - } - return move(index: index, download: download, operations, console) - } - if offer.leaderDownloads { - console.say("Press enter to get it, n to stop here.") - } else if offer.downloadAlternative { - console.say("Press enter to copy it over the Thunderbolt cable (recommended), d to download it from Darkbloom's catalog instead, n to stop here.") - } else { - console.say("Press enter to copy it over the Thunderbolt cable, n to stop here.") + // Every copy is a choice from the list, the copy first so enter takes it; a short one says how long it takes + // (2026-11-02 review: no key to press to do something, the same list as the rest of Darkbloom). + let get = offer.leaderDownloads ? "Get it (download, then copy over the cable)" + : offer.quickSeconds.map { "Copy it over the Thunderbolt cable (\(Self.duration($0)))" } + ?? (offer.downloadAlternative ? "Copy it over the Thunderbolt cable (recommended)" : "Copy it over the Thunderbolt cable") + let options = [get] + (offer.downloadAlternative ? ["Download it from Darkbloom's catalog instead"] : []) + ["Stop here"] + guard let answer = console.choose(options, selected: 0), answer != options.count - 1 else { + console.say("Nothing was copied or downloaded. Run `darkbloom cluster` here again to choose.") + return .stopped } - answer: while true { - guard let key = console.key(milliseconds: 60_000) else { - if console.closed { return .stopped } - continue - } - switch key { - case "\r", "\n", "c", "C": break answer - case "d" where offer.downloadAlternative, "D" where offer.downloadAlternative: download = true; break answer - case "n", "N", "q", "Q": - console.say("Nothing was copied or downloaded. Run `darkbloom cluster` here again to choose.") - return .stopped - default: continue - } - } - return move(index: index, download: download, operations, console) + return move(index: index, download: offer.downloadAlternative && answer == 1, operations, console) } /// "about 3 s", "about 2 min" (as `ClusterModelProvisioning.duration`, which this file does not link). @@ -1420,12 +1583,12 @@ public enum ClusterOnboardingDriver { } } - static func test(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, setup: Bool = false) -> Bool { - console.heading(setup ? "5 / 5 Test a response" : "Test a response") - console.say("Sending one test request…") - switch busy(console, "Waiting for the first tokens", operations.testRequest) { + /// One test request; its answer on one line ("✓ Test response: …"), or what went wrong. + static func test(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> Bool { + switch busy(console, "Sending a test request", operations.testRequest) { case .success(let lines): - for line in lines { console.say(" " + line) } + console.say(" \(done) Test response: " + (lines.first ?? "answered")) + for line in lines.dropFirst() { console.say(" " + line) } return true case .failure(let failure): for line in failure.lines { console.say(" " + line) } @@ -1442,6 +1605,9 @@ final class ClusterOnboardingMailbox: @unchecked Sendable { func post(_ value: Value) { lock.lock(); items.append(value); lock.unlock() } + /// Something was posted and not taken yet. + var hasItems: Bool { lock.lock(); defer { lock.unlock() }; return !items.isEmpty } + func take() -> [Value] { lock.lock() defer { items.removeAll(); lock.unlock() } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift index d865e3ae9c..f4b3a4b473 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift @@ -33,7 +33,7 @@ extension ClusterOnboardingOperations { pair: { events in live.pair(events) }, answerCode: { live.answer($0) }, ensureService: { live.ensureService() }, - reachMembers: { say in live.reachMembers(say) }, + reachMembers: { live.reachMembers() }, planModels: { live.planModels() }, adopt: { live.adopt($0) }, serve: { live.serve() }, @@ -49,7 +49,14 @@ extension ClusterOnboardingOperations { saveDiagnostics: { live.saveDiagnostics() }, developerNotice: { ClusterForcedModeSetting.notice(environment: ProcessInfo.processInfo.environment) }, setScope: { live.setScope($0) }, - register: { live.register() }) + register: { live.register() }, + localNetwork: { subject in + subject == .service ? ClusterLocalNetworkAccess.serviceState() : ClusterLocalNetworkAccess.probe() + }, + commandApp: { ClusterLocalNetworkAccess.commandApp() }, + runAsAdministrator: { ClusterLocalNetworkAccess.runLinkScriptWithSudo($0, paths: paths) }, + serviceOutlivesWindow: { live.serviceOutlivesWindow() }, + remote: { ClusterLocalNetworkAccess.overSSH() }) } } @@ -307,6 +314,8 @@ final class OnboardingLive: @unchecked Sendable { var flow = ClusterLinkSetupFlow(mayPrompt: true, device: device, plain: true) var step = flow.begin() let started = Date() + // Where macOS could not show its prompt: the script of the same commands, which the onboarding runs with sudo. + var manualScript: String? while true { for line in step.lines { say(line) } switch step.action { @@ -328,17 +337,19 @@ final class OnboardingLive: @unchecked Sendable { last = report step = flow.observed(report) case .fix(let device): - // The one macOS approval; where no prompt can show, one owner-only script and one line to run. - say("Darkbloom needs network access for the cluster cable: approve the macOS prompt (once per Mac).") - let result = ClusterLinkRepair.fix(device: device, mode: .durable, dryRun: false) - if let script = result.manualScript { - say("No macOS prompt can show here. Run this one line once, as an administrator, then run `darkbloom cluster` again:") - say(" sudo sh \(script)") + // The one macOS approval; where no prompt can show (an SSH session has no window to show it in), one + // owner-only script, which the onboarding runs with sudo in this terminal (the person never has to + // find it, so the link flow's line telling them to run it by hand is not shown). + if !ClusterLocalNetworkAccess.overSSH() { + say("macOS asks for your password to set up the cable's port: approve it (once per Mac).") } + let result = ClusterLinkRepair.fix(device: device, mode: .durable, dryRun: false) + manualScript = result.manualScript step = flow.repaired(result) + if manualScript != nil { step = .init(lines: step.lines.filter { $0 != result.message }, action: step.action) } case .finish(let code): if !flow.choices.isEmpty { return .init(ready: false, exitCode: max(code, 1), ports: flow.choices.map { $0.interface }) } - guard code == 0, flow.linkState == .ready else { return .init(ready: false, exitCode: max(code, 1)) } + guard code == 0, flow.linkState == .ready else { return .init(ready: false, exitCode: max(code, 1), manualScript: manualScript) } // A port isolated as link setup v2 leaves it but with no record (an administrator ran the commands // by hand): recorded now, with no prompt and no change, so the earlier settings can be restored. if let ready = last?.devices.first(where: { $0.portActive && $0.verdict == .ready && (device == nil || $0.device == device) }), @@ -383,7 +394,8 @@ final class OnboardingLive: @unchecked Sendable { case .dialing: events(.joining) case .connected: events(.connected) case .refused(let reason): events(.note("The cable connection was refused (\(reason)); still trying…")) - case .storing: events(.note("Pinning each other's Secure Enclave keys (owner-only files)…")) + // Saving each other's keys takes a moment and needs nothing from the person: no line for it. + case .storing: break } }, askConfirmation: { [self] code, peer, respond in let early: Bool? = lock.withLock { @@ -462,10 +474,16 @@ final class OnboardingLive: @unchecked Sendable { lock.withLock { serviceAtLogin } == true ? restartLine() : nil } + /// The service started in this run is a login agent (it keeps serving once the window closes), not a development + /// build's session service. + func serviceOutlivesWindow() -> Bool { + lock.withLock { serviceAtLogin } != false + } + /// Installs this Mac's cluster service as its login agent (it starts at login, and its supervisor restarts it - /// with backoff), idempotently, and says what happens after a restart. Where launchd cannot take the job, the - /// service still starts for this session, and the screen says it will not come back by itself. - func ensureService() -> Result { + /// with backoff), idempotently. Where launchd cannot take the job, the service still starts for this session, and + /// the screen says to keep the window open (`serviceOutlivesWindow`). + func ensureService() -> Result { let executable = settings.service.wizard.darkbloomExecutable let arguments = settings.serviceArguments let options = Array(arguments.starts(with: ["cluster", "service"]) ? arguments.dropFirst(2) : arguments[...]) @@ -478,33 +496,23 @@ final class OnboardingLive: @unchecked Sendable { reason: refusal + "; install the signed Darkbloom release for a service that starts at login") } do { - let outcome = try ClusterService.installAtLogin(executable: executable, serviceOptions: options) + _ = try ClusterService.installAtLogin(executable: executable, serviceOptions: options) lock.withLock { serviceAtLogin = true } - switch outcome { - case .installed, .replaced: - return .success("Started this Mac's cluster service: it runs this Mac's part whenever the cluster serves. " + restartLine()) - case .restarted: - return .success("Restarted this Mac's cluster service. " + restartLine()) - case .unchanged: - return .success("This Mac's cluster service is running. " + restartLine()) - } + return .success(()) } catch let agentError { lock.withLock { serviceAtLogin = false } return sessionService(executable: executable, arguments: arguments, reason: Self.reason(agentError)) } } - /// The service for this session only (no login agent). The screen says what to do after a restart; why it cannot + /// The service for this session only (no login agent): the screen says to keep the window open; why it cannot /// start at login (`reason`, e.g. an ad-hoc signed build) goes to the service log, not the screen. - private func sessionService(executable: URL, arguments: [String], reason: String) -> Result { + private func sessionService(executable: URL, arguments: [String], reason: String) -> Result { do { let started = try ClusterService.ensureRunning(executable: executable, arguments: arguments) // Once per service start, not on every `darkbloom cluster`. if started { Self.logLoginAgentReason(reason) } - return .success((started ? "Started this Mac's cluster service" : "This Mac's cluster service is running") - + " for this development session; it is not installed at login. " - + "Keep the originating Terminal or SSH session open: a detached service can lose Local Network access " - + "when that session closes. Use a signed Darkbloom.app for reliable background serving.") + return .success(()) } catch let failure as ClusterOnboardingFailure { return .failure(failure) } catch { @@ -536,11 +544,9 @@ final class OnboardingLive: @unchecked Sendable { // MARK: - The leader - func reachMembers(_ say: @escaping @Sendable (String) -> Void) -> Result<[ClusterOnboardingMachine], ClusterOnboardingFailure> { + func reachMembers() -> Result<[ClusterOnboardingMachine], ClusterOnboardingFailure> { let local = (try? ClusterSetupLinkExchange.pairing())?.localMemberID - return routed(.init(op: .reachMembers), seconds: 150, acting: true, - forwarding: { say("Asking the control leader, \(ClusterOnboardingMacName.other(named: self.leaderName)), over the cable…") }, - local: { localReachMembers(say) }) { reply in + return routed(.init(op: .reachMembers), seconds: 150, acting: true, local: { localReachMembers { _ in } }) { reply in (reply.machines ?? []).map { machine in var machine = machine machine.here = machine.memberID != nil && machine.memberID == local @@ -654,7 +660,8 @@ final class OnboardingLive: @unchecked Sendable { ? namesByArtifact[option.model.artifactSHA256].map { [modelID: $0] } ?? [:] : names) guard let plan = option.plan else { keys.append((option.model.folder, "", modelID, [], nil, nil)) - return .init(title: title, lines: [], blocker: option.blocker ?? "Not offered on these Macs.", modelID: modelID) + return .init(title: title, lines: [], blocker: option.blocker ?? "Not offered on these Macs.", modelID: modelID, + validated: approved(option.model.artifactSHA256)) } let offer = option.onOtherMac != false ? nil : copyOffer(model: option.model, peer: peer) // One line: size, how it is split (the planner's choice), each Mac's share, the expected speed. @@ -674,7 +681,7 @@ final class OnboardingLive: @unchecked Sendable { blocker: option.blocker, provision: offer, fitRemedy: remedy, modelID: modelID, publicTraffic: context.settings.privateImageQualification ? "Private unqualified image candidate; public traffic is prohibited." : plan.publicTraffic, - tensorParallelNote: plan.tensorParallelNote) + tensorParallelNote: plan.tensorParallelNote, validated: approved(option.model.artifactSHA256)) } // Open choices first (the models this Mac has), then catalog models no Mac has yet, then the blocked ones. typealias Listed = (choice: ClusterOnboardingModelChoice, key: ChoiceKey, artifact: ListedArtifact?) @@ -699,13 +706,16 @@ final class OnboardingLive: @unchecked Sendable { ordered.append((.init(title: ClusterOnboardingDeployment.title(modelID: model.modelID, displayNames: names), lines: ["\(ClusterModelProvisioning.gigabytes(model.totalBytes)) · only on \(thereShort): copied over the cable first"], blocker: nil, provision: .init(lines: ClusterModelProvisioning.lines(plan), downloadAlternative: false, leaderDownloads: true, blocker: plan.blocker, - quickSeconds: ClusterModelProvisioning.quickCopySeconds(plan)), modelID: model.modelID), + quickSeconds: ClusterModelProvisioning.quickCopySeconds(plan)), modelID: model.modelID, + validated: approved(model.artifactSHA256)), (model.folder, "", model.modelID, [], nil, nil), ListedArtifact(model))) } for model in catalogModels(catalogAll, peer: peer) where !held.contains(model.aggregateSHA256 ?? "") && ClusterModelCopyTrust.servableArtifacts.contains(model.aggregateSHA256 ?? "") { catalog[ordered.count] = model - ordered.append((downloadChoice(model, peer: peer), ("", "", model.id, [], nil, nil), + var offer = downloadChoice(model, peer: peer) + offer.validated = approved(model.aggregateSHA256) + ordered.append((offer, ("", "", model.id, [], nil, nil), model.aggregateSHA256.map { ListedArtifact(aggregate: $0, files: nil) })) } ordered += planned.filter { $0.choice.blocker != nil } @@ -720,6 +730,16 @@ final class OnboardingLive: @unchecked Sendable { } } + /// Whether the owner approved the model for clusters (`ClusterPublicModels.declared`, by its artifact): the setup + /// lists only those. Nil, no judgement, in a private image qualification run (its candidate is never public). + func approved(_ artifactSHA256: String?) -> Bool? { + guard !context.settings.privateImageQualification else { return nil } + guard let artifactSHA256 else { return false } + return ClusterPublicModels.declared.contains { + ClusterPairServingGrants.qualifyingArtifact(for: artifactSHA256, runtimeModelID: $0.runtimeModelID) == $0.artifactSHA256 + } + } + /// An artifact as the model list compares it: the manifest's aggregate digest, and its files digest when reported. struct ListedArtifact: Sendable, Equatable { var aggregate: String diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingTerminal.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingTerminal.swift index 6067900a76..45b7aeb33d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingTerminal.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingTerminal.swift @@ -2,17 +2,20 @@ import Foundation import Darwin /// The onboarding's console on a terminal: plain lines (it scrolls like any -/// command, so what was said stays readable), single keys without enter for -/// y, n and q, and one typed line for the model number. Keys are read with -/// line editing and echo off; ^C still ends the command, and the terminal's -/// mode is put back on every way out, a signal included. +/// command, so what was said stays readable), choices from a list, and single +/// keys (q cancels). Keys are read with line editing and echo off; ^C still +/// ends the command, and the terminal's mode is put back on every way out, a +/// signal included. /// -/// With colour on a UTF-8 terminal at least 40 columns wide, headings carry a -/// step meter and long work shows a one-row live line that the next said line -/// replaces; where the mark and its text fit on one row each, the setup opens -/// with the Darkbloom mark. The mark blooms and the live -/// line turns unless DARKBLOOM_NO_ANIMATION or CI is set. Without colour -/// (NO_COLOR, TERM=dumb, a pipe) every byte is the plain transcript. +/// With colour on a terminal, a choice is a list the person moves through with +/// ↑ and ↓ and takes with enter, as `darkbloom start` picks models; once taken +/// it folds to the one chosen line. With colour on a UTF-8 terminal at least +/// 40 columns wide, headings carry a step meter and long work shows a one-row +/// live line that the next said line replaces; where the mark and its text fit +/// on one row each, the setup opens with the Darkbloom mark. The mark blooms +/// and the live line turns unless DARKBLOOM_NO_ANIMATION or CI is set. Without +/// colour (NO_COLOR, TERM=dumb, a pipe) every byte is the plain transcript: a +/// choice is its numbered lines and one key (a number, enter, or a letter). public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { private let input: Int32 private let output: Int32 @@ -29,12 +32,16 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { private var drawnFrame = -1 private let echoesInput: Bool private var saved = termios() + /// The mode keys are read in (no line editing, no echo), put back after `suspended`. + private var reading = termios() private var configured = false public private(set) var closed = false /// The mode to put back from a signal handler (one terminal per process). nonisolated(unsafe) private static var restoreInput: Int32 = -1 nonisolated(unsafe) private static var restoreMode = termios() + /// A list is up with the cursor hidden: a signal shows it again before the command ends. + nonisolated(unsafe) private static var cursorHidden = false public init(input: Int32, output: Int32, environment: [String: String] = ProcessInfo.processInfo.environment) { self.input = input; self.output = output @@ -55,6 +62,7 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { $0.withMemoryRebound(to: cc_t.self, capacity: Int(NCCS)) { $0[Int(VMIN)] = 1; $0[Int(VTIME)] = 0 } } guard tcsetattr(input, TCSANOW, &mode) == 0 else { return } + reading = mode configured = true Self.restoreInput = input Self.restoreMode = saved @@ -62,6 +70,10 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { signal(number) { received in var mode = ClusterOnboardingTerminal.restoreMode if ClusterOnboardingTerminal.restoreInput >= 0 { _ = tcsetattr(ClusterOnboardingTerminal.restoreInput, TCSANOW, &mode) } + if ClusterOnboardingTerminal.cursorHidden { + let show = Array("\u{1B}[?25h".utf8) + _ = show.withUnsafeBytes { Darwin.write(STDOUT_FILENO, $0.baseAddress, $0.count) } + } let text = Array("\r\nStopped. Run `darkbloom cluster` again to continue where it was.\r\n".utf8) _ = text.withUnsafeBytes { Darwin.write(STDOUT_FILENO, $0.baseAddress, $0.count) } Darwin._exit(128 + received) @@ -173,19 +185,27 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { } public func key(milliseconds: Int) -> Character? { + guard let byte = rawByte(milliseconds: milliseconds) else { return nil } + guard byte == 0x1B else { return Character(UnicodeScalar(byte)) } + // A lone escape is a key (it cancels a wait); a key that sends a sequence (an arrow) is none, so an arrow + // pressed during a wait never stops it. + guard rawByte(milliseconds: 30) != nil else { return "\u{1B}" } + drainSequence() + return nil + } + + /// One byte of input, or nil when `milliseconds` passed with none or the input closed. + private func rawByte(milliseconds: Int) -> UInt8? { guard !closed else { return nil } var descriptor = pollfd(fd: input, events: Int16(POLLIN), revents: 0) - let ready = Darwin.poll(&descriptor, 1, Int32(clamping: milliseconds)) - guard ready > 0 else { return nil } + guard Darwin.poll(&descriptor, 1, Int32(clamping: milliseconds)) > 0 else { return nil } var byte: UInt8 = 0 let count = Darwin.read(input, &byte, 1) if count <= 0 { if count == 0 || (errno != EINTR && errno != EAGAIN) { closed = true } return nil } - // A key that sends a sequence (an arrow) is one escape; the rest is dropped. - if byte == 0x1B { drainSequence(); return "\u{1B}" } - return Character(UnicodeScalar(byte)) + return byte } private func drainSequence() { @@ -194,31 +214,152 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { while Darwin.poll(&descriptor, 1, 20) > 0, Darwin.read(input, &byte, 1) == 1 {} } - public func line(prompt: String) -> String? { + // MARK: - Choices + + /// One of `options`: a list moved with ↑↓ (the ▸ marks the line) and taken with enter where the terminal shows + /// colour, as `darkbloom start` picks models; elsewhere the numbered lines and one key. + public func choose(_ options: [String], selected: Int, abandon: () -> Bool) -> Int? { + guard !options.isEmpty else { return nil } settle() + let start = min(max(0, selected), options.count - 1) + return usesColor ? pick(options, start, abandon) : typedChoice(options, start, abandon) + } + + /// The list, redrawn in place on each key; once taken it folds to the chosen line (cancelled: to nothing), so + /// what scrolls up is what was chosen. q cancels; a number takes its line, and so does a letter only one option + /// starts with. Every row, the hint's too, fits the window: a wrapped row would stay behind when the list folds. + private func pick(_ options: [String], _ start: Int, _ abandon: () -> Bool) -> Int? { + var cursor = start + let marker = decorates ? "\u{25B8}" : ">" + let room = columns > 10 ? columns - 6 : Int.max + let rows = options.count + 1 + func fit(_ text: String) -> String { text.count > room ? String(text.prefix(room - 1)) + "\u{2026}" : text } + let hints = decorates ? ["\u{2191}\u{2193} move \u{00B7} enter select \u{00B7} q cancel", "\u{2191}\u{2193} \u{00B7} enter \u{00B7} q"] + : ["up/down move, enter select, q cancel", "up/down, enter, q"] + let hint = fit(hints.first { $0.count <= room } ?? hints[hints.count - 1]) + func draw(again: Bool) { + var frame = again ? "\u{1B}[\(rows)A" : "" + frame += "\r\u{1B}[J \u{1B}[2m\(hint)\u{1B}[0m\n" + for (index, option) in options.enumerated() { + frame += index == cursor ? " \u{1B}[\(brand)m\(marker)\u{1B}[0m \u{1B}[1m\(fit(option))\u{1B}[0m\n" : " \(fit(option))\n" + } + write(frame) + } + // The cursor is hidden while the list is up and shown again as it folds, before the chosen line, so no line + // after a choice starts with a terminal code. + func fold(_ chosen: Int?) -> Int? { + write("\u{1B}[\(rows)A\r\u{1B}[J\u{1B}[?25h") + Self.cursorHidden = false + if let chosen { write(" \u{1B}[\(brand)m\(marker)\u{1B}[0m \(fit(options[chosen]))\n") } + return chosen + } + Self.cursorHidden = true + write("\u{1B}[?25l") + draw(again: false) + while true { + if abandon() { return fold(nil) } + guard let key = readKey(milliseconds: 100) else { + if closed { return fold(nil) } + continue + } + switch key { + case .up: cursor = (cursor + options.count - 1) % options.count + case .down: cursor = (cursor + 1) % options.count + case .enter: return fold(cursor) + case .cancel: return fold(nil) + case .character(let character): + // q is cancel before it is a letter ("Qwen3.8 27B" is taken with the arrows, its number or another letter). + if character == "q" || character == "Q" { return fold(nil) } + if let number = character.wholeNumberValue, options.count <= 9 { + if options.indices.contains(number - 1) { return fold(number - 1) } + } else if character.isLetter, let index = ClusterOnboardingChoice.match(String(character), options: options, selected: cursor) { + return fold(index) + } + continue + } + draw(again: true) + } + } + + /// The plain transcript's choice: the numbered lines once, then one key where it can only mean one line (a number + /// of a short list, a letter one option starts with), enter for the default, or a number and enter. The prompt's + /// line ends with the option taken, written the same on a terminal and a pipe (no echo), so every plain + /// presentation keeps one transcript. + private func typedChoice(_ options: [String], _ start: Int, _ abandon: () -> Bool) -> Int? { + for (index, option) in options.enumerated() { say(" \(index + 1)) \(option)") } + let prompt = " Choose 1-\(options.count) (enter = \(start + 1)): " + func finish(_ index: Int?) -> Int? { + write((index.map { options[$0] } ?? "") + "\n") + return index + } write(prompt) - var typed = "" + var text = "" while true { - guard let key = key(milliseconds: 60_000) else { - if closed { write("\n"); return nil } + if abandon() { return finish(nil) } + guard let key = key(milliseconds: 100) else { + if closed { return finish(nil) } continue } switch key { case "\r", "\n": - write("\n") - return typed + if let index = ClusterOnboardingChoice.match(text, options: options, selected: start) { + // Typed digits are on screen already; enter alone shows the default it took. + if text.isEmpty { return finish(index) } + write("\n") + return index + } + text = "" + write("\n" + prompt) case "\u{7F}", "\u{08}": - if !typed.isEmpty { - typed.removeLast() + if !text.isEmpty { + text.removeLast() if echoesInput && configured { write("\u{08} \u{08}") } } case "\u{1B}": - continue + return finish(nil) default: - guard key.isASCII, !key.isNewline, let value = key.asciiValue, value >= 0x20, typed.count < 16 else { continue } - typed.append(key) + guard key.isASCII, let value = key.asciiValue, value >= 0x20, text.count < 8 else { continue } + if text.isEmpty { + if key == "q" || key == "Q" { return finish(nil) } + if let number = key.wholeNumberValue, options.count <= 9 { + if options.indices.contains(number - 1) { return finish(number - 1) } + continue + } + if key.isLetter, let index = ClusterOnboardingChoice.match(String(key), options: options, selected: start) { + return finish(index) + } + } + text.append(key) if echoesInput && configured { write(String(key)) } } } } + + private enum Key: Equatable { case up, down, enter, cancel, character(Character) } + + /// One key with the arrows decoded (ESC [ A, ESC O B); a lone escape cancels; other sequences are dropped. + private func readKey(milliseconds: Int) -> Key? { + guard let first = rawByte(milliseconds: milliseconds) else { return nil } + switch first { + case 0x1B: + guard let second = rawByte(milliseconds: 30) else { return .cancel } + guard second == 0x5B || second == 0x4F, let third = rawByte(milliseconds: 30) else { drainSequence(); return nil } + switch third { + case 0x41: return .up + case 0x42: return .down + default: drainSequence(); return nil + } + case 0x0D, 0x0A: return .enter + default: return .character(Character(UnicodeScalar(first))) + } + } + + /// The terminal in its ordinary mode while `body` runs (sudo reads a password there), the live line cleared. + public func suspended(_ body: () -> T) -> T { + settle() + guard configured else { return body() } + _ = tcsetattr(input, TCSANOW, &saved) + defer { _ = tcsetattr(input, TCSANOW, &reading) } + return body() + } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index 9f3dd5d8e6..ca3379ea52 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -263,6 +263,9 @@ public final class ClusterService: @unchecked Sendable { try? Data("\(getpid())\n".utf8).write(to: files.pid, options: .atomic) defer { unlink(files.pid.path) } say("started (pid \(getpid()))") + // Makes macOS ask once about Darkbloom's Local Network access now: the onboarding starts this service right + // after pairing, while the person is at this Mac, and waits for the answer (`ClusterLocalNetworkAccess`). + ClusterLocalNetworkAccess.startServiceProbe(say: say) refreshPowerAssertions(power) // A part a previous run of this service started and left running (that run ended without stopping it, e.g. // killed): stopped before anything starts, or it would hold the model's memory and the serving port forever. diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterServiceControl.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterServiceControl.swift index b9510b2354..29384003b8 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterServiceControl.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterServiceControl.swift @@ -195,7 +195,8 @@ extension ClusterService { members.append(local) let claim = start.claim let node = ClusterControlNode(localID: local.memberID, members: members, claim: claim, rankOrder: rankOrder(), - now: Self.monotonicSeconds(), ttl: Self.leaseTTLSeconds, soloGrace: Self.soloGraceSeconds) + now: Self.monotonicSeconds(), ttl: Self.leaseTTLSeconds, soloGrace: Self.soloGraceSeconds, + preferredLeader: ClusterSetupMemberFacts.memberID(pin: leadership.leaderPin)) lock.withLock { if control == nil { control = node } } } diff --git a/provider-swift/Sources/darkbloom/DoctorClusterChecks.swift b/provider-swift/Sources/darkbloom/DoctorClusterChecks.swift new file mode 100644 index 0000000000..3639712e88 --- /dev/null +++ b/provider-swift/Sources/darkbloom/DoctorClusterChecks.swift @@ -0,0 +1,25 @@ +import Foundation +import ProviderCore + +/// `darkbloom doctor`'s cluster checks: on a Mac paired for a cluster, the checks `darkbloom cluster doctor` runs +/// (installed metadata, trust files, the Thunderbolt RDMA link, the saved setup), each as one doctor check, so one +/// command answers for the whole Mac (2026-11-02 onboarding review: "darkbloom doctor > integrate clustering"). A Mac +/// that is not paired gets none: a single-Mac provider's report is unchanged, and its link is never inspected. +func buildClusterDoctorChecks(configPath: String?, paired: Bool = !ClusterService.holdsNoPairing()) async -> [DoctorCheck] { + guard paired, let path = configPath ?? (try? ConfigManager.defaultConfigPath().path), path.hasPrefix("/") else { return [] } + let report = await ClusterDiagnostics.doctor(providerConfiguration: URL(fileURLWithPath: path)) + return clusterDoctorChecks(report.checks.map { ($0.name, $0.outcome, $0.detail) }) +} + +/// The cluster checks that ran, named as cluster checks; one that could not run or observe anything is left out +/// (`darkbloom cluster doctor` lists those). +func clusterDoctorChecks(_ checks: [(name: String, outcome: ClusterDiagnosticsReport.Outcome, detail: String)]) -> [DoctorCheck] { + checks.compactMap { check in + switch check.outcome { + case .passed: return DoctorCheck(name: "cluster \(check.name)", status: .pass, detail: check.detail) + case .failed: return DoctorCheck(name: "cluster \(check.name)", status: .fail, + detail: check.detail + " (details: `darkbloom cluster doctor`)") + case .notRun, .notObserved: return nil + } + } +} diff --git a/provider-swift/Sources/darkbloom/DoctorCommand.swift b/provider-swift/Sources/darkbloom/DoctorCommand.swift index de1daadff9..bbcc24e686 100644 --- a/provider-swift/Sources/darkbloom/DoctorCommand.swift +++ b/provider-swift/Sources/darkbloom/DoctorCommand.swift @@ -46,6 +46,8 @@ struct Doctor: AsyncParsableCommand { snapshot: snapshot, coordinatorOverride: coordinator )) + // A Mac paired for a cluster: the cluster's own checks too (none on a single Mac). + checks.append(contentsOf: await buildClusterDoctorChecks(configPath: configOptions.config)) // Operator-facing diagnosis: trust reason, SE key, model fit, runtime, // billing, version — the "why am I / aren't I earning?" answers. diff --git a/provider-swift/Tests/ClusterControlChecks/ControlChecks.swift b/provider-swift/Tests/ClusterControlChecks/ControlChecks.swift index 05b10e7390..f6764a7fe3 100644 --- a/provider-swift/Tests/ClusterControlChecks/ControlChecks.swift +++ b/provider-swift/Tests/ClusterControlChecks/ControlChecks.swift @@ -76,6 +76,46 @@ import Darwin // Same GPU memory, more cores wins. let cores = [mac("mac-aaaaaaaaaaaa", "Apple M4 Max, 128 GB", 128, 32), mac("mac-bbbbbbbbbbbb", "Apple M4 Max, 128 GB", 128, 40)] expect(ClusterControlDerivation.derive(members: cores, present: Set(cores.map(\.memberID)), rankOrder: nil)?.memberID == "mac-bbbbbbbbbbbb", "cores") + // 2026-11-02 (onboarding review): the Mac the cluster was set up on leads whenever no plan's rank 0 decides, on + // identical Macs (where the lower identity won) and on a smaller Mac alike; a plan's rank 0 still leads, and a + // set-up Mac that is away never does. + let setUp = ClusterControlDerivation.derive(members: twins, present: all, rankOrder: nil, preferred: "mac-bbbbbbbbbbbb") + expect(setUp?.memberID == "mac-bbbbbbbbbbbb" && setUp!.reason == "the Mac the cluster was set up on", + "identical Macs: the set-up Mac leads, not the lower identity: \(String(describing: setUp))") + expect(ClusterControlDerivation.derive(members: mixed, present: Set(mixed.map(\.memberID)), rankOrder: nil, + preferred: "mac-000000000001")?.memberID == "mac-000000000001", "the set-up Mac leads before memory") + expect(ClusterControlDerivation.derive(members: mixed, present: Set(mixed.map(\.memberID)), + rankOrder: ["mac-ffffffffffff", "mac-000000000001"], preferred: "mac-000000000001")?.memberID + == "mac-ffffffffffff", "a plan's rank 0 still leads") + let away = ClusterControlDerivation.derive(members: twins, present: ["mac-aaaaaaaaaaaa"], rankOrder: nil, preferred: "mac-bbbbbbbbbbbb") + expect(away?.memberID == "mac-aaaaaaaaaaaa", "a set-up Mac that is away does not lead") + let failover = ClusterControlDerivation.derive(members: three, present: ["mac-111111111111", "mac-333333333333"], + rankOrder: ["mac-222222222222", "mac-111111111111", "mac-333333333333"], preferred: "mac-111111111111") + expect(failover?.memberID == "mac-111111111111" && failover!.reason.contains("rank 0 is absent"), + "rank 0 away: the set-up Mac, when present: \(String(describing: failover))") + // Both Macs of a pair derive the same first claim from the same record: the set-up Mac. + let a = ClusterControlNode(localID: "mac-aaaaaaaaaaaa", members: twins, claim: nil, rankOrder: nil, now: 0, ttl: 30, + preferredLeader: "mac-bbbbbbbbbbbb") + let b = ClusterControlNode(localID: "mac-bbbbbbbbbbbb", members: twins, claim: nil, rankOrder: nil, now: 0, ttl: 30, + preferredLeader: "mac-bbbbbbbbbbbb") + expect(a.claim == b.claim && a.claim.leaderID == "mac-bbbbbbbbbbbb", "both derive the set-up Mac: \(a.claim) / \(b.claim)") + // Every plan names the set-up Mac as rank 0, made on either Mac, the smaller one included: a pair the joined Mac + // led (a plan whose rank 0 was the Mac that joined) moves back at its next plan, a re-plan on the joined Mac + // included. With no set-up Mac of this pair on record, the Mac planning. + let pair = mixed.map(\.memberID) + expect(ClusterControlDerivation.planLeader(setUp: "mac-000000000001", members: pair, localID: "mac-000000000001") + == "mac-000000000001", "a plan on the set-up Mac: it is rank 0") + let replan = ClusterControlDerivation.planLeader(setUp: "mac-000000000001", members: pair, localID: "mac-ffffffffffff") + expect(replan == "mac-000000000001", "a re-plan on the joined Mac: the set-up Mac is rank 0, not the Mac planning") + let joinedLed = ClusterControlDerivation.derive(members: mixed, present: Set(pair), rankOrder: ["mac-ffffffffffff", "mac-000000000001"], + preferred: "mac-000000000001") + let movedBack = ClusterControlDerivation.derive(members: mixed, present: Set(pair), rankOrder: [replan] + pair.filter { $0 != replan }, + preferred: "mac-000000000001") + expect(joinedLed?.memberID == "mac-ffffffffffff" && movedBack?.memberID == "mac-000000000001" && movedBack!.reason.contains("rank 0"), + "the joined Mac leads until the re-plan, then the set-up Mac does: \(String(describing: movedBack))") + expect(ClusterControlDerivation.planLeader(setUp: nil, members: pair, localID: "mac-ffffffffffff") == "mac-ffffffffffff" + && ClusterControlDerivation.planLeader(setUp: "mac-999999999999", members: pair, localID: "mac-ffffffffffff") == "mac-ffffffffffff", + "no set-up Mac of this pair on record (none, or an earlier pairing's): the Mac planning") } static func restartsReformIdentically() { diff --git a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift index aca40f6a19..51f8f0a875 100644 --- a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift +++ b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift @@ -15,7 +15,7 @@ import Darwin } static func main() { - signal(SIGALRM) { _ in Darwin._exit(124) }; alarm(180); defer { alarm(0) } + signal(SIGALRM) { _ in Darwin._exit(124) }; alarm(300); defer { alarm(0) } // A run over pipes that ended closes its end; a late key is then an error, never the end of the checks. signal(SIGPIPE, SIG_IGN) privateMiMoSelectionRefusesBeforeAnyActionOnMemberOrUnpairedMac() @@ -36,8 +36,6 @@ import Darwin linkNotReady() memberAgain() resumedMacsOpenWithTheMark() - memberChangesModel() - memberVerifiesTeardown() leaderAgainServing() leaderPairedNotServing() noModelOffered() @@ -51,8 +49,8 @@ import Darwin copyBlockedByDisk() copyInterrupted() // Finish 2026-10-13 night: failing first on c35897c36. - shortCopyStartsWithAStatedLine() - shortCopyStillStopsWithN() + shortCopyIsAListLikeAnyOther() + shortCopyStopsFromItsList() // One-command fixes 2026-10-14: failing first on 265648289. deploymentWords() cableLinesStreamBeforeTheApproval() @@ -76,13 +74,29 @@ import Darwin localNamesTheModel() memberJoinsWithLocal() servingScopeValues() - notOfferedGroupedByReason() sameTitleShowsTheID() // Tensor parallel made visible (2026-10-24). tensorParallelNotesOnTheModelLine() // Two identical Macs named apart, and the plain presentations of those lines (2026-10-25). identicalMacsAreToldApart() plainPresentationsKeepTheNewLines() + // The 2026-11-02 onboarding review: lists, permissions asked at stated moments, a read-only member, approved + // models only, sudo instead of a script, and the window's fate said on both Macs. + arrowKeysTakeAMenuItem() + onlyApprovedModelsAreListed() + memberLocalPointsToTheLeader() + localNetworkAskedAtStatedMoments() + cablePortSetUpWithSudoWhereNoPromptShows() + codeListEndsWhenThePairingDoes() + developmentBuildKeepsTheWindowsOpen() + // The audit of that change: keys during waits, q, SSH, a probe that tells nothing, a slow Allow on the other + // Mac, and how the pair serves. + arrowKeysDoNotStopAWait() + qCancelsAListBeforeALetter() + sshSessionsAreToldWhereThePromptIs() + serviceThatCannotTellStillGetsTheAsk() + otherMacThatDidNotAnswerOffersTryAgain() + startSaysHowThePairServes() print("onboarding checks: \(passed) passed, \(failures.count) failed") for failure in failures { print("FAIL " + failure) } exit(failures.isEmpty ? 0 : 1) @@ -110,48 +124,57 @@ import Darwin defer { for fd in output { Darwin.close(fd) } } let terminal = ClusterOnboardingTerminal(input: input[0], output: output[1], environment: color) terminal.heading("Choose a model") + // A list too long for one key: typed digits, with a backspace, then enter. + let options = (1...13).map { "Model \($0)" } let keys = Array("12\u{08}3\n".utf8) _ = keys.withUnsafeBytes { Darwin.write(input[1], $0.baseAddress, $0.count) } - expect(terminal.line(prompt: "Number: ") == "13", "plain input keeps line editing semantics") + expect(terminal.choose(options, selected: 0) == 12, "plain input keeps line editing semantics") var buffer = [UInt8](repeating: 0, count: 1024) let count = Darwin.read(output[0], &buffer, buffer.count) let text = String(decoding: buffer.prefix(max(0, count)), as: UTF8.self) - expect(text == "\nChoose a model\nNumber: \n", "pipe output has no colors, backspaces or echoed input: \(text)") + let listed = options.enumerated().map { " \($0.offset + 1)) \($0.element)\n" }.joined() + expect(text == "\nChoose a model\n" + listed + " Choose 1-13 (enter = 1): \n", + "pipe output has no colors, backspaces or echoed input: \(text)") } /// The coloured setup on a UTF-8 terminal: the Darkbloom mark beside the - /// setup's name, a meter on each stage, and live lines that the next said - /// line replaces. Every stage and line still reads in order; the mark - /// blooms (cursor up) only when animation is allowed, and nothing clears the screen. + /// setup's name, a meter on each stage, choices as lists moved with the + /// arrows (as `darkbloom start` picks models) that fold to the chosen line, + /// and live lines that the next said line replaces. Every stage and line + /// still reads in order; the mark blooms (cursor up) only when animation is + /// allowed, and nothing clears the screen. static func colourSetupDrawsTheMarkAndKeepsTheTranscript() { for animated in [false, true] { let recorder = Recorder() var environment = ["TERM": "xterm-256color", "LANG": "en_US.UTF-8"] if !animated { environment["DARKBLOOM_NO_ANIMATION"] = "1" } - let run = TerminalRun(operations(recorder, pairEvents: [.searching, .waitingAsLeader, .connected, - .code("123456", peer: ["Apple M3 Ultra, 256 GB"]), .peerDecided(true)], + let run = TerminalRun(operations(recorder, pairEvents: leaderEvents, pairResult: .paired(role: .leader, peerName: "Apple M3 Ultra, 256 GB")), environment: environment) - expect(run.waitFor("Does the other Mac show 123 456?"), "colour: the code question") + expect(run.waitFor(codeQuestion), "colour: the code question") + expect(run.waitFor(arrowHint), "colour: the answers as a list moved with the arrows") run.type("y") - expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "colour: the model choice") + expect(run.waitFor(arrowHint, count: 2), "colour: the model list") run.type("\r") let code = run.finish() expect(code == 0, "colour: exit 0, got \(String(describing: code))") let screen = visible(run.text) expect(ClusterOnboardingBrand.rows().allSatisfy { row in screen.contains { $0.contains(row) } }, "colour: the whole mark") - expect(screen.contains { $0.contains("Darkbloom") } && screen.contains { $0.contains("Connect / Pair / Choose / Start / Test") }, + expect(screen.contains { $0.contains("Darkbloom") } && screen.contains { $0.contains(ClusterOnboardingDriver.setupSubtitle) }, "colour: the name and the steps beside the mark") - 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(), "colour: stages in order") for (index, stage) in stages.enumerated() { - let meter = String(repeating: "\u{25CF}", count: index + 1) + String(repeating: "\u{25CB}", count: 4 - index) + let meter = String(repeating: "\u{25CF}", count: index + 1) + String(repeating: "\u{25CB}", count: 3 - index) expect(screen.contains { $0.contains(stage) && $0.contains(meter) }, "colour: \(stage) carries its meter") } - expect(screen.contains("Serving Qwen3.5-9B across both Macs: pipeline, the other Mac 16 layers / this Mac 16 layers."), + // A taken choice folds to its one line: the ▸ and the option, the list and its hint erased. + expect(screen.contains(" \u{25B8} Yes, pair") && screen.contains(" \u{25B8} Qwen3.8-27B-4bit-mtp — 16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers"), + "colour: each choice folds to the chosen line") + expect(run.text.contains("\u{1B}[3A\r\u{1B}[J"), "colour: the list is erased in place once chosen") + expect(screen.contains(" Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers."), "colour: the serving line reads plainly") - for live in ["Checking the cable", "Reading both Macs", "Planning on both Macs' memory", "Loading Qwen3.5-9B on both Macs", - "Waiting for the first tokens"] { + for live in ["Checking the cable", "Reading both Macs over the cable", "Planning each model for both Macs", + "Loading Qwen3.8-27B-4bit-mtp on both Macs", "Sending a test request"] { expect(!screen.contains { $0.contains(live + "\u{2026}") }, "colour: the live line \(live) is replaced, never left behind") } expect(run.text.contains("\u{1B}[\(ClusterOnboardingBrand.height)A") == animated, "colour: the mark blooms only when animating") @@ -168,7 +191,7 @@ import Darwin && ClusterOnboardingBrand.bloom.count == ClusterOnboardingBrand.pixels.joined().filter { $0 == "#" }.count, "the bloom draws every pixel once") expect(ClusterOnboardingBrand.rows(revealed: 0).allSatisfy { $0.allSatisfy { $0 == " " } }, "an unopened bloom is blank") - expect(ClusterOnboardingBrand.meter("2 / 5 Pair securely") == "\u{25CF}\u{25CF}\u{25CB}\u{25CB}\u{25CB}" + expect(ClusterOnboardingBrand.meter("2 / 4 Pair") == "\u{25CF}\u{25CF}\u{25CB}\u{25CB}" && ClusterOnboardingBrand.meter("Test a response") == nil && ClusterOnboardingBrand.meter("6 / 5 x") == nil, "the step meter") expect(!ClusterOnboardingBrand.drawsBlocks(["LANG": "C"]) && ClusterOnboardingBrand.drawsBlocks(["LC_ALL": "en_US.UTF-8"]), "blocks only where the locale is UTF-8") @@ -177,30 +200,35 @@ import Darwin } /// Colour on a terminal too narrow for the mark (an SSH window, a split - /// pane), or a locale without UTF-8: the coloured headings only, no mark, - /// no meter, no live line and no cursor movement, every line in order. + /// pane), or a locale without UTF-8: the coloured headings, no mark, no + /// meter and no live line, every line in order; choices are still lists + /// moved with the arrows (ASCII words where the locale has no arrows), each + /// row cut to the window so a redraw never meets a wrapped row. static func narrowOrPlainLocaleColourKeepsPlainLines() { - for (label, environment, columns) in [ - ("narrow", ["TERM": "xterm-256color", "LANG": "en_US.UTF-8"], UInt16(30)), - ("ascii locale", ["TERM": "xterm-256color", "LANG": "C"], UInt16(132)), + // 30 columns cannot hold the keys' long hint: the short one, so the list's rows each take one row of the window. + for (label, environment, columns, hint) in [ + ("narrow", ["TERM": "xterm-256color", "LANG": "en_US.UTF-8"], UInt16(30), "up/down, enter, q"), + ("ascii locale", ["TERM": "xterm-256color", "LANG": "C"], UInt16(132), "up/down move, enter select, q cancel"), ] { let recorder = Recorder() - let run = TerminalRun(operations(recorder, pairEvents: [.searching, .waitingAsLeader, .connected, - .code("123456", peer: ["Apple M3 Ultra, 256 GB"]), .peerDecided(true)], + let run = TerminalRun(operations(recorder, pairEvents: leaderEvents, pairResult: .paired(role: .leader, peerName: "Apple M3 Ultra, 256 GB")), environment: environment, columns: columns) - expect(run.waitFor("Does the other Mac show 123 456?"), "\(label): the code question") + expect(run.waitFor(codeQuestion), "\(label): the code question") + expect(run.waitFor(hint), "\(label): the list's keys in words") run.type("y") - expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "\(label): the model choice") + expect(run.waitFor(hint, count: 2), "\(label): the model list") + let hints = visible(run.text).filter { $0.contains(hint) } + expect(!hints.isEmpty && hints.allSatisfy { $0.count < Int(columns) }, "\(label): the keys' hint fits its row, so none stays behind: \(hints)") run.type("\r") let code = run.finish() expect(code == 0, "\(label): exit 0, got \(String(describing: code))") let screen = visible(run.text) - expect(!run.text.contains("\u{2588}") && !run.text.contains("\u{2580}") && !run.text.contains("\u{25CF}"), - "\(label): no mark and no meter") + expect(!run.text.contains("\u{2588}") && !run.text.contains("\u{2580}") && !run.text.contains("\u{25CF}") && !run.text.contains("\u{25B8}"), + "\(label): no mark, no meter, no block glyphs") expect(!run.text.contains("\u{1B}[\(ClusterOnboardingBrand.height)A") && !run.text.contains("\u{1B}[K"), - "\(label): no cursor movement or live line") + "\(label): no bloom and no live line") expect(run.text.contains("\u{1B}[1;36m"), "\(label): the headings keep their colour") - 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"] + expect(screen.allSatisfy { $0.count <= Int(columns) || !$0.hasPrefix(" > ") }, "\(label): the list's rows fit the window") let rows = stages.compactMap { stage in screen.firstIndex { $0.contains(stage) } } expect(rows.count == stages.count && rows == rows.sorted(), "\(label): stages in order") expect(Array(recorder.all.suffix(2)) == ["testRequest", "register"], "\(label): the setup ran to its test: \(recorder.all)") @@ -214,21 +242,23 @@ import Darwin /// erases all of it. static func narrowColourWindowKeepsOneRowLines() { let recorder = Recorder() - let run = TerminalRun(operations(recorder, pairEvents: [.searching, .waitingAsLeader, .connected, - .code("123456", peer: ["Apple M3 Ultra, 256 GB"]), .peerDecided(true)], + let run = TerminalRun(operations(recorder, pairEvents: leaderEvents, pairResult: .paired(role: .leader, peerName: "Apple M3 Ultra, 256 GB")), environment: ["TERM": "xterm-256color", "LANG": "en_US.UTF-8"], columns: 45) - expect(run.waitFor("Does the other Mac show 123 456?"), "45 columns: the code question") + expect(run.waitFor(codeQuestion), "45 columns: the code question") + expect(run.waitFor(arrowHint), "45 columns: the answers") run.type("y") - expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "45 columns: the model choice") + expect(run.waitFor(arrowHint, count: 2), "45 columns: the model list") run.type("\r") let code = run.finish() expect(code == 0, "45 columns: exit 0, got \(String(describing: code))") let screen = visible(run.text) expect(!run.text.contains("\u{2588}") && !run.text.contains("\u{1B}[\(ClusterOnboardingBrand.height)A"), "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}") }, + expect(screen.contains { $0.contains("1 / 4 Connect") && $0.contains("\u{25CF}\u{25CB}\u{25CB}\u{25CB}") }, "45 columns: headings keep the meter") + let wide = screen.filter { $0.contains("\u{25B8}") && $0.count > 45 } + expect(wide.isEmpty, "45 columns: the list's rows fit the window: \(wide)") 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 @@ -255,7 +285,8 @@ import Darwin /// What a person reads: escapes removed and each row as it was last written. static func visible(_ text: String) -> [String] { text.components(separatedBy: "\n").map { line in - let plain = line.replacingOccurrences(of: "\u{1B}\\[[0-9;]*[A-Za-z]", with: "", options: .regularExpression) + // Every CSI sequence, the cursor's own (`ESC [ ? 25 l`) included. + let plain = line.replacingOccurrences(of: "\u{1B}\\[[0-9;?]*[A-Za-z]", with: "", options: .regularExpression) return plain.components(separatedBy: "\r").last ?? plain } } @@ -265,13 +296,11 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), testResult: .failure(.init(["Test response timed out."])))) - expect(run.waitFor("Choose a model"), "failed test: choose model") - run.type("\r") - expect(run.waitFor("press n to stop here."), "failed test: start countdown") + expect(run.waitFor(prompt(2)), "failed test: choose model") run.type("\r") expect(run.finish() == 1, "failed test returns failure") expect(run.text.contains("Setup saved, but the test request failed."), "failure is explicit") - expect(run.text.contains("retry the test with t"), "failure has a next action") + expect(run.text.hasSuffix("Run `darkbloom cluster` to see the status and test again.\n"), "failure ends with its next action") expect(!run.text.contains("Done."), "failed response never reports setup success") expect(recorder.all.suffix(3) == ["serve", "waitReady", "testRequest"], "readiness and actual test still run") } @@ -285,68 +314,93 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: choices)) - expect(run.waitFor("Choose a model [1-1, enter = 1]: "), "every family uses the existing choice flow") - expect(run.text.contains(" 1. MiMo"), "offered MiMo remains selectable") - expect(run.text.contains("Enter selects MiMo."), "default names the actual first choice") - expect(run.text.contains("GLM: Not qualified for this cluster"), "qualification blocker remains visible") - expect(!run.text.contains(" 2. GLM"), "blocked GLM is not selectable") - run.type("\r") - expect(run.waitFor("Starting MiMo on both Macs"), "default preserves the selected model") - run.type("n") - expect(run.finish() == 0, "stopping before start stays available") + expect(run.waitFor(prompt(1)), "every family uses the same list") + expect(run.text.contains(" 1) MiMo — Fits these Macs\n"), "offered MiMo remains selectable") + expect(!run.text.contains("GLM"), "a model that cannot be served here is not listed") + run.type("q") + expect(run.finish() == 0, "q cancels the choice") + expect(run.text.contains("Nothing was changed. Run `darkbloom cluster` again to choose."), "cancelled: said") expect(!recorder.all.contains("adopt 0") && !recorder.all.contains("serve"), "presentation does not bypass start checks") } static func pairingStateMachine() { var machine = ClusterOnboardingPairing() expect(machine.role == nil, "no role before the pairing moves") - expect(machine.handle(.searching) == ["Looking for a Mac waiting on the cable…"], "searching line") + expect(machine.handle(.searching).isEmpty && machine.working == "Looking for the other Mac on the cable", + "searching: a live line, no said line") let wait = machine.handle(.waitingAsLeader) expect(machine.role == .leader && machine.phase == .waiting, "listening makes this Mac the leader-to-be") - expect(wait.contains(" On your other Mac, run `darkbloom cluster`."), "the other-Mac instruction, word for word: \(wait)") - expect(wait.contains { $0.contains("press q to cancel") }, "the cancel key is named") + expect(wait.last == "Now run `darkbloom cluster` on the other Mac.", "the action is the last line, word for word: \(wait)") + expect(wait.first?.contains("q cancels") == true, "the cancel key is named") + expect(machine.working?.contains("run `darkbloom cluster` there") == true, "the live line repeats the action while it waits") expect(machine.handle(.waitingAsLeader).isEmpty, "the wait is announced once (idempotent)") + expect(machine.handle(.connected).isEmpty, "connected: nothing said") let code = machine.handle(.code("123456", peer: ["Apple M5 Ultra, 256 GB", "macOS 27.0.1"])) expect(machine.asking == "123 456", "the code waits for an answer") - expect(code.contains("Does the other Mac show 123 456? Press y if it does, n if it does not."), "the question: \(code)") - expect(code.contains("The other Mac: Apple M5 Ultra, 256 GB"), "the other Mac is named by its hardware, never a host name") - expect(machine.answered(true) == ["Confirmed here; waiting for the other Mac…"], "answer y") - expect(machine.answered(true).isEmpty, "a second y answers nothing") + expect(code == ["The other Mac: Apple M5 Ultra, 256 GB", " macOS 27.0.1", "Code: 123 456", codeQuestion], + "the other Mac, the code and the question: \(code)") + expect(ClusterOnboardingPairing.codeAnswers == ["Yes, pair", "No"], "the two answers") + expect(machine.answered(true) == [ClusterOnboardingPairing.otherMacAnswerLine] && machine.working == "Waiting for the other Mac to confirm the code", + "answer yes: the other Mac's turn, said, and the wait is live") + expect(machine.answered(true).isEmpty, "a second answer answers nothing") + var first = ClusterOnboardingPairing() + _ = first.handle(.code("123456", peer: ["Apple M5 Ultra, 256 GB"])) + _ = first.handle(.peerDecided(true)) + expect(first.answered(true).isEmpty, "the other Mac answered first: nothing more to do there") expect(machine.finished(.paired(role: .leader, peerName: "Apple M5 Ultra, 256 GB")).last - == "Paired with the other Mac (Apple M5 Ultra, 256 GB). This Mac leads the cluster.", "leader's paired line") + == "\u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). This Mac leads.", "leader's paired line") var joiner = ClusterOnboardingPairing() _ = joiner.handle(.searching) - expect(joiner.handle(.joining) == ["Found a Mac waiting on the cable: this Mac joins its cluster."], "a waiting leader is found") + expect(joiner.handle(.joining) == ["Found the other Mac on the cable: it leads, and this Mac joins it."], "a waiting leader is found") expect(joiner.role == .member, "dialing a waiting Mac makes this one a member") expect(joiner.finished(.paired(role: .member, peerName: "Apple M3 Ultra, 256 GB")).last - == "Paired with the other Mac (Apple M3 Ultra, 256 GB). Continue on the other Mac.", "member's paired line, word for word") + == "\u{2713} Paired with the other Mac (Apple M3 Ultra, 256 GB). It leads; this Mac follows it.", "member's paired line, word for word") var tie = ClusterOnboardingPairing() _ = tie.handle(.waitingAsLeader) expect(tie.handle(.joining) == ["The other Mac started waiting at the same moment and leads; this Mac joins it."], "a tie is explained") expect(tie.role == .member, "the Mac that yields joins") + var declining = ClusterOnboardingPairing() + _ = declining.handle(.code("123456", peer: [])) + expect(declining.answered(false) == ["Declined here: nothing is paired."], "answer no") + var failed = ClusterOnboardingPairing() expect(failed.finished(.failed(["The code was declined."])) == ["Not paired.", "The code was declined.", "Run `darkbloom cluster` again to try again."], "a failed pairing says how to retry") expect(ClusterOnboardingPairing.spaced("654321") == "654 321", "code spacing") + + // A typed answer: enter, a number, or a letter only one option starts with. + typealias C = ClusterOnboardingChoice + let answers = ClusterOnboardingPairing.codeAnswers + expect(C.match("", options: answers, selected: 0) == 0 && C.match("2", options: answers, selected: 0) == 1 + && C.match("y", options: answers, selected: 0) == 0 && C.match("N", options: answers, selected: 0) == 1 + && C.match("3", options: answers, selected: 0) == nil && C.match("x", options: answers, selected: 0) == nil, + "typed answers") + expect(C.match("c", options: ["Change model", "Check both Macs released their memory"], selected: 0) == nil, + "a letter two options start with picks neither") } // MARK: - Pseudo-terminal flows static let leaderHardware = [ClusterOnboardingMachine(name: "Apple M5 Ultra, 256 GB", memoryGB: 256, gpuCores: 80, leads: true, models: 2), ClusterOnboardingMachine(name: "Apple M3 Ultra, 256 GB", memoryGB: 256, gpuCores: 80, leads: false, models: 2)] + + /// The models approved for clusters (`ClusterPublicModels.declared`), planned with this Mac, which leads, at rank 0; + /// a model these chips may not serve is not listed. static let choices = [ - ClusterOnboardingModelChoice(title: "Qwen3.5-9B", lines: ["rank 0: Apple M3 Ultra, 256 GB, layers 0-15", "rank 1 (decodes): Apple M5 Ultra, 256 GB (this Mac), layers 16-31"], blocker: nil), - ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["rank 0: Apple M3 Ultra, 256 GB, layers 0-31"], blocker: nil), + ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers"], blocker: nil, + validated: true), + ClusterOnboardingModelChoice(title: "Z.ai: GLM-5.3-Flash", lines: ["181.8 GB · tensor parallel · this Mac 50% / the other Mac 50%"], blocker: nil, + validated: true), ClusterOnboardingModelChoice(title: "gpt-oss-20b", lines: [], blocker: "not granted for this pair of chips")] /// A copy's live report, logged for a transcript, then the line for the record. static let copyReports: [ClusterOnboardingProgress] = [ - .live({ _ in "Copying Qwen3.5-9B to the other Mac (Apple M3 Ultra, 256 GB) over the Thunderbolt cable: 3.1 of 6.1 GB, 2.40 GB/s, about 1 s left" }, + .live({ _ in "Copying Qwen3.8-27B-4bit-mtp to the other Mac (Apple M3 Ultra, 256 GB) over the Thunderbolt cable: 8.2 of 16.3 GB, 2.40 GB/s, about 1 s left" }, logged: true), - .line("Copied 6.1 GB in 2.6 s (2.35 GB/s); every file matched its manifest digest.")] + .line("Copied 16.3 GB in 6.9 s (2.36 GB/s); every file matched its manifest digest.")] final class Recorder: @unchecked Sendable { let lock = NSLock() @@ -361,7 +415,7 @@ import Darwin pairEvents: [ClusterOnboardingPairEvent], pairResult: ClusterOnboardingPairResult, choices: [ClusterOnboardingModelChoice] = choices, replanned: [ClusterOnboardingModelChoice]? = nil, - provisionResult: Result<[String], ClusterOnboardingFailure> = .success(["The other Mac (Apple M3 Ultra, 256 GB) has Qwen3.5-9B now: 12 files verified against the catalog manifest."]), + provisionResult: Result<[String], ClusterOnboardingFailure> = .success(["The other Mac (Apple M3 Ultra, 256 GB) has Qwen3.8-27B-4bit-mtp now: 12 files verified against the catalog manifest."]), provisionReports: [ClusterOnboardingProgress] = copyReports, provisionReportPause: useconds_t = 30_000, linkPorts: [String] = [], @@ -371,10 +425,16 @@ import Darwin developerNotice: String? = nil, testResult: Result<[String], ClusterOnboardingFailure> = .success(["\"Red, Blue, Green\" (6 tokens, first token 0.61 s)"]), machines: [ClusterOnboardingMachine] = leaderHardware, - answeredSeconds: String = "0.4", registerResult: Result<[String], ClusterOnboardingFailure> = .success([]), - readyResult: Result = .success(.init(servedBy: "the other Mac (Apple M3 Ultra, 256 GB)", port: 8000, - deployment: "Serving Qwen3.5-9B across both Macs: pipeline, the other Mac 16 layers / this Mac 16 layers"))) -> ClusterOnboardingOperations { + localNetwork: @escaping @Sendable (ClusterOnboardingLocalNetworkSubject) -> ClusterOnboardingLocalNetwork = { _ in .allowed }, + linkScript: String? = nil, + sudoSucceeds: Bool = true, + outlivesWindow: Bool = true, + remote: Bool = false, + commandApp: String = "Terminal", + reachFailures: Int = 0, + readyResult: Result = .success(.init(servedBy: "this Mac", port: 8000, + deployment: "Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers"))) -> ClusterOnboardingOperations { let answered = DispatchSemaphore(value: 0) let chosenPort = Recorder() return ClusterOnboardingOperations( @@ -386,6 +446,11 @@ import Darwin say("Darkbloom needs network access for the cluster cable: approve the macOS prompt (once per Mac).") _ = approvalGate.wait(timeout: .now() + 5) } + if let linkScript, !recorder.all.contains("runAsAdministrator") { + say("Cable found.") + say("macOS asks for your password to set up the cable's port: approve it (once per Mac).") + return .init(ready: false, exitCode: 1, manualScript: linkScript) + } if linkPorts.count > 1, chosenPort.all.isEmpty { say("Cable found on \(linkPorts.count) ports.") return .init(ready: false, exitCode: 1, ports: linkPorts) @@ -417,10 +482,12 @@ import Darwin recorder.lock.lock(); recorder.answers.append(accept); recorder.lock.unlock() recorder.note("answer \(accept ? "y" : "n")"); answered.signal() }, - ensureService: { recorder.note("ensureService"); return .success("This Mac's cluster service is running.") }, - reachMembers: { say in + ensureService: { recorder.note("ensureService"); return .success(()) }, + reachMembers: { recorder.note("reachMembers") - say("\(ClusterOnboardingMacName.sentence(ClusterOnboardingMacName.other(named: machines.last?.name))) answered over the cable in \(answeredSeconds) s.") + if recorder.all.filter({ $0 == "reachMembers" }).count <= reachFailures { + return .failure(.init("The other Mac did not answer over the cable.")) + } return .success(machines) }, planModels: { @@ -435,8 +502,12 @@ import Darwin return readyResult }, testRequest: { recorder.note("testRequest"); return testResult }, - status: { recorder.note("status"); return ["Serving Qwen3.5-9B across both Macs: pipeline, the other Mac 16 layers / this Mac 16 layers.", - "API at http://localhost:8000 on the other Mac (Apple M3 Ultra, 256 GB); 2 of 2 parts ready."] }, + // Rank 0, which serves the API, is the Mac that leads: this Mac on the leader, the other Mac on a member. + status: { recorder.note("status"); return resume.role == .member + ? ["Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, the other Mac 32 layers / this Mac 32 layers.", + "API at http://localhost:8000 on the other Mac (Apple M3 Ultra, 256 GB); 2 of 2 parts ready."] + : ["Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers.", + "API at http://localhost:8000 on this Mac; 2 of 2 parts ready."] }, stop: { recorder.note("stop"); return .success(["Both Macs stopped serving."]) }, provision: { index, download, progress in recorder.note("provision \(index) \(download ? "download" : "copy")") @@ -457,7 +528,12 @@ import Darwin recorder.note(scope.bind.map { "setScope local \($0)" } ?? "setScope public") return .success([scope.isLocalOnly ? "Saved: this cluster serves locally only." : "Saved: this cluster serves through Darkbloom."]) }, - register: { recorder.note("register"); return registerResult }) + register: { recorder.note("register"); return registerResult }, + localNetwork: { subject in localNetwork(subject) }, + commandApp: { commandApp }, + runAsAdministrator: { script in recorder.note("runAsAdministrator"); return sudoSucceeds && script == linkScript }, + serviceOutlivesWindow: { outlivesWindow }, + remote: { remote }) } static func privateMiMoSelectionRefusesBeforeAnyActionOnMemberOrUnpairedMac() { @@ -474,18 +550,17 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: .init(role: .leader), pairEvents: [], pairResult: .failed([])), request: invalid) expect(run.finish() == 1 && recorder.all.isEmpty, "public scope cannot trigger private setup actions") - // The real driver still reaches normal planning on the supported leader. - // Stop at its existing countdown: no synthetic Ready or model success. + // The real driver still reaches normal planning on the supported leader, and stops at the start's own fit + // check: no synthetic Ready or model success. let leaderRecorder = Recorder() let choice = ClusterOnboardingModelChoice(title: "MiMo private PNG", lines: ["private qualification"], blocker: nil, modelID: ClusterOnboardingRequest.privateMiMoModelID) let leader = TerminalRun(operations(leaderRecorder, resume: .init(role: .leader), pairEvents: [], pairResult: .failed([]), - choices: [choice]), request: request) - expect(leader.waitFor("Starting MiMo private PNG on both Macs"), "leader reaches the normal plan/choose/start countdown") - leader.type("n") - expect(leader.finish() == 0, "qualification can be cancelled before adoption/start") + choices: [choice], recheck: "Quit apps first."), request: request) + expect(leader.finish() == 1, "qualification stops at the start's fit check here") + expect(leader.text.contains("MiMo private PNG does not fit in the Macs' free memory now: Quit apps first."), "leader reaches the start") expect(leaderRecorder.all.contains("planModels"), "leader uses normal planning") - expect(!leaderRecorder.all.contains("adopt 0") && !leaderRecorder.all.contains("serve"), "cancelled draft creates no saved plan or Ready") + expect(!leaderRecorder.all.contains("adopt 0") && !leaderRecorder.all.contains("serve"), "a stopped draft creates no saved plan or Ready") } /// One driver run on a pseudo-terminal: the keys are typed only once the text before them is on screen. @@ -530,10 +605,11 @@ import Darwin var text: String { lock.lock(); defer { lock.unlock() }; return String(decoding: captured, as: UTF8.self).replacingOccurrences(of: "\r\n", with: "\n") } var code: Int32? { lock.lock(); defer { lock.unlock() }; return exitCode } - func waitFor(_ needle: String, seconds: Double = 10) -> Bool { + func waitFor(_ needle: String, seconds: Double = 10, count: Int = 1) -> Bool { let deadline = Date().addingTimeInterval(seconds) - while Date() < deadline { if text.contains(needle) { return true }; usleep(10_000) } - return text.contains(needle) + func seen() -> Bool { text.components(separatedBy: needle).count - 1 >= count } + while Date() < deadline { if seen() { return true }; usleep(10_000) } + return seen() } func type(_ keys: String) { @@ -587,10 +663,11 @@ import Darwin var text: String { lock.withLock { String(decoding: captured, as: UTF8.self) } } - func waitFor(_ needle: String, seconds: Double = 10) -> Bool { + func waitFor(_ needle: String, seconds: Double = 10, count: Int = 1) -> Bool { let deadline = Date().addingTimeInterval(seconds) - while Date() < deadline { if text.contains(needle) { return true }; usleep(10_000) } - return text.contains(needle) + func seen() -> Bool { text.components(separatedBy: needle).count - 1 >= count } + while Date() < deadline { if seen() { return true }; usleep(10_000) } + return seen() } func type(_ keys: String) { @@ -608,44 +685,42 @@ import Darwin static func leaderFromScratch() { let recorder = Recorder() - let run = TerminalRun(operations(recorder, pairEvents: [.searching, .waitingAsLeader, .connected, - .code("123456", peer: ["Apple M3 Ultra, 256 GB"]), .peerDecided(true)], + let run = TerminalRun(operations(recorder, pairEvents: leaderEvents, pairResult: .paired(role: .leader, peerName: "Apple M3 Ultra, 256 GB"))) - expect(run.waitFor(" On your other Mac, run `darkbloom cluster`.\n"), "leader: the instruction for the other Mac, on its own line") - expect(run.waitFor("Does the other Mac show 123 456? Press y if it does, n if it does not."), "leader: the code question") + expect(run.waitFor(" Now run `darkbloom cluster` on the other Mac.\n"), "leader: the one thing to do on the other Mac, on its own line") + expect(run.waitFor(codeQuestion + "\n 1) Yes, pair\n 2) No\n " + prompt(2)), "leader: the code question and its answers") run.type("y") - expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "leader: the model choice (two offered, one not)") - expect(run.text.contains(" Apple M5 Ultra, 256 GB · 256 GB · 80-core GPU · 2 models · leads (this Mac)"), "leader: its own hardware") - expect(run.text.contains(" Apple M3 Ultra, 256 GB · 256 GB · 80-core GPU · 2 models · member (the other Mac)\n"), "leader: the member's hardware, named the other Mac") - expect(run.text.contains(" 1. Qwen3.5-9B — rank 0: Apple M3 Ultra, 256 GB, layers 0-15\n"), "leader: one line per model: \(run.text)") - expect(!run.text.contains("rank 1 (decodes)"), "leader: the rest of a model's lines waits until it is chosen") - expect(run.text.contains(" gpt-oss-20b: not granted for this pair of chips"), "leader: a blocked model with its reason") + expect(run.waitFor(" " + prompt(2), count: 2), "leader: the model list") + let listed = run.text + expect(listed.contains(" This Mac: Apple M5 Ultra, 256 GB \u{00B7} the other Mac: Apple M3 Ultra, 256 GB\n"), "leader: both Macs in one line") + expect(listed.contains(" 1) Qwen3.8-27B-4bit-mtp — 16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers\n"), "leader: one line per model: \(listed)") + expect(!listed.contains("rank 1 (decodes)"), "leader: the rest of a model's lines is not said") + expect(!listed.contains("gpt-oss-20b"), "leader: a model these Macs cannot serve is not listed") run.type("\r") - // The choice is the start: one stated line with a moment to stop, no second question. - expect(run.waitFor("Starting Qwen3.5-9B on both Macs in 3 s; press n to stop here."), "leader: the timed start") - expect(run.text.contains("Options: always on (each Mac starts its part again by itself); serves your own requests through " - + "Darkbloom, and public requests where Darkbloom has qualified this model and split.\n"), - "leader: a cluster serving through Darkbloom says who it serves") let code = run.finish() expect(code == 0, "leader: exit 0, got \(String(describing: code))") let text = run.text - expect(!text.contains("Press y to start"), "leader: no second y/n after the model choice") - expect(text.contains("Serving Qwen3.5-9B across both Macs: pipeline, the other Mac 16 layers / this Mac 16 layers.\n"), - "leader: the deployment in one plain line") - expect(text.contains("API at http://localhost:8000 on the other Mac (Apple M3 Ultra, 256 GB).\n"), "leader: the API place names the Mac") - expect(text.contains("Saving the setup and sending it to the other Mac over the cable…\n"), "leader: the setup goes to the other Mac") + for line in [ + " \(prompt(2))Yes, pair", + " \u{2713} Paired with the other Mac (Apple M3 Ultra, 256 GB). This Mac leads.", + " \(prompt(2))Qwen3.8-27B-4bit-mtp — 16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers", + " \u{2713} Setup sent to the other Mac.", + " Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers.", + " API at http://localhost:8000 on this Mac.", + " \u{2713} Test response: \"Red, Blue, Green\" (6 tokens, first token 0.61 s)", + ] { + expect(text.contains(line + "\n"), "leader: \(line)") + } + // What is done, then the one thing to do next: the last line. + expect(text.hasSuffix("Done. You can close this window here and on the other Mac.\n" + + "To test, change the model or stop: run `darkbloom cluster` on this Mac.\n"), "leader: the last lines: \(text)") expect(!text.contains("127.0.0.1"), "leader: no bare loopback address") - expect(text.contains("Nothing else is needed on the other Mac.\n"), "leader: the member needs nothing") - expect(!text.contains("After a Mac restarts, run `darkbloom cluster`"), "leader: no command needed after a restart") expect(!text.contains("Run `darkbloom cluster` on the other Mac too."), "leader: the link flow's own ending is not repeated") - expect(text.contains(ClusterOnboardingDriver.localNetworkLine), "leader: the Local Network prompt is announced") - expect(text.contains("Working out the fastest way to split each model across both Macs…"), "leader: the planning line") - expect(!text.contains("which one decodes"), "leader: no phase-split wording in the planning line") - 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"] + expect(!text.contains("press n to stop") && !text.contains("Options:"), "leader: no countdown and no options paragraph after the choice") let positions = stages.compactMap { text.range(of: $0)?.lowerBound } expect(positions.count == stages.count && positions == positions.sorted(), "setup stages stay in order") - expect(text.contains("Enter selects Qwen3.5-9B. Choose another model by number."), "default choice is explicit") expect(!text.contains("\u{1B}"), "NO_COLOR transcript has no terminal escapes") + expect(visible(text).filter { !$0.isEmpty }.count <= 32, "leader: a short screen: \(visible(text).filter { !$0.isEmpty }.count) lines") expect(run.keys == 2, "leader: two keys (y, enter), got \(run.keys)") expect(recorder.all == ["checkLink", "pair", "answer y", "ensureService", "reachMembers", "planModels", "recheckFit 0", "adopt 0", "serve", "waitReady", "testRequest", "register"], "leader: operations in order: \(recorder.all)") @@ -665,12 +740,11 @@ import Darwin ] for (label, result, restart) in cases { let recorder = Recorder() - let run = TerminalRun(operations(recorder, pairEvents: [.searching, .waitingAsLeader, .connected, - .code("123456", peer: ["Apple M3 Ultra, 256 GB"]), .peerDecided(true)], + let run = TerminalRun(operations(recorder, pairEvents: leaderEvents, pairResult: .paired(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), registerResult: result)) - expect(run.waitFor("Does the other Mac show 123 456? Press y if it does, n if it does not."), "\(label): the code question") + expect(run.waitFor(codeQuestion), "\(label): the code question") run.type("y") - expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "\(label): the model choice") + expect(run.waitFor(prompt(2), count: 2), "\(label): the model choice") run.type("\r") _ = run.finish() let text = run.text @@ -683,30 +757,28 @@ import Darwin } /// DEVELOPER ONLY (`DARKBLOOM_CLUSTER_FORCE_MODE` in a debug build): a forced mode is said loudly, in one line, on - /// the setup screen right under the planning line; without the setting the screen has no such line. + /// the setup screen right under the line of both Macs; without the setting the screen has no such line. static func forcedModeNoticeOnTheSetupScreen() { let notice = "Developer setting: tensor parallel forced (DARKBLOOM_CLUSTER_FORCE_MODE=tensor_parallel_v1; debug build only)." let recorder = Recorder() - let run = TerminalRun(operations(recorder, pairEvents: [.searching, .waitingAsLeader, .connected, - .code("123456", peer: ["Apple M3 Ultra, 256 GB"]), .peerDecided(true)], + let run = TerminalRun(operations(recorder, pairEvents: leaderEvents, pairResult: .paired(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), developerNotice: notice)) - expect(run.waitFor("Does the other Mac show 123 456? Press y if it does, n if it does not."), "forced mode: the code question") + expect(run.waitFor(codeQuestion), "forced mode: the code question") run.type("y") - expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "forced mode: the model choice") + expect(run.waitFor(prompt(2), count: 2), "forced mode: the model choice") let text = run.text - expect(text.contains("Working out the fastest way to split each model across both Macs…\n" + notice + "\n"), - "forced mode: the notice in one line right under the planning line") + expect(text.contains(" This Mac: Apple M5 Ultra, 256 GB \u{00B7} the other Mac: Apple M3 Ultra, 256 GB\n" + notice + "\n"), + "forced mode: the notice in one line right under the Macs") expect(text.components(separatedBy: "Developer setting:").count == 2, "forced mode: said once") run.type("\r") _ = run.finish() transcript("leader-forced-mode", run.text, keys: run.keys) let plain = Recorder() - let other = TerminalRun(operations(plain, pairEvents: [.searching, .waitingAsLeader, .connected, - .code("123456", peer: ["Apple M3 Ultra, 256 GB"]), .peerDecided(true)], + let other = TerminalRun(operations(plain, pairEvents: leaderEvents, pairResult: .paired(role: .leader, peerName: "Apple M3 Ultra, 256 GB"))) - expect(other.waitFor("Does the other Mac show 123 456? Press y if it does, n if it does not."), "no setting: the code question") + expect(other.waitFor(codeQuestion), "no setting: the code question") other.type("y") - expect(other.waitFor("Choose a model [1-2, enter = 1]: "), "no setting: the model choice") + expect(other.waitFor(prompt(2), count: 2), "no setting: the model choice") expect(!other.text.contains("Developer setting"), "no setting: no developer line on the setup screen") other.type("\r") _ = other.finish() @@ -751,22 +823,21 @@ import Darwin static func memberFromScratch() { let recorder = Recorder() - let run = TerminalRun(operations(recorder, pairEvents: [.searching, .joining, .connected, - .code("123456", peer: ["Apple M5 Ultra, 256 GB"]), .peerDecided(true)], + let run = TerminalRun(operations(recorder, pairEvents: memberEvents, pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"))) - expect(run.waitFor("Found a Mac waiting on the cable: this Mac joins its cluster."), "member: finds the waiting leader by itself") - expect(run.waitFor("Press y if it does"), "member: the code question") + expect(run.waitFor("Found the other Mac on the cable: it leads, and this Mac joins it."), "member: finds the waiting leader by itself") + expect(run.waitFor(codeQuestion), "member: the code question") run.type("y") let code = run.finish() expect(code == 0, "member: exit 0") let text = run.text - expect(text.contains("Paired with the other Mac (Apple M5 Ultra, 256 GB). Continue on the other Mac.\n"), "member: where to continue, word for word") - expect(text.contains("This Mac's cluster service is running."), "member: its service runs with no manual start") - expect(text.contains(ClusterOnboardingDriver.localNetworkLine + "\nNothing else to do on this Mac"), - "member: the Local Network prompt is announced before 'Nothing else to do'") - expect(!text.contains("On your other Mac"), "member: never told to go to another Mac to run anything") - expect(text.hasSuffix(ClusterOnboardingDriver.joinedLine + "\n") && !text.contains("cluster local"), - "member: the last line, and no `local` line for a plain join") + expect(text.contains(" \u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). It leads; this Mac follows it.\n"), + "member: who leads, word for word") + expect(text.hasSuffix("Done on this Mac. " + ClusterOnboardingDriver.closeWindowLine + "\n" + ClusterOnboardingDriver.joinedLine + "\n"), + "member: whether the window may close, then where to continue, last: \(text)") + expect(!text.contains("Now run `darkbloom cluster` on the other Mac."), "member: never told to run anything on another Mac") + expect(!text.contains("cluster local"), "member: no `local` line for a plain join") + expect(visible(text).filter { !$0.isEmpty }.count <= 20, "member: a short screen: \(visible(text).filter { !$0.isEmpty }.count) lines") expect(run.keys == 1, "member: one key (y)") expect(recorder.all == ["checkLink", "pair", "answer y", "ensureService"], "member: operations \(recorder.all)") transcript("member-from-scratch", text, keys: run.keys) @@ -777,9 +848,9 @@ import Darwin let run = TerminalRun(operations(recorder, pairEvents: [.searching, .waitingAsLeader, .joining, .code("111222", peer: ["Apple M3 Ultra, 256 GB"])], pairResult: .paired(role: .member, peerName: "Apple M3 Ultra, 256 GB"))) expect(run.waitFor("The other Mac started waiting at the same moment and leads; this Mac joins it."), "tie: explained") - expect(run.waitFor("111 222"), "tie: code shown"); run.type("y") + expect(run.waitFor("Code: 111 222"), "tie: code shown"); run.type("y") expect(run.finish() == 0, "tie: joins and ends") - expect(run.text.contains("Paired with the other Mac (Apple M3 Ultra, 256 GB). Continue on the other Mac."), "tie: continue on the leader") + expect(run.text.contains("Paired with the other Mac (Apple M3 Ultra, 256 GB). It leads; this Mac follows it."), "tie: follows the leader") } static func cancelWhileWaiting() { @@ -787,7 +858,7 @@ import Darwin let run = TerminalRun(operations(recorder, pairEvents: [.searching, .waitingAsLeader, .note("still waiting"), .note("still waiting"), .note("still waiting"), .note("still waiting"), .note("still waiting"), .note("still waiting"), .note("still waiting")] + Array(repeating: .note(""), count: 200), pairResult: .failed(["expired"]))) - expect(run.waitFor("press q to cancel"), "cancel: the wait is on screen") + expect(run.waitFor("q cancels"), "cancel: the wait is on screen") run.type("q") expect(run.finish() == 130, "cancel: q ends with 130") expect(run.text.contains("Cancelled: nothing was paired. Run `darkbloom cluster` again to start over."), "cancel: says nothing was paired") @@ -797,8 +868,9 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, pairEvents: [.searching, .joining, .code("123456", peer: ["Apple M5 Ultra, 256 GB"])], pairResult: .paired(role: .member, peerName: "x"))) - expect(run.waitFor("Press y if it does"), "declined: code shown"); run.type("n") + expect(run.waitFor(codeQuestion), "declined: code shown"); run.type("n") expect(run.finish() == 1, "declined: exit 1") + expect(run.text.contains(" " + prompt(2) + "No\n"), "declined: the answer on the prompt's line") expect(run.text.contains("Declined here: nothing is paired."), "declined: said") expect(run.text.contains("Run `darkbloom cluster` again to try again."), "declined: how to retry") expect(!recorder.all.contains("ensureService"), "declined: no service started") @@ -815,89 +887,62 @@ import Darwin /// A member is not sent elsewhere: its commands run on the derived control leader (forwarded by the live operations). static func memberResume(serving: Bool = true) -> ClusterOnboardingResume { - var resume = ClusterOnboardingResume(role: .member, peerName: "Apple M3 Ultra, 256 GB", serving: serving, modelName: "Qwen3.5-9B") + var resume = ClusterOnboardingResume(role: .member, peerName: "Apple M3 Ultra, 256 GB", serving: serving, modelName: "Qwen3.8-27B-4bit-mtp") resume.leaderName = "Apple M3 Ultra, 256 GB" resume.leaderReason = "rank 0 of the adopted plan: requests enter there and the coordinator registers it as the head" resume.term = 2 return resume } + /// 2026-11-02: "why does the member have the choices to change model, test, describe". A member's screen is the + /// cluster as it is and where to manage it: no list, no key, nothing run but its own service and the status. static func memberAgain() { let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: memberResume(), pairEvents: [], pairResult: .failed([]))) - expect(run.waitFor("Enter Leave setup unchanged"), - "member again: the same menu as the leader") + expect(run.finish() == 0, "member again: ends by itself") let text = run.text - expect(text.contains("This Mac is a member of the cluster led by the other Mac (Apple M3 Ultra, 256 GB)."), "member again: who leads") + expect(text.contains("This Mac follows the other Mac (Apple M3 Ultra, 256 GB)"), "member again: who leads, in the opening") expect(!text.contains("derived") && !text.contains("term ") && !text.contains("rank 0"), "member again: no leadership jargon") - expect(text.contains("Commands typed here run on the other Mac over the cable."), "member again: forwarding said") - expect(text.contains(" Serving Qwen3.5-9B across both Macs: pipeline, the other Mac 16 layers / this Mac 16 layers.\n"), "member again: the deployment line first") - run.type("s") - expect(run.finish() == 0, "member again: stop from the member") - expect(run.text.contains("Both Macs stopped serving."), "member again: the leader's answer shown") - expect(recorder.all == ["ensureService", "status", "stop"], "member again: status then stop, no pairing: \(recorder.all)") - expect(run.keys == 1, "member again: one key") - transcript("member-again", run.text, keys: run.keys) - } - - static func memberChangesModel() { - let recorder = Recorder() - let run = TerminalRun(operations(recorder, resume: memberResume(), pairEvents: [], pairResult: .failed([]))) - expect(run.waitFor("v Check both Macs released their memory"), "member model change: menu") - run.type("m") - expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "member model change: the leader's choices") - 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", - "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") - && !run.text.contains("sending it to the other Mac"), "member model change: where the setup is saved and sent") - transcript("member-changes-model", run.text, keys: run.keys) - } - - static func memberVerifiesTeardown() { - let recorder = Recorder() - let run = TerminalRun(operations(recorder, resume: memberResume(serving: false), pairEvents: [], pairResult: .failed([]))) - expect(run.waitFor("Not serving. Press m to choose a model and serve; enter to leave."), "teardown: menu when stopped") - run.type("v") - expect(run.finish() == 0, "teardown: exit 0") - expect(run.text.contains(" This Mac: nothing left running\n The other Mac (Apple M3 Ultra, 256 GB): nothing left running\n"), "teardown: each Mac's summary") - expect(recorder.all == ["ensureService", "status", "verifyTeardown"], "teardown: \(recorder.all)") + expect(text.contains(" Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, the other Mac 32 layers / this Mac 32 layers.\n"), "member again: the status") + expect(text.hasSuffix("This Mac's part runs by itself: nothing to do here.\n" + + "To test, change the model or stop: run `darkbloom cluster` on the other Mac (Apple M3 Ultra, 256 GB).\n"), + "member again: where to manage the cluster, last: \(text)") + expect(!text.contains("Change model") && !text.contains("Test a response") && !text.contains("Choose 1-"), "member again: no menu") + expect(recorder.all == ["ensureService", "status"], "member again: its service and the status only: \(recorder.all)") + expect(run.keys == 0, "member again: no key") + transcript("member-again", text, keys: run.keys) } /// `darkbloom cluster` run again on a Mac already in a cluster (the leader or a member) opens with the same - /// Darkbloom mark as the setup, with what can be done here, before anything else is said: the mark and the + /// Darkbloom mark as the setup and the part this Mac plays, before anything else is said: the mark and the /// name on a colour UTF-8 terminal, the two heading lines in a plain transcript. static func resumedMacsOpenWithTheMark() { let D = ClusterOnboardingDriver.self let resumes: [(String, ClusterOnboardingResume, String)] = [ - ("member", memberResume(), "This Mac is a member of the cluster led by the other Mac (Apple M3 Ultra, 256 GB)."), - ("leader", .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: true, modelName: "Qwen3.5-9B"), - "This Mac leads the cluster."), + ("member", memberResume(), "This Mac follows the other Mac (Apple M3 Ultra, 256 GB)"), + ("leader", .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), D.leaderSubtitle), ] - for (label, resume, first) in resumes { + for (label, resume, subtitle) in resumes { for colour in [true, false] { let recorder = Recorder() let environment = colour ? ["TERM": "xterm-256color", "LANG": "en_US.UTF-8", "DARKBLOOM_NO_ANIMATION": "1"] : ["NO_COLOR": "1"] let run = TerminalRun(operations(recorder, resume: resume, pairEvents: [], pairResult: .failed([])), environment: environment) - expect(run.waitFor("Enter Leave setup unchanged"), "\(label) again (\(colour ? "colour" : "plain")): the menu") - run.type("\r") - expect(run.finish() == 0, "\(label) again (\(colour ? "colour" : "plain")): enter leaves") + if label == "leader" { + expect(run.waitFor(colour ? arrowHint : prompt(6)), "\(label) again (\(colour ? "colour" : "plain")): the menu") + run.type("q") + } + expect(run.finish() == 0, "\(label) again (\(colour ? "colour" : "plain")): leaves") let screen = visible(run.text) // Beside the mark the name wraps a word per row ("Darkbloom", then "cluster"); plain text keeps one line. - let name = colour ? String(D.resumeTitle.split(separator: " ")[0]) : D.resumeTitle + let name = colour ? String(D.title.split(separator: " ")[0]) : D.title guard let title = screen.firstIndex(where: { $0.contains(name) }), - let opening = screen.firstIndex(where: { $0.contains(first) }) else { + let opening = screen.firstIndex(where: { $0.contains(subtitle) }) else { expect(false, "\(label) again (\(colour ? "colour" : "plain")): the title and the opening line: \(screen)") continue } - expect(title < opening && screen.contains { $0.contains(D.resumeSubtitle) }, - "\(label) again (\(colour ? "colour" : "plain")): the name and what can be done open the screen") + expect(title <= opening, "\(label) again (\(colour ? "colour" : "plain")): the name and the part this Mac plays open the screen") if colour { expect(ClusterOnboardingBrand.rows().allSatisfy { row in screen.contains { $0.contains(row) } }, "\(label) again (colour): the whole mark") @@ -909,13 +954,19 @@ import Darwin } } + /// The leader's `darkbloom cluster`: the status, then a list (2026-11-02: "a selectable interface ... like the + /// normal Darkbloom models"), the first item taken with enter. static func leaderAgainServing() { let recorder = Recorder() - let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: true, modelName: "Qwen3.5-9B"), + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([]))) - expect(run.waitFor("Enter Leave setup unchanged"), "leader again: the menu") - run.type("t") + expect(run.waitFor(prompt(6)), "leader again: the menu") + let menu = run.text + expect(menu.contains(" 1) Test a response\n 2) Change model\n 3) Serve locally only (no coordinator)\n 4) Stop serving\n" + + " 5) Check both Macs released their memory\n 6) Quit\n"), "leader again: every choice, one per line: \(menu)") + run.type("\r") expect(run.finish() == 0, "leader again: test request") + expect(run.text.contains(" \u{2713} Test response: \"Red, Blue, Green\""), "leader again: the answer") expect(recorder.all == ["ensureService", "status", "testRequest"], "leader again: no pairing, no plan: \(recorder.all)") transcript("leader-again", run.text, keys: run.keys) } @@ -924,13 +975,10 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: false), pairEvents: [], pairResult: .failed([]))) - expect(run.waitFor("Choose a model"), "leader resumed before a model was chosen: goes to the choice") - run.type("2\r") - expect(run.waitFor("Starting Qwen3.8-27B-4bit-mtp on both Macs in 3 s; press n to stop here."), "leader resumed: the second model chosen by number") - run.type("n") - expect(run.finish() == 0, "leader resumed: n stops with nothing changed") - expect(run.text.contains("Nothing was changed. Run `darkbloom cluster` here again to choose."), "leader resumed: n said") - expect(!recorder.all.contains("adopt 1"), "leader resumed: nothing adopted after n") + expect(run.waitFor(prompt(2)), "leader resumed before a model was chosen: goes to the choice") + run.type("2") + expect(run.finish() == 0, "leader resumed: the second model chosen by number, at once") + expect(recorder.all.contains("adopt 1") && !recorder.all.contains("adopt 0"), "leader resumed: the second model: \(recorder.all)") } static func noModelOffered() { @@ -938,35 +986,34 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: [ClusterOnboardingModelChoice(title: "big", lines: [], blocker: "too large for this pair")])) expect(run.finish() == 1, "no model: exit 1") - expect(run.text.contains("No model can be served by these Macs now; the reasons are above."), "no model: said") + expect(run.text.contains("No model approved for clusters can run on these two Macs now.\n big: too large for this pair\n"), + "no model: said, with why: \(run.text)") } - // MARK: - Provisioning: no manual model downloads static let copyOffer = ClusterOnboardingProvisionOffer( - lines: ["The other Mac (Apple M3 Ultra, 256 GB): copy from this Mac over the Thunderbolt cable (6.1 GB, about 3 s)"], + lines: ["The other Mac (Apple M3 Ultra, 256 GB): copy from this Mac over the Thunderbolt cable (16.3 GB, about 7 s)"], downloadAlternative: true, leaderDownloads: false) + static let copyChoices = [ - ClusterOnboardingModelChoice(title: "Qwen3.5-9B", lines: ["rank 0: Apple M3 Ultra, 256 GB, layers 0-15"], blocker: nil, provision: copyOffer), - ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["rank 0: Apple M3 Ultra, 256 GB, layers 0-31"], blocker: nil)] + ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers"], blocker: nil, provision: copyOffer), + ClusterOnboardingModelChoice(title: "Z.ai: GLM-5.3-Flash", lines: ["181.8 GB · tensor parallel · this Mac 50% / the other Mac 50%"], blocker: nil)] static func leaderCopiesAMissingModelOverTheCable() { let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: copyChoices)) - expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "copy: the choice") + expect(run.waitFor(prompt(2)), "copy: the choice") expect(!run.text.contains("needs: "), "copy: the list stays one line per model") run.type("\r") - expect(run.waitFor(" The other Mac (Apple M3 Ultra, 256 GB): copy from this Mac over the Thunderbolt cable (6.1 GB, about 3 s)"), - "copy: once chosen, what the model needs, with size and time") - expect(run.waitFor("Qwen3.5-9B is not on every Mac yet. No download by hand is needed:"), "copy: what is missing, said") - expect(run.waitFor("Press enter to copy it over the Thunderbolt cable (recommended), d to download it from Darkbloom's catalog instead, n to stop here."), - "copy: the cable is the default") + expect(run.waitFor(" Qwen3.8-27B-4bit-mtp is not on every Mac yet:\n The other Mac (Apple M3 Ultra, 256 GB): copy from this Mac over the Thunderbolt cable (16.3 GB, about 7 s)\n"), + "copy: once chosen, what is missing, with size and time") + expect(run.waitFor(" 1) Copy it over the Thunderbolt cable (recommended)\n 2) Download it from Darkbloom's catalog instead\n 3) Stop here\n " + prompt(3)), + "copy: the cable first, as a list") run.type("\r") - expect(run.waitFor(" Copying Qwen3.5-9B to the other Mac (Apple M3 Ultra, 256 GB) over the Thunderbolt cable: 3.1 of 6.1 GB, 2.40 GB/s, about 1 s left"), "copy: progress on the leader") + expect(run.waitFor(" Copying Qwen3.8-27B-4bit-mtp to the other Mac (Apple M3 Ultra, 256 GB) over the Thunderbolt cable: 8.2 of 16.3 GB, 2.40 GB/s, about 1 s left"), "copy: progress on the leader") 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", "register"], "copy: copied before the setup is synced: \(recorder.all)") @@ -979,11 +1026,10 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: copyChoices)) - expect(run.waitFor("Choose a model"), "catalog: the choice"); run.type("\r") - expect(run.waitFor("d to download it"), "catalog: the alternative is offered"); run.type("d") - expect(run.waitFor("Starting Qwen3.5-9B on both Macs in 3 s"), "catalog: then the timed start"); run.type("n") - expect(run.finish() == 0, "catalog: n stops after the download") - expect(recorder.all.contains("provision 0 download") && !recorder.all.contains("adopt 0"), "catalog: downloaded, nothing adopted: \(recorder.all)") + expect(run.waitFor(prompt(2)), "catalog: the choice"); run.type("\r") + expect(run.waitFor("Download it from Darkbloom's catalog instead"), "catalog: the alternative is offered"); run.type("2") + expect(run.finish() == 0, "catalog: served after the download") + expect(recorder.all.contains("provision 0 download") && recorder.all.contains("adopt 0"), "catalog: downloaded, then adopted: \(recorder.all)") } static func leaderDownloadsAModelNoMacHas() { @@ -992,15 +1038,12 @@ import Darwin "The other Mac (Apple M3 Ultra, 256 GB): copy from this Mac over the Thunderbolt cable (16.3 GB)"], downloadAlternative: false, leaderDownloads: true) let before = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["not on these Macs yet: planned once it is on this Mac"], blocker: nil, provision: offer)] - let after = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["rank 0: Apple M3 Ultra, 256 GB, layers 0-31", "rank 1 (decodes): Apple M5 Ultra, 256 GB (this Mac), layers 32-63"], blocker: nil)] + let after = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers", "rank 1 (decodes): Apple M5 Ultra, 256 GB (this Mac), layers 32-63"], blocker: nil)] let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: before, replanned: after)) - expect(run.waitFor("Choose a model [1-1, enter = 1]: "), "download: a catalog model is offered"); run.type("\r") - expect(run.waitFor("Qwen3.8-27B-4bit-mtp is not on this Mac yet. No download by hand is needed:"), "download: said") - expect(run.waitFor("Press enter to get it, n to stop here."), "download: one key"); run.type("\r") - expect(run.waitFor("Planning Qwen3.8-27B-4bit-mtp now that it is on this Mac…"), "download: planned after") - 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.waitFor(prompt(1)), "download: a catalog model is offered"); run.type("\r") + expect(run.waitFor(" Qwen3.8-27B-4bit-mtp is not on this Mac yet:\n"), "download: said") + expect(run.waitFor(" 1) Get it (download, then copy over the cable)\n 2) Stop here\n"), "download: one choice"); run.type("\r") expect(run.finish() == 0, "download: served") 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)") @@ -1025,7 +1068,7 @@ import Darwin let offer = ClusterOnboardingProvisionOffer(lines: ["This Mac: download from Darkbloom's catalog (16.3 GB)"], downloadAlternative: false, leaderDownloads: true) let before = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["not on these Macs yet: planned once it is on this Mac"], blocker: nil, provision: offer)] - let after = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["rank 0: Apple M3 Ultra, 256 GB, layers 0-31"], blocker: nil)] + let after = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers"], blocker: nil)] for colour in [true, false] { let label = colour ? "live download" : "plain download" let widths = Recorder() @@ -1034,10 +1077,9 @@ import Darwin pairResult: .failed([]), choices: before, replanned: after, provisionReports: downloadReports(widths: widths), provisionReportPause: 2_000), environment: environment, columns: 100) - expect(run.waitFor("Choose a model [1-1, enter = 1]: "), "\(label): the choice"); run.type("\r") - expect(run.waitFor("Press enter to get it, n to stop here."), "\(label): one key"); run.type("\r") - expect(run.waitFor("Starting Qwen3.8-27B-4bit-mtp on both Macs in 3 s"), "\(label): then the timed start"); run.type("n") - expect(run.finish() == 0, "\(label): n stops after the download") + expect(run.waitFor(colour ? arrowHint : prompt(1)), "\(label): the choice"); run.type("\r") + expect(run.waitFor(colour ? arrowHint : prompt(2), count: colour ? 2 : 1), "\(label): get it"); run.type("\r") + expect(run.finish() == 0, "\(label): served after the download") let rows = run.text.components(separatedBy: "\n").filter { $0.contains("Downloading Qwen3.8-27B-4bit-mtp") } let screen = visible(run.text) expect(screen.contains(" Downloaded 16.3 GB in 130.2 s; every file matched the catalog manifest."), "\(label): the line for the record") @@ -1059,8 +1101,8 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: copyChoices)) - expect(run.waitFor("Choose a model"), "declined copy: choice"); run.type("\r") - expect(run.waitFor("n to stop here."), "declined copy: offer"); run.type("n") + expect(run.waitFor(prompt(2)), "declined copy: choice"); run.type("\r") + expect(run.waitFor("3) Stop here"), "declined copy: offer"); run.type("3") expect(run.finish() == 0, "declined copy: exit 0") expect(run.text.contains("Nothing was copied or downloaded. Run `darkbloom cluster` here again to choose."), "declined copy: said") expect(!recorder.all.contains { $0.hasPrefix("provision") || $0.hasPrefix("adopt") }, "declined copy: nothing moved or adopted") @@ -1068,13 +1110,13 @@ import Darwin static func copyBlockedByDisk() { let recorder = Recorder() - let blocked = [ClusterOnboardingModelChoice(title: "Qwen3.5-9B", lines: [], blocker: nil, provision: .init(lines: ["The other Mac (Apple M3 Ultra, 256 GB): copy from this Mac over the Thunderbolt cable (6.1 GB) — cannot start: the other Mac (Apple M3 Ultra, 256 GB) has 3.0 GB free; the model needs 6.1 GB and 2.1 GB to spare"], - downloadAlternative: true, leaderDownloads: false, blocker: "the other Mac (Apple M3 Ultra, 256 GB) has 3.0 GB free; the model needs 6.1 GB and 2.1 GB to spare"))] + let blocked = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: [], blocker: nil, provision: .init(lines: ["The other Mac (Apple M3 Ultra, 256 GB): copy from this Mac over the Thunderbolt cable (6.1 GB) — cannot start: the other Mac (Apple M3 Ultra, 256 GB) has 3.0 GB free; the model needs 16.3 GB and 2.1 GB to spare"], + downloadAlternative: true, leaderDownloads: false, blocker: "the other Mac (Apple M3 Ultra, 256 GB) has 3.0 GB free; the model needs 16.3 GB and 2.1 GB to spare"))] let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: blocked)) - expect(run.waitFor("Choose a model"), "disk: choice"); run.type("\r") + expect(run.waitFor(prompt(1)), "disk: choice"); run.type("\r") expect(run.finish() == 1, "disk: exit 1") - expect(run.text.contains("It cannot start: the other Mac (Apple M3 Ultra, 256 GB) has 3.0 GB free; the model needs 6.1 GB and 2.1 GB to spare. Free some space and run `darkbloom cluster` here again."), + expect(run.text.contains("It cannot start: the other Mac (Apple M3 Ultra, 256 GB) has 3.0 GB free; the model needs 16.3 GB and 2.1 GB to spare. Free some space and run `darkbloom cluster` here again."), "disk: the free-disk refusal in words") expect(!recorder.all.contains { $0.hasPrefix("provision") }, "disk: nothing started") } @@ -1082,51 +1124,56 @@ import Darwin static func copyInterrupted() { let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), - choices: copyChoices, provisionResult: .failure(.init("The copy to the other Mac (Apple M3 Ultra, 256 GB) stopped at 2.0 of 6.1 GB: the cable connection ended.")))) - expect(run.waitFor("Choose a model"), "interrupted: choice"); run.type("\r") - expect(run.waitFor("n to stop here."), "interrupted: offer"); run.type("\r") + choices: copyChoices, provisionResult: .failure(.init("The copy to the other Mac (Apple M3 Ultra, 256 GB) stopped at 2.0 of 16.3 GB: the cable connection ended.")))) + expect(run.waitFor(prompt(2)), "interrupted: choice"); run.type("\r") + expect(run.waitFor("3) Stop here"), "interrupted: offer"); run.type("\r") expect(run.finish() == 1, "interrupted: exit 1") expect(run.text.contains("Run `darkbloom cluster` here again: a copy or download resumes where it stopped."), "interrupted: resumes next time") expect(!recorder.all.contains("adopt 0"), "interrupted: no setup synced for a model a Mac lacks") } - // MARK: - Only large copies are asked for + // MARK: - A short copy is a list like any other (2026-11-02: no key to press to do something) static let quickOffer = ClusterOnboardingProvisionOffer( - lines: ["The other Mac (Apple M3 Ultra, 256 GB): copy from this Mac over the Thunderbolt cable (6.1 GB, about 3 s)"], - downloadAlternative: true, leaderDownloads: false, quickSeconds: 3.05) + lines: ["The other Mac (Apple M3 Ultra, 256 GB): copy from this Mac over the Thunderbolt cable (16.3 GB, about 7 s)"], + downloadAlternative: true, leaderDownloads: false, quickSeconds: 6.9) - /// A copy predicted under 30 s (from the copy rate measured on these Macs) starts with a stated line: no key. - static func shortCopyStartsWithAStatedLine() { + /// A copy predicted under 30 s (from the copy rate measured on these Macs) is the list's first item, its time on + /// it, so enter takes it: no countdown, nothing that starts by itself, no letter keys. + static func shortCopyIsAListLikeAnyOther() { let recorder = Recorder() - let choices = [ClusterOnboardingModelChoice(title: "Qwen3.5-9B", lines: ["rank 0: Apple M3 Ultra, 256 GB, layers 0-15"], blocker: nil, provision: quickOffer)] + let choices = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers"], blocker: nil, provision: quickOffer)] let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: choices)) - expect(run.waitFor("Choose a model [1-1, enter = 1]: "), "short copy: the choice"); run.type("\r") - expect(run.waitFor("Copying it over the Thunderbolt cable now (about 3 s at the speed measured on these Macs); press n in the next 3 s to stop here, d to download it from Darkbloom's catalog instead."), - "short copy: a stated line, n still visible") - 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.waitFor(prompt(1)), "short copy: the choice"); run.type("\r") + expect(run.waitFor(" 1) Copy it over the Thunderbolt cable (about 7 s)\n 2) Download it from Darkbloom's catalog instead\n 3) Stop here\n " + prompt(3)), + "short copy: the copy first in the list, its time on it") + usleep(300_000) + expect(!recorder.all.contains { $0.hasPrefix("provision") }, "short copy: nothing starts by itself: \(recorder.all)") + run.type("\r") 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(!run.text.contains("press n") && !run.text.contains("d to download") && !run.text.contains("in the next 3 s"), "short copy: no keys to learn") 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)") + expect(run.keys == 2, "short copy: enter (model), enter (copy); got \(run.keys)") transcript("leader-short-copy-not-asked", run.text, keys: run.keys) } - static func shortCopyStillStopsWithN() { - let recorder = Recorder() - let choices = [ClusterOnboardingModelChoice(title: "Qwen3.5-9B", lines: [], blocker: nil, provision: quickOffer)] - let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), - choices: choices)) - expect(run.waitFor("Choose a model"), "short copy n: choice"); run.type("\r") - expect(run.waitFor("press n in the next 3 s to stop here"), "short copy n: the stated line"); run.type("n") - expect(run.finish() == 0, "short copy n: exit 0") - expect(run.text.contains("Nothing was copied or downloaded. Run `darkbloom cluster` here again to choose."), "short copy n: said") - expect(!recorder.all.contains { $0.hasPrefix("provision") || $0.hasPrefix("adopt") }, "short copy n: nothing moved: \(recorder.all)") + /// The list's last item stops there, and so does q. + static func shortCopyStopsFromItsList() { + for (label, key) in [("stop here", "3"), ("q", "q")] { + let recorder = Recorder() + let choices = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: [], blocker: nil, provision: quickOffer)] + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), + choices: choices)) + expect(run.waitFor(prompt(1)), "short copy, \(label): choice"); run.type("\r") + expect(run.waitFor(prompt(3)), "short copy, \(label): the list"); run.type(key) + expect(run.finish() == 0, "short copy, \(label): exit 0") + expect(run.text.contains("Nothing was copied or downloaded. Run `darkbloom cluster` here again to choose."), "short copy, \(label): said") + expect(!recorder.all.contains { $0.hasPrefix("provision") || $0.hasPrefix("adopt") }, "short copy, \(label): nothing moved: \(recorder.all)") + } } - // MARK: - One-command fixes (2026-10-14) static func deploymentWords() { @@ -1160,7 +1207,7 @@ import Darwin pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), approvalGate: gate)) expect(run.waitFor("approve the macOS prompt (once per Mac).", seconds: 3), "cable: the approval line shows while the prompt is up") gate.signal() - expect(run.waitFor("Press y if it does"), "cable: then pairing"); run.type("y") + expect(run.waitFor(codeQuestion), "cable: then pairing"); run.type("y") expect(run.finish() == 0, "cable: member done") expect(run.text.contains(" Cable found.\n") && run.text.contains(" Cable ready.\n"), "cable: plain lines") } @@ -1169,10 +1216,9 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, pairEvents: [.searching, .joining, .code("123456", peer: ["Apple M5 Ultra, 256 GB"])], pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), linkPorts: ["en5", "en6"])) - expect(run.waitFor("Two cables found: 1) en5 2) en6 [enter = 1]: "), "two cables: asked on screen") - run.type("2\r") - expect(run.waitFor("Using en6 for the cluster."), "two cables: the choice said") - expect(run.waitFor("Press y if it does"), "two cables: pairing goes on"); run.type("y") + expect(run.waitFor(" Two cables are connected. Which one goes to the other Mac?\n 1) en5\n 2) en6\n " + prompt(2)), "two cables: asked as a list") + run.type("2") + expect(run.waitFor(codeQuestion), "two cables: pairing goes on"); run.type("y") expect(run.finish() == 0, "two cables: done") expect(recorder.all.prefix(3) == ["checkLink", "useLinkPort en6", "checkLink"], "two cables: the chosen port is set up: \(recorder.all)") expect(!run.text.contains("cluster link") && !run.text.contains("--device"), "two cables: no developer command") @@ -1182,14 +1228,14 @@ import Darwin static func fittingChoicesComeFirst() { let recorder = Recorder() let choices = [ - ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · M3 Ultra 40 layers / M5 Ultra 24 layers"], blocker: nil, + ClusterOnboardingModelChoice(title: "Z.ai: GLM-5.3-Flash", lines: ["181.8 GB · tensor parallel · M3 Ultra 50% / M5 Ultra 50%"], blocker: nil, fitRemedy: "Quit apps on the other Mac (Apple M3 Ultra, 256 GB) first."), - ClusterOnboardingModelChoice(title: "Qwen3.5-9B", lines: ["6.1 GB · pipeline · M3 Ultra 16 layers / M5 Ultra 16 layers"], blocker: nil)] + ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · M3 Ultra 32 layers / M5 Ultra 32 layers"], blocker: nil)] let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: choices)) - expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "fit: the choice") - expect(run.text.contains(" 1. Qwen3.5-9B — 6.1 GB · pipeline") && run.text.contains(" 2. Qwen3.8-27B-4bit-mtp — 16.3 GB · pipeline"), "fit: the one that fits is 1") - expect(run.text.contains(" does not fit now: Quit apps on the other Mac (Apple M3 Ultra, 256 GB) first.\n"), "fit: the remedy in plain words") + expect(run.waitFor(prompt(2)), "fit: the choice") + expect(run.text.contains(" 1) Qwen3.8-27B-4bit-mtp — 16.3 GB · pipeline") && run.text.contains(" 2) Z.ai: GLM-5.3-Flash — 181.8 GB · tensor parallel"), "fit: the one that fits is 1") + expect(run.text.contains("M5 Ultra 50% · does not fit now\n"), "fit: the one that does not is marked on its line") run.type("\r") expect(run.finish() == 0, "fit: served") expect(recorder.all.contains("adopt 1") && !recorder.all.contains("adopt 0"), "fit: enter chose the fitting model: \(recorder.all)") @@ -1199,9 +1245,9 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), recheck: "Restart the other Mac (Apple M3 Ultra, 256 GB) to free memory.")) - expect(run.waitFor("Choose a model"), "recheck: choice"); run.type("\r") + expect(run.waitFor(prompt(2)), "recheck: choice"); run.type("\r") expect(run.finish() == 1, "recheck: stops at once") - expect(run.text.contains("Qwen3.5-9B does not fit in the Macs' free memory now: Restart the other Mac (Apple M3 Ultra, 256 GB) to free memory."), "recheck: the same remedy line") + expect(run.text.contains("Qwen3.8-27B-4bit-mtp does not fit in the Macs' free memory now: Restart the other Mac (Apple M3 Ultra, 256 GB) to free memory."), "recheck: the same remedy line") expect(!recorder.all.contains { $0.hasPrefix("adopt") || $0 == "serve" || $0 == "waitReady" }, "recheck: nothing adopted or started: \(recorder.all)") } @@ -1210,9 +1256,9 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), readyResult: .failure(.init(["The cluster did not report ready within 15 minutes.", "The other Mac (Apple M3 Ultra, 256 GB): its part ended: out of memory.", "This Mac: loading layers 16-31."])))) - expect(run.waitFor("Choose a model"), "timeout: choice"); run.type("\r") - expect(run.waitFor("Press d to save a diagnostics file to send to Darkbloom, enter to leave."), "timeout: one key for diagnostics") - run.type("d") + expect(run.waitFor(prompt(2)), "timeout: choice"); run.type("\r") + expect(run.waitFor(" 1) Save a diagnostics file to send to Darkbloom\n 2) Leave\n"), "timeout: one choice for diagnostics") + run.type("1") expect(run.finish() == 1, "timeout: exit 1") expect(run.text.contains("The other Mac (Apple M3 Ultra, 256 GB): its part ended: out of memory."), "timeout: each Mac's last error on screen") expect(run.text.contains("Saved a diagnostics file"), "timeout: the file is saved") @@ -1224,10 +1270,10 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), afterRestart: "After a restart or power cut, this Mac serves again once someone logs in.")) - expect(run.waitFor("Choose a model"), "restart line: choice"); run.type("\r") + expect(run.waitFor(prompt(2)), "restart line: choice"); run.type("\r") expect(run.finish() == 0, "restart line: served") - expect(run.text.contains("Nothing else is needed on the other Mac. After a restart or power cut, this Mac serves again once someone logs in.\n"), - "restart line: what happens after a restart, from the service's real state") + expect(run.text.contains("After a restart or power cut, this Mac serves again once someone logs in.\nDone. "), + "restart line: what happens after a restart, from the service's real state, before Done") } /// What happens after a restart, from the Mac's own settings (A9): never a promise a FileVault Mac cannot keep. @@ -1316,15 +1362,16 @@ import Darwin guard let directory = ProcessInfo.processInfo.environment["ONBOARDING_TRANSCRIPTS"] else { return } try? (text + "\n[keys typed: \(keys)]\n").write(toFile: directory + "/" + name + ".txt", atomically: true, encoding: .utf8) } - /// F9: a leader whose model was stopped gets the same menu as a member (m or v), not straight to the model chooser, - /// so `v` (both Macs released their memory) is reachable on whichever Mac leads after the stop. + + /// F9: a leader whose model was stopped gets the menu (choose a model, or check the memory), not straight to the + /// model chooser, so checking that both Macs released their memory is reachable after the stop. static func stoppedLeaderOffersTeardown() { let recorder = Recorder() - let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.5-9B"), + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([]))) - expect(run.waitFor("Not serving. Press m to choose a model and serve; enter to leave."), - "stopped leader: the menu with v") - run.type("v") + expect(run.waitFor(" 1) Choose a model and serve\n 2) Serve locally only (no coordinator)\n 3) Check both Macs released their memory\n 4) Quit\n"), + "stopped leader: the menu") + run.type("3") expect(run.finish() == 0, "stopped leader: teardown checked") expect(run.text.contains(" This Mac: nothing left running"), "stopped leader: each Mac's summary") expect(recorder.all == ["ensureService", "status", "verifyTeardown"], "stopped leader: status then teardown, no planning: \(recorder.all)") @@ -1358,29 +1405,26 @@ import Darwin // MARK: - `darkbloom cluster local` (owner 2026-10-15): failing first on 69ba75be7 (no scope, no request). static let localRequest = ClusterOnboardingRequest(scope: .localOnly(bind: ClusterServingScope.localOnlyDefaultBind)) + static let localReady = ClusterOnboardingReady(servedBy: "this Mac", port: 8000, - deployment: "Serving Qwen3.5-9B across both Macs: pipeline, M4 Max 16 layers / M4 Max 16 layers", + deployment: "Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, M4 Max 32 layers / M4 Max 32 layers", notice: "Serving locally only on this Mac's API: no coordinator, no public traffic", network: true) /// From scratch with `darkbloom cluster local`: the same pairing and choice, the screen says the cluster serves /// locally only, and the scope is saved after the adopt and before the start. static func localFromScratch() { let recorder = Recorder() - let run = TerminalRun(operations(recorder, pairEvents: [.searching, .waitingAsLeader, .connected, - .code("123456", peer: ["Apple M3 Ultra, 256 GB"]), .peerDecided(true)], + let run = TerminalRun(operations(recorder, pairEvents: leaderEvents, pairResult: .paired(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), readyResult: .success(localReady)), request: localRequest) - expect(run.waitFor("Does the other Mac show 123 456?"), "local from scratch: the same pairing") + expect(run.waitFor(codeQuestion), "local from scratch: the same pairing") run.type("y") - expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "local from scratch: the same choice") + expect(run.waitFor(prompt(2), count: 2), "local from scratch: the same choice") run.type("\r") expect(run.finish() == 0, "local from scratch: exit 0") let text = run.text - expect(text.contains("Options: always on (each Mac starts its part again by itself); local only: no coordinator; the API listens on this Mac's networks (LAN or tailnet) and needs its API key (`darkbloom local` shows it).\n"), - "local from scratch: the options line says local only") - expect(!text.contains("public serving through Darkbloom is off"), "local from scratch: no public-serving line") - expect(text.contains("API at http://localhost:8000 on this Mac, and at port 8000 of its LAN or tailnet address.\n"), + expect(text.contains(" API at http://localhost:8000 on this Mac, and at port 8000 of its LAN or tailnet address.\n"), "local from scratch: the API line names the network") - expect(text.contains("Serving locally only on this Mac's API: no coordinator, no public traffic.\n"), "local from scratch: the local-only line") + expect(text.contains(" Serving locally only on this Mac's API: no coordinator, no public traffic.\n"), "local from scratch: the local-only line") expect(recorder.all == ["checkLink", "pair", "answer y", "ensureService", "reachMembers", "planModels", "recheckFit 0", "adopt 0", "setScope local 0.0.0.0", "serve", "waitReady", "testRequest"], "local from scratch: scope saved after the adopt, before the start: \(recorder.all)") expect(run.keys == 2, "local from scratch: the same two keys (y, enter), got \(run.keys)") @@ -1390,10 +1434,10 @@ import Darwin /// `darkbloom cluster local` on a paired leader that is not serving: straight to the choice (the command asks to serve). static func localOnAStoppedLeader() { let recorder = Recorder() - let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.5-9B"), + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([]), readyResult: .success(localReady)), request: localRequest) - expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "local, stopped leader: goes to the choice") - run.type("2\r") + expect(run.waitFor(prompt(2)), "local, stopped leader: goes to the choice") + run.type("2") expect(run.finish() == 0, "local, stopped leader: exit 0") expect(recorder.all == ["ensureService", "reachMembers", "planModels", "recheckFit 1", "adopt 1", "setScope local 0.0.0.0", "serve", "waitReady", "testRequest"], "local, stopped leader: no menu, scope then start: \(recorder.all)") @@ -1403,132 +1447,110 @@ import Darwin /// screen waits for the leading part to serve again. static func localSwitchesAServingCluster() { let recorder = Recorder() - let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: true, modelName: "Qwen3.5-9B"), + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([]), readyResult: .success(localReady)), request: localRequest) expect(run.finish() == 0, "local switch: exit 0") let text = run.text - expect(text.contains("Serving locally only from now on (no coordinator)…\n"), "local switch: said first") - expect(text.contains(" Saved: this cluster serves locally only.\n"), "local switch: the leader's lines") - expect(text.contains("Serving locally only on this Mac's API: no coordinator, no public traffic.\n"), "local switch: ready again, local only") + expect(text.contains(ClusterServingScope.localOnly(bind: "0.0.0.0").line + ".\n"), "local switch: how it serves now") + expect(text.contains(" Serving locally only on this Mac's API: no coordinator, no public traffic.\n"), "local switch: ready again, local only") expect(recorder.all == ["ensureService", "setScope local 0.0.0.0", "waitReady"], "local switch: \(recorder.all)") expect(run.keys == 0, "local switch: no key") } - /// `darkbloom cluster local` when it already serves locally only: the ordinary menu, which says so and offers `p`. + /// `darkbloom cluster local` when it already serves locally only: the ordinary menu, whose scope item switches back. static func localAgainShowsTheMenu() { let recorder = Recorder() - var resume = ClusterOnboardingResume(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: true, modelName: "Qwen3.5-9B") + var resume = ClusterOnboardingResume(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp") resume.scope = .localOnly(bind: "0.0.0.0") let run = TerminalRun(operations(recorder, resume: resume, pairEvents: [], pairResult: .failed([])), request: localRequest) - expect(run.waitFor("This cluster serves locally only (no coordinator); press p to serve through Darkbloom instead."), "local again: the menu says it") - run.type("\r") - expect(run.finish() == 0, "local again: enter leaves it") + expect(run.waitFor(" 3) Serve through Darkbloom\n"), "local again: the menu offers the other way") + run.type("q") + expect(run.finish() == 0, "local again: q leaves it") expect(recorder.all == ["ensureService", "status"], "local again: nothing changed: \(recorder.all)") } - /// Plain `darkbloom cluster`: `l` switches a serving cluster to local only, `p` back; each waits for it to serve. + /// Plain `darkbloom cluster`: the scope item switches a serving cluster to local only and back; each waits for it + /// to serve. Stopped, it saves the scope for the next start. static func menuKeysSwitchTheScope() { let recorder = Recorder() - let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: true, modelName: "Qwen3.5-9B"), + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([]), readyResult: .success(localReady))) - expect(run.waitFor("Press l to serve locally only (no coordinator)."), "menu: the l key is offered") - run.type("l") - expect(run.finish() == 0, "menu l: exit 0") - expect(recorder.all == ["ensureService", "status", "setScope local 0.0.0.0", "waitReady"], "menu l: \(recorder.all)") + expect(run.waitFor(" 3) Serve locally only (no coordinator)\n"), "menu: local only is offered") + run.type("3") + expect(run.finish() == 0, "menu local: exit 0") + expect(recorder.all == ["ensureService", "status", "setScope local 0.0.0.0", "waitReady"], "menu local: \(recorder.all)") let back = Recorder() - var resume = ClusterOnboardingResume(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: true, modelName: "Qwen3.5-9B") + var resume = ClusterOnboardingResume(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp") resume.scope = .localOnly(bind: "0.0.0.0") let again = TerminalRun(operations(back, resume: resume, pairEvents: [], pairResult: .failed([]))) - expect(again.waitFor("press p to serve through Darkbloom instead."), "menu: the p key is offered when local only") - again.type("l") - again.type("p") - expect(again.finish() == 0, "menu p: exit 0") - expect(back.all == ["ensureService", "status", "setScope public", "waitReady"], "menu p (l ignored while local only): \(back.all)") - expect(again.text.contains("Serving through Darkbloom from now on…\n"), "menu p: said") + expect(again.waitFor(" 3) Serve through Darkbloom\n"), "menu: through Darkbloom is offered when local only") + again.type("3") + expect(again.finish() == 0, "menu public: exit 0") + expect(back.all == ["ensureService", "status", "setScope public", "waitReady"], "menu public: \(back.all)") + expect(again.text.contains(ClusterServingScope.publicServing.line + ".\n"), "menu public: said") let stopped = Recorder() - let idle = TerminalRun(operations(stopped, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.5-9B"), + let idle = TerminalRun(operations(stopped, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([]))) - expect(idle.waitFor("Press l to serve locally only (no coordinator)."), "menu, stopped: the l key is offered") - idle.type("l") - expect(idle.finish() == 0, "menu l, stopped: exit 0") - expect(stopped.all == ["ensureService", "status", "setScope local 0.0.0.0"], "menu l, stopped: saved, nothing started: \(stopped.all)") - expect(idle.text.contains("Not serving now: the next start serves this way."), "menu l, stopped: when it applies") + expect(idle.waitFor(" 2) Serve locally only (no coordinator)\n"), "menu, stopped: local only is offered") + idle.type("2") + expect(idle.finish() == 0, "menu local, stopped: exit 0") + expect(stopped.all == ["ensureService", "status", "setScope local 0.0.0.0"], "menu local, stopped: saved, nothing started: \(stopped.all)") + expect(idle.text.contains("Not serving now: the next start serves this way."), "menu local, stopped: when it applies") } - /// `darkbloom cluster local `: the named model (id or title, any case) is chosen without the list's question. + /// `darkbloom cluster local `: the named model (id or title, any case) is chosen without the list. static func localNamesTheModel() { let recorder = Recorder() var request = localRequest request.model = "qwen3.8-27b-4bit-MTP" - let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: true, modelName: "Qwen3.5-9B"), + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([]), readyResult: .success(localReady)), request: request) expect(run.finish() == 0, "named model: exit 0") - expect(run.text.contains("Chosen: Qwen3.8-27B-4bit-mtp.\n"), "named model: said") - expect(!run.text.contains("Choose a model ["), "named model: no question") - expect(recorder.all == ["ensureService", "reachMembers", "planModels", "recheckFit 1", "adopt 1", "setScope local 0.0.0.0", "serve", "waitReady", "testRequest"], + expect(!run.text.contains("Choose 1-"), "named model: no list") + expect(recorder.all == ["ensureService", "reachMembers", "planModels", "recheckFit 0", "adopt 0", "setScope local 0.0.0.0", "serve", "waitReady", "testRequest"], "named model: adopt (which stops the old one) before the scope: \(recorder.all)") let blocked = Recorder() request.model = "gpt-oss-20b" - let refused = TerminalRun(operations(blocked, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.5-9B"), + let refused = TerminalRun(operations(blocked, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([])), request: request) expect(refused.finish() == 1, "named blocked model: exit 1") - expect(refused.text.contains("gpt-oss-20b is not offered on these Macs: not granted for this pair of chips\n"), "named blocked model: why") + expect(refused.text.contains("gpt-oss-20b is not offered on these Macs: not granted for this pair of chips.\n"), "named blocked model: why") expect(blocked.all == ["ensureService", "reachMembers", "planModels"], "named blocked model: nothing adopted: \(blocked.all)") let unknown = Recorder() request.model = "no-such-model" - let asked = TerminalRun(operations(unknown, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.5-9B"), + let asked = TerminalRun(operations(unknown, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([])), request: request) - expect(asked.waitFor("No model on the list is named no-such-model; choose one by its number."), "unknown model: said") - expect(asked.waitFor("Choose a model [1-2, enter = 1]: "), "unknown model: the list asks") + expect(asked.waitFor("No model on the list is named no-such-model.\n"), "unknown model: said") + expect(asked.waitFor(prompt(2)), "unknown model: the list asks") asked.type("\r") expect(asked.finish() == 0, "unknown model: the first choice served after enter") expect(unknown.all.contains("adopt 0"), "unknown model: the typed choice is adopted: \(unknown.all)") } - /// Shorter screens (owner, 2026-10-15): models held back for the same reason share one line, reasons in list order. - static func notOfferedGroupedByReason() { - let builds = "the two Macs run different Darkbloom builds; install the same Darkbloom on both" - let grouped = [choices[0], - ClusterOnboardingModelChoice(title: "gemma-4-26b-qat-4bit", lines: [], blocker: builds), - ClusterOnboardingModelChoice(title: "Bonsai", lines: [], blocker: "not supported on a cluster yet"), - ClusterOnboardingModelChoice(title: "gpt-oss-20b", lines: [], blocker: builds)] - let recorder = Recorder() - let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M4 Max, 128 GB", serving: false), - pairEvents: [], pairResult: .failed([]), choices: grouped)) - expect(run.waitFor("Choose a model [1-1, enter = 1]: "), "grouped: the one open choice") - let text = run.text - expect(text.contains(" Not offered:\n gemma-4-26b-qat-4bit, gpt-oss-20b: \(builds)\n Bonsai: not supported on a cluster yet\n"), - "grouped: one line per reason, in list order: \(text)") - run.type("\r") - expect(run.finish() == 0, "grouped: the open choice still serves") - } - - /// A Mac that joins with `darkbloom cluster local` (a model named too) stops once paired, as a plain join does (step - /// 3: nothing else is asked there): the Mac that leads chooses the model and how the cluster serves, and the screen - /// says to run the command there. 2026-10-25: the joining Mac showed its own model list while the leading Mac showed - /// the same list. + /// A Mac that joins with `darkbloom cluster local` (a model named too) stops once paired, as a plain join does: + /// the Mac that leads chooses the model and how the cluster serves, and the screen says to run the command there. + /// 2026-10-25: the joining Mac showed its own model list while the leading Mac showed the same list. static func memberJoinsWithLocal() { var named = localRequest named.model = "EigenLabs/GLM-5.3-Flash-MLX-NVFP4-mtp" for request in [localRequest, named] { let recorder = Recorder() - let run = TerminalRun(operations(recorder, pairEvents: [.searching, .joining, .connected, - .code("123456", peer: ["Apple M5 Ultra, 256 GB"]), .peerDecided(true)], + let run = TerminalRun(operations(recorder, pairEvents: memberEvents, pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB")), request: request) let label = request.model == nil ? "member local" : "member local with a model" - expect(run.waitFor("Press y if it does"), "\(label): the code question") + expect(run.waitFor(codeQuestion), "\(label): the code question") run.type("y") expect(run.finish() == 0, "\(label): exit 0 once paired") let text = run.text - expect(text.contains("Paired with the other Mac (Apple M5 Ultra, 256 GB). Continue on the other Mac.\n"), "\(label): where to continue") - expect(text.contains(ClusterOnboardingDriver.localNetworkLine + "\n" + ClusterOnboardingDriver.joinedLocalLine + "\n" - + ClusterOnboardingDriver.joinedLine + "\n"), "\(label): where `local` counts, then the end: \(text)") - expect(text.hasSuffix(ClusterOnboardingDriver.joinedLine + "\n"), "\(label): the last line") - expect(!text.contains("3 / 5") && !text.contains("Choose a model") && !text.contains("Cluster status"), + expect(text.hasSuffix("Done on this Mac. " + ClusterOnboardingDriver.closeWindowLine + "\n" + ClusterOnboardingDriver.joinedLocalContinueLine + "\n"), + "\(label): one line for the other Mac, `local` in it, last: \(text)") + expect(!text.contains(ClusterOnboardingDriver.joinedLine) && !text.contains(ClusterOnboardingDriver.joinedLocalLine), + "\(label): no second instruction for the other Mac") + expect(!text.contains("3 / 4") && !text.contains("Choose a model") && !text.contains("Test a response"), "\(label): no model list and no menu on the Mac that joined") expect(recorder.all == ["checkLink", "pair", "answer y", "ensureService"], "\(label): nothing after its service: \(recorder.all)") expect(run.keys == 1, "\(label): one key (y), got \(run.keys)") @@ -1559,10 +1581,8 @@ import Darwin let identical = [ClusterOnboardingMachine(name: "Apple M5 Ultra, 256 GB", memoryGB: 256, gpuCores: 80, leads: true, models: 2), ClusterOnboardingMachine(name: "Apple M5 Ultra, 256 GB", memoryGB: 256, gpuCores: 80, leads: false, models: 2)] - expect(identical[0].line(inPair: true) == " Apple M5 Ultra, 256 GB · 256 GB · 80-core GPU · 2 models · leads (this Mac)", "machine: this Mac") - expect(identical[1].line(inPair: true) == " Apple M5 Ultra, 256 GB · 256 GB · 80-core GPU · 2 models · member (the other Mac)", - "machine: the other Mac") - expect(identical[1].line(inPair: false) == " Apple M5 Ultra, 256 GB · 256 GB · 80-core GPU · 2 models · member", "machine: no 'other' among three") + expect(ClusterOnboardingDriver.machinesLine(identical) == "This Mac: Apple M5 Ultra, 256 GB \u{00B7} the other Mac: Apple M5 Ultra, 256 GB", + "machines: both in one line, each said which") typealias D = ClusterOnboardingDeployment let tp = [D.Share(name: "Apple M5 Ultra, 256 GB", layers: 78, weightsBytes: 91, label: N.other), @@ -1580,24 +1600,19 @@ import Darwin let recorder = Recorder() let run = TerminalRun(identicalOperations(recorder)) - expect(run.waitFor("Does the other Mac show 123 456?"), "identical: the code question") + expect(run.waitFor(codeQuestion), "identical: the code question") run.type("y") - expect(run.waitFor("Choose a model [1-1, enter = 1]: "), "identical: the model choice") + expect(run.waitFor(prompt(1)), "identical: the model choice") run.type("\r") - expect(run.waitFor("press n to stop here."), "identical: the timed start") - run.type("y") expect(run.finish() == 0, "identical: exit 0") let text = run.text for line in [ - "Paired with the other Mac (Apple M5 Ultra, 256 GB). This Mac leads the cluster.", - " The other Mac (Apple M5 Ultra, 256 GB) answered over the cable in 4.0 s.", - " Apple M5 Ultra, 256 GB · 256 GB · 80-core GPU · 2 models · leads (this Mac)", - " Apple M5 Ultra, 256 GB · 256 GB · 80-core GPU · 2 models · member (the other Mac)", - " 1. Z.ai: GLM-5.3-Flash — 181.8 GB · tensor parallel · the other Mac 50% / this Mac 50%", - " Started the other Mac's part over the cable (its cluster service runs it); this Mac's service runs its own.", - "Serving Z.ai: GLM-5.3-Flash across both Macs: tensor parallel, the other Mac 50% / this Mac 50%.", - "API at http://localhost:8000 on the other Mac (Apple M5 Ultra, 256 GB).", - "Serving locally only on that Mac's API: no coordinator, no public traffic.", + " \u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). This Mac leads.", + " This Mac: Apple M5 Ultra, 256 GB \u{00B7} the other Mac: Apple M5 Ultra, 256 GB", + " 1) Z.ai: GLM-5.3-Flash — 181.8 GB · tensor parallel · this Mac 50% / the other Mac 50%", + " Serving Z.ai: GLM-5.3-Flash across both Macs: tensor parallel, this Mac 50% / the other Mac 50%.", + " API at http://localhost:8000 on this Mac.", + " Serving locally only on this Mac's API: no coordinator, no public traffic.", ] { expect(text.contains(line + "\n"), "identical: \(line)") } @@ -1606,59 +1621,66 @@ import Darwin let lower = line.lowercased() expect(lower.contains("this mac") || lower.contains("the other mac"), "identical: the line says which Mac: \(line)") } - expect(!text.contains("Not offered"), "identical: one line for the one model") transcript("leader-identical-macs", text, keys: run.keys) } - /// Two identical Macs as the live operations name them on the leading Mac (ONB-B47's screen, with the API on the - /// other Mac and the cluster serving locally only). + /// Two identical Macs as the live operations name them on the leading Mac (ONB-B47's screen, serving locally only), + /// with rank 0 and so the API on this Mac, which leads. static func identicalOperations(_ recorder: Recorder) -> ClusterOnboardingOperations { let mac = "Apple M5 Ultra, 256 GB" let identical = [ClusterOnboardingMachine(name: mac, memoryGB: 256, gpuCores: 80, leads: true, models: 2), ClusterOnboardingMachine(name: mac, memoryGB: 256, gpuCores: 80, leads: false, models: 2)] - let glm = ClusterOnboardingModelChoice(title: "Z.ai: GLM-5.3-Flash", lines: ["181.8 GB · tensor parallel · the other Mac 50% / this Mac 50%", + let glm = ClusterOnboardingModelChoice(title: "Z.ai: GLM-5.3-Flash", lines: ["181.8 GB · tensor parallel · this Mac 50% / the other Mac 50%", "Tensor parallel: the model fits, so both Macs share every layer of every token."], blocker: nil, - modelID: "EigenLabs/GLM-5.3-Flash-MLX-NVFP4-mtp") + modelID: "EigenLabs/GLM-5.3-Flash-MLX-NVFP4-mtp", validated: true) return operations(recorder, pairEvents: [.searching, .waitingAsLeader, .connected, .code("123456", peer: [mac, "Mac17,15, macOS 27.0.1; SIP on, Secure Boot full, sealed system volume"]), .peerDecided(true)], - pairResult: .paired(role: .leader, peerName: mac), choices: [glm], machines: identical, answeredSeconds: "4.0", - readyResult: .success(.init(servedBy: ClusterOnboardingMacName.other(named: mac), port: 8000, - deployment: "Serving Z.ai: GLM-5.3-Flash across both Macs: tensor parallel, the other Mac 50% / this Mac 50%", + pairResult: .paired(role: .leader, peerName: mac), choices: [glm], machines: identical, + readyResult: .success(.init(servedBy: ClusterOnboardingMacName.this, port: 8000, + deployment: "Serving Z.ai: GLM-5.3-Flash across both Macs: tensor parallel, this Mac 50% / the other Mac 50%", notice: "Serving locally only on this Mac's API: no coordinator, no public traffic", network: false))) } /// The new lines under every plain presentation: NO_COLOR, TERM=dumb and redirected input and output print the same - /// plain transcript, byte for byte; a colour window too narrow for the mark and meter (30 columns) reads the same - /// once its heading colour is set aside. No terminal escape in a plain transcript, and no credential, host name, - /// address or SSH in any of them. + /// plain transcript, byte for byte; a colour window too narrow for the mark and meter (30 columns) says every line + /// of it but the choices' (a list moved with the arrows there), in order. No terminal escape in a plain transcript, + /// and no credential, host name, address or SSH in any of them. static func plainPresentationsKeepTheNewLines() { struct Flow { let name: String; let operations: (Recorder) -> ClusterOnboardingOperations; let request: ClusterOnboardingRequest; let keys: [(String, String)] } let flows = [ Flow(name: "identical Macs", operations: identicalOperations, request: .init(), - keys: [("Does the other Mac show 123 456?", "y"), ("Choose a model [1-1, enter = 1]: ", "\r"), ("press n to stop here.", "y")]), - Flow(name: "member with local", operations: { recorder in operations(recorder, pairEvents: [.searching, .joining, .connected, - .code("123456", peer: ["Apple M5 Ultra, 256 GB"]), .peerDecided(true)], pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB")) }, - request: localRequest, keys: [("Press y if it does", "y")]), + keys: [(codeQuestion, "y"), ("3 / 4 Choose a model", "\r")]), + Flow(name: "member with local", operations: { recorder in operations(recorder, pairEvents: memberEvents, + pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB")) }, + request: localRequest, keys: [(codeQuestion, "y")]), ] for flow in flows { var plain = [String: String]() for (presentation, environment) in [("NO_COLOR", ["NO_COLOR": "1", "TERM": "xterm-256color"]), ("TERM=dumb", ["TERM": "dumb"])] { let run = TerminalRun(flow.operations(Recorder()), request: flow.request, environment: environment) - for (needle, key) in flow.keys { expect(run.waitFor(needle), "\(flow.name), \(presentation): \(needle)"); run.type(key) } + for (needle, key) in flow.keys { expect(run.waitFor(needle), "\(flow.name), \(presentation): \(needle)"); usleep(50_000); run.type(key) } expect(run.finish() == 0, "\(flow.name), \(presentation): exit 0") plain[presentation] = run.text } let piped = PipeRun(flow.operations(Recorder()), request: flow.request, environment: ["TERM": "xterm-256color", "LANG": "en_US.UTF-8"]) - for (needle, key) in flow.keys { expect(piped.waitFor(needle), "\(flow.name), pipes: \(needle)"); piped.type(key) } + for (needle, key) in flow.keys { expect(piped.waitFor(needle), "\(flow.name), pipes: \(needle)"); usleep(50_000); piped.type(key) } expect(piped.finish() == 0, "\(flow.name), pipes: exit 0") plain["pipes"] = piped.text let narrow = TerminalRun(flow.operations(Recorder()), request: flow.request, environment: ["TERM": "xterm-256color", "LANG": "en_US.UTF-8"], columns: 30) - for (needle, key) in flow.keys { expect(narrow.waitFor(needle), "\(flow.name), 30 columns: \(needle)"); narrow.type(key) } + for (needle, key) in flow.keys { expect(narrow.waitFor(needle), "\(flow.name), 30 columns: \(needle)"); usleep(50_000); narrow.type(key) } expect(narrow.finish() == 0, "\(flow.name), 30 columns: exit 0") let reference = plain["NO_COLOR"] ?? "" expect(!reference.isEmpty && plain.values.allSatisfy { $0 == reference }, "\(flow.name): one plain transcript, byte for byte: \(plain.keys.sorted())") - expect(visible(narrow.text) == visible(reference), "\(flow.name), 30 columns: the same lines once the heading colour is set aside") + // The narrow window's lines are the plain transcript's, in order, but for the choices. + let said = visible(reference).filter { !$0.isEmpty && !$0.contains("Choose 1-") && $0.range(of: #"^ \d\) "#, options: .regularExpression) == nil } + var lines = visible(narrow.text)[...] + let missing = said.first { line in + guard let at = lines.firstIndex(of: line) else { return true } + lines = lines[(at + 1)...] + return false + } + expect(missing == nil, "\(flow.name), 30 columns: every said line of the plain transcript, in order; missing \(missing ?? "")") for (presentation, text) in plain.merging(["30 columns": visible(narrow.text).joined(separator: "\n")], uniquingKeysWith: { first, _ in first }) { if presentation != "30 columns" { expect(!text.contains("\u{1B}"), "\(flow.name), \(presentation): no terminal escape") } let lower = text.lowercased() @@ -1681,13 +1703,13 @@ import Darwin blocker: nil, modelID: "gemma-4-26b")] let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Max, 128 GB"), pairEvents: [], pairResult: .failed([]), choices: twins), request: localRequest) - expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "twins: the list") - expect(run.text.contains(" 1. Gemma 4 26B (gemma-4-26b-qat-4bit) — 15.6 GB · pipeline") && run.text.contains(" 2. Gemma 4 26B (gemma-4-26b) — 28.0 GB"), + expect(run.waitFor(prompt(2)), "twins: the list") + expect(run.text.contains(" 1) Gemma 4 26B (gemma-4-26b-qat-4bit) — 15.6 GB · pipeline") && run.text.contains(" 2) Gemma 4 26B (gemma-4-26b) — 28.0 GB"), "twins: each names its id: \(run.text)") run.type("\r") - expect(run.waitFor(" Pipeline: this model has no tensor-parallel plan.\n"), "twins: the reason once chosen") expect(run.finish() == 0, "twins: served") - expect(!run.text.contains("qualified for public traffic"), "twins: no public-traffic line when serving locally only") + expect(!run.text.contains("qualified for public traffic") && !run.text.contains("Pipeline: this model has no tensor-parallel plan."), + "twins: the list's line is what is said about a model") } /// Why not tensor parallel, at the end of the model's one line (owner, 2026-10-15: one line per model): a few words @@ -1710,7 +1732,7 @@ import Darwin expect(line("tensor parallel: \u{1B}[2J") == "m — a", "TP note: a note with terminal control characters is not said") expect(line(nil) == "m — a" && line("") == "m — a", "TP note: no note, nothing added") let older = try? JSONDecoder().decode(C.self, from: Data(#"{"title":"m","lines":["a"]}"#.utf8)) - expect(older != nil && older?.tensorParallelNote == nil, "TP note: an older Mac's choice decodes without it") + expect(older != nil && older?.tensorParallelNote == nil && older?.validated == nil, "TP note: an older Mac's choice decodes without it") let listed = [ C(title: "Qwen3.5-9B", lines: ["6.1 GB · pipeline · M3 Ultra 16 layers / M5 Max 16 layers · about 92 tokens/s", "Pipeline: tensor parallel is predicted slower for requests of 1024 prompt and 256 answer tokens."], blocker: nil, @@ -1725,22 +1747,17 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Max, 128 GB"), pairEvents: [], pairResult: .failed([]), choices: listed), columns: 40) - expect(run.waitFor("Choose a model [1-4, enter = 1]: "), "TP note: the list") + expect(run.waitFor(prompt(4)), "TP note: the list") let text = run.text - expect(text.contains(" 1. Qwen3.5-9B — 6.1 GB · pipeline · M3 Ultra 16 layers / M5 Max 16 layers · about 92 tokens/s" - + " · tensor parallel: slower here\n 2. Qwen3.8-27B — "), "TP note: at the end of the line it is about: \(text)") - expect(text.contains("about 41 tokens/s\n 3. Bonsai 27B — 7.2 GB · pipeline · M3 Ultra 4 layers / M5 Max 60 layers\n" - + " does not fit now: Quit apps on the other Mac (Apple M5 Max, 128 GB) first.\n 4. Qwen3.6-35B-A3B — "), + expect(text.contains(" 1) Qwen3.5-9B — 6.1 GB · pipeline · M3 Ultra 16 layers / M5 Max 16 layers · about 92 tokens/s" + + " · tensor parallel: slower here\n 2) Qwen3.8-27B — "), "TP note: at the end of the line it is about: \(text)") + expect(text.contains("about 41 tokens/s\n 3) Bonsai 27B — 7.2 GB · pipeline · M3 Ultra 4 layers / M5 Max 60 layers · does not fit now\n 4) Qwen3.6-35B-A3B — "), "TP note: none for tensor parallel chosen or a model without it: \(text)") - expect(text.contains("M5 Max 36 layers · tensor parallel: does not fit now\n does not fit now: Quit apps on the other Mac (Apple M5 Max, 128 GB) first.\n"), - "TP note: on the line, before the fit remedy: \(text)") + expect(text.contains("M5 Max 36 layers · tensor parallel: does not fit now · does not fit now\n"), + "TP note: on the line, before the fit mark: \(text)") expect(!text.contains("Tensor parallel: pipeline is left out") && !text.contains("Pipeline: tensor parallel is predicted slower"), - "TP note: the full reasons wait until a model is chosen") - let rows = visible(text).filter { $0.hasPrefix(" tensor parallel:") || $0.hasPrefix(" no tensor parallel") } - expect(rows.isEmpty, "TP note: no row of its own (one line per model): \(rows)") + "TP note: the planner's full reasons are not said") run.type("\r") - expect(run.waitFor(" Pipeline: tensor parallel is predicted slower for requests of 1024 prompt and 256 answer tokens.\n"), - "TP note: the planner's reason once chosen") expect(run.finish() == 0, "TP note: served") } @@ -1783,4 +1800,270 @@ import Darwin let older = try? JSONDecoder().decode(ClusterOnboardingReady.self, from: Data(#"{"servedBy":"this Mac","port":8000}"#.utf8)) expect(older?.network == nil, "ready: an older Mac's answer decodes without the network field") } + + /// The four steps, in order. + static let stages = ["1 / 4 Connect", "2 / 4 Pair", "3 / 4 Choose a model", "4 / 4 Start"] + + static let codeQuestion = ClusterOnboardingPairing.codeQuestion + + /// The list's keys on a colour UTF-8 terminal. + /// An arrow pressed while the setup waits (here for Allow) is no key: only q or a lone escape stops a wait. + static func arrowKeysDoNotStopAWait() { + let states = Recorder() + let network: @Sendable (ClusterOnboardingLocalNetworkSubject) -> ClusterOnboardingLocalNetwork = { subject in + guard subject == .thisCommand else { return .allowed } + states.note("command") + return states.all.count > 3 ? .allowed : .blocked + } + let run = TerminalRun(operations(Recorder(), pairEvents: [], pairResult: .failed([]), localNetwork: network)) + expect(run.waitFor("click Allow."), "arrow in a wait: the prompt line") + run.type("\u{1B}[A") + run.type("\u{1B}[B") + expect(run.waitFor(" \u{2713} Local network allowed for Terminal.\n"), "arrow in a wait: still waiting, then allowed") + _ = run.finish() + expect(!run.text.contains("still off"), "arrow in a wait: not stopped: \(run.text)") + } + + /// q cancels a list even where an option starts with q (2026-11-02: q took "Qwen3.8 27B"). + static func qCancelsAListBeforeALetter() { + let qwen = [ClusterOnboardingModelChoice(title: "Qwen3.8 27B", lines: ["16.3 GB · tensor parallel"], blocker: nil, validated: true), + ClusterOnboardingModelChoice(title: "Z.ai: GLM-5.3-Flash", lines: ["181.8 GB · tensor parallel"], blocker: nil, validated: true)] + for (label, environment) in [("plain", ["NO_COLOR": "1"]), ("colour", ["TERM": "xterm-256color", "LANG": "en_US.UTF-8", "DARKBLOOM_NO_ANIMATION": "1"])] { + let recorder = Recorder() + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), choices: qwen), environment: environment) + expect(run.waitFor("Qwen3.8 27B"), "q, \(label): the list") + run.type("q") + expect(run.finish() == 0, "q, \(label): exit 0") + expect(run.text.contains("Nothing was changed. Run `darkbloom cluster` again to choose."), "q, \(label): cancelled") + expect(!recorder.all.contains { $0.hasPrefix("adopt") || $0.hasPrefix("recheckFit") }, "q, \(label): nothing chosen: \(recorder.all)") + } + } + + /// Over SSH the prompts are on the Mac's own screen: the lines say so, and name the program macOS shows. + static func sshSessionsAreToldWhereThePromptIs() { + let states = Recorder() + let network: @Sendable (ClusterOnboardingLocalNetworkSubject) -> ClusterOnboardingLocalNetwork = { subject in + guard subject == .thisCommand else { return .allowed } + states.note("command") + return states.all.count > 2 ? .allowed : .blocked + } + let run = TerminalRun(operations(Recorder(), pairEvents: [], pairResult: .failed([]), localNetwork: network, remote: true, + commandApp: "sshd-keygen-wrapper")) + expect(run.waitFor(" " + ClusterOnboardingDriver.approvalsLine(remote: true) + "\n"), "SSH: the approvals, where each is answered") + expect(run.waitFor(" macOS asks on this Mac's own screen (use Screen Sharing if it has no display) to let sshd-keygen-wrapper find devices on your local network: click Allow.\n"), + "SSH: the prompt is on the Mac's screen, and the program macOS names") + expect(run.waitFor(" \u{2713} Local network allowed for sshd-keygen-wrapper.\n"), "SSH: allowed") + _ = run.finish() + } + + /// A service that does not report its probe (an older build) still gets the prompt's line, as an "if". + static func serviceThatCannotTellStillGetsTheAsk() { + let recorder = Recorder() + let run = TerminalRun(operations(recorder, pairEvents: memberEvents, pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), + localNetwork: { $0 == .service ? .unknown : .allowed })) + expect(run.waitFor(codeQuestion), "unknown: the code"); run.type("y") + expect(run.finish(seconds: 30) == 0, "unknown: the member's setup ends") + expect(run.text.contains(" " + ClusterOnboardingDriver.localNetworkMaybeLine("Darkbloom") + " " + ClusterOnboardingDriver.otherMacAllowLine + "\n"), + "unknown: the prompt's line as an if: \(run.text)") + expect(run.text.contains("Done on this Mac."), "unknown: nothing to wait for") + } + + /// The leader reads both Macs once paired; the other Mac's service may still wait for its Allow: a list to try + /// again instead of an end. + static func otherMacThatDidNotAnswerOffersTryAgain() { + let recorder = Recorder() + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), reachFailures: 1)) + expect(run.waitFor("The other Mac did not answer over the cable.\n"), "try again: what happened") + expect(run.waitFor("1) Try again\n 2) Stop here\n"), "try again: the list") + run.type("\r") + expect(run.waitFor(prompt(2), count: 2), "try again: then the model list") + run.type("\r") + expect(run.finish() == 0, "try again: served") + expect(recorder.all.filter { $0 == "reachMembers" }.count == 2, "try again: read twice: \(recorder.all)") + } + + /// The setup's last word says how the pair serves: through Darkbloom (it earns), or locally (its notice says it). + /// The chosen model's public-traffic line is said at the choice. + static func startSaysHowThePairServes() { + let qualified = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers"], + blocker: nil, publicTraffic: "qualified for public traffic in pipeline mode", validated: true)] + let recorder = Recorder() + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), choices: qualified)) + expect(run.waitFor(prompt(1)), "serves: the list"); run.type("\r") + expect(run.finish() == 0, "serves: exit 0") + let text = run.text + expect(text.contains(" Qualified for public traffic in pipeline mode.\n"), "serves: the public-traffic line at the choice: \(text)") + expect(text.contains("\n" + ClusterOnboardingDriver.earnsLine + "\n"), "serves: through Darkbloom, said at the end") + let local = TerminalRun(operations(Recorder(), resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), choices: qualified, readyResult: .success(localReady)), request: localRequest) + expect(local.waitFor(prompt(1)), "serves locally: the list"); local.type("\r") + expect(local.finish() == 0, "serves locally: exit 0") + expect(!local.text.contains("public traffic in pipeline mode") && !local.text.contains(ClusterOnboardingDriver.earnsLine), + "serves locally: neither line; the notice says how it serves: \(local.text)") + } + + static let arrowHint = "\u{2191}\u{2193} move \u{00B7} enter select \u{00B7} q cancel" + + /// A plain transcript's choice prompt. + static func prompt(_ count: Int, enter: Int = 1) -> String { "Choose 1-\(count) (enter = \(enter)): " } + + /// The leader's pairing: nobody waits on the cable, the other Mac joins, both confirm the code. + static let leaderEvents: [ClusterOnboardingPairEvent] = [.searching, .waitingAsLeader, .connected, + .code("123456", peer: ["Apple M3 Ultra, 256 GB"]), .peerDecided(true)] + + static let memberEvents: [ClusterOnboardingPairEvent] = [.searching, .joining, .connected, + .code("123456", peer: ["Apple M5 Ultra, 256 GB"]), .peerDecided(true)] + + /// A development build's service lives only as long as its window: both screens say to keep it open. + static func developmentBuildKeepsTheWindowsOpen() { + let member = Recorder() + let joined = TerminalRun(operations(member, pairEvents: memberEvents, + pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), outlivesWindow: false)) + expect(joined.waitFor(codeQuestion), "dev member: the code question"); joined.type("y") + expect(joined.finish() == 0, "dev member: exit 0") + expect(joined.text.contains("Done on this Mac. " + ClusterOnboardingDriver.keepWindowLine + "\n"), "dev member: keep the window open") + let leader = Recorder() + let led = TerminalRun(operations(leader, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), outlivesWindow: false)) + expect(led.waitFor(prompt(2)), "dev leader: the list"); led.type("\r") + expect(led.finish() == 0, "dev leader: exit 0") + expect(led.text.contains("Done. Keep this window and the other Mac's open: this development build serves only while they stay open.\n"), + "dev leader: keep both windows open") + } + + /// The code's list ends by itself when the pairing does meanwhile (the other Mac declined): no answer is waited for. + static func codeListEndsWhenThePairingDoes() { + let recorder = Recorder() + let run = TerminalRun(operations(recorder, pairEvents: [.searching, .joining, .code("123456", peer: ["Apple M5 Ultra, 256 GB"])], + pairResult: .failed(["The other Mac declined the code."]))) + expect(run.waitFor(codeQuestion), "ended: the code shown") + expect(run.finish(seconds: 15) == 1, "ended: exit 1 with no key") + expect(run.text.contains("The other Mac declined the code.") && run.text.contains("Run `darkbloom cluster` again to try again."), + "ended: the pairing's own reason") + expect(run.keys == 0, "ended: no key typed") + } + + /// 2026-11-02: macOS could not show its password window (an SSH session), and the setup said to run a script by + /// hand. Now the same commands run with sudo right there, and the setup goes on; only a failed sudo names the script. + static func cablePortSetUpWithSudoWhereNoPromptShows() { + let recorder = Recorder() + let run = TerminalRun(operations(recorder, pairEvents: memberEvents, + pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), linkScript: "~/.darkbloom/cluster-device/link-fix.sh")) + expect(run.waitFor(" macOS could not show its password window here. Type this Mac's password for sudo to set up the cable's port:\n"), + "sudo: said before sudo asks") + expect(run.waitFor(codeQuestion), "sudo: then the cable is ready and pairing goes on"); run.type("y") + expect(run.finish() == 0, "sudo: member done") + expect(recorder.all.prefix(3) == ["checkLink", "runAsAdministrator", "checkLink"], "sudo: the script, then the cable again: \(recorder.all)") + expect(!run.text.contains("sudo sh"), "sudo: no script to run by hand") + transcript("cable-port-with-sudo", run.text, keys: run.keys) + + let failed = Recorder() + let refused = TerminalRun(operations(failed, pairEvents: [], pairResult: .failed([]), + linkScript: "~/.darkbloom/cluster-device/link-fix.sh", sudoSucceeds: false)) + expect(refused.finish() == 1, "sudo failed: stops") + expect(refused.text.contains("The cable's port was not set up. Run `darkbloom cluster` again, or run: sudo sh ~/.darkbloom/cluster-device/link-fix.sh\n"), + "sudo failed: what to do, the script last") + expect(!failed.all.contains("pair"), "sudo failed: no pairing") + } + + /// 2026-11-02: macOS's Local Network prompts came out of sync, on the other Mac's turn. This command's is asked in + /// Connect and Darkbloom's right after pairing, each with what to click, and the setup waits for the answer. + static func localNetworkAskedAtStatedMoments() { + let states = Recorder() + // Each subject is refused twice (macOS's prompt is up), then allowed. + let network: @Sendable (ClusterOnboardingLocalNetworkSubject) -> ClusterOnboardingLocalNetwork = { subject in + let name = subject == .service ? "service" : "command" + states.note(name) + return states.all.filter { $0 == name }.count > 2 ? .allowed : .blocked + } + let recorder = Recorder() + let run = TerminalRun(operations(recorder, pairEvents: memberEvents, + pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), localNetwork: network)) + expect(run.waitFor(" macOS asks to let Terminal find devices on your local network: click Allow.\n"), "local network: this command's prompt, in Connect") + expect(run.waitFor(" \u{2713} Local network allowed for Terminal.\n"), "local network: allowed, then pairing") + expect(run.waitFor(codeQuestion), "local network: the code"); run.type("y") + expect(run.waitFor(" macOS asks to let Darkbloom find devices on your local network: click Allow. " + ClusterOnboardingDriver.otherMacAllowLine + "\n"), + "local network: Darkbloom's, once paired, the other Mac's said too") + expect(run.finish(seconds: 20) == 0, "local network: member done") + let text = run.text + let order = ["1 / 4 Connect", "click Allow.", "Local network allowed for Terminal.", "2 / 4 Pair", "Paired with", "Darkbloom find devices", + "Local network allowed for Darkbloom.", "Done on this Mac."].compactMap { text.range(of: $0)?.lowerBound } + expect(order.count == 8 && order == order.sorted(), "local network: asked in order, each before the next step: \(text)") + transcript("member-local-network-prompts", text, keys: run.keys) + + // Refused and left so: q stops with where to turn it on. + let blocked = TerminalRun(operations(Recorder(), pairEvents: [], pairResult: .failed([]), localNetwork: { _ in .blocked })) + expect(blocked.waitFor("click Allow."), "refused: the prompt line") + blocked.type("q") + expect(blocked.finish() == 1, "refused: stops") + expect(blocked.text.hasSuffix("Turn it on in System Settings → Privacy & Security → Local Network, then run `darkbloom cluster` again.\n"), + "refused: where to turn it on, last") + } + + /// `darkbloom cluster local` on a member: it takes effect on the Mac that leads, so the screen says so and nothing runs. + static func memberLocalPointsToTheLeader() { + let recorder = Recorder() + let run = TerminalRun(operations(recorder, resume: memberResume(), pairEvents: [], pairResult: .failed([])), request: localRequest) + expect(run.finish() == 1, "member local: exit 1") + expect(run.text.hasSuffix(ClusterOnboardingDriver.joinedLocalLine + "\n"), "member local: where to run it") + expect(recorder.all == ["ensureService", "status"], "member local: nothing changed: \(recorder.all)") + } + + /// The leader's list moved with the arrows: ↓ twice then enter takes the third item, the list folds to it. + static func arrowKeysTakeAMenuItem() { + let recorder = Recorder() + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), + pairEvents: [], pairResult: .failed([]), readyResult: .success(localReady)), + environment: ["TERM": "xterm-256color", "LANG": "en_US.UTF-8", "DARKBLOOM_NO_ANIMATION": "1"]) + expect(run.waitFor(arrowHint), "arrows: the list") + run.type("\u{1B}[B") + expect(run.waitFor("\u{25B8}\u{1B}[0m \u{1B}[1mChange model", seconds: 5), "arrows: ↓ moves the ▸ to the second item") + run.type("\u{1B}[B") + expect(run.waitFor("\u{25B8}\u{1B}[0m \u{1B}[1mServe locally only", seconds: 5), "arrows: and to the third") + run.type("\r") + expect(run.finish() == 0, "arrows: exit 0") + expect(visible(run.text).contains(" \u{25B8} Serve locally only (no coordinator)"), "arrows: the list folds to the item taken") + expect(recorder.all == ["ensureService", "status", "setScope local 0.0.0.0", "waitReady"], "arrows: the third item ran: \(recorder.all)") + transcript("leader-again-arrows", run.text, keys: run.keys) + } + + /// 2026-11-02: "only allow ones that are allowed to cluster serve and validated". A model the owner has not + /// approved for clusters is not listed, and is refused by name; a list with none approved says so. + static func onlyApprovedModelsAreListed() { + typealias C = ClusterOnboardingModelChoice + let mixed = [ + C(title: "Qwen 3.5 9B", lines: ["6.1 GB · pipeline"], blocker: nil, modelID: "Qwen3.5-9B", validated: false), + C(title: "Z.ai: GLM-5.3-Flash", lines: ["181.8 GB · tensor parallel"], blocker: nil, modelID: "glm-5.3-flash", validated: true), + C(title: "Qwen3.8 27B", lines: ["16.3 GB · tensor parallel"], blocker: nil, modelID: "EigenLabs/Qwen3.8-27B-4bit-mtp", validated: true), + C(title: "Gemma 4 26B", lines: [], blocker: "too large for this pair", modelID: "gemma-4-26b", validated: false)] + expect(mixed.map(\.listed) == [false, true, true, false], "approved: listed only when approved and servable") + expect(C(title: "m", lines: [], blocker: nil).listed, "approved: an older leader's choice (no word) is listed") + let recorder = Recorder() + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), + choices: mixed)) + expect(run.waitFor(prompt(2)), "approved: the list of two") + let text = run.text + expect(text.contains(" 1) Z.ai: GLM-5.3-Flash — 181.8 GB · tensor parallel\n 2) Qwen3.8 27B — 16.3 GB · tensor parallel\n"), + "approved: only the approved models: \(text)") + expect(!text.contains("Qwen 3.5 9B") && !text.contains("Gemma"), "approved: nothing else, not even as not offered") + run.type("2") + expect(run.finish() == 0, "approved: served") + expect(recorder.all.contains("adopt 2"), "approved: the list's second line is choice 2: \(recorder.all)") + + var named = localRequest + named.model = "Qwen3.5-9B" + let refused = TerminalRun(operations(Recorder(), resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "glm-5.3-flash"), + pairEvents: [], pairResult: .failed([]), choices: mixed), request: named) + expect(refused.finish() == 1, "approved: a named unapproved model is refused") + expect(refused.text.contains("Qwen 3.5 9B is not approved for clusters yet.\n"), "approved: why") + + let none = TerminalRun(operations(Recorder(), resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), + choices: [mixed[0], mixed[3]])) + expect(none.finish() == 1, "approved: none approved stops") + expect(none.text.contains("No model approved for clusters can run on these two Macs now.\n"), "approved: said") + expect(!none.text.contains("Qwen 3.5 9B"), "approved: an unapproved model is not named among the reasons") + } } diff --git a/provider-swift/Tests/DarkbloomCLITests/DoctorClusterChecksTests.swift b/provider-swift/Tests/DarkbloomCLITests/DoctorClusterChecksTests.swift new file mode 100644 index 0000000000..4228ad640f --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/DoctorClusterChecksTests.swift @@ -0,0 +1,28 @@ +import Foundation +import ProviderCore +import Testing + +@testable import darkbloom + +@Suite("Doctor cluster checks") +struct DoctorClusterChecksTests { + @Test("a Mac that is not paired gets no cluster checks and its link is not inspected") + func unpairedMacGetsNone() async { + let checks = await buildClusterDoctorChecks(configPath: "/nonexistent/provider.toml", paired: false) + #expect(checks.isEmpty) + } + + @Test("checks that ran become doctor checks; a failure fails the run and points to the cluster doctor") + func ranChecksBecomeDoctorChecks() { + let checks = clusterDoctorChecks([ + ("RDMA link", .passed, "rdma_en3 active on en3"), + ("trust files", .failed, "the pairing's link key is missing"), + ("live leader", .notObserved, "no leader observed"), + ("recovery", .notRun, "read-only"), + ]) + #expect(checks.map(\.name) == ["cluster RDMA link", "cluster trust files"]) + #expect(checks.map(\.status) == [.pass, .fail]) + #expect(checks[1].detail == "the pairing's link key is missing (details: `darkbloom cluster doctor`)") + #expect(checks.contains { $0.status.isFailure(strict: false) }) + } +} From b65ae59cf2ab5a94da5534aa0c3b30b417b8e2ce Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:13:40 -0800 Subject: [PATCH 0199/1441] fix(cluster): findings from the two-Mac test and the final review The guided setup ran end to end on two M5 Ultras over Thunderbolt (dev build of the previous commit, `darkbloom cluster local`, coordinator pointed at loopback). It passed; these are the fixes for what it and the final review found: - `darkbloom doctor` no longer fails a healthy pair: on a Mac that serves its share of a cluster's model, "model fits in RAM" says the single-Mac load check does not apply and points to `darkbloom cluster doctor` (`ModelFitDiagnostic.clusterMember`), instead of weighing the whole model against memory that already holds this Mac's share. - On identical Macs each Mac names itself by its computer name ("This Mac (Studio A) leads."), and the leader no longer repeats that commands typed there are handled by this Mac. - The stopped status names the model by its catalog title; a model only the other Mac holds is offered as a copy, not a download; the keep-the-window lines hold for any build; "does not fit now" is said once. - The service's Local Network probe writes under the service's own paths and runs only for this Mac's real home, so tests that run the service no longer touch `~/.darkbloom` or the cable; it keeps probing (every 2 s for 5 min, then every 10 s) until access is allowed, as the setup now waits without a deadline. - Final refactor pass: the planner comment matches `planLeader`, a shared test helper replaces three copied closures, an unused test parameter goes. - `ClusterConfiguration.swift` is back to dev's text: #1718 rewrites those lines. Tested: ClusterOnboardingChecks 706/0, ClusterControlChecks 229/0, ClusterPlacementChecks 237, ClusterSupervisionChecks 179, ClusterLinkChecks 2453, ClusterDiagnosticsChecks, ClusterInstalledSessionChecks and ClusterConfigurationChecks pass; `swift build --build-tests` is clean; the doctor suites with the new DoctorClusterModelFitTests (15 tests) and the new Local Network probe test pass; ClusterServiceRecoveryTests and ClusterApprovalServiceStartTests pass (6/6 each, run alone as before); docs-check, docs-impact against origin/dev and changelog-check pass; trial merges with every open PR touching these files lose no PR line. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-onboarding-simple.md | 25 +-- docs/architecture/inference.md | 59 +++++-- docs/provider/cli-reference.md | 11 +- docs/provider/two-mac-cluster.md | 108 ++++++++----- .../Config/ClusterConfiguration.swift | 2 +- .../Diagnostics/ModelFitDiagnostic.swift | 13 ++ .../Console/ClusterSetupWizardPlanning.swift | 4 +- .../ClusterLocalNetworkAccess.swift | 39 +++-- .../Onboarding/ClusterOnboardingFlow.swift | 78 +++++++--- .../Onboarding/ClusterOnboardingLive.swift | 21 ++- .../Onboarding/ClusterService.swift | 6 +- .../darkbloom/Diagnostics/DoctorRunner.swift | 17 +- .../OnboardingChecks.swift | 147 ++++++++++++++---- .../DoctorClusterModelFitTests.swift | 36 +++++ .../ClusterLocalNetworkAccessTests.swift | 59 +++++++ 15 files changed, 477 insertions(+), 148 deletions(-) create mode 100644 provider-swift/Tests/DarkbloomCLITests/DoctorClusterModelFitTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterLocalNetworkAccessTests.swift diff --git a/changelog.d/cluster-onboarding-simple.md b/changelog.d/cluster-onboarding-simple.md index e8f7cb403f..0a671f73bb 100644 --- a/changelog.d/cluster-onboarding-simple.md +++ b/changelog.d/cluster-onboarding-simple.md @@ -1,17 +1,18 @@ ### Simpler two-Mac cluster setup -- `darkbloom cluster` setup is shorter and asks with lists: four steps (Connect, Pair, Choose a model, Start), one line - for each thing that happened, and every choice (the pairing code, the model, a missing model's copy, the leader's - menu) is a list moved with ↑↓ and taken with enter, as `darkbloom start` picks models; plain transcripts number the - list and take one key. The last line of each screen is the one thing to do next. +- `darkbloom cluster` setup is shorter: four steps (Connect, Pair, Choose a model, Start), one line for each thing that + happened, and the next thing to do as each screen's last line. Every choice, a short model copy included, is a list + moved with ↑↓ and taken with enter, as `darkbloom start` picks models (numbered in plain transcripts); q or Esc + cancels, and no prompt asks for a key to do something. - The model list shows only the models approved for clusters (GLM-5.3-Flash and Qwen3.8 27B) that the two Macs can - serve, and a named model that is not approved is refused. + serve; a named model that is not approved is refused. - The Mac you set up on leads and keeps leading: every plan puts rank 0 (the API and the coordinator's registration) - on it, and before a plan exists it is the leader on identical Macs too. -- macOS's permissions are asked at stated moments on each Mac, with what to click: the cable's port and this - terminal's Local Network access in Connect, Darkbloom's Local Network access right after the code is confirmed. - Where macOS cannot show its password window (an SSH session), the setup runs the port's commands with sudo in that - terminal instead of sending you to run a script. -- On the Mac that follows, `darkbloom cluster` shows the status and where to manage the cluster, with nothing to - choose; both Macs say whether their window can be closed. + on it, the cluster service's own re-plans included, so a pair set up with 0.10.6 whose other Mac took over leading + moves back at its next plan. +- Connect names the macOS approvals each Mac asks for: the cable's port (with sudo in the terminal over SSH, instead of + a script to run by hand) and Darkbloom's Local Network access, which both Macs ask right after pairing; the setup + waits until Allow or q. +- Both Macs confirm the pairing code. The Mac that follows shows the status and where to manage the cluster; both Macs + say whether their window can close, and a pair served through Darkbloom says it earns for the public requests it + serves. - `darkbloom doctor` includes the cluster's checks on a Mac paired for a cluster. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 082cec2fb3..f3cb485cdf 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -255,7 +255,7 @@ service names members the same way in its control lines and refusals keeps hardware names; lines shown now carry the screen's words (`ClusterOnboardingDeployment.Share.label`). The Mac that joins ends its onboarding once paired, also for `darkbloom cluster local` -(`ClusterOnboardingDriver.joinedLocalLine`). The model list keeps one line per +(`ClusterOnboardingDriver.joinedLocalContinueLine`). The model list keeps one line per artifact and name (`OnboardingLive.presentedChoices`): a choice that cannot be served is left out when another offers the same digests under the same name, and an artifact this build serves is never called unsupported for a copy the @@ -265,29 +265,52 @@ Every choice goes through one console call (`ClusterOnboardingConsole.choose`): on a color terminal a list moved with ↑↓ and taken with enter that folds to the chosen line (`ClusterOnboardingTerminal.pick`), elsewhere numbered lines and one key read the same way on every console (`ClusterOnboardingChoice.match`), so the -plain transcript stays byte for byte the same on a terminal and a pipe. The +plain transcript stays byte for byte the same on a terminal and a pipe. q or a +lone escape cancels any list, and a key that sends a sequence (an arrow) reads +as no key, so it never stops a wait (`ClusterOnboardingTerminal.key`). The setup's list holds only models the owner approved for clusters (`ClusterOnboardingModelChoice.validated`, `listed`; `OnboardingLive.approved` against `ClusterPublicModels.declared`); an older leader's choices carry no such field and are listed as they come. A member's `darkbloom cluster` shows -the status and where to manage the cluster, with no list -(`ClusterOnboardingDriver.member`); the leader's is a list of the control -operations (`ClusterOnboardingDriver.menu`). - -The Mac the cluster was set up on leads. `LiveContext.plan` makes the Mac that -plans (the control leader) every plan's rank 0, so the derived leadership -(rank 0 of the adopted plan) stays there, and before a plan exists derivation +the status and where to manage the cluster, with a list only to set up a cable +port that is not set up yet (`ClusterOnboardingDriver.member`, `fixPortItem`); +the leader's is a list of the control operations (`ClusterOnboardingDriver.menu`). +Every copy of a missing model is a list as well, a short one with its +predicted time (`ClusterOnboardingDriver.provision`). Served through Darkbloom, +the chosen model's public-traffic line follows the choice +(`ClusterOnboardingModelChoice.publicTraffic`), and the start ends with +`ClusterOnboardingDriver.earnsLine`, except for a private image candidate and +where the pair serves locally, which a notice under the API line already says +(`servesLine`). When the other Mac does not answer over the +cable, the leader asks **Try again** or **Stop here** (`chooseAndServe`). + +The Mac the cluster was set up on leads. `LiveContext.plan` makes that Mac every +plan's rank 0, whichever Mac plans (`ClusterControlDerivation.planLeader`, from +the pairing's leader pin), the cluster service's re-plans on the control leader +included (after an update or a memory refusal), so a pair the joined Mac led +moves back at its next plan and the derived leadership (rank 0 of the adopted +plan) stays on the set-up Mac; when that Mac is not one of the plan's members +(no record, or one of an earlier pairing), the Mac planning takes rank 0, as +before. Before a plan exists derivation prefers it among the members present (`ClusterControlDerivation.derive`, `preferred`; `ClusterControlNode.preferredLeader`, from the pairing's leader pin). A Mac that is away never leads, so failover is unchanged. macOS's permissions are asked at stated moments -(`ClusterOnboardingDriver.allowLocalNetwork`): the command probes Local Network +(`ClusterOnboardingDriver.allowLocalNetwork`), and Connect's first line names +them (`ClusterOnboardingDriver.approvalsLine`). The command probes Local Network access in the Connect step (`ClusterLocalNetworkAccess.probe`: one datagram to -the cable's subnet broadcast, refused with `EHOSTUNREACH` until allowed), and -the cluster service probes as it starts, right after pairing, keeping each +the cable's subnet broadcast, refused with `EHOSTUNREACH` until allowed). macOS +lets a command run from a terminal or over SSH through by itself (TN3179), so +macOS asks only where the probe finds the cable blocked, naming the terminal app +or `sshd-keygen-wrapper` (`ClusterLocalNetworkAccess.commandApp`). The cluster +service, a launchd agent, probes as it starts, right after pairing, keeping each outcome for the onboarding (`ClusterLocalNetworkAccess.startServiceProbe`, -`serviceState`). Where macOS shows no approval window for the cable's port, the +`serviceState`). The onboarding waits for Allow until it comes or q, with no +time limit, and a service that reports nothing within `serviceReportSeconds` +(10 s) gets the prompt's line as an "if" (`localNetworkMaybeLine`); over SSH +(`ClusterLocalNetworkAccess.overSSH`) the lines put the prompt on the Mac's own +screen. Where macOS shows no approval window for the cable's port, the link setup's owner-only script runs with sudo in the same terminal (`ClusterOnboardingLinkResult.manualScript`, `ClusterLocalNetworkAccess.runLinkScriptWithSudo`), with the terminal in its @@ -2956,8 +2979,11 @@ 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 coordinator decides each public -placement ([serving a pair](../reference/cluster-control-protocol.md#serving-a-pair)). +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`); +the coordinator decides each public placement. ### Two-Mac cluster stages (experimental) @@ -3027,8 +3053,7 @@ answer with the same worker build (`ClusterOnboardingUpdate.oneBuild`): the [pair's coordinated update](../provider/cluster-always-on.md#the-pairs-coordinated-update) restarts the two Macs seconds apart, and a plan made while one still runs the other build would fail and wait 600 s. A model change of -a serving cluster (**Change model** in the leader's menu, `ClusterOnboardingDriver.menu`, -or `darkbloom cluster local `) plans the same way: +a serving cluster (`m`, or `darkbloom cluster local `) plans the same way: its list was priced while the running parts held their memory, where tensor parallel may not fit now, so once both parts stopped and both Macs gave the memory back (`OnboardingLive.awaitReleased`) it plans again and adopts the diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index b5f8224bb7..76af53135b 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -590,9 +590,9 @@ saved in the leader's setup record (`ClusterOnboardingLeadership.localOnly`, `localBind`) until **Serve through Darkbloom** in `darkbloom cluster` serves through Darkbloom again. The leader part then starts with `--no-coordinator`. Needs a terminal; exit 1 -otherwise. On the Mac that joins a waiting leader it pairs, says to run it on -the leader and ends (exit 0) like `darkbloom cluster` -(`ClusterOnboardingDriver.joinedLocalLine`). Steps: [Serving locally only](./two-mac-cluster.md#serving-locally-only) +otherwise. On the Mac that joins a waiting leader it pairs, says to continue on +the leader with `darkbloom cluster local` and ends (exit 0) like `darkbloom cluster` +(`ClusterOnboardingDriver.joinedLocalContinueLine`). Steps: [Serving locally only](./two-mac-cluster.md#serving-locally-only) (`provider-swift/Sources/darkbloom/ClusterLocalCommand.swift`). `darkbloom cluster status` prints `MTP: on (decode verifies drafts of the @@ -1466,7 +1466,10 @@ Thunderbolt RDMA link, the saved setup), each named `cluster `; a failed one fails the run and points to `darkbloom cluster doctor` for its details. A Mac that is not paired gets none of them, and its link is not inspected (`provider-swift/Sources/darkbloom/DoctorClusterChecks.swift`, -`buildClusterDoctorChecks`). +`buildClusterDoctorChecks`). On a Mac that serves its share of a cluster's +model, **model fits in RAM** says the single-Mac load check does not apply +and points to `darkbloom cluster doctor`, instead of weighing the whole model +against this Mac's memory (`ModelFitDiagnostic.clusterMember`). The operator report begins with a readiness summary and the first concrete action. A failed model-fit check names the live usable memory, the required load budget and their shortfall; it tells the operator to free memory, rerun diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 0f5151f2dd..3bdbafa582 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -30,7 +30,10 @@ Run `darkbloom cluster` on each Mac, pick a model, done. The Mac you start on leads the cluster and keeps leading: it chooses the model, sends the other Mac its setup over the cable and starts it, and it holds rank 0, where requests enter and which the coordinator registers (and pays) for the pair. Every plan -puts rank 0 on it (`LiveContext.plan`), and before a plan exists the cluster's +puts rank 0 on it, whichever Mac makes the plan, including the plans the +cluster service makes by itself after an update or after a Mac's memory +refused its share (`LiveContext.plan`, `ClusterControlDerivation.planLeader`). +Before a plan exists the cluster's leader is derived as that Mac (`ClusterControlDerivation.derive`, `preferred`). The other Mac follows; you never go back to it (see [If a Mac goes away](#if-a-mac-goes-away)). @@ -42,32 +45,51 @@ models: the answer to the pairing code, the model, how a missing model gets onto the Macs and, later, what to do with a running cluster. Where the screen has no color (`NO_COLOR`, `TERM=dumb`, a pipe), the same list is numbered and one key answers it: a number, enter for the first line, or a letter only one -line starts with (`y` for "Yes, pair"). The model list shows only models +line starts with (`y` for "Yes, pair"). q or Esc cancels any list, so q never +picks a line such as "Qwen3.8 27B". While the setup waits (for the other Mac, +for Allow), q or Esc stops it and an arrow key does nothing; no prompt asks for +a key to do something. The model list shows only models approved for clusters (`ClusterPublicModels.declared`: GLM-5.3-Flash and Qwen3.8 27B) that these two Macs can serve; any other model is left out, and a model named on the command line that is not approved is refused. -macOS asks for its permissions at two stated moments on each Mac, while you are -at that Mac, and the screen says what each prompt is and what to click: - -- **Connect:** the cable's port, once (your password), and Local Network access - for the program macOS attributes this command to: the terminal app, or sshd - in an SSH session. A probe that sends one datagram on the cable is what makes - macOS ask (`ClusterLocalNetworkAccess.probe`), and the setup waits for Allow. -- **Right after the code is confirmed:** Local Network access for Darkbloom, - which this Mac's cluster service asks for as it starts - (`ClusterLocalNetworkAccess.startServiceProbe`); the setup waits for Allow. +Each Mac asks for up to two macOS approvals, at stated moments while you are at +that Mac, and Connect's first line names them ("Up to two macOS approvals on +this Mac: the cable's port (now) and Local Network for Darkbloom (once +paired)."). Each prompt's line says what to click: + +- **Connect:** the cable's port, once per Mac (your password). macOS lets a + command run from a terminal or over SSH onto the local network by itself + (Apple's TN3179), so this command's own probe, one datagram on the cable + (`ClusterLocalNetworkAccess.probe`), asks nothing unless macOS blocks it + anyway; macOS then names the terminal app (Terminal, iTerm, …), or + `sshd-keygen-wrapper` over SSH, and the setup waits for Allow. +- **Right after pairing:** Local Network access for Darkbloom, which this Mac's + cluster service (a launchd agent, which macOS does ask about) asks for as it + starts (`ClusterLocalNetworkAccess.startServiceProbe`). Pairing ends on both + Macs at once, so both ask at the same moment: "macOS asks to let Darkbloom + find devices on your local network: click Allow. The other Mac may ask too: + click Allow there as well." The setup waits until Allow, however long you + take at the other Mac, or until q; after 15 s it also names the switch in + System Settings → Privacy & Security → Local Network. A cluster service that + reports no probe within 10 s (an older build) gets the line as an "if", and + the setup goes on. When macOS cannot show its password window (an SSH session with no desktop), the setup runs the same commands with `sudo` in that terminal: you type this Mac's password into sudo, not into Darkbloom, and the setup goes on. Only when -sudo fails does it name the script to run yourself. +sudo fails does it name the script to run yourself. Over SSH, Darkbloom's Local +Network prompt still appears on the Mac's own screen, and its line says so +("use Screen Sharing if it has no display"). The Mac that joins ends once paired: it says it follows the other Mac, whether -its window can close (a signed Darkbloom.app keeps serving; a development build -serves only while the window stays open), and, last, to continue on the other -Mac. The leader ends the same way: what serves, whether the windows can close, -and, last, the command to manage it. +its window can close (a signed Darkbloom.app's login agent keeps serving; +without one, as for a development build, the Mac serves only while the window +stays open), and, last, to continue on the other +Mac (with `darkbloom cluster local` when it was started that way). The leader +ends the same way: what serves (served through Darkbloom, "Serving through +Darkbloom: the pair earns for the public requests it serves."), whether the +windows can close, and, last, the command to manage it. On a color terminal with a UTF-8 locale and at least 40 columns, setup opens with the Darkbloom mark, which blooms in pixel by pixel. Each step's heading @@ -90,9 +112,11 @@ check its status, and choose **Test a response** to try again. `darkbloom cluster` run again shows the cluster's status and, on the leader, a list: **Test a response**, **Change model** (**Choose a model and serve** when stopped), **Serve locally only** or **Serve through Darkbloom**, **Stop -serving**, **Check both Macs released their memory** and **Quit**. On the -other Mac it shows the status and where to manage the cluster, with nothing to -choose: its part runs by itself. +serving**, **Check both Macs released their memory** and **Quit**, with **Set +up the cable's port** first when the cable moved to a port not set up yet. On +the other Mac it shows the status and where to manage the cluster: its part +runs by itself, and setting up such a port is the only choice it offers +([below](#when-something-is-in-the-way)). The planner picks tensor parallel or pipeline for your Macs by itself. Phase split is off. A model whose artifact ships a speculative (MTP) head can also @@ -145,17 +169,17 @@ format instruction only, as on one Mac | # | Where | What you do | What it asks | |---|---|---|---| -| 1 | the first Mac | Run `darkbloom cluster`. It checks the Thunderbolt cable ("Cable found.", "Cable ready.") and Local Network access. Nobody waits on the cable yet, so this Mac leads; its last line is **"Now run `darkbloom cluster` on the other Mac."**, and it waits (q cancels). With two cables it asks which one to use. | the cable's port, once (your password; sudo in this terminal where macOS shows no window), and Local Network access for the terminal app | -| 2 | the other Mac | Run `darkbloom cluster`. The same checks; then it finds the waiting Mac on the cable by itself (no address, no host name). Both screens show the same six-digit code. | the same two permissions; **Yes, pair** on each Mac when the codes match | -| 3 | — | The other Mac says **"Paired with the other Mac (). It leads; this Mac follows it."** Its cluster service now runs, and macOS asks once to let Darkbloom find devices on your local network (Allow). Nothing else is ever asked there, also when it was started with `darkbloom cluster local` (it then says to run that on the Mac that leads); its last line says to continue on the other Mac. | Local Network access for Darkbloom, once | -| 4 | the leader | It shows both Macs in one line ("This Mac: … · the other Mac: …") and every model approved for clusters that the pair can serve (held by both Macs, by one of them, or in Darkbloom's catalog), one line each: size, how it is split, each Mac's share ("this Mac 50% / the other Mac 50%") and the expected speed. A model a Mac holds twice (a catalog download beside the cluster's own copy) is listed once. A model that has tensor parallel but is split otherwise says why at the end of its line (for example "tensor parallel: slower here", "tensor parallel: not measured yet" or "tensor parallel: link unmeasured"). Models that fit in the Macs' free memory now come first; one that does not ends with "does not fit now". Choose the model with ↑↓ and enter (enter takes the first). A model the other Mac lacks says how it gets there ("copy ... over the Thunderbolt cable (6.1 GB)"). | the copy first in a list (a copy predicted under 30 s at the speed measured on these Macs starts by itself, `n` within 3 s stops it) | -| 5 | — | Choosing is starting: the leader saves the setup, sends it to the other Mac over the cable, starts both Macs, waits until both are loaded and answers one test request, each said in one line. | nothing | +| 1 | the first Mac | Run `darkbloom cluster`. Its first line names the approvals this Mac may ask for. It checks the Thunderbolt cable ("Cable found.", "Cable ready.") and Local Network access. Nobody waits on the cable yet, so this Mac leads; its last line is **"Now run `darkbloom cluster` on the other Mac."**, and it waits (q cancels). With two cables it asks which one to use. | the cable's port, once (your password; sudo in this terminal where macOS shows no window); Local Network access for the terminal app only where macOS blocks it | +| 2 | the other Mac | Run `darkbloom cluster`. The same checks; then it finds the waiting Mac on the cable by itself (no address, no host name). Both screens show the same six-digit code and "Does the other Mac show the same code? Answer on both Macs."; a Mac that answered first says "Now choose “Yes, pair” on the other Mac too." | the same as the first Mac; **Yes, pair** on each Mac when the codes match | +| 3 | both Macs | Each says it is paired; the other Mac: **"Paired with the other Mac (). It leads; this Mac follows it."** Both cluster services now run, and macOS asks on both Macs at the same moment to let Darkbloom find devices on your local network: click Allow on each; each screen waits for its own. Nothing else is ever asked on the other Mac; its last line says to continue on the other Mac (with `darkbloom cluster local` when it was started that way). | Local Network access for Darkbloom, once on each Mac | +| 4 | the leader | It shows both Macs in one line ("This Mac: … · the other Mac: …") and every model approved for clusters that the pair can serve (held by both Macs, by one of them, or in Darkbloom's catalog), one line each: size, how it is split, each Mac's share ("this Mac 50% / the other Mac 50%") and the expected speed. A model a Mac holds twice (a catalog download beside the cluster's own copy) is listed once. A model that has tensor parallel but is split otherwise says why at the end of its line (for example "tensor parallel: slower here", "tensor parallel: not measured yet" or "tensor parallel: link unmeasured"). Models that fit in the Macs' free memory now come first; one that does not ends with "does not fit now". Choose the model with ↑↓ and enter (enter takes the first). Served through Darkbloom, a line under the choice says whether public traffic may reach the model ("Not yet qualified for public traffic."). A model the other Mac lacks says how it gets there ("copy ... over the Thunderbolt cable (6.1 GB)"). If the other Mac does not answer over the cable (its Darkbloom prompt may still wait for Allow), it offers **Try again** or **Stop here**. | the copy first in a list; a short one says its time ("Copy it over the Thunderbolt cable (about 7 s)") | +| 5 | — | Choosing is starting: the leader saves the setup, sends it to the other Mac over the cable, starts both Macs, waits until both are loaded and answers one test request, each said in one line. Served through Darkbloom, it ends with "Serving through Darkbloom: the pair earns for the public requests it serves." | nothing | When it serves, the screen says how in one line, for example: ``` -Serving Qwen3.8-27B across both Macs: pipeline, the other Mac 40 layers / this Mac 24 layers. -API at http://localhost:8000 on the other Mac (Apple M3 Ultra, 256 GB). +Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers. +API at http://localhost:8000 on this Mac. ``` Every screen names the Macs from where it is shown: "this Mac" is the Mac the @@ -259,7 +283,9 @@ model on the leader (three keys), plus the macOS prompts [above](#the-steps-once Running `darkbloom cluster` again on either Mac opens with the same Darkbloom mark, beside "Darkbloom cluster" and the part this Mac plays ("This Mac leads -the cluster", or "This Mac follows the other Mac (…)"), then shows the +the cluster", or "This Mac follows the other Mac (…)"; with the name System +Settings gives this Mac, "This Mac (Studio A) leads the cluster", so two +identical Macs each say which they are), then shows the cluster's state (the deployment line first) and, on the leader, the list [above](#the-steps-once). The other Mac ends with where to manage the cluster ("To test, change the model or stop: run `darkbloom cluster` on the other Mac @@ -286,11 +312,11 @@ decodes with its speculative assistant under the default `mtp_mode` ``` Not paired yet, it pairs first as in [the steps](#the-steps-once). Name a - model to skip the list: `darkbloom cluster local Qwen3.5-9B` (its id or the + model to skip the list: `darkbloom cluster local glm-5.3-flash` (its id or the name the list shows). On a cluster that already serves, it switches the cluster to local only and waits until it serves again. On the Mac that joins - a waiting leader, it pairs and stops there like `darkbloom cluster`, and says - to run it on the leader. + a waiting leader, it pairs and stops there like `darkbloom cluster`; its last + line says to continue on the leader with `darkbloom cluster local`. 2. Read the API's place from the ready screen: ``` @@ -400,7 +426,8 @@ under the near-tie rule) do two things only: public placement. A model or mode with no passing record is served for you, and the plan says in -one line: "not yet qualified for public traffic". +one line, as the setup does under the chosen model when the pair serves +through Darkbloom: "not yet qualified for public traffic". Time budgets (startup, first token, stop) are derived from the setup and the installed artifact, not from a per-model table: @@ -474,7 +501,10 @@ cable out), the other keeps its part ready for 10 minutes; if the Mac comes back in that time, the cluster re-forms with nothing to do. After that, a Mac that can hold the model alone serves it alone until the other Mac is back, and `darkbloom cluster` on it says so. When the Mac you set up on is back, it leads -again (it holds rank 0). Manage the cluster on the Mac that leads; on the other +again (it holds rank 0). A pair set up with Darkbloom 0.10.6, on which the Mac +that joined took over leading, moves back to the Mac you set up on at its next +plan: normally the re-plan after its update, which restarts both parts anyway. +Manage the cluster on the Mac that leads; on the other Mac, `darkbloom cluster` shows the status and names the Mac to use. ## How the split is chosen @@ -658,7 +688,9 @@ drained for an update yet: its update waits while it serves (the log says says it and offers **Save a diagnostics file to send to Darkbloom**; both Macs keep trying by themselves. - **The leader cannot reach the other Mac**: make sure the other Mac is on and - logged in; it rejoins by itself. If you denied the Local Network prompt there, + logged in; it rejoins by itself. During setup the leader offers **Try again** + and **Stop here**, since the other Mac's Darkbloom prompt may still be waiting + for Allow. If you denied the Local Network prompt there, allow Darkbloom in System Settings → Privacy & Security → Local Network, then run `darkbloom cluster` again. - **A model is not offered**: the list leaves out every model that is not @@ -669,10 +701,10 @@ drained for an update yet: its update waits while it serves (the log says the models it holds back, for example "supported on a cluster, but this Mac's cluster worker does not take this copy of it"; a model is listed once when another copy of it can be served. -- **A model does not fit now**: it is listed after the ones that fit, its line - ending "does not fit now". The fit is checked again right before the start; a - model that still does not fit is not started, and the screen says what frees - the memory ("Quit apps on the other Mac (…) first."). +- **A model does not fit now**: it is listed after the ones that fit, ending + "does not fit now". What frees the memory ("Quit apps on the other Mac (…) + first.") is said, and nothing starts, if it still does not fit when checked + again right before the start. - **The start does not finish**: the screen shows each Mac's last error and offers **Save a diagnostics file to send to Darkbloom**, which writes one to your home folder (no keys, addresses or names in it; nothing is written if any diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift b/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift index 9dd00dfe12..eb481decf4 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift @@ -110,7 +110,7 @@ public struct ClusterConfiguration: Codable, Sendable, Equatable { /// approval runs this rule before any part stops (`ClusterApprovalAttachment.attachment`). Short enough to reach /// the leader whole through the other Mac's refusal (`ClusterSetupFailure` keeps 240 characters). static let tensorAssistantServesLocally = "Qwen's speculative assistant serves local clusters only (not qualified for " - + "public traffic); with mtp_mode \"auto\", choose Change model in `darkbloom cluster` to drop it" + + "public traffic); with mtp_mode \"auto\", press m in `darkbloom cluster` to plan without it" func validate(capability: ClusterRuntimeCapability, rawCapabilitySHA256: String) throws { func require(_ value: Bool, _ message: String) throws { diff --git a/provider-swift/Sources/ProviderCore/Diagnostics/ModelFitDiagnostic.swift b/provider-swift/Sources/ProviderCore/Diagnostics/ModelFitDiagnostic.swift index 8f214a6dc1..798f3c57ec 100644 --- a/provider-swift/Sources/ProviderCore/Diagnostics/ModelFitDiagnostic.swift +++ b/provider-swift/Sources/ProviderCore/Diagnostics/ModelFitDiagnostic.swift @@ -81,6 +81,19 @@ public enum ModelFitDiagnostic { } } + /// The fit row of a Mac set up for a two-Mac cluster. The pair holds this + /// Mac's share of its model and the single-Mac provider cannot run beside it, + /// so no single-Mac cold-load verdict applies: weighing the pair's whole + /// model against memory that already holds this Mac's share would fail every + /// serving pair. `cluster doctor` checks the pair. + public static func clusterMember() -> Diagnostic { + Diagnostic( + section: .traffic, name: "model fits in RAM", level: .info, + message: "this Mac serves its share of a two-Mac cluster's model, so the single-Mac load check " + + "does not apply; `\(BuildEnvironment.current.cliName) cluster doctor` checks the pair.", + fix: nil) + } + /// Builds the traffic-readiness diagnostic for a single target model. /// `weightGb` is the model's overhead-included estimated size; `alternatives` /// are locally-available models, used to suggest a fit. `servingSetIDs` is diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift index 85e3b9e42c..8ea1bbfaea 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift @@ -99,8 +99,8 @@ enum ClusterSetupPlanning { shareProbes: ClusterShareProbeHistory? = nil, now: Double = Date().timeIntervalSince1970, peerMayReceive: Bool = false, keeping: [String: ClusterGenerationMode] = [:], coordinator: Bool = false) -> [Decision] { - // The wizard's own steps lead from this Mac; the onboarding (`nil`) leaves which Mac leads the - // session (rank 0) and which decodes to the planner and the model's pair-serving grant. + // The wizard's own steps lead from this Mac; the onboarding and the service's re-plans pass the Mac the cluster + // was set up on (`ClusterControlDerivation.planLeader`). A `nil` leader leaves rank 0 to the planner. let sessionLeader: String? = leader ?? localMemberID let peerID = description.members.first { $0.id != localMemberID }?.id ?? "the other Mac" // Developer bench only (`ClusterBenchChip`): both Macs are planned and checked as that chip; a release build diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift index d243e1b44b..282e20be42 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift @@ -1,5 +1,6 @@ import Foundation import Darwin +import SystemConfiguration /// Local Network privacy (macOS 15 and later) for the cluster: macOS asks once per program before the program may /// reach other devices on the local network, the Thunderbolt cable included, and refuses the program's packets @@ -85,6 +86,12 @@ public enum ClusterLocalNetworkAccess { } } + /// This Mac's name as System Settings shows it (General → About), for its own screen only: two identical Macs + /// read the same hardware, so each says which it is. Nil when macOS gives none. + public static func computerName() -> String? { + SCDynamicStoreCopyComputerName(nil, nil) as String? + } + // MARK: - The cluster service's own probe /// What the service last saw, for the onboarding to read. @@ -94,36 +101,46 @@ public enum ClusterLocalNetworkAccess { var pid: Int32 } - /// How long the service keeps probing while refused, and how often. - static let serviceProbeSeconds: Double = 900 + /// How often the service probes while refused: every 2 s for the first minutes, then every 10 s for as long as it + /// runs (the onboarding waits for the answer without a deadline, so an Allow clicked later is still seen). + static let serviceProbeFastSeconds: Double = 300 static let serviceProbeInterval: useconds_t = 2_000_000 + static let serviceProbeSlowInterval: useconds_t = 10_000_000 + + /// The report in a service's own directory (the one its pid file is in). + static func reportFile(in directory: URL) -> URL { directory.appendingPathComponent("local-network.json") } static func reportFile() -> URL? { - (try? ClusterService.paths())?.pid.deletingLastPathComponent().appendingPathComponent("local-network.json") + (try? ClusterService.paths()).map { reportFile(in: $0.pid.deletingLastPathComponent()) } } - /// The service's side, from its start: probes at once (the probe that makes macOS ask about Darkbloom), then every - /// 2 s while refused, for up to 15 minutes, keeping each outcome for the onboarding; stops once allowed. Off the + /// The service's side, from its start: probes at once (the probe that makes macOS ask about Darkbloom), then while + /// refused, keeping each outcome in `directory` (the service's own) for the onboarding; stops once allowed. Off the /// service's thread; says each change in the service log. - public static func startServiceProbe(say: @escaping @Sendable (String) -> Void) { + static func startServiceProbe(directory: URL, + probe: @escaping @Sendable () -> ClusterOnboardingLocalNetwork = { probe() }, + fastSeconds: Double = serviceProbeFastSeconds, + intervals: (fast: useconds_t, slow: useconds_t) = (serviceProbeInterval, serviceProbeSlowInterval), + say: @escaping @Sendable (String) -> Void) { + let file = reportFile(in: directory) Thread.detachNewThread { let started = Date() var last: ClusterOnboardingLocalNetwork? - while Date().timeIntervalSince(started) < serviceProbeSeconds { + while true { let state = probe() if state != last { - write(Report(state: state, pid: getpid())) + write(Report(state: state, pid: getpid()), to: file) if state != .unknown { say("local network access for this service: \(state.rawValue)") } last = state } if state == .allowed { return } - usleep(serviceProbeInterval) + usleep(Date().timeIntervalSince(started) < fastSeconds ? intervals.fast : intervals.slow) } } } - static func write(_ report: Report) { - guard let file = reportFile(), let data = try? JSONEncoder().encode(report) else { return } + static func write(_ report: Report, to file: URL) { + guard let data = try? JSONEncoder().encode(report) else { return } try? data.write(to: file, options: [.atomic]) chmod(file.path, 0o600) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift index f5b162e138..20b1d184b8 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift @@ -226,8 +226,8 @@ public struct ClusterOnboardingModelChoice: Codable, Sendable, Equatable { public var fitRemedy: String? /// The model's id (`title` is its catalog display name when the catalog gave one); nil from an older build. public var modelID: String? - /// Whether public traffic may reach it yet, in one line, for an older member's screen, which says it once the model - /// is chosen (this build's list does not). Nil from an older build (which put the line in `lines`). + /// Whether public traffic may reach it yet, in one line; said once it is chosen, and only when the cluster serves + /// through Darkbloom. Nil from an older build (which put the line in `lines`). public var publicTraffic: String? /// Why the planner's split is not tensor parallel, in a few words ("tensor parallel: slower here"), for a model /// with a tensor-parallel plan that the planner did not give one. Nil when the split is tensor parallel, when the @@ -373,10 +373,14 @@ public struct ClusterOnboardingProvisionOffer: Codable, Sendable, Equatable { /// bytes to move; `ClusterModelProvisioning.quickCopySeconds`): the list's copy item says it. Nil: a long copy, a /// download, or no rate measured yet. public var quickSeconds: Double? + /// This Mac lacks it and copies it from the other Mac over the cable (with `leaderDownloads`: planned from its + /// files afterwards, but nothing is downloaded). + public var fromOtherMac: Bool - public init(lines: [String], downloadAlternative: Bool, leaderDownloads: Bool, blocker: String? = nil, quickSeconds: Double? = nil) { + public init(lines: [String], downloadAlternative: Bool, leaderDownloads: Bool, blocker: String? = nil, quickSeconds: Double? = nil, + fromOtherMac: Bool = false) { self.lines = lines; self.downloadAlternative = downloadAlternative; self.leaderDownloads = leaderDownloads; self.blocker = blocker - self.quickSeconds = quickSeconds + self.quickSeconds = quickSeconds; self.fromOtherMac = fromOtherMac } } @@ -665,10 +669,14 @@ public struct ClusterOnboardingOperations: Sendable { /// person types this Mac's password into sudo, never into Darkbloom. True when it exited 0. public var runAsAdministrator: @Sendable (_ script: String) -> Bool /// This Mac's cluster service keeps running once this window closes (a login agent of the signed app). False for a - /// development build, whose service lives only as long as the session that started it. + /// service for this session only (a development build, or a login agent launchd did not take), which lives only as + /// long as the session that started it. public var serviceOutlivesWindow: @Sendable () -> Bool /// This command runs over SSH: macOS shows its prompts on this Mac's own screen, not in this terminal. public var remote: @Sendable () -> Bool + /// This Mac's name as System Settings shows it, said on its own screen beside the part it plays (two identical + /// Macs read the same hardware); nil when unknown. + public var thisMacName: @Sendable () -> String? public init(resume: @escaping @Sendable () -> ClusterOnboardingResume, checkLink: @escaping @Sendable (@escaping @Sendable (String) -> Void) -> ClusterOnboardingLinkResult, @@ -698,7 +706,8 @@ public struct ClusterOnboardingOperations: Sendable { commandApp: @escaping @Sendable () -> String = { "Terminal" }, runAsAdministrator: @escaping @Sendable (String) -> Bool = { _ in false }, serviceOutlivesWindow: @escaping @Sendable () -> Bool = { true }, - remote: @escaping @Sendable () -> Bool = { false }) { + remote: @escaping @Sendable () -> Bool = { false }, + thisMacName: @escaping @Sendable () -> String? = { nil }) { self.resume = resume; self.checkLink = checkLink; self.pair = pair; self.answerCode = answerCode self.ensureService = ensureService; self.reachMembers = reachMembers; self.planModels = planModels self.adopt = adopt; self.serve = serve; self.waitReady = waitReady; self.testRequest = testRequest @@ -706,7 +715,7 @@ public struct ClusterOnboardingOperations: Sendable { self.useLinkPort = useLinkPort; self.recheckFit = recheckFit; self.afterRestart = afterRestart; self.saveDiagnostics = saveDiagnostics self.developerNotice = developerNotice; self.setScope = setScope; self.register = register self.localNetwork = localNetwork; self.commandApp = commandApp; self.runAsAdministrator = runAsAdministrator - self.serviceOutlivesWindow = serviceOutlivesWindow; self.remote = remote + self.serviceOutlivesWindow = serviceOutlivesWindow; self.remote = remote; self.thisMacName = thisMacName } } @@ -792,16 +801,18 @@ public struct ClusterOnboardingPairing: Sendable, Equatable { return peerAnswered ? [] : [Self.otherMacAnswerLine] } - public mutating func finished(_ result: ClusterOnboardingPairResult) -> [String] { + /// `named`: this Mac's own name, said beside "this Mac" (`ClusterOnboardingDriver.thisMac`). + public mutating func finished(_ result: ClusterOnboardingPairResult, named: String? = nil) -> [String] { phase = .done asking = nil switch result { case .paired(let role, let peerName): self.role = role let other = ClusterOnboardingMacName.other(named: peerName) + let this = ClusterOnboardingDriver.thisMac(named: named) switch role { - case .member: return ["\(ClusterOnboardingDriver.done) Paired with \(other). It leads; this Mac follows it."] - case .leader: return ["\(ClusterOnboardingDriver.done) Paired with \(other). This Mac leads."] + case .member: return ["\(ClusterOnboardingDriver.done) Paired with \(other). It leads; \(this.prefix(1).lowercased() + this.dropFirst()) follows it."] + case .leader: return ["\(ClusterOnboardingDriver.done) Paired with \(other). \(this) leads."] } case .failed(let lines): return ["Not paired."] + lines + ["Run `darkbloom cluster` again to try again."] @@ -885,24 +896,37 @@ public enum ClusterOnboardingDriver { if request.privateMiMoImageQualification { console.say("Private unqualified MiMo PNG candidate selected; actual image and all applicable modality gates remain open.") } + let named = shownName(operations.thisMacName()) switch resume.role { case .member: - console.banner(title, followerSubtitle(resume)) + console.banner(title, followerSubtitle(resume, named: named)) return member(resume, operations, console, request: request) case .leader: - console.banner(title, leaderSubtitle) + console.banner(title, leaderSubtitle(named: named)) return leader(resume, operations, console, justPaired: false, request: request) case nil: return onboard(operations, console, request: request) } } /// The setup's opening, and the opening on a Mac that is already in a cluster (`darkbloom cluster` run again): - /// the same mark, with the part this Mac plays. + /// the same mark, with the part this Mac plays. `named`: this Mac's own name beside "This Mac" (`thisMac`). public static let title = "Darkbloom cluster" public static let setupSubtitle = "Two Macs, one model: connect, pair, choose, start" public static let leaderSubtitle = "This Mac leads the cluster" - static func followerSubtitle(_ resume: ClusterOnboardingResume) -> String { - "This Mac follows " + ClusterOnboardingMacName.other(named: resume.leaderName ?? resume.peerName) + static func leaderSubtitle(named: String?) -> String { thisMac(named: named) + " leads the cluster" } + static func followerSubtitle(_ resume: ClusterOnboardingResume, named: String? = nil) -> String { + thisMac(named: named) + " follows " + ClusterOnboardingMacName.other(named: resume.leaderName ?? resume.peerName) + } + + /// "This Mac", with its own name when known ("This Mac (Studio A)"): two identical Macs read the same hardware, so + /// each screen says which physical Mac it is. Said on that Mac's own screen only; the name never crosses the cable. + static func thisMac(named: String?) -> String { named.map { "This Mac (\($0))" } ?? "This Mac" } + + /// A name macOS gave, when it can be said plainly in a line: no control characters, at most 40 characters. + static func shownName(_ name: String?) -> String? { + guard let name = name?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty, name.count <= 40, + ClusterOnboardingDeployment.shownPlainly(name) else { return nil } + return name } /// A step that is done, at the start of its line. @@ -943,9 +967,10 @@ public enum ClusterOnboardingDriver { /// runs here, because the Mac that leads chooses how the cluster serves and its model. public static let joinedLocalLine = "`darkbloom cluster local` takes effect on the Mac that leads: run it on the other Mac." - /// Whether the window may close: a login agent keeps serving; a development build's session service does not. + /// Whether the window may close: a login agent keeps serving; a service for this session only (a development + /// build, or one launchd did not take as a login agent) does not. public static let closeWindowLine = "You can close this window." - public static let keepWindowLine = "Keep this window open: this development build serves only while it stays open." + public static let keepWindowLine = "Keep this window open: this Mac serves only while it stays open." /// How long the setup waits for a service that was just started to report its own probe (a service that never /// reports is an older build: nothing to wait for). A Local Network prompt itself is waited for until it is @@ -1103,7 +1128,7 @@ public enum ClusterOnboardingDriver { } } console.settle() - for line in pairing.finished(result!) { console.say(" " + line) } + for line in pairing.finished(result!, named: shownName(operations.thisMacName())) { console.say(" " + line) } guard case .paired(let role, let peerName) = result! else { return 1 } switch role { case .member: @@ -1344,8 +1369,11 @@ public enum ClusterOnboardingDriver { let titles = choices.map(\.title) let lines = open.map { index -> String in let shared = titles.filter { $0 == choices[index].title }.count > 1 - let line = choices[index].listLine(sameTitleElsewhere: shared) - return choices[index].fitRemedy == nil ? line : line + " · does not fit now" + var choice = choices[index] + guard choice.fitRemedy != nil else { return choice.listLine(sameTitleElsewhere: shared) } + // A model that does not fit now says so once: a tensor-parallel note saying only that is left out. + if choice.tensorParallelNote?.hasSuffix("does not fit now") == true { choice.tensorParallelNote = nil } + return choice.listLine(sameTitleElsewhere: shared) + " · does not fit now" } guard let picked = console.choose(lines, selected: 0) else { console.say("Nothing was changed. Run `darkbloom cluster` again to choose.") @@ -1364,11 +1392,12 @@ public enum ClusterOnboardingDriver { case .stopped: return 0 case .failed: return 1 case .done: - // A model this Mac downloaded is planned from its own files now. + // A model this Mac downloaded (or copied from the other Mac) is planned from its own files now. if offer.leaderDownloads { guard case .success(let again) = busy(console, "Planning \(choice.title)", operations.planModels), let index = again.firstIndex(where: { ($0.modelID ?? $0.title) == (choice.modelID ?? choice.title) }) else { - console.say("\(choice.title) could not be planned after the download. Run `darkbloom cluster` here again.") + console.say("\(choice.title) could not be planned after the \(offer.fromOtherMac ? "copy" : "download"). " + + "Run `darkbloom cluster` here again.") return 1 } if let blocker = again[index].blocker { @@ -1431,7 +1460,7 @@ public enum ClusterOnboardingDriver { if !privateImage, let line = servesLine(scope: scope, ready: ready) { console.say(line) } if let restart = operations.afterRestart() { console.say(restart) } console.say("Done. " + (operations.serviceOutlivesWindow() ? "You can close this window here and on the other Mac." - : "Keep this window and the other Mac's open: this development build serves only while they stay open.")) + : "Keep this window and the other Mac's open: these Macs serve only while they stay open.")) console.say("To test, change the model or stop: run `darkbloom cluster` on this Mac.") return 0 } @@ -1512,7 +1541,8 @@ public enum ClusterOnboardingDriver { } // Every copy is a choice from the list, the copy first so enter takes it; a short one says how long it takes // (2026-11-02 review: no key to press to do something, the same list as the rest of Darkbloom). - let get = offer.leaderDownloads ? "Get it (download, then copy over the cable)" + let get = offer.fromOtherMac ? "Copy it from the other Mac over the Thunderbolt cable" + (offer.quickSeconds.map { " (\(Self.duration($0)))" } ?? "") + : offer.leaderDownloads ? "Get it (download, then copy over the cable)" : offer.quickSeconds.map { "Copy it over the Thunderbolt cable (\(Self.duration($0)))" } ?? (offer.downloadAlternative ? "Copy it over the Thunderbolt cable (recommended)" : "Copy it over the Thunderbolt cable") let options = [get] + (offer.downloadAlternative ? ["Download it from Darkbloom's catalog instead"] : []) + ["Stop here"] diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift index f4b3a4b473..57feea58e3 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift @@ -56,7 +56,8 @@ extension ClusterOnboardingOperations { commandApp: { ClusterLocalNetworkAccess.commandApp() }, runAsAdministrator: { ClusterLocalNetworkAccess.runLinkScriptWithSudo($0, paths: paths) }, serviceOutlivesWindow: { live.serviceOutlivesWindow() }, - remote: { ClusterLocalNetworkAccess.overSSH() }) + remote: { ClusterLocalNetworkAccess.overSSH() }, + thisMacName: { ClusterLocalNetworkAccess.computerName() }) } } @@ -706,7 +707,7 @@ final class OnboardingLive: @unchecked Sendable { ordered.append((.init(title: ClusterOnboardingDeployment.title(modelID: model.modelID, displayNames: names), lines: ["\(ClusterModelProvisioning.gigabytes(model.totalBytes)) · only on \(thereShort): copied over the cable first"], blocker: nil, provision: .init(lines: ClusterModelProvisioning.lines(plan), downloadAlternative: false, leaderDownloads: true, blocker: plan.blocker, - quickSeconds: ClusterModelProvisioning.quickCopySeconds(plan)), modelID: model.modelID, + quickSeconds: ClusterModelProvisioning.quickCopySeconds(plan), fromOtherMac: true), modelID: model.modelID, validated: approved(model.artifactSHA256)), (model.folder, "", model.modelID, [], nil, nil), ListedArtifact(model))) } @@ -1537,6 +1538,14 @@ final class OnboardingLive: @unchecked Sendable { return lines } + /// A model id as the screens name it: its catalog name, when the last catalog this Mac read has one. + func modelTitle(_ modelID: String) -> String { + let catalog = (ClusterModelStore.readSmall(store.paths.directory.appendingPathComponent("catalog.json")) + .flatMap { try? JSONDecoder().decode([CatalogModel].self, from: $0) }) ?? [] + return ClusterOnboardingDeployment.title(modelID: modelID, + displayNames: Dictionary(catalog.map { ($0.id, $0.displayName) }, uniquingKeysWith: { first, _ in first })) + } + func localStatus() -> [String] { var lines = [String]() // After a Darkbloom update this Mac's service sets the cluster up again by itself; said first while it runs. @@ -1547,10 +1556,10 @@ final class OnboardingLive: @unchecked Sendable { lines.append("Commands typed here are handled by \(here).") return lines } - let model = leadership?.modelName ?? "the chosen model" + let model = (leadership?.modelName).map(modelTitle) ?? "the chosen model" let now = session() if leadership?.serving != true { - lines.append("Not serving (stopped)\(leadership?.modelName.map { "; the last model was " + $0 } ?? "").") + lines.append("Not serving (stopped)\(leadership?.modelName.map { "; the last model was " + modelTitle($0) } ?? "").") if let scope = leadership?.scope, scope.isLocalOnly { lines.append("When it starts: " + scope.line + ".") } } else if let offered = offeredLine() { let ready = offeredReadiness(offered, own: ClusterService.published()?.child) @@ -1575,10 +1584,6 @@ final class OnboardingLive: @unchecked Sendable { lines.append("\(model) is starting (both Macs keep trying by themselves).") } lines.append(answering ? "Leader: \(here). This Mac is a member." : "Member: \(there). This Mac leads.") - // On the leader's own screen only: a member that forwarded this already says where its commands go. - if let control = ClusterService.published()?.control, control.leads, !answering { - lines.append("Commands typed here are handled by this Mac.") - } return lines } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index ca3379ea52..4a54356def 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -265,7 +265,11 @@ public final class ClusterService: @unchecked Sendable { say("started (pid \(getpid()))") // Makes macOS ask once about Darkbloom's Local Network access now: the onboarding starts this service right // after pairing, while the person is at this Mac, and waits for the answer (`ClusterLocalNetworkAccess`). - ClusterLocalNetworkAccess.startServiceProbe(say: say) + // Only the service of this Mac's own home probes: one run on other paths (a test's) neither sends on the cable + // nor writes the report the onboarding reads. + if (try? Self.paths())?.pid == files.pid { + ClusterLocalNetworkAccess.startServiceProbe(directory: store.paths.directory, say: say) + } refreshPowerAssertions(power) // A part a previous run of this service started and left running (that run ended without stopping it, e.g. // killed): stopped before anything starts, or it would hold the model's memory and the serving port forever. diff --git a/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift b/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift index a4d4dc71c5..f6681f7c5d 100644 --- a/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift +++ b/provider-swift/Sources/darkbloom/Diagnostics/DoctorRunner.swift @@ -209,7 +209,12 @@ enum DoctorRunner { ? daemonBasis.map(\.id) : daemonBasis.map(\.id).filter(enabled.contains) } - for target in targets { + // A Mac set up for a two-Mac cluster holds its share of the pair's + // model: one row says so instead of a single-Mac verdict + // (`ModelFitDiagnostic.clusterMember`). + let clusterMember = servesCluster(snapshot.config) + if clusterMember { out.append(ModelFitDiagnostic.clusterMember()) } + for target in targets where !clusterMember { let targetID = target.id out.append(ModelFitDiagnostic.diagnose( modelID: targetID, weightGb: target.weightGb, @@ -301,6 +306,16 @@ enum DoctorRunner { return out } + /// Whether this Mac is set up for a two-Mac cluster: its provider config + /// names a saved cluster setup and it holds a pairing. The pairing store is + /// read only when the config names a setup, so a Mac without one is + /// diagnosed exactly as before. + static func servesCluster( + _ config: ProviderConfig, paired: @autoclosure () -> Bool = !ClusterService.holdsNoPairing() + ) -> Bool { + config.cluster != nil && paired() + } + private static func formatDuration(_ seconds: Double) -> String { DurationFormatting.compact(seconds, spaced: false, elideZeroMinutesInHourRange: false) } diff --git a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift index 51f8f0a875..382b221d71 100644 --- a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift +++ b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift @@ -97,6 +97,11 @@ import Darwin serviceThatCannotTellStillGetsTheAsk() otherMacThatDidNotAnswerOffersTryAgain() startSaysHowThePairServes() + // The two-Mac test on two M5 Ultras and the final review: which physical Mac plays which part, a model copied + // from the other Mac, a model that does not fit now, and the window's line. + eachMacNamesItselfBesideItsPart() + modelOnTheOtherMacIsCopiedNotDownloaded() + modelThatDoesNotFitSaysSoOnce() print("onboarding checks: \(passed) passed, \(failures.count) failed") for failure in failures { print("FAIL " + failure) } exit(failures.isEmpty ? 0 : 1) @@ -432,6 +437,7 @@ import Darwin outlivesWindow: Bool = true, remote: Bool = false, commandApp: String = "Terminal", + thisMacName: String? = nil, reachFailures: Int = 0, readyResult: Result = .success(.init(servedBy: "this Mac", port: 8000, deployment: "Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers"))) -> ClusterOnboardingOperations { @@ -533,7 +539,8 @@ import Darwin commandApp: { commandApp }, runAsAdministrator: { script in recorder.note("runAsAdministrator"); return sudoSucceeds && script == linkScript }, serviceOutlivesWindow: { outlivesWindow }, - remote: { remote }) + remote: { remote }, + thisMacName: { thisMacName }) } static func privateMiMoSelectionRefusesBeforeAnyActionOnMemberOrUnpairedMac() { @@ -1753,8 +1760,8 @@ import Darwin + " · tensor parallel: slower here\n 2) Qwen3.8-27B — "), "TP note: at the end of the line it is about: \(text)") expect(text.contains("about 41 tokens/s\n 3) Bonsai 27B — 7.2 GB · pipeline · M3 Ultra 4 layers / M5 Max 60 layers · does not fit now\n 4) Qwen3.6-35B-A3B — "), "TP note: none for tensor parallel chosen or a model without it: \(text)") - expect(text.contains("M5 Max 36 layers · tensor parallel: does not fit now · does not fit now\n"), - "TP note: on the line, before the fit mark: \(text)") + expect(text.contains("M5 Max 36 layers · does not fit now\n"), + "TP note: a note that only says the model does not fit now is left to the fit mark, said once: \(text)") expect(!text.contains("Tensor parallel: pipeline is left out") && !text.contains("Pipeline: tensor parallel is predicted slower"), "TP note: the planner's full reasons are not said") run.type("\r") @@ -1806,16 +1813,21 @@ import Darwin static let codeQuestion = ClusterOnboardingPairing.codeQuestion - /// The list's keys on a colour UTF-8 terminal. + /// Local Network access while macOS's prompt is up: refused for each of `subjects` until it was probed `refusals` + /// times, then allowed (the person clicked Allow); any other subject is allowed at once. + static func refusedThenAllowed(_ refusals: Int, _ subjects: [ClusterOnboardingLocalNetworkSubject] = [.thisCommand]) + -> @Sendable (ClusterOnboardingLocalNetworkSubject) -> ClusterOnboardingLocalNetwork { + let probes = Recorder() + return { subject in + guard subjects.contains(subject) else { return .allowed } + probes.note("\(subject)") + return probes.all.filter { $0 == "\(subject)" }.count > refusals ? .allowed : .blocked + } + } + /// An arrow pressed while the setup waits (here for Allow) is no key: only q or a lone escape stops a wait. static func arrowKeysDoNotStopAWait() { - let states = Recorder() - let network: @Sendable (ClusterOnboardingLocalNetworkSubject) -> ClusterOnboardingLocalNetwork = { subject in - guard subject == .thisCommand else { return .allowed } - states.note("command") - return states.all.count > 3 ? .allowed : .blocked - } - let run = TerminalRun(operations(Recorder(), pairEvents: [], pairResult: .failed([]), localNetwork: network)) + let run = TerminalRun(operations(Recorder(), pairEvents: [], pairResult: .failed([]), localNetwork: refusedThenAllowed(3))) expect(run.waitFor("click Allow."), "arrow in a wait: the prompt line") run.type("\u{1B}[A") run.type("\u{1B}[B") @@ -1842,13 +1854,7 @@ import Darwin /// Over SSH the prompts are on the Mac's own screen: the lines say so, and name the program macOS shows. static func sshSessionsAreToldWhereThePromptIs() { - let states = Recorder() - let network: @Sendable (ClusterOnboardingLocalNetworkSubject) -> ClusterOnboardingLocalNetwork = { subject in - guard subject == .thisCommand else { return .allowed } - states.note("command") - return states.all.count > 2 ? .allowed : .blocked - } - let run = TerminalRun(operations(Recorder(), pairEvents: [], pairResult: .failed([]), localNetwork: network, remote: true, + let run = TerminalRun(operations(Recorder(), pairEvents: [], pairResult: .failed([]), localNetwork: refusedThenAllowed(2), remote: true, commandApp: "sshd-keygen-wrapper")) expect(run.waitFor(" " + ClusterOnboardingDriver.approvalsLine(remote: true) + "\n"), "SSH: the approvals, where each is answered") expect(run.waitFor(" macOS asks on this Mac's own screen (use Screen Sharing if it has no display) to let sshd-keygen-wrapper find devices on your local network: click Allow.\n"), @@ -1905,10 +1911,11 @@ import Darwin "serves locally: neither line; the notice says how it serves: \(local.text)") } + /// The list's keys on a colour UTF-8 terminal. static let arrowHint = "\u{2191}\u{2193} move \u{00B7} enter select \u{00B7} q cancel" - /// A plain transcript's choice prompt. - static func prompt(_ count: Int, enter: Int = 1) -> String { "Choose 1-\(count) (enter = \(enter)): " } + /// A plain transcript's choice prompt (enter takes the first option). + static func prompt(_ count: Int) -> String { "Choose 1-\(count) (enter = 1): " } /// The leader's pairing: nobody waits on the cable, the other Mac joins, both confirm the code. static let leaderEvents: [ClusterOnboardingPairEvent] = [.searching, .waitingAsLeader, .connected, @@ -1930,7 +1937,7 @@ import Darwin pairResult: .failed([]), outlivesWindow: false)) expect(led.waitFor(prompt(2)), "dev leader: the list"); led.type("\r") expect(led.finish() == 0, "dev leader: exit 0") - expect(led.text.contains("Done. Keep this window and the other Mac's open: this development build serves only while they stay open.\n"), + expect(led.text.contains("Done. Keep this window and the other Mac's open: these Macs serve only while they stay open.\n"), "dev leader: keep both windows open") } @@ -1972,16 +1979,9 @@ import Darwin /// 2026-11-02: macOS's Local Network prompts came out of sync, on the other Mac's turn. This command's is asked in /// Connect and Darkbloom's right after pairing, each with what to click, and the setup waits for the answer. static func localNetworkAskedAtStatedMoments() { - let states = Recorder() - // Each subject is refused twice (macOS's prompt is up), then allowed. - let network: @Sendable (ClusterOnboardingLocalNetworkSubject) -> ClusterOnboardingLocalNetwork = { subject in - let name = subject == .service ? "service" : "command" - states.note(name) - return states.all.filter { $0 == name }.count > 2 ? .allowed : .blocked - } let recorder = Recorder() let run = TerminalRun(operations(recorder, pairEvents: memberEvents, - pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), localNetwork: network)) + pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), localNetwork: refusedThenAllowed(2, [.thisCommand, .service]))) expect(run.waitFor(" macOS asks to let Terminal find devices on your local network: click Allow.\n"), "local network: this command's prompt, in Connect") expect(run.waitFor(" \u{2713} Local network allowed for Terminal.\n"), "local network: allowed, then pairing") expect(run.waitFor(codeQuestion), "local network: the code"); run.type("y") @@ -2066,4 +2066,93 @@ import Darwin expect(none.text.contains("No model approved for clusters can run on these two Macs now.\n"), "approved: said") expect(!none.text.contains("Qwen 3.5 9B"), "approved: an unapproved model is not named among the reasons") } + + /// Two identical Macs read the same hardware ("Apple M5 Ultra, 256 GB"), so each says which physical Mac it is, + /// by the name System Settings gives it, beside the part it plays: on its own screen only, and only a name that + /// can be said plainly. + static func eachMacNamesItselfBesideItsPart() { + let D = ClusterOnboardingDriver.self + expect(D.shownName(" Studio A ") == "Studio A", "names: trimmed") + expect(D.shownName(nil) == nil && D.shownName(" ") == nil, "names: none given") + expect(D.shownName("Studio\u{1B}[2J") == nil, "names: a control character is never said") + expect(D.shownName(String(repeating: "x", count: 41)) == nil, "names: at most 40 characters") + expect(D.leaderSubtitle(named: "Studio A") == "This Mac (Studio A) leads the cluster", "names: the leader's opening") + expect(D.leaderSubtitle(named: nil) == D.leaderSubtitle, "names: unknown, unchanged") + expect(D.followerSubtitle(memberResume(), named: "Studio B") == "This Mac (Studio B) follows the other Mac (Apple M3 Ultra, 256 GB)", + "names: the member's opening") + var leads = ClusterOnboardingPairing() + expect(leads.finished(.paired(role: .leader, peerName: "Apple M5 Ultra, 256 GB"), named: "Studio A").last + == "\u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). This Mac (Studio A) leads.", "names: the leader's paired line") + var follows = ClusterOnboardingPairing() + expect(follows.finished(.paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), named: "Studio B").last + == "\u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). It leads; this Mac (Studio B) follows it.", "names: the member's paired line") + + let mac = "Apple M5 Ultra, 256 GB" + let paired = TerminalRun(operations(Recorder(), pairEvents: [.searching, .waitingAsLeader, .connected, .code("123456", peer: [mac]), + .peerDecided(true)], pairResult: .paired(role: .leader, peerName: mac), machines: [ + ClusterOnboardingMachine(name: mac, memoryGB: 256, gpuCores: 80, leads: true, models: 2), + ClusterOnboardingMachine(name: mac, memoryGB: 256, gpuCores: 80, leads: false, models: 2)], thisMacName: "Studio A")) + expect(paired.waitFor(codeQuestion), "names: the code question"); paired.type("y") + expect(paired.waitFor(prompt(2), count: 2), "names: the model list"); paired.type("\r") + expect(paired.finish() == 0, "names: served") + expect(paired.text.contains(" \u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). This Mac (Studio A) leads.\n"), + "names: identical Macs, this one named where it says it leads") + for (label, resume, name, opening) in [ + ("leader", ClusterOnboardingResume(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), + "Studio A", "This Mac (Studio A) leads the cluster"), + ("member", memberResume(), "Studio B", "This Mac (Studio B) follows the other Mac (Apple M3 Ultra, 256 GB)"), + ("unsayable", ClusterOnboardingResume(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), + "Studio\u{07}", D.leaderSubtitle)] { + let run = TerminalRun(operations(Recorder(), resume: resume, pairEvents: [], pairResult: .failed([]), thisMacName: name)) + if resume.role == .leader { expect(run.waitFor(prompt(6)), "names (\(label) again): the menu"); run.type("q") } + expect(run.finish() == 0, "names (\(label) again): leaves") + expect(visible(run.text).contains { $0.contains(opening) }, "names (\(label) again): opens with \(opening): \(visible(run.text).prefix(4))") + expect(!run.text.contains("\u{07}"), "names (\(label) again): nothing unsayable on screen") + } + } + + /// A model only the other Mac has is copied to this Mac over the cable, then planned here: its list item says a + /// copy, never a download, and how long a short one takes; a catalog model still says it is downloaded first + /// (`leaderDownloadsAModelNoMacHas`). + static func modelOnTheOtherMacIsCopiedNotDownloaded() { + let recorder = Recorder() + let offer = ClusterOnboardingProvisionOffer(lines: ["This Mac: copy from the other Mac (Apple M3 Ultra, 256 GB) over the Thunderbolt cable (16.3 GB, about 7 s)"], + downloadAlternative: false, leaderDownloads: true, quickSeconds: 6.9, fromOtherMac: true) + let before = [ClusterOnboardingModelChoice(title: "Qwen3.8 27B", lines: ["16.3 GB · only on the other Mac: copied over the cable first"], blocker: nil, + provision: offer, validated: true)] + let after = [ClusterOnboardingModelChoice(title: "Qwen3.8 27B", lines: ["16.3 GB · tensor parallel · this Mac 50% / the other Mac 50%"], blocker: nil, + validated: true)] + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), + choices: before, replanned: after)) + expect(run.waitFor(prompt(1)), "from the other Mac: offered"); run.type("\r") + expect(run.waitFor(" Qwen3.8 27B is not on this Mac yet:\n"), "from the other Mac: said") + expect(run.waitFor(" 1) Copy it from the other Mac over the Thunderbolt cable (about 7 s)\n 2) Stop here\n"), + "from the other Mac: a copy, with its time: \(run.text)") + expect(!run.text.contains("download"), "from the other Mac: no download is mentioned") + run.type("\r") + expect(run.finish() == 0, "from the other Mac: served") + expect(recorder.all.contains("provision 0 copy") && recorder.all.filter { $0 == "planModels" }.count == 2, + "from the other Mac: copied, then planned here: \(recorder.all)") + } + + /// A model that does not fit now says so once at the end of its line: a tensor-parallel note that only says the + /// same is left out, any other note stays. + static func modelThatDoesNotFitSaysSoOnce() { + typealias C = ClusterOnboardingModelChoice + let choices = [ + C(title: "Qwen3.8 27B", lines: ["16.3 GB · tensor parallel"], blocker: nil, validated: true), + C(title: "Z.ai: GLM-5.3-Flash", lines: ["181.8 GB · pipeline"], blocker: nil, fitRemedy: "quit the apps holding 20 GB first", + tensorParallelNote: "tensor parallel: does not fit now", validated: true), + C(title: "Gemma 4 31B", lines: ["58.2 GB · pipeline"], blocker: nil, fitRemedy: "quit the apps holding 4 GB first", + tensorParallelNote: "tensor parallel: slower here", validated: true)] + let run = TerminalRun(operations(Recorder(), resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), + choices: choices)) + expect(run.waitFor(prompt(3)), "fit: the list") + let text = run.text + expect(text.contains(" 2) Z.ai: GLM-5.3-Flash — 181.8 GB · pipeline · does not fit now\n"), "fit: said once: \(text)") + expect(!text.contains("does not fit now · does not fit now") && !text.contains("tensor parallel: does not fit now"), "fit: never twice") + expect(text.contains(" 3) Gemma 4 31B — 58.2 GB · pipeline · tensor parallel: slower here · does not fit now\n"), "fit: another note stays") + run.type("1") + expect(run.finish() == 0, "fit: the model that fits is served") + } } diff --git a/provider-swift/Tests/DarkbloomCLITests/DoctorClusterModelFitTests.swift b/provider-swift/Tests/DarkbloomCLITests/DoctorClusterModelFitTests.swift new file mode 100644 index 0000000000..deef5fb7e9 --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/DoctorClusterModelFitTests.swift @@ -0,0 +1,36 @@ +import Foundation +import ProviderCore +import Testing + +@testable import darkbloom + +/// `darkbloom doctor` on a Mac set up for a two-Mac cluster: the pair holds +/// this Mac's share of its model, so the single-Mac cold-load verdict gives way +/// to one informational row (the 2026-11-03 two-Mac test: a healthy serving +/// pair failed "model fits in RAM" for its own model and doctor exited 1). +@Suite("Doctor model fit on a cluster Mac") +struct DoctorClusterModelFitTests { + @Test("only a Mac with a saved cluster setup and a pairing is a cluster member; the pairing is read only then") + func clusterMemberNeedsSetupAndPairing() throws { + let plain = ProviderConfig.defaultForHardware(CLICommandSandbox.hardware) + var set = plain + set.cluster = try ClusterConfigurationReference( + configuration: "/tmp/darkbloom-cluster-configuration.json", sha256: String(repeating: "a", count: 64)) + // Outside `#expect`, which evaluates a call's arguments itself to show them. + var asked = false + let plainServes = DoctorRunner.servesCluster(plain, paired: { asked = true; return true }()) + #expect(!plainServes) + #expect(!asked) + #expect(DoctorRunner.servesCluster(set, paired: true)) + #expect(!DoctorRunner.servesCluster(set, paired: false)) + } + + @Test("the cluster member's row is informational, not a failure, and points to the cluster doctor") + func clusterMemberRow() { + let row = ModelFitDiagnostic.clusterMember() + #expect(row.name == "model fits in RAM") + #expect(row.section == .traffic) + #expect(row.level == .info) + #expect(row.message.contains("cluster doctor")) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterLocalNetworkAccessTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterLocalNetworkAccessTests.swift new file mode 100644 index 0000000000..6edccc1d0c --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterLocalNetworkAccessTests.swift @@ -0,0 +1,59 @@ +import Foundation +import Testing +@testable import ProviderCore + +/// The cluster service's own Local Network probe (`ClusterLocalNetworkAccess.startServiceProbe`), with the probe and +/// its timing injected: no datagram leaves this Mac and nothing under the real home is written. +@Suite("Cluster service Local Network probe") +struct ClusterLocalNetworkAccessTests { + /// Refused six times, then allowed: the probe keeps asking past its fast minutes (the onboarding waits for the + /// answer without a deadline, so a late Allow is still seen), writes each change in the service's own directory, + /// and stops once allowed. + @Test func probeKeepsAskingUntilAllowedAndWritesInTheServicesOwnDirectory() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("cluster-lna-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let answers = Answers(refusals: 6) + let said = Said() + ClusterLocalNetworkAccess.startServiceProbe(directory: directory, probe: { answers.next() }, fastSeconds: 0.005, + intervals: (fast: 1_000, slow: 20_000), say: { said.add($0) }) + let file = ClusterLocalNetworkAccess.reportFile(in: directory) + let deadline = Date().addingTimeInterval(10) + var state: ClusterOnboardingLocalNetwork? + while Date() < deadline, state != .allowed { + if let data = try? Data(contentsOf: file) { + state = (try? JSONDecoder().decode(ClusterLocalNetworkAccess.Report.self, from: data))?.state + } + usleep(5_000) + } + #expect(state == .allowed, "the late Allow reaches the report") + usleep(100_000) + #expect(answers.count == 7, "six refusals, then allowed, then no more probes: \(answers.count)") + #expect(said.all == ["local network access for this service: blocked", "local network access for this service: allowed"], + "each change said once: \(said.all)") + #expect(file.deletingLastPathComponent().standardizedFileURL == directory.standardizedFileURL, "the report is in the service's own directory") + } + + final class Answers: @unchecked Sendable { + private let lock = NSLock() + private var refusals: Int + private var probes = 0 + init(refusals: Int) { self.refusals = refusals } + var count: Int { lock.withLock { probes } } + func next() -> ClusterOnboardingLocalNetwork { + lock.withLock { + probes += 1 + guard refusals > 0 else { return .allowed } + refusals -= 1 + return .blocked + } + } + } + + final class Said: @unchecked Sendable { + private let lock = NSLock() + private var lines = [String]() + func add(_ line: String) { lock.withLock { lines.append(line) } } + var all: [String] { lock.withLock { lines } } + } +} From ac21409e11453e03858de7b0dd5bd5414c3096d1 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:30:16 -0800 Subject: [PATCH 0200/1441] fix(cluster): the first Mac's wait line names this Mac MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two-Mac smoke test of b65ae59cf2 showed the fresh setup's opening wait line ("This Mac leads. It waits up to 10 minutes…") still unnamed while the paired line and the repeat-run banner named the Mac. The pairing state machine now takes this Mac's shown name, so on identical Macs the first line the leader prints says which physical Mac it is too. Tested: ClusterOnboardingChecks 708/0 (two new expectations). Co-Authored-By: Claude Opus 5.5 --- .../Distributed/Onboarding/ClusterOnboardingFlow.swift | 9 ++++++--- .../Tests/ClusterOnboardingChecks/OnboardingChecks.swift | 5 +++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift index 20b1d184b8..5ab23c1ab9 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift @@ -734,8 +734,10 @@ public struct ClusterOnboardingPairing: Sendable, Equatable { private var peerAnswered = false /// The code is on screen and waits for its answer (`codeAnswers`). public private(set) var asking: String? + /// This Mac's own name, said beside "this Mac" (`ClusterOnboardingDriver.thisMac`). + private let named: String? - public init() {} + public init(named: String? = nil) { self.named = named } /// The one thing to do on the other Mac while this one waits: said last, so it is the line the person reads. public static let otherMacLine = "Now run `darkbloom cluster` on the other Mac." @@ -769,7 +771,8 @@ public struct ClusterOnboardingPairing: Sendable, Equatable { role = .leader guard !announcedWait else { return [] } announcedWait = true - return ["This Mac leads. It waits up to 10 minutes for the other Mac (q cancels).", Self.otherMacLine] + return [ClusterOnboardingDriver.thisMac(named: named) + " leads. It waits up to 10 minutes for the other Mac (q cancels).", + Self.otherMacLine] case .joining: let yielded = role == .leader phase = .joining @@ -1090,7 +1093,7 @@ public enum ClusterOnboardingDriver { let events = ClusterOnboardingMailbox() let outcome = ClusterOnboardingMailbox() Thread.detachNewThread { outcome.post(operations.pair { events.post($0) }) } - var pairing = ClusterOnboardingPairing() + var pairing = ClusterOnboardingPairing(named: shownName(operations.thisMacName())) var result: ClusterOnboardingPairResult? func show() { for event in events.take() { for line in pairing.handle(event) { console.say(" " + line) } } } while result == nil { diff --git a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift index 382b221d71..474b5d49b8 100644 --- a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift +++ b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift @@ -2080,6 +2080,9 @@ import Darwin expect(D.leaderSubtitle(named: nil) == D.leaderSubtitle, "names: unknown, unchanged") expect(D.followerSubtitle(memberResume(), named: "Studio B") == "This Mac (Studio B) follows the other Mac (Apple M3 Ultra, 256 GB)", "names: the member's opening") + var waits = ClusterOnboardingPairing(named: "Studio A") + expect(waits.handle(.waitingAsLeader).first == "This Mac (Studio A) leads. It waits up to 10 minutes for the other Mac (q cancels).", + "names: the first Mac's wait") var leads = ClusterOnboardingPairing() expect(leads.finished(.paired(role: .leader, peerName: "Apple M5 Ultra, 256 GB"), named: "Studio A").last == "\u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). This Mac (Studio A) leads.", "names: the leader's paired line") @@ -2097,6 +2100,8 @@ import Darwin expect(paired.finish() == 0, "names: served") expect(paired.text.contains(" \u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). This Mac (Studio A) leads.\n"), "names: identical Macs, this one named where it says it leads") + expect(paired.text.contains(" This Mac (Studio A) leads. It waits up to 10 minutes for the other Mac (q cancels).\n"), + "names: identical Macs, this one named where it starts waiting") for (label, resume, name, opening) in [ ("leader", ClusterOnboardingResume(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), "Studio A", "This Mac (Studio A) leads the cluster"), From 13dd7edf8ff815164777fe0d297c0b1167950755 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:46:15 -0800 Subject: [PATCH 0201/1441] fix(cluster): wait for the sudo link script with ProcessExitObserver CI's ChildExitWaitConventionTests (shard 5) flagged ClusterLocalNetworkAccess.runLinkScriptWithSudo: provider code waits for a child through ProcessExitObserver, never Process.waitUntilExit(), whose run loop slices can stall a dispatch thread. The sudo run of the link script now starts and waits through the observer, as ReportCommand and LogsCommand do. Tested: swift build --build-tests; ChildExitWaitConventionTests and the Local Network probe test pass. Co-Authored-By: Claude Opus 5.5 --- .../Distributed/Onboarding/ClusterLocalNetworkAccess.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift index 282e20be42..5843970ca2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift @@ -173,8 +173,9 @@ public enum ClusterLocalNetworkAccess { process.standardInput = FileHandle.standardInput process.standardOutput = FileHandle.standardOutput process.standardError = FileHandle.standardError - do { try process.run() } catch { return false } - process.waitUntilExit() + let childExit = ProcessExitObserver() + do { try childExit.run(process) } catch { return false } + childExit.wait() return process.terminationStatus == 0 } } From 02bb2899ebfc0280f61b222d47c1927f56ee7478 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Mon, 2 Nov 2026 23:23:18 -0800 Subject: [PATCH 0202/1441] docs: reconcile pipeline notes with current dev Preserve the authored pipeline decode notes and the current dev documentation before a non-force dev refresh. Only documentation conflict preparation; no production qualification claim. AI-assisted integration by Darkbloom Provider (Hermes). --- docs/architecture/hardware-support.md | 57 +++++- docs/architecture/inference.md | 252 ++++++++++++++++++++++++-- 2 files changed, 283 insertions(+), 26 deletions(-) diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index d74f5b25b9..4da0ba050d 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1220,17 +1220,54 @@ Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacem ### Qwen27 TP batch prefix ownership -`QwenTensorParallelBatchPrefixBudget` separately bounds every compact attention, -conv and SSM array using the native allocator metadata. Full unsliced geometry -conservatively covers either rank and unequal shares. The complete native -batch allowance adds one snapshot bank per live lane plus two banks for the -resident cache; the existing live-state, gather, replacement and collective -charges remain. The metadata planner and verified LOAD call the same helper. -A reused prefix does not lower admission or refund the destination's future -state. The configured budget is a ceiling; cache arrays materialize only on -capture. See [prefix ownership](prefix-cache.md#cluster-sliding-prefix-adoption). +`QwenTensorParallelBatchPrefixBudget` prices one plain lane's prompt-prefix +capture, separately bounding every array with the native allocator metadata: +its own heads' keys and values to its deepest kept boundary, and one +convolution and SSM state for every boundary a prompt with that deepest +boundary keeps (`pricedStates`: the deepest, the margin boundary, and the +stripe boundaries up to nine, so at most eleven, and never fewer for a longer +prompt). Each request's reservation charges its own prompt's capture +(`QwenTensorParallelRequestCharge`); LOAD and the placement quote charge one +capture of the profile's longest prompt per lane (`promptTokens`), and nothing +for a resident tier. The geometry is the rank's own heads at LOAD and in each +rank's placement quote; without a rank, the full unsliced geometry covers either +rank and unequal shares. The existing live-state, gather, replacement and +collective charges remain, and a reused prefix does not lower admission or +refund the destination's future state. + +The memory tier that keeps captures after their requests is charged nowhere. +Its budget is half the room LOAD measures beside its whole quote +(`ClusterStagePrefixBudget.roomBytes`, `QwenStagePrefixCache.budget(roomBytes:)`): +at most a thirty-second of the Mac's memory, in 256 MiB steps, and 0 when the +room is under 512 MiB. The reservation and running-batch gates do not credit +its entries as the owner's own allocations, nor, while the SSD writer is busy, +up to its queue's byte bound for the retired captures it still holds; the +writer drains and then the entries give way before either gate refuses +(`QwenTensorParallelSnapshotCache.yieldingMemory`). A capture always keeps what +its request's charge covers. With no tier budget it keeps nothing resident and +still writes its SSD record. A request whose prompt exceeds the memory plan's +is charged at its own prompt, outside LOAD's per-lane quote +([native context](inference.md#qwen27-tensor-parallel-native-context)). The assistant's lanes +keep their single 4,096-token frontier and its two charged resident banks +(`QwenTensorParallelMTPPrefixBudget`). See [prefix ownership](prefix-cache.md#cluster-sliding-prefix-adoption). + +The registered Qwen3.8 27B, one rank's own heads at the memory plan (32,768 +prompt tokens, 65,536 context, 16 KiB allocator pages; +`QwenTensorParallelBatchPrefixTests`, `QwenTensorParallelPrefixPlacementTests`): + +| Term | Before (`qwen-tp-batch-grid-prefix-4096-v1`) | Now (`qwen-tp-batch-prefix-depth-v2`) | +|---|---|---| +| A lane's capture | 212,860,928 B (4,096 tokens) | 1,764,753,408 B (rows to 32,256 and nine recurrent states) | +| Resident tier in the quote | 425,721,856 B (two banks) | 0 (half the measured room) | +| LOAD request bytes, one lane | 9,184,591,872 B | 10,310,762,496 B | +| LOAD request bytes, eight lanes | 28,471,181,312 B | 40,460,599,296 B | +| Idle pairs the planner places tensor parallel on, one lane | 2 x 36 GiB and larger | the same; a rank needs 1,126,170,624 B more | +| The same, eight lanes | 2 x 96 GiB and larger | the same; a rank needs 11,989,417,984 B more | + +The planner rows leave out the vision tower's resident bytes, as the served +layout does; both columns leave them out alike. Source: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift` -(`derive`). +(`captureBytes`, `derive`). A drained automatic batch replacement uses the device index and this pair's recorded keyed-link measurement. Missing or invalid measurements continue to diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index d032d74517..8273852658 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1581,6 +1581,15 @@ never crosses a cache scope; `DARKBLOOM_TTFT_PROMPT_CACHE=0` restores the unchanged path ([configuration](../reference/configuration.md#prompt-preparation-and-admission)). +Decoded text keeps the spacing the tokens spell, unless the tokenizer config sets +`clean_up_tokenization_spaces` to true. swift-transformers reads an absent key as +true, which drops the space in sequences such as ` .`, ` ,`, ` ?`, ` !` and ` 's`, +and can make a streamed decode repeat bytes it already sent. Gemma 4's published +config omits the key. `LocalTokenizerLoader` +(`provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift`) +resolves an absent key to false in memory, as Python Transformers does, and keeps +an explicit Boolean. Input IDs, sampling and cache keys do not depend on it. + Bridge-side order (`EngineV2Bridge.submitTokenized`): request-id normalisation (`maxRequestIdLength = 256`; duplicates rejected) → first deadline check → translation (`maxTokens = request.max_tokens ?? @@ -1594,11 +1603,21 @@ The SSD stage runs before `engine.submit`, off the engine queue, while the engine may be evaluating another request's prefill chunk under MLX-Swift's process-wide `evalLock`. A provider-staged complete-checkpoint import therefore creates its destinations already available from host bytes and never evaluates -or fences them, so staging does not wait for that chunk +or fences them, so staging does not wait for that chunk; its CPU decode tests each +restored row once for values the native dtype cannot hold, and a refused row never +reaches a destination ([destination contract](../reference/ssd-kv-cache.md#complete-checkpoint-payload), `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTransfer.swift` (`CBv2CompleteCheckpointImport`)). +A donor's stream retires only after its complete checkpoint is published +(`EngineLoopV2.finishAfterCompletePrefixPublication`), so export time is added +to the donating response's end. At a quantized checkpoint precision, export +encodes each older attention row on the CPU with one prepared row encoder per +segment read, which writes the scalar codec's exact bytes +([conversion](../reference/ssd-kv-cache.md#complete-checkpoint-payload), +`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/NativeQuantizedCheckpointTensorSource.swift`). + Segmented paged admission no longer waits for queued GPU work. A released row's free 64 MiB segments are parked per pool, up to `min(2 GiB, slot grant / 8)`, outside the grant, floor and ledger charge, and the next admission of the same @@ -2891,7 +2910,15 @@ 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. Under a model approval, which names no build, the plan also carries +coordinator. So a cluster served through Darkbloom is planned with equal shares +only (`ClusterPlacementPolicy.equalTensorShares`, which +`ClusterPlacementFlow.decide` sets for the coordinator scope: the guided setup, +the plans it forwards and the service's re-plans after an update or a memory +refusal), and a local cluster keeps the faster unequal split. Each Mac's check +of a cluster approval refuses one beside unequal shares +(`ClusterApprovalAttachment.attachment`; +[coordinator-paired member](../reference/configuration.md#coordinator-paired-member)). +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 @@ -2961,9 +2988,16 @@ live line (`ClusterOnboardingDriver.move`, `ClusterOnboardingProgress.live`), laid out by `TransferProgressLine` through `ClusterTransferReports`; a transcript without a live line keeps only the reports `TransferProgressLine.takeLogLine` marks and the lines for the record. +Its restart line reads FileVault with `fdesetup isactive` +(`OnboardingLive.fileVaultOn`): five seconds, then SIGTERM and two more, and no +answer reads as unknown. The exit comes from `ProcessExitObserver`, which does not run the calling thread's run loop. After a Darkbloom update changes a Mac's worker digest, the control leader's cluster service re-plans and re-adopts the same model by itself -(`ClusterService.checkForUpdate`, `ClusterOnboardingUpdate`). A model change of +(`ClusterService.checkForUpdate`, `ClusterOnboardingUpdate`), once both Macs +answer with the same worker build (`ClusterOnboardingUpdate.oneBuild`): the +[pair's coordinated update](../provider/cluster-always-on.md#the-pairs-coordinated-update) +restarts the two Macs seconds apart, and a plan made while one still runs the +other build would fail and wait 600 s. A model change of a serving cluster (`m`, or `darkbloom cluster local `) plans the same way: its list was priced while the running parts held their memory, where tensor parallel may not fit now, so once both parts stopped and both Macs gave the @@ -3538,6 +3572,41 @@ part the same key with a different file (`ClusterServiceAgent.partHealthPath`, service's heartbeat and still waits for its registration as a supervised member. An empty or absent key is passed on unchanged. +## Cluster service listeners follow the cable and the pairing + +Each Mac's cluster service answers the other Mac on two listeners: the setup +exchange's (`ClusterSetupLinkExchange.port`) and the control lease's +(`ClusterSetupLinkExchange.controlPort`). A listener binds the cable's port and +address as they are when it starts, and is keyed with the pairing that holds +then (`ClusterSetupLinkExchange.Responder.pairing`). It refuses every handshake +the other Mac keys with a later pairing (`handshakeRejected` there), so a +listener left on an earlier pairing refuses every lease and setup request. + +At most once per `ClusterService.listenerCheckSeconds` +(`static let listenerCheckSeconds: Double = 5`) seconds for each listener, +`ClusterService.listenerChange` compares the listener with what holds now: + +- a cable on another port or address restarts it there; +- another pairing restarts it with that pairing. `ClusterSetupLinkExchange.Pairing.Identity` + compares both pins, the cluster label, the link epoch and the edge, never the + edge secret; every ceremony derives a new link epoch, so pairing the same two + Macs again is another pairing; +- no pairing at all stops it; +- a pairing store that cannot be read changes nothing, as an unreadable setup + record leaves a running part alone. + +Each restart or stop of the exchange's listener names its reason in the service +log; the control lease's listener restarts and stops without a line. The +control node of an earlier pairing is dropped once the pairing names another +local or peer member (`ClusterService.ensureControl`). + +Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift` +(`ClusterService.listenerChange`, `ensureResponder`), +`provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterServiceControl.swift` +(`ensureControlResponder`, `ensureControl`) and +`provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupLinkExchange.swift` +(`ClusterSetupLinkExchange.Responder`). + ## GLM tool-stream completion GLM tool output uses the SDK GLM parser to validate the complete tool suffix at @@ -3790,7 +3859,24 @@ forwards fuse, on the families measured byte-equal to the unfused operations the Gated DeltaNet convolution step (concatenation, depthwise convolution and SiLU) and its q/k normalization, the attention output gate, the SwiGLU product, and a single vector's gate, up and SwiGLU in one launch (a window keeps the two -projections: the fused kernel measured slower there). A residual stream +projections: the fused kernel measured slower there). That one-launch SwiGLU +(`AffineQuantizedVectors.projectSwiGLU`) computes its sigmoid as MLX's +`Sigmoid` does, with `metal::precise::exp`; Metal's default fast `exp` rounds +the bf16 gate -6.84375 to another SwiGLU value. Only a tensor-parallel batch +session's one-row decode step takes that kernel (it needs +`Qwen35BatchDecodeScope.exactVectors`; single-Mac serving and +`darkbloom-cluster-tp-check run` never do), so with the fast `exp` a registered +27B row alone left the bits of its cohort and window steps. Tensor-parallel +serving output recorded with an earlier build differs only where such a step +met that gate, and is regenerated once. +`AffineQuantizedVectorsTests.swigluEqualsTheCompiledSwiGLUAtEveryGateValue` +compares the kernel with the two projections and the compiled SwiGLU at every +normal bf16 and f16 gate value. The convolution step's SiLU +(`GatedDeltaConvolution`) still uses the default `exp`, so it can round +differently from the unfused SiLU that prompt chunks of more than eight tokens +take (`Qwen35DecodeFusionParityTests` finds f16 and f32 differences); every +decode row count and window of up to eight columns takes that kernel, so rows +still agree. A residual stream narrower than its norms (the Prism/Bonsai packs: FP16 packed embedding rows under FP32 norms and projections) keeps the unfused sum that promotes it to FP32 on every family (`Qwen35DecoderLayer.residualNorm`); the fused step @@ -4037,7 +4123,7 @@ See [focused cluster tests](../developer/test.md#focused-qwen35-moe-tensor-paral GLM's placement family (`GLM5NextPlacementFamily`, `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Metadata/GLM5NextServingMetadata.swift`) offers the two-rank plan `glm5_next_heads_and_expert_channels_v1` whenever the registered row lists `tensor_parallel_v1` and the geometry halves. Each text-layer tensor is divided or replicated exactly as the SDK's `GLM5NextTensorShard.splitAxis` loads it; the embedding, final norm and head are replicated, and the NextN layer and vision tower belong to no text range. Every rank decodes in speculative rounds with the NextN layer, which it holds whole beside its share, so the plan states it (`ClusterTensorParallelFamilyPlan.speculativeHead`, `GLM5NextPlacementFamily.tensorParallelSpeculativeHead`): the planner charges each tensor-parallel rank the layout's `speculativeHead` part (4,183,320,576 stored bytes, each tensor in whole pages, as `mtp_bytes` on the worker's load line) and the request memory the rounds add at the memory plan's context (the larger of the contiguous and the paged NextN charge of `GLM5NextTensorParallelRequestCharge`), and divides a token's predicted decode step by the speed-up the pair measured at the runtime's depth over one token per step (76.0 against 62.6 tok/s at depth 2, `GLM5NextPlacementFamily.measuredTensorParallelDecode`). Served tensor-parallel requests are taken back to one-token steps by the same speed-up before they correct the shares (`ClusterServedCalibration`), so the next plan predicts what was served. Without it the plan priced no NextN bytes and one token per step: it could admit a pair the load gate then refused, and it predicted decode too slow. Three terms of the load gate are not in the plan yet: the vision tower rank 0 holds for media (1.13 GB), the freed-buffer cache (`GLM5NextTensorParallelResidentRuntime.freedBufferCacheBytes`) and the bulk prefill's further workspaces and sealed sums' buffers (`bulkPrefillChunkTokens`). On two M5 Ultra 256 GB, adding them to the planner's estimate as it stands would put each rank's need above the at-rest ceiling (`ClusterDeviceProfile.atRestAdmissibleBytes`), so the pair would no longer plan tensor parallel; they wait for the gate's own charge to replace the estimate rather than be added to it. The plan sums two partials of the 4096-wide residual per layer and one per step (91 per decode step); the partials are the row-parallel projections' bfloat16 outputs, sent as they are and added in float32 with one rounding (`GLM5NextTensorParallelResidentRuntime.partialsTransport`, bound into the load agreement). That is bit-identical to widening them to float32 before the link, as `ClusterTensorParallelTerms.current` (`partialsDType` float32) describes, with half the bytes: GLM's projections never kept float32 partials (flagged for platform review) and holds request state whole on each rank, since the DSA latent cache is replicated. The pipeline's private image profile stays pipeline-only, in both the layout and the capability; tensor parallel serves media under the text profile (below). The hardware prior (`ClusterHardwarePrior.decodeBytesPerToken`) counts a mixture of experts' routed experts at the fraction a token is routed to (`ClusterRoutedExperts`; 8 of GLM's 288), not every expert byte. Of the bytes a step reads, a tensor-parallel share divides only the plan's divided bytes (`dividedDecodeFraction`), because every rank reads its replicated bytes whole. On two identical M5 Ultra 256 GB with GLM measured alone the product's rule (tensor parallel first wherever it fits) places tensor parallel on equal shares with the NextN layer priced, both on a new pair before any load measured the link and after the first load's keyed probe; the planner's own speed comparison (the plan tool without `--tensor-parallel-first`) chooses tensor parallel once the keyed link is measured and a pipeline before (`GLMTensorParallelChecks`; through `ClusterPlacementFlow.decide` in `PlacementSetupCheck.glmTensorParallelPair`). The pair serves it with eight lanes (`DistributedInstalledPlan.tensorParallelBatchLanes`). -A chosen GLM tensor-parallel placement is served by `GLM5NextTensorParallelResidentRuntime` (`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/`). Each rank verifies the whole artifact, loads every layer's share through `GLM5NextTensorShard`, and sums each layer's attention and feed-forward partials (bfloat16, added in float32) over the sealed all-sum (AES-256-GCM on the keyed JACCL data plane; a peer piece that does not open fails the request). On the JACCL mesh the sum is streamed in one CPU-stream task: each 256 KiB sealed piece carries its own tag, crosses as soon as it is sealed and is opened and added as soon as it lands, so only the first and last pieces wait for crypto (`SealedAllSum`, `sealed_stream.h`); other groups seal and gather the whole frame. Prefill runs 4,096-token chunks on both ranks (`prefillChunkTokens`: the M5 neural accelerators reach ~94 TFLOPS on 4,096-row NVFP4 matmuls against ~62 at 2,048; charged as a second request workspace), each chunk as two micro-batches whose sums are issued as soon as their partials exist, so one computes while the other's sum crosses the link (`GLM5NextTextStage.tensorParallelMicroBatches`; 2,532 against 1,767 tok/s whole); sampled decode runs one token per step, and the ranks' tokens must agree at every step. A tensor-parallel worker lifts MLX's per-command-buffer input-size bound before anything native starts (`WorkerCommandBufferBudget`, `MLX_MAX_MB_PER_BUFFER`; a launcher value is kept): every MoE launch takes a whole expert bank as input, so decode committed ~88 buffers a step instead of ~22 (measured 19.0 -> 16.8 ms a step; the 50-operation bound stays). Decode steps, MTP rounds and lane rounds encode with at most 100 operations a buffer on the thread that encodes them (`GLM5NextTensorParallelResidentRuntime.decodeCommandBuffers`), above the owner's 16-operation rank guard, which prefill keeps: each further buffer is a GPU gap of about 10 µs (13.24 -> 12.56 ms a step, tokens identical). An MTP round submits its NextN priming and proposals as soon as they are built, so the GPU runs them while the host builds the verification forward (`GLM5NextTensorParallelSpeculation.EarlySubmission.proposals`; before, the whole round's graph, about 1.8 ms of host work, was built with the GPU idle): a depth-2 round 23.06 -> 21.64 ms (95.9 -> 102.7 tok/s), two lanes 115.2 -> 121.6 tok/s, tokens and top logits identical. A greedy round reads out half the head's vocabulary rows on each rank and agrees on every window token through the round's existing agreement sum: each rank's slot carries its half's maximum and argmax, and the larger maximum wins, rank 0's lower index on a tie, which is the whole head's argmax (`GLM5NextTensorParallelSpeculation.splitsVocabulary`, `GLM5NextTextStageReadout.allTokensVocabularyPart`): 21.32 -> 21.05 ms a depth-2 round, tokens identical; sampled rounds keep the whole head. A GLM tensor-parallel worker lets the hyper-connection site that reads a sum wait for it itself (`WorkerFenceFusion`: `MLX_METAL_FENCED_INPUTS`; a launcher value is kept), one dependent dispatch fewer on each of a step's 90 sums. The core's fused fence update (`MLX_METAL_FUSED_FENCE_UPDATE`) stays a launcher's choice: above 32 KB a partial's update is split over several threadgroups and that path never signals the CPU, so two batched lanes (six verification rows) stalled every round about 0.7 s. The load gate charges the shard, the NextN layer, both pipeline ranks' request budgets plus speculative decode's request state, and a 4 GiB freed-buffer cache (the load runs with MLX's cache at zero; serving with it at zero halves prefill and decode). READY names the installed partition's plan hash, as a pipeline rank does. Prompt prefixes are reused as under Qwen tensor parallel: each rank keeps its own stage cache (its heads' KDA state and the replicated DSA latents) at a prompt's last whole chunk boundary in memory (`GLM5NextTensorParallelPrefixCache`, at most 8 GiB), and a request restores the longest boundary both ranks hold after one sealed vote, or neither does; entries give way first under memory pressure and every failure drops them. Each request's entries are its own partition's (`GLM5NextTensorParallelResidentRuntime.prefixScope`, see [tenant partitions](prefix-cache.md#cluster-prefix-tenant-partitions)): a tenant's boundaries are voted, restored and kept for that tenant alone, and a request whose cache is off votes and keeps none, on a cache-on request's frames. Each rank also keeps a cleanly retired request's boundary in the encrypted SSD tier, read from the memory entry's pages behind serving; the vote counts those records, and a boundary taken from one is restored into the request's own pages only after a second sealed exchange confirms both ranks have it, in the same partition (`prefixDiskScope`), so a restarted pair restores what the last one kept ([GLM TP prefix SSD tier](prefix-cache.md#glm-tp-prefix-ssd-tier)). The link probe that prices the reduction (`QwenTensorParallelLinkProbe`, recorded by both pipeline and tensor-parallel loads) times the sealed all-sum after one unmeasured pass with the same bounded cache, so the planner prices what a ready rank pays (a cold probe read 16.9 ms per 32 MiB against 5.8 ms ready). +A chosen GLM tensor-parallel placement is served by `GLM5NextTensorParallelResidentRuntime` (`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/`). Each rank verifies the whole artifact, loads every layer's share through `GLM5NextTensorShard`, and sums each layer's attention and feed-forward partials (bfloat16, added in float32) over the sealed all-sum (AES-256-GCM on the keyed JACCL data plane; a peer piece that does not open fails the request). On the JACCL mesh the sum is streamed in one CPU-stream task: each 256 KiB sealed piece carries its own tag, crosses as soon as it is sealed and is opened and added as soon as it lands, so only the first and last pieces wait for crypto (`SealedAllSum`, `sealed_stream.h`); other groups seal and gather the whole frame. Prefill runs 4,096-token chunks on both ranks (`prefillChunkTokens`: the M5 neural accelerators reach ~94 TFLOPS on 4,096-row NVFP4 matmuls against ~62 at 2,048; charged as a second request workspace), each chunk as two micro-batches whose sums are issued as soon as their partials exist, so one computes while the other's sum crosses the link (`GLM5NextTextStage.tensorParallelMicroBatches`; 2,532 against 1,767 tok/s whole); greedy and sampled requests then decode in MTP rounds (below). A tensor-parallel worker lifts MLX's per-command-buffer input-size bound before anything native starts (`WorkerCommandBufferBudget`, `MLX_MAX_MB_PER_BUFFER`; a launcher value is kept): every MoE launch takes a whole expert bank as input, so decode committed ~88 buffers a step instead of ~22 (measured 19.0 -> 16.8 ms a step; the 50-operation bound stays). Decode steps, MTP rounds and lane rounds encode with at most 100 operations a buffer on the thread that encodes them (`GLM5NextTensorParallelResidentRuntime.decodeCommandBuffers`), above the owner's 16-operation rank guard, which prefill keeps: each further buffer is a GPU gap of about 10 µs (13.24 -> 12.56 ms a step, tokens identical). An MTP round submits its NextN priming and proposals as soon as they are built, so the GPU runs them while the host builds the verification forward (`GLM5NextTensorParallelSpeculation.EarlySubmission.proposals`; before, the whole round's graph, about 1.8 ms of host work, was built with the GPU idle): a depth-2 round 23.06 -> 21.64 ms (95.9 -> 102.7 tok/s), two lanes 115.2 -> 121.6 tok/s, tokens and top logits identical. A greedy round reads out half the head's vocabulary rows on each rank and agrees on every window token through the round's existing agreement sum: each rank's slot carries its half's maximum and argmax, and the larger maximum wins, rank 0's lower index on a tie, which is the whole head's argmax (`GLM5NextTensorParallelSpeculation.splitsVocabulary`, `GLM5NextTextStageReadout.allTokensVocabularyPart`): 21.32 -> 21.05 ms a depth-2 round, tokens identical; sampled rounds keep the whole head. A GLM tensor-parallel worker lets the hyper-connection site that reads a sum wait for it itself (`WorkerFenceFusion`: `MLX_METAL_FENCED_INPUTS`; a launcher value is kept), one dependent dispatch fewer on each of a step's 90 sums. The core's fused fence update (`MLX_METAL_FUSED_FENCE_UPDATE`) stays a launcher's choice: above 32 KB a partial's update is split over several threadgroups and that path never signals the CPU, so two batched lanes (six verification rows) stalled every round about 0.7 s. The load gate charges the shard, the NextN layer, both pipeline ranks' request budgets plus speculative decode's request state, and a 4 GiB freed-buffer cache (the load runs with MLX's cache at zero; serving with it at zero halves prefill and decode). READY names the installed partition's plan hash, as a pipeline rank does. Prompt prefixes are reused as under Qwen tensor parallel: each rank keeps its own stage cache (its heads' KDA state and the replicated DSA latents) at a prompt's last whole chunk boundary in memory (`GLM5NextTensorParallelPrefixCache`, at most 8 GiB), and a request restores the longest boundary both ranks hold after one sealed vote, or neither does; entries give way first under memory pressure and every failure drops them. Each request's entries are its own partition's (`GLM5NextTensorParallelResidentRuntime.prefixScope`, see [tenant partitions](prefix-cache.md#cluster-prefix-tenant-partitions)): a tenant's boundaries are voted, restored and kept for that tenant alone, and a request whose cache is off votes and keeps none, on a cache-on request's frames. Each rank also keeps a cleanly retired request's boundary in the encrypted SSD tier, read from the memory entry's pages behind serving; the vote counts those records, and a boundary taken from one is restored into the request's own pages only after a second sealed exchange confirms both ranks have it, in the same partition (`prefixDiskScope`), so a restarted pair restores what the last one kept ([GLM TP prefix SSD tier](prefix-cache.md#glm-tp-prefix-ssd-tier)). The link probe that prices the reduction (`QwenTensorParallelLinkProbe`, recorded by both pipeline and tensor-parallel loads) times the sealed all-sum after one unmeasured pass with the same bounded cache, so the planner prices what a ready rank pays (a cold probe read 16.9 ms per 32 MiB against 5.8 ms ready). Greedy requests under GLM tensor parallel decode speculatively with the model's own NextN (MTP) layer (`GLM5NextTensorParallelResidentRuntime.mtpDepth`, depth 2; `GLM5NextTensorParallelSpeculation`). Every rank loads the layer whole beside its shard (about 4.2 GB; it shares the replicated embedding and head and needs no sums), so both ranks propose the same tokens from the same inputs. A round proposes up to `mtpDepth` tokens (step 0, then index-shared continuations for depth 2 and 3), verifies the last committed token and the proposals in one stage forward (`GLM5NextTextStage.prepareVerification`: a `[1, 1 + depth]` window through the same 91 sums), and keeps the longest prefix of proposals equal to the target's greedy tokens, plus the target's next token. Each KDA layer adopts the state it captured after the last kept token and each DSA history drops the rest (`GLM5NextTextStageCandidate.commit(afterEvaluating:keeping:)`), so a rejected proposal costs no replay forward. The round's one sealed reduction carries each rank's target tokens, proposals and stop flag: tokens or proposals that differ end the request, and a stop flag on either rank ends both after the same round. Rounds are not pipelined; each reads its agreement before the next is built, but a round's tokens are committed while the next round runs (`GLM5NextTensorParallelSpeculation.round`, `whileRunning`), unless they end the request. The NextN history is primed from the prompt's hidden rows (history only: no attention, MoE or readout) and afterwards only from verified pairs, and prompt-prefix entries keep it at their boundary. Tokens leave one at a time through the same stop and length rules. The output is the target's greedy tokens, computed in windows of up to `1 + depth` rows instead of one-row steps. MLX runs a one-row quantized projection (and the head) as `qmv` and a multi-row one as `qmv_wide`, which reduces K in a different order, so every window rounds differently from a one-token step and the KDA and DSA histories carry that forward: a long speculative decode drifts from one-token greedy decode and can choose a different token after tens to hundreds of tokens, not only at near-ties (measured on the 3,931-token prompt: first difference at output 104 for depths 1 and 2, and at 89 for depth 3; `qmv_wide` rounds a row the same in two- and three-row windows). The ranks never differ, and a one-token window is bitwise an ordinary step (`darkbloom-cluster-tp-check glm --mtp-check one-token`; `keep-first` decodes one token per round through full windows to separate this arithmetic from acceptance and rollback). On the pair (sealed, 256 tokens) decode measured 62.6 tok/s one token per step, 68.7 at depth 1, 76.0 at depth 2 (2.24 tokens a round) and 71.8 at depth 3. Sampled requests decode in rounds too: each proposal is drawn with the request's own sampler and the keyed noise of the output index it is for (coupled drafting, `GLM5NextTensorParallelResidentRuntime.coupledDraftSharpness`), and every committed token is the target's draw from its window logits; the sampler moves only acceptance. The load agreement binds the depth (`glm5-next-tp-mtp-v1`). The planner prices the rounds and the NextN layer as described above (`ClusterTensorParallelSpeculativeHead`). @@ -4045,7 +4131,7 @@ The proposals a round verifies can follow the pair's load (`GLM5NextTensorParall GLM image and video input under tensor parallel (`ClusterGLMMedia`, contract `glm53_tp_media_v1`) is the single-Mac product's media path split across the leader and rank 0. The leader runs the product's code up to the vision tower (`DistributedGLMMediaIngress`): `EngineV2VisionPrefill.glm5NextUserInput` (the bounded `MediaIngest` decode and every product cap) and `GLM5NextProcessor.prepareDetailed` with the artifact's processor budgets and the thinking-off tokenizer, on the CPU device, so the expanded prompt, its spans and its patches are the product's; it checks them as `buildGLM5NextSubmission` does and describes each part: its encoded bytes' digest, grid, per-pair token offsets, the product's tower limits for one frame (`VisionTowerBudget.glm5FrameLimits`) and a SHA-256 of its prepared patches. Rank 0's reservation carries the encoded bytes as well (at most 32 MiB, the one worker command above the 8 MiB command bound: `ClusterWorkerLimits.mediaCommandBytes`); rank 1's carries the digests only, and both bind the envelope's fingerprint into the request digest. Rank 0 holds the vision tower (1.13 GB of bfloat16 weights, charged at load). From the reservation on, off the executor and without MLX, rank 0 rebuilds the ingest's media values, prepares them with the SDK's `GLM5NextProcessor.prepareMediaValues` (the media half of `prepareDetailed`, as host values) and requires every grid and patch digest to equal the leader's; the reservation itself returns at once. When the request opens, after the digest agreement, both ranks exchange small sealed sums carrying that preparation's status and each rank's stop until it ended (a stop ends the request on both ranks before anything is made; a failed or different preparation is an agreement failure on both). Rank 0 then runs the tower once per temporal pair with the leader's limits on the default GPU stream, as the product does, and one sealed all-sum per frame carries the features to rank 1, which adds negative zero (the additive identity for every value, signed zeros included, rounded once); rank 0 checks each result bit for bit and a last small sum carries its verdict, so both ranks end together on a difference. Every one of these sums is evaluated alone. With batch lanes a media lane runs the same open, frames and rounds: rank 0 joins it only once its preparation ended (`GLM5NextTensorParallelLaneReservation.joinable`), so the running lanes never wait for a decode, and its media charge is held with its lane state. A prefill frame that holds media positions replaces their embedding rows with the features by concatenation (the product's `spliceEmbeddings`) and runs from those embeddings through the same chunks and micro-batches (`GLM5NextTextStage.prepareForward(embeddings:cache:segments:readout:snapshotAfter:)`), so a frame merging several chunks stays bitwise for media rows as for text; every other row and frame is the text path's, on tensor parallel's own chunk grid. Unlike the single-Mac product, which decodes media requests target-only, a media request here decodes speculatively as text does: the NextN history is primed with the same input rows, so a media position's next input is its feature row (`GLM5NextMTP.primeHistory(shiftedEmbeddings:)`, as a multimodal target's drafter is fed). It neither restores nor stores prompt prefixes. Workers advertise the contract at READY (`ClusterWorkerReady.media`) with a request capacity that covers one media request (`GLM5NextTensorParallelMedia.capacityBytes`); a text request is still charged only its own context. The leader binds media only when both ranks advertise it, and the pipeline's private image profile is unchanged. -Rank 0 hands each committed token to its owner and reads the owner's answer late (`ClusterCommittedTokenChannel`, `WorkerRuntime.start(_:tokens:)`): it publishes the token at once, and reads the answer after the next step or round was submitted, before it publishes the next token. The protocol's token credit is unchanged (`ClusterWorkerSession` still refuses a token before the answer to the one before, and anything after a stop), but the answer's round trip through the owner (pipes, the provider's token callback and detokenizer; about 0.7 ms a token measured at the endpoint; greedy decode went from 73.5 to 76.8 tok/s through the API, matching the bench) now overlaps the next step's encoding and GPU time instead of sitting between steps. A stop answer takes effect one step or round later; that work is computed and never published, and its flag reaches the peer in the next submitted sum as before. Other runtimes publish and wait as before (the protocol's default implementation). +Rank 0 hands each committed token to its owner and reads the owner's answer late (`ClusterCommittedTokenChannel`, `WorkerRuntime.start(_:tokens:)`): it publishes the token at once, and reads the answer after the next step or round was submitted, before it publishes the next token. The protocol's token credit is unchanged (`ClusterWorkerSession` still refuses a token before the answer to the one before, and anything after a stop), but the answer's round trip through the owner (pipes, the provider's token callback and detokenizer; about 0.7 ms a token measured at the endpoint; greedy decode went from 73.5 to 76.8 tok/s through the API, matching the bench) now overlaps the next step's encoding and GPU time instead of sitting between steps. A stop answer takes effect one step or round later; that work is computed and never published, and its flag reaches the peer in the next submitted sum as before. A rank that stopped commits nothing more, but still ends at a stop token its peer commits, so both ranks leave after the same round or step: in MTP rounds, and in the one-token steps a build without the NextN layer runs (`GLM5NextTensorParallelStepLoop`, `ClusterGLMTensorParallel.speculativeDepth` 0). Rank 0's count and finish then cross in one small agreement, and rank 1 adopts them unless it stopped on its own (`QwenTensorParallelStopRule.reconcile`). Other runtimes publish and wait as before (the protocol's default implementation). GLM's decode and prefill kernels changed only in ways that keep every output bit for bit (they serve one Mac and the cluster alike). Decode: each hyper-connection site is one launch whose last threadgroup finishes the Sinkhorn and collapse (`GLM5NextHyperConnectionNormFusion`, `SplitForm.oneLaunch`); the MoE decode router spreads each expert row over 8 SIMD groups and replays top-K with `simd_max`/`simd_min` in the same order (`GLM5NextMoEDecodeKernel`); DSA decode uses smaller, more numerous threadgroups, a 1,024-thread top-k and a two-launch cache append that writes fresh buffers (`GLM5NextSparseDecodeKernel`, `GLM5NextTextCache`); per-call constants are cached and dead KDA nodes are no longer built. Prefill: the MoE gathers decode a packed NVFP4 word at a time (`GLM5NextMoEPrefillKernel`) and DSA's absorbed queries run beside the first index-score block. A prefill hyper-connection site that folds the previous expand (89 of a forward's 90) computes each expanded value inside the mix fragment that multiplies it and stores it there, so the expand's memory traffic overlaps the matrix products and no barrier precedes the mix, and its rows' collapses share one barrier (`GLM5NextHyperConnectionKernel.fusedExpandPrefillSource`; `GLM53_HC_FUSED_EXPAND=0` keeps the two-pass site): every per-element expression and sum order is the two-pass kernel's, 0.61 -> 0.56 ms a site at 4,096 rows on one M5 Ultra rank, about 5 ms per 4,096 prompt tokens per rank. Host: MLX shares generated kernel sources, resolves pipelines once and binds repeat launches without rebuilding names or keys. Core's fused fence update and fenced custom-kernel inputs (`MLX_METAL_FUSED_FENCE_UPDATE`, `MLX_METAL_FENCED_INPUTS`) are off by default; a GLM tensor-parallel rank turns the fenced inputs on (`WorkerFenceFusion`) and leaves the fused fence update to its launcher. Measured on two M5 Ultra (sealed TP2, MTP depth 2): plain decode 14.45 -> 12.43 ms a step, an MTP round 27.8 -> 23.9 ms, 15.7K-token prefill 3,819 -> 3,917 tok/s, tokens and top logits identical. Changes that only reorder sums were measured with a teacher-forced full-model perplexity bench and rejected (KDA paired order, DSA absorbed product on the tensor units, the tensor-unit prefill router, INT8 activations: +0.4 to +5.6 % perplexity, about 79 % top-1 agreement against a 99.4 % noise floor of the product's own chunking). @@ -4509,18 +4595,32 @@ synchronizes before dropping request caches on completion or failure. Copies share immutable old pages; a later write replaces the affected page handle. Sliding histories release old pages when they repack or enter the fixed ring. +Sliding pages also keep the ring's wrapped flag: a one-token write that rotates +sets it, and a chunk or trim clears it. Their `metaState` is the seven values the +pinned SDK writes for `RotatingKVCache(maxSize: window)` in the same state: keep, +window, step, offset, write index, capacity origin and wrapped flag +(`GPTOSSSlidingRing`). Restoring accepts only that layout for the cache's window, +and only with the rows that ring holds: its first `index` rows, or the whole +window once wrapped. It refuses the five-value legacy layout, a rewind reserve, a +kept prefix, and any other step, window or capacity origin. It also refuses an +unwrapped ring that has evicted rows but holds fewer than `window - 1`, which the +SDK's `trim` after eviction can leave: pages cap masks and trims by the offset, +the SDK by the rows it holds. GPT-OSS serving never reads or restores this +metadata. + `GPTOSSRequestStateBudget` keeps the existing full-request admission scope and never lowers its previous contiguous allowance. It also charges each page's allocator bound separately, the gathered attention view, and partial-page copies; sliding repacking includes old and new page versions. Physical allocation is demand-grown even though the request is admitted conservatively for its whole declared scope. LOAD and live-memory gates remain authoritative. -CPU parity against the actual SDK caches covers ring/page/chunk boundaries and -sinks. Real two-Mac numerical acceptance, resource release and performance -remain separate qualification gates. +CPU parity against the actual SDK caches covers ring/page/chunk boundaries, +metadata, restores and sinks. Real two-Mac numerical acceptance, resource release +and performance remain separate qualification gates. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift` -(`GPTOSSPagedKVCache`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift`, +(`GPTOSSPagedKVCache`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift` +(`GPTOSSSlidingRing`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift`, `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift`, and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Resident/GPTOSSResidentAdmission.swift` (`loadAgreementFingerprint`). See [focused cache checks](../developer/test.md#gpt-oss-cluster-paged-kv-checks). @@ -4853,6 +4953,32 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Reside and `MiMoV26IndependentHistoryCache.swift`. See [MiMo independent-history checks](../developer/test.md#mimo-independent-history-batch-checks). +### MiMo contiguous ring metadata + +Only image-candidate loads keep MiMo's ordinary caches: `KVCacheSimple` for +full attention and `RotatingKVCache(maxSize: window)` for each sliding window. +The four text modes use pages with cluster prefix reuse off +([independent histories](#mimo-plain-pipeline-independent-histories)), so only +image candidates take cluster prompt-prefix snapshots. `MiMoPhaseSplitState` +also handles ordinary caches, but no load reaches that branch: image candidates +refuse phase split (`MiMoResidentRuntime.load`). The pinned SDK writes a ring's +`metaState` as seven values: keep, window, step, offset, write index, capacity +origin and wrapped flag. A rewind reserve adds an eighth. + +| Path | What it writes or accepts | +|---|---| +| Model ring check (`MiMoSlidingRing.isModelRing`) | Only the model's own ring: every value except offset, write index and wrapped flag equals a fresh ring's | +| Prefix capture and restore (`MiMoStagePrefixSnapshot`) | Restores a tail at the frontier's offset and write index, not wrapped | +| Phase split (`MiMoPhaseSplitState`) | Replays the frame grid for the write index and wrapped flag; exports or adopts a ring only when its whole metadata matches | +| Verify-window rollback (`MiMoWindowRollback`) | Cuts a multi-token window's rows and rewrites only offset and write index; that window left the wrapped flag false | +| Page histories (`MiMoPhaseSplitState.pagedMetadata`) | Keep their own five values | + +The snapshot and the phase split refuse a kept prefix, another step or origin, +a rewind reserve or another layout. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoSlidingRing.swift`, +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoPhaseSplit.swift`, +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Prefix/MiMoStagePrefixSnapshot.swift` +and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoWindowRollback.swift`. + ### Gemma paged prefix restoration Installed plain Gemma pipelines retain the paged KV default at every supported @@ -4891,6 +5017,17 @@ replace full-artifact qualification. Preserve earlier solo/pair reports and failed records; remeasure the candidate with the original comparator and qualification schedules. See [the test guide](../developer/test.md). +## GPT-OSS decode command buffers + +GPT-OSS's plain decode steps (every row one token) commit a Metal command buffer +every 100 operations with no input-size bound (`GPTOSSDecodeCommandBuffers`, +through `CBv2DecodeCommandBufferLimitsProviding`). MLX's defaults commit every 40 +to 50 operations or 40 to 50 M distinct input elements, and a step's inputs include +the expert banks and each 64 MiB KV segment its history reads, so decode committed +after almost every MoE layer and waited on MLX's limit of ten command buffers in +flight. Results do not depend on the partitioning. Prefill chunks keep MLX's +defaults. + ## Nemotron prefix chunk arithmetic The registered Nemotron 3.5 Lightning stage preserves the original global @@ -5169,6 +5306,20 @@ acknowledgement. Failed release retains the reservation for cleanup or the worker's process fence. Every row's singleton and batch owners publish raw selection logprobs through the committed-token channel. +Selection checks finiteness inside its own sealed sum, as the assistant's greedy +choice does (`QwenTensorParallelNativeBatchExecutor.select`): each rank adds its +rows' non-finite logit counts beside their maximum and first global index (a +sampled cohort counts the gathered rows), and both ranks read them from the +same evaluation that yields the tokens. A non-finite logit on either rank fails +both ranks before any token is chosen, a sampler advances or anything is +published, so neither rank waits in a collective its peer never enters. The +load agreement binds this selection sum +(`qwen-tensor-parallel-selection-nonfinite-in-sum-v1`): a rank whose selection +sums other words refuses to load beside it rather than meet it in a sum of +another length. The decode step pays no separate finiteness read +(`QwenTensorParallelBatchSession.validateLogits` checks shape and dtype), and +every selected token is unchanged. + The batch path can restore mutually held original-grid prefix snapshots into fresh request-owned state. TP speculative rounds remain a separate integration. Installed owners propagate a priced saved width or explicit diagnostic width for every Qwen TP row; automatic placement @@ -5179,8 +5330,54 @@ the 27B, whose features keep it in tensor parallel, and an assistant quote bind placement to tensor parallel as before. Synthetic CPU and both-chip native fixtures are not full-artifact, RDMA, tower, throughput or endpoint evidence. +Each rank logs its decode routes once per loaded model when its native +executor first starts serving (`darkbloom-qwen-tp-decode-census-v1`, +`QwenTensorParallelBatchSession.censusLine`): every projection's route (the +batch-invariant kernel `aqv`, a row-parallel FP32 partial on it `partial`, or +MLX's own kernels with the reason, `mlx-...`) and each projection shape's +layout per vector count (plain rows of one to eight and their four-column +windows), the residual-norm form, the paged attention geometry and partition +size, the selection, and any arithmetic switch the launcher set. A registered +27B rank reports `mlx=0`. Only host values are read; nothing is evaluated. +Layouts are listed per checkpoint projection: the SDK multiplies a Gated +DeltaNet layer's four input projections as one call of their summed rows, and +fuses gate, up and SwiGLU at `swiglu_fused_vectors` only while its decode +fusions are on. A routed-expert row's switch projections are not listed. + +`QwenTensorParallelRowsCheck` checks the row contract at the registered 27B +per-rank widths (three Gated DeltaNet layers and one attention layer; the +whole 248,320-row vocabulary) with random weights that follow the registered +artifact's value statistics: MLX's affine 4-bit quantization of near-normal +weights (group 64, signed BF16 scales of 0.001 to 0.005, biases -8 times the +scale, codes about 8), its norm, convolution, `A_log` and `dt_bias` ranges, +and gate rows whose SwiGLU inputs reach its range (about ±30). A row's logits +and history equal its run alone, on a one- or an eight-lane host, beside rows +of 100 to 4,600 tokens that join and leave, across two KV segments, while an +assistant observes the cohort, and at every position of a four-column verify +window alone and in a cohort. Both ranks run it in one process +(`QwenTensorParallelRealGeometryRowsTests`, `QWEN_TP_REAL_GEOMETRY_GPU=1`) or +as two processes over the loopback ring (`darkbloom-cluster-tp-check +qwen-rows`, native or sealed sums, with the worker's arithmetic environment). +It refuses to report when a logit is not finite, when its reference logits are +not all distinct, when the long rows fit one KV segment, or when its comparison +misses a planted difference. `qwen-rows run` also loads a registered +checkpoint directory on a Mac with the memory for it, reading the files +directly as `tp-check run` does, not through the product's verified load +(`QwenTensorParallelVerifiedLoad`: no artifact hashes, inventory or load memory +gate). `qwen-rows layers` names the first decoder layer where a row's step +beside another leaves its solo bits +(`QwenTensorParallelRowsCheck.firstDifferingLayers`, through +`Qwen35LayerSubmission.observer`). On an M5 Ultra every comparison is bitwise +equal, with the fixture and with the registered checkpoint. It covers neither +JACCL's streamed sealed sums, the driver under live traffic nor the HTTP +stream. + Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift` -(`QwenTensorParallelBatchSession`), +(`QwenTensorParallelBatchSession`, `censusLine`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift` +(`QwenTensorParallelRowsCheck`), +`libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift` +(`QwenRowsCheck`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift` (`serve`, `makePlan`, `join`, `leave`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Batch/QwenBatchDecodeCoalescing.swift` @@ -5213,17 +5410,21 @@ and verify transients. The shared charge is never below LOAD's. Each rank's live gate (`reserveLane`, with the same OS and allocator checks) admits the whole charge or refuses that request alone. The endpoint then answers 503 with the context the pair serves now, and the pair keeps serving. A request within the -memory plan is charged as before and must still fit LOAD's per-lane quote. +memory plan, at most its context and its prompt, must still fit LOAD's per-lane +quote. A longer prompt within that context is charged at its own prompt, as a +longer context is, because each request's prefix capture grows with its prompt +(`QwenTensorParallelRequestCharge.withinMemoryPlan`). READY's request capacity is the larger of LOAD's quote and one request at 262,144 tokens. READY, and every keep-warm answer while no lane is held, carry the longest context the reservation gate admits now (`servingContextTokens`, computed with the gate's own arithmetic). The pair refuses a longer request before either rank is asked. With the registered inventory on an M5 Ultra -(256 GB), eight lanes with the depth-3 assistant reserve 48.4 GB a rank at LOAD -(4.6 GB a lane). A 262,144-token request beside seven standard ones is charged -69.4 GB a rank (a 13.9 GB lane and 22.8 GB of shared workspaces), beside at most -16.3 GB of weights (`QwenTensorParallelNativeContextTests`). +(256 GB), eight lanes with the depth-3 assistant reserve 60.4 GB a rank at LOAD +(6.2 GB a lane). A 262,144-token request beside seven standard ones is charged +89.0 GB a rank (a 23.1 GB lane, including its own prompt's prefix capture, and +22.4 GB of shared workspaces), beside at most 16.3 GB of weights +(`QwenTensorParallelNativeContextTests`). The pipeline and hand-off modes stay at the memory plan. Their LOAD gates size it, and they refuse a longer reservation (`requireWithinMemoryProfile`). Provider @@ -5263,6 +5464,25 @@ Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Ten `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/State/CBv2OwnedRequestState.swift` (`growReservation`). +### Qwen27 tensor-parallel prompt-prefix depth + +A plain Qwen tensor-parallel lane keeps prompt-prefix boundaries to its request's +context on its own 512-token chunk grid, not to a fixed 4,096 tokens: the +deepest whole chunk before the final token, a boundary 64 tokens before the +prompt end for the next turn, and one Mac's 4,096-token stripe boundaries for +a shared system prompt (`QwenTensorParallelBatchPrefixBudget`, policy +`qwen-tp-batch-prefix-depth-v2`, which the load agreement binds). A repeated +33K-token prompt restores 32,768 tokens on both ranks, as one Mac reuses. A +request restored from memory or a native SSD record computes exactly what a +cold one computes on the same grid; the SSD tier's default `balanced` records +keep their older rows approximate. +The mechanism, the parity cases and the SSD records are in +[the Qwen27 TP prefixes](prefix-cache.md#qwen27-tp-prefix-ssd-tier) and the +section before it; the memory each request and LOAD charge is in +[Qwen27 TP batch prefix ownership](hardware-support.md#qwen27-tp-batch-prefix-ownership). +The assistant's lanes keep one boundary of at most 4,096 tokens +([assistant prefix ownership](prefix-cache.md#qwen27-tp-assistant-prefix-ownership)). + ### Qwen27 cluster media ingress ownership The scheduler routes image/video requests through `DistributedQwenMediaIngress` From ebcab3dda90247ff5aba1da7891dc0d2e292d2ea Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Mon, 2 Nov 2026 23:26:32 -0800 Subject: [PATCH 0203/1441] docs: align merge preimage headers with dev Resolve only the date-header merge conflict; preserve both documentation bodies. The latest authored date is restored immediately after the signed dev merge. No runtime source change. AI-assisted integration by Darkbloom Provider (Hermes). --- docs/architecture/hardware-support.md | 2 +- docs/architecture/inference.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 4da0ba050d..8b28d8d119 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1,6 +1,6 @@ # Hardware support and the provider memory model -> Last updated: 2026-11-02 +> Last updated: 2026-11-01 What hardware the provider runs on and how it decides, in bytes, whether a model may load and how much KV cache each resident model may use. Read this to diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 8273852658..9fee7d6546 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-11-02 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` From df5d76b05b4f554ee377044cd225b2182b2847f3 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Mon, 2 Nov 2026 23:27:16 -0800 Subject: [PATCH 0204/1441] docs: retain authored pipeline verification dates Restore the authored 2026-11-02 dates after the non-force dev refresh. The final tree equals the locally checked two-parent merge with only the date conflicts resolved; both documentation bodies are preserved. No additional runtime edits. AI-assisted integration by Darkbloom Provider (Hermes). --- docs/architecture/hardware-support.md | 2 +- docs/architecture/inference.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 8b28d8d119..4da0ba050d 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1,6 +1,6 @@ # Hardware support and the provider memory model -> Last updated: 2026-11-01 +> Last updated: 2026-11-02 What hardware the provider runs on and how it decides, in bytes, whether a model may load and how much KV cache each resident model may use. Read this to diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 9fee7d6546..8273852658 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-11-01 +> Last updated: 2026-11-02 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` From 29c84b6fbc05b0f4e2f0b7c6587cd3de0b5f1756 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:53:56 -0800 Subject: [PATCH 0205/1441] feat(cluster): cut the guided setup's words by two thirds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner reviewed the screens and asked for about 70% fewer words: "less is better", as the 2026-11-02 interview said. Every screen now says only what the person must do or what went wrong: - Connect: one line asks to allow macOS's password and Local Network prompts, then "✓ Cable ready". - Pair: "Run `darkbloom cluster` on the other Mac.", "Code 123 456. Same on the other Mac?" (Yes / No on both Macs), "✓ Paired. This Mac leads." - Model: one line per approved model, name and size. - Start: "✓ Serving … at http://localhost:8000 (earning through Darkbloom)" and the test's time; "Done. You can close both windows." - Again: one status line and a short menu (Test, Change model, Serve locally, Stop, Check memory is freed, Quit); the member: nothing to do here. Waits and progress stay on the live line only. The subtitle, repeated confirmations, the machines line and split details are gone. Word budget checks hold the from-scratch screens under 100 (leader) and 60 (member) words. Across the scripted flows: 4,506 → 1,518 words. Tested: ClusterOnboardingChecks 692/0, ClusterControlChecks 229, ClusterPlacementChecks 237, ClusterSupervisionChecks 179, ClusterLinkChecks 2453, diagnostics, installed-session and configuration pass; `swift build --build-tests` clean; convention, Local Network probe and doctor tests pass; no open PR loses a line. Co-Authored-By: Claude Opus 5.5 --- .../Onboarding/ClusterOnboardingBrand.swift | 5 +- .../Onboarding/ClusterOnboardingFlow.swift | 345 ++++++------ .../Onboarding/ClusterOnboardingLive.swift | 69 +-- .../ClusterOnboardingTerminal.swift | 18 +- .../OnboardingChecks.swift | 511 +++++++++--------- 5 files changed, 458 insertions(+), 490 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingBrand.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingBrand.swift index 733ba6c030..f596bcc5ad 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingBrand.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingBrand.swift @@ -44,10 +44,11 @@ public enum ClusterOnboardingBrand { } } - /// "●●○○○" for a heading that starts "2 / 5"; nil for any other heading. + /// "●●○○○" for a heading that starts "2/5" (or "2 / 5"); nil for any other heading. static func meter(_ title: String) -> String? { let parts = title.split(separator: " ", maxSplits: 3, omittingEmptySubsequences: true) - guard parts.count >= 3, parts[1] == "/", let step = Int(parts[0]), let total = Int(parts[2]), + let fraction = parts.count >= 3 && parts[1] == "/" ? [parts[0], parts[2]] : parts.first?.split(separator: "/") ?? [] + guard fraction.count == 2, let step = Int(fraction[0]), let total = Int(fraction[1]), (1...9).contains(total), (1...total).contains(step) else { return nil } return String(repeating: "\u{25CF}", count: step) + String(repeating: "\u{25CB}", count: total - step) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift index 5ab23c1ab9..a442446de3 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift @@ -5,13 +5,12 @@ import Foundation // Mac 1: `darkbloom cluster` -> checks (RDMA, cable, isolation behind ONE // macOS approval, or sudo in this terminal where none can show, GID) and // this command's Local Network access -> nobody waits on the cable, so this -// Mac leads, answers discovery on the cable and says "Now run `darkbloom +// Mac leads, answers discovery on the cable and says "Run `darkbloom // cluster` on the other Mac." -> waits (q cancels). // Mac 2: `darkbloom cluster` -> its own checks -> finds the waiting leader -// on the cable by itself -> the same code on both screens, "Yes, pair" on -// each -> "Paired with the other Mac (). It leads; this Mac follows -// it." -> its cluster service runs (macOS asks about Darkbloom's Local -// Network access), and nothing else is asked there. +// on the cable by itself -> the same code on both screens, "Yes" on each -> +// "Paired. The other Mac leads." -> its cluster service runs (macOS asks +// about Darkbloom's Local Network access), and nothing else is asked there. // Mac 1 (the leader, where onboarding started): its service's Local Network // access, both Macs in one line, the choice among the models approved for // clusters, the planner's placement (this Mac is rank 0), the setup synced @@ -84,11 +83,11 @@ public enum ClusterServingScope: Sendable, Equatable { public var line: String { switch self { case .publicServing: - return "Serving through Darkbloom (public traffic when the coordinator supports clusters)" + return "Serving through Darkbloom" case .localOnly(let bind): - let reach = bind == Self.localOnlyDefaultBind ? "on this Mac's networks (LAN or tailnet)" + let reach = bind == Self.localOnlyDefaultBind ? "on this Mac's networks" : reachableFromNetwork ? "at \(bind)" : "on this Mac only (\(bind))" - return "Local only: no coordinator; the API listens \(reach) and needs its API key (`darkbloom local` shows it)" + return "Local only, \(reach); API key: `darkbloom local`" } } } @@ -248,25 +247,14 @@ public struct ClusterOnboardingModelChoice: Codable, Sendable, Equatable { /// Offered on the setup's list: it can be served on these Macs and is not known to be unapproved. public var listed: Bool { blocker == nil && validated != false } - /// The list's one line: the title (with the model's id when another choice shows the same title), the first of - /// its lines (size and how it is split, or how it gets onto the Macs) and, at its end, the tensor-parallel note - /// when there is one it can say. + /// The list's one line: the title (with the model's id when another choice shows the same title) and its size, + /// the first fact of its first line, then "copy" or "download" when it has to reach a Mac first (2026-11-03: the + /// list keeps only what the choice needs; how it is split is the planner's business). public func listLine(sameTitleElsewhere: Bool) -> String { let name = sameTitleElsewhere ? "\(title) (\(modelID ?? title))" : title - let line = lines.first.map { "\(name) — \($0)" } ?? name - return sayableTensorParallelNote.map { line + " · " + $0 } ?? line - } - - /// The longest tensor-parallel note the list says, a few words at the end of the model's line (the planner keeps - /// its notes within it: `ClusterPlacementExplanation.tensorParallelNoteLimit`). - public static let tensorParallelNoteLimit = 33 - - /// `tensorParallelNote` when the list can say it: plain words within the limit (the note may come from the other - /// Mac's build). - public var sayableTensorParallelNote: String? { - guard let note = tensorParallelNote, !note.isEmpty, note.count <= Self.tensorParallelNoteLimit, - ClusterOnboardingDeployment.shownPlainly(note) else { return nil } - return note + let size = lines.first?.components(separatedBy: " · ").first.flatMap { $0.isEmpty ? nil : $0 } + let move = provision.map { $0.leaderDownloads && !$0.fromOtherMac ? "download" : "copy" } + return ([name] + [size, move].compactMap { $0 }).joined(separator: " · ") } } @@ -389,12 +377,9 @@ public struct ClusterOnboardingProvisionOffer: Codable, Sendable, Equatable { /// itself only when the Mac logs in by itself; FileVault keeps the disk locked until someone logs in. public enum ClusterOnboardingRestart { public static func line(mac: String, autoLogin: Bool, fileVault: Bool?) -> String { - if autoLogin { return "After a restart or power cut, \(mac) comes back by itself and serves again (automatic login is on)." } - if fileVault == true { - return "After a restart or power cut, \(mac) serves again once someone logs in (FileVault keeps the disk locked until then)." - } - return "After a restart or power cut, \(mac) serves again once someone logs in. To make it automatic, turn on automatic login " - + "(System Settings → Users & Groups; needs FileVault off)." + if autoLogin { return "After a restart, \(mac) serves again by itself." } + if fileVault == true { return "After a restart, \(mac) serves again once someone logs in." } + return "After a restart, \(mac) serves again once someone logs in (or turn on automatic login)." } } @@ -535,6 +520,15 @@ public struct ClusterOnboardingReady: Codable, Sendable, Equatable { self.offered = offered } + /// The screens' one line (2026-11-03: less is better), "Serving Qwen3.8 27B at http://localhost:8000": when rank 0, + /// which serves the API, is the other Mac the line says so (this Mac's own loopback serves nothing), and listening + /// on the network too, it says that. Offered for pairing, the offered line instead: there is no local API. + public func summary(model: String) -> String { + if let offered { return "Serving \(model): \(offered)" } + return "Serving \(model) at http://localhost:\(port)" + (servesHere ? "" : " on the other Mac") + + (network == true ? " and on the network" : "") + } + /// "API at http://localhost:8000 on this Mac": the serving API listens on loopback on the Mac that runs rank 0, so /// when that is the other Mac the line names it (this Mac's own loopback serves nothing). Listening on the network /// too, the line says so: other computers use that Mac's LAN or tailnet address with the same port. @@ -734,21 +728,19 @@ public struct ClusterOnboardingPairing: Sendable, Equatable { private var peerAnswered = false /// The code is on screen and waits for its answer (`codeAnswers`). public private(set) var asking: String? - /// This Mac's own name, said beside "this Mac" (`ClusterOnboardingDriver.thisMac`). - private let named: String? - public init(named: String? = nil) { self.named = named } + public init() {} /// The one thing to do on the other Mac while this one waits: said last, so it is the line the person reads. - public static let otherMacLine = "Now run `darkbloom cluster` on the other Mac." + public static let otherMacLine = "Run `darkbloom cluster` on the other Mac." - /// The question under the code, and its two answers (a menu: arrows and enter, or 1 and 2). Each Mac answers for + /// The question after the code, and its two answers (a menu: arrows and enter, or 1 and 2). Each Mac answers for /// itself: a "yes" passed on from the other Mac could come from a Mac in between. - public static let codeQuestion = "Does the other Mac show the same code? Answer on both Macs." - public static let codeAnswers = ["Yes, pair", "No"] + public static let codeQuestion = "Same on the other Mac?" + public static let codeAnswers = ["Yes", "No"] /// Said once this Mac answered yes and the other Mac has not answered yet: the next thing to do, kept on screen /// (a plain console shows no live line). - public static let otherMacAnswerLine = "Now choose \u{201C}Yes, pair\u{201D} on the other Mac too." + public static let otherMacAnswerLine = "Now confirm on the other Mac." /// What the live line says while the pairing runs: the action again while this Mac waits for the other one. public var working: String? { @@ -761,6 +753,8 @@ public struct ClusterOnboardingPairing: Sendable, Equatable { } } + /// What the pairing's progress says on screen: the action on the other Mac while this one waits, the code with its + /// question, and a code the other Mac declined. Finding, joining and its confirmation stay on the live line. public mutating func handle(_ event: ClusterOnboardingPairEvent) -> [String] { switch event { case .searching: @@ -771,25 +765,21 @@ public struct ClusterOnboardingPairing: Sendable, Equatable { role = .leader guard !announcedWait else { return [] } announcedWait = true - return [ClusterOnboardingDriver.thisMac(named: named) + " leads. It waits up to 10 minutes for the other Mac (q cancels).", - Self.otherMacLine] + return [Self.otherMacLine] case .joining: - let yielded = role == .leader phase = .joining role = .member - return [yielded ? "The other Mac started waiting at the same moment and leads; this Mac joins it." - : "Found the other Mac on the cable: it leads, and this Mac joins it."] + return [] case .connected: return [] - case .code(let code, let peer): + case .code(let code, _): let shown = Self.spaced(code) phase = .confirming(shown) asking = shown - return ["The other Mac: " + (peer.first ?? "a Mac on the cable")] + peer.dropFirst().map { " " + $0 } - + ["Code: \(shown)", Self.codeQuestion] + return ["Code \(shown). " + Self.codeQuestion] case .peerDecided(let accepted): peerAnswered = true - return [accepted ? "The other Mac confirmed the code." : "The other Mac declined the code."] + return accepted ? [] : ["The other Mac declined the code."] case .note(let text): return [text] } @@ -800,25 +790,23 @@ public struct ClusterOnboardingPairing: Sendable, Equatable { guard asking != nil else { return [] } asking = nil phase = .confirmed - guard accept else { return ["Declined here: nothing is paired."] } + guard accept else { return ["Declined: nothing paired."] } return peerAnswered ? [] : [Self.otherMacAnswerLine] } - /// `named`: this Mac's own name, said beside "this Mac" (`ClusterOnboardingDriver.thisMac`). + /// `named`: this Mac's own name, said beside "this Mac" where it leads (`ClusterOnboardingDriver.thisMac`). public mutating func finished(_ result: ClusterOnboardingPairResult, named: String? = nil) -> [String] { phase = .done asking = nil switch result { - case .paired(let role, let peerName): + case .paired(let role, _): self.role = role - let other = ClusterOnboardingMacName.other(named: peerName) - let this = ClusterOnboardingDriver.thisMac(named: named) switch role { - case .member: return ["\(ClusterOnboardingDriver.done) Paired with \(other). It leads; \(this.prefix(1).lowercased() + this.dropFirst()) follows it."] - case .leader: return ["\(ClusterOnboardingDriver.done) Paired with \(other). \(this) leads."] + case .member: return ["\(ClusterOnboardingDriver.done) Paired. The other Mac leads."] + case .leader: return ["\(ClusterOnboardingDriver.done) Paired. \(ClusterOnboardingDriver.thisMac(named: named)) leads."] } case .failed(let lines): - return ["Not paired."] + lines + ["Run `darkbloom cluster` again to try again."] + return ["Not paired."] + lines + ["Run `darkbloom cluster` again."] } } @@ -858,7 +846,7 @@ public protocol ClusterOnboardingConsole: AnyObject { public extension ClusterOnboardingConsole { /// Scrollable sections also work in transcripts and non-terminal consoles. func heading(_ title: String) { say(""); say(title) } - func banner(_ title: String, _ subtitle: String) { heading(title); say(subtitle) } + func banner(_ title: String, _ subtitle: String) { heading(title); if !subtitle.isEmpty { say(subtitle) } } func working(_ text: String) {} func settle() {} func progress(_ text: (_ width: Int?) -> String, logged: Bool) { if logged { say(" " + text(nil)) } } @@ -902,7 +890,7 @@ public enum ClusterOnboardingDriver { let named = shownName(operations.thisMacName()) switch resume.role { case .member: - console.banner(title, followerSubtitle(resume, named: named)) + console.banner(title, followerSubtitle(named: named)) return member(resume, operations, console, request: request) case .leader: console.banner(title, leaderSubtitle(named: named)) @@ -911,15 +899,13 @@ public enum ClusterOnboardingDriver { } } - /// The setup's opening, and the opening on a Mac that is already in a cluster (`darkbloom cluster` run again): - /// the same mark, with the part this Mac plays. `named`: this Mac's own name beside "This Mac" (`thisMac`). + /// The setup's opening (the name alone), and the opening on a Mac that is already in a cluster (`darkbloom + /// cluster` run again): the same mark, with the part this Mac plays. `named`: this Mac's own name beside "This + /// Mac" (`thisMac`). public static let title = "Darkbloom cluster" - public static let setupSubtitle = "Two Macs, one model: connect, pair, choose, start" - public static let leaderSubtitle = "This Mac leads the cluster" - static func leaderSubtitle(named: String?) -> String { thisMac(named: named) + " leads the cluster" } - static func followerSubtitle(_ resume: ClusterOnboardingResume, named: String? = nil) -> String { - thisMac(named: named) + " follows " + ClusterOnboardingMacName.other(named: resume.leaderName ?? resume.peerName) - } + public static let leaderSubtitle = "This Mac leads" + static func leaderSubtitle(named: String?) -> String { thisMac(named: named) + " leads" } + static func followerSubtitle(named: String? = nil) -> String { thisMac(named: named) + " follows the other Mac" } /// "This Mac", with its own name when known ("This Mac (Studio A)"): two identical Macs read the same hardware, so /// each screen says which physical Mac it is. Said on that Mac's own screen only; the name never crosses the cable. @@ -935,45 +921,46 @@ public enum ClusterOnboardingDriver { /// A step that is done, at the start of its line. public static let done = "\u{2713}" - /// What macOS asks, and where to answer it, for the program it names. `remote` (over SSH): the prompt is on this - /// Mac's own screen, not in this terminal. + /// What to answer, for the program macOS names. `remote` (over SSH): the prompt is on this Mac's own screen, not in + /// this terminal. public static func localNetworkLine(_ app: String, remote: Bool = false) -> String { - "macOS asks\(onScreen(remote)) to let \(app) find devices on your local network: click Allow." + "Click Allow on the Local Network prompt for \(app)\(onScreen(remote))." } /// The same where the probe could not tell whether macOS will ask (nothing to wait for). public static func localNetworkMaybeLine(_ app: String, remote: Bool = false) -> String { - "If macOS asks\(onScreen(remote)) to let \(app) find devices on your local network, click Allow." + "If macOS asks about Local Network for \(app)\(onScreen(remote)), click Allow." } private static func onScreen(_ remote: Bool) -> String { - remote ? " on this Mac's own screen (use Screen Sharing if it has no display)" : "" + remote ? " on this Mac's screen (Screen Sharing if headless)" : "" } /// Said once paired: both cluster services ask at the same moment, one on each Mac. - public static let otherMacAllowLine = "The other Mac may ask too: click Allow there as well." + public static let otherMacAllowLine = "Allow it on the other Mac too." - /// Connect's first line: every approval the setup asks for on this Mac, and when (2026-11-02 review: "bundle all - /// of the permissions ahead of time"). + /// Connect's first line: every approval the setup asks for on this Mac (2026-11-02 review: "bundle all of the + /// permissions ahead of time"). public static func approvalsLine(remote: Bool) -> String { - remote ? "Up to two approvals on this Mac: the cable's port (now, with sudo in this terminal) and Local Network for Darkbloom (once paired, on this Mac's own screen)." - : "Up to two macOS approvals on this Mac: the cable's port (now) and Local Network for Darkbloom (once paired)." + remote ? "Allow macOS's password prompt here and its Local Network prompt on this Mac's screen (Screen Sharing if headless)." + : "Allow macOS's password and Local Network prompts." } - /// The Mac that joined ends its onboarding once paired; the last thing it says (the one thing to do next). - public static let joinedLine = "Continue on the other Mac: it chooses the model and starts this Mac's part." + /// The Mac that joined ends its onboarding once paired; the last thing it says (the one thing to do next), with + /// whether its window may close. + public static let joinedLine = "Done here: the other Mac chooses the model." /// The same, for a Mac that joined when it was asked for `darkbloom cluster local`. - public static let joinedLocalContinueLine = "Continue on the other Mac with `darkbloom cluster local`: it chooses the model and starts this Mac's part." + public static let joinedLocalContinueLine = "Done here: run `darkbloom cluster local` on the other Mac." /// Said on the Mac that joined when it was asked for `darkbloom cluster local` (a model too, perhaps): nothing of it /// runs here, because the Mac that leads chooses how the cluster serves and its model. - public static let joinedLocalLine = "`darkbloom cluster local` takes effect on the Mac that leads: run it on the other Mac." + public static let joinedLocalLine = "Run `darkbloom cluster local` on the other Mac: it leads." /// Whether the window may close: a login agent keeps serving; a service for this session only (a development /// build, or one launchd did not take as a login agent) does not. public static let closeWindowLine = "You can close this window." - public static let keepWindowLine = "Keep this window open: this Mac serves only while it stays open." + public static let keepWindowLine = "Keep this window open." /// How long the setup waits for a service that was just started to report its own probe (a service that never /// reports is an older build: nothing to wait for). A Local Network prompt itself is waited for until it is @@ -982,12 +969,20 @@ public enum ClusterOnboardingDriver { /// After this long still refused, the screen also says where the setting is (the prompt was answered before). static let settingsHintSeconds: Double = 15 + /// The cable check's line as the setup says it: "✓ Cable ready" for its plain "Cable ready.", nothing for a found + /// cable (the ready line or what is wrong follows) or the link flow's own pointer to the other Mac (Pair says it). + static func linkLine(_ line: String) -> String? { + if line == "Cable ready." { return "\(done) Cable ready" } + if line.hasPrefix("Cable found") || line == "Run `darkbloom cluster` on the other Mac too." { return nil } + return line + } + /// Runs the cable checks with each line shown as it is made (the approval line comes before the macOS prompt). static func checkLink(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> ClusterOnboardingLinkResult { let lines = ClusterOnboardingMailbox() let finished = ClusterOnboardingMailbox() Thread.detachNewThread { finished.post(operations.checkLink { lines.post($0) }) } - func show() { for line in lines.take() where line != "Run `darkbloom cluster` on the other Mac too." { console.say(" " + line) } } + func show() { for line in lines.take().compactMap(linkLine) { console.say(" " + line) } } while true { show() if let result = finished.take().first { show(); console.settle(); return result } @@ -1038,13 +1033,13 @@ public enum ClusterOnboardingDriver { state = operations.localNetwork(subject) if state == .allowed { console.settle() - console.say(" \(done) Local network allowed for \(app).") + console.say(" \(done) Allowed") return true } } console.settle() - console.say(" Local network access is still off for \(app) on this Mac.") - console.say("Turn it on in System Settings → Privacy & Security → Local Network, then run `darkbloom cluster` again.") + console.say("Local Network is off for \(app). Turn it on in System Settings → Privacy & Security → Local Network, " + + "then run `darkbloom cluster` again.") return false } @@ -1061,15 +1056,15 @@ public enum ClusterOnboardingDriver { /// No pairing yet: checks, then find a waiting leader or become one. static func onboard(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, request: ClusterOnboardingRequest = .init()) -> Int32 { - console.banner(title, setupSubtitle) - console.heading("1 / 4 Connect") + console.banner(title, "") + console.heading("1/4 Connect") console.say(" " + approvalsLine(remote: operations.remote())) var link = checkLink(operations, console) if !link.ready, link.ports.count > 1 { // Two cables (two links to the other Mac, or one to a third Mac): the person says which one to use here. - console.say(" \(link.ports.count == 2 ? "Two" : "\(link.ports.count)") cables are connected. Which one goes to the other Mac?") + console.say(" Which cable goes to the other Mac?") guard let index = console.choose(link.ports, selected: 0) else { - console.say("Nothing was changed.") + console.say("Nothing changed.") return 1 } operations.useLinkPort(link.ports[index]) @@ -1079,21 +1074,21 @@ public enum ClusterOnboardingDriver { // macOS could not show its approval window (an SSH session with no desktop): the same commands with sudo // right here, instead of a script for the person to find and run by hand (2026-11-02, `link-fix.sh`). guard setUpPortWithSudo(script, operations, console) else { - console.say("The cable's port was not set up. Run `darkbloom cluster` again, or run: sudo sh \(script)") + console.say("Cable port not set up. Run `darkbloom cluster` again.") return 1 } link = checkLink(operations, console) } guard link.ready else { - console.say("The cable is not ready yet, so pairing waits. Run `darkbloom cluster` again when the step above is done.") + console.say("Cable not ready. Fix the step above, then run `darkbloom cluster` again.") return max(link.exitCode, 1) } guard allowLocalNetwork(.thisCommand, operations, console) else { return 1 } - console.heading("2 / 4 Pair") + console.heading("2/4 Pair") let events = ClusterOnboardingMailbox() let outcome = ClusterOnboardingMailbox() Thread.detachNewThread { outcome.post(operations.pair { events.post($0) }) } - var pairing = ClusterOnboardingPairing(named: shownName(operations.thisMacName())) + var pairing = ClusterOnboardingPairing() var result: ClusterOnboardingPairResult? func show() { for event in events.take() { for line in pairing.handle(event) { console.say(" " + line) } } } while result == nil { @@ -1110,7 +1105,7 @@ public enum ClusterOnboardingDriver { let answer = console.choose(ClusterOnboardingPairing.codeAnswers, selected: 0, abandon: { outcome.hasItems }) if answer == nil { if outcome.hasItems { continue } - if console.closed { console.say("The input closed: nothing was paired."); return 1 } + if console.closed { console.say("Input closed: nothing paired."); return 1 } } let accept = answer == 0 // What the other Mac said while the list was up comes first: its answer decides what this one says. @@ -1121,12 +1116,12 @@ public enum ClusterOnboardingDriver { } if let working = pairing.working { console.working(working) } guard let key = console.key(milliseconds: 100) else { - if console.closed { console.say("The input closed: nothing was paired."); return 1 } + if console.closed { console.say("Input closed: nothing paired."); return 1 } continue } if key == "q" || key == "Q" || key == "\u{1B}", pairing.phase != .confirmed { console.settle() - console.say("Cancelled: nothing was paired. Run `darkbloom cluster` again to start over.") + console.say("Cancelled: nothing paired.") return 130 } } @@ -1136,30 +1131,32 @@ public enum ClusterOnboardingDriver { switch role { case .member: guard startService(operations, console) else { - console.say("Run `darkbloom cluster` here again to start it; the pairing is kept.") + console.say("Run `darkbloom cluster` again to start it (the pairing is kept).") return 1 } guard allowLocalNetwork(.service, operations, console) else { return 1 } // Nothing else is asked on the Mac that joined, `darkbloom cluster local` included: the Mac that leads is on // its own model list by now (2026-10-25: both Macs showed the list). Its last line is the one thing to do - // on the other Mac, `local` included. + // on the other Mac, `local` included, and whether this window may close. console.say("") if let restart = operations.afterRestart() { console.say(restart) } - console.say("Done on this Mac. " + (operations.serviceOutlivesWindow() ? closeWindowLine : keepWindowLine)) - console.say(request.scope?.isLocalOnly == true ? joinedLocalContinueLine : joinedLine) + console.say((request.scope?.isLocalOnly == true ? joinedLocalContinueLine : joinedLine) + " " + + (operations.serviceOutlivesWindow() ? closeWindowLine : keepWindowLine)) return 0 case .leader: return leader(.init(role: .leader, peerName: peerName), operations, console, justPaired: true, request: request) } } + /// The member's last line once it is in a cluster: where the cluster is managed. + public static let memberNothingLine = "Nothing to do here: manage it on the other Mac (`darkbloom cluster`)." + /// A member: its part runs by itself and the cluster is managed on the Mac that leads, so it shows the cluster as /// it is and says where to manage it (2026-11-02: "why does the member have the choices to change model, test …"). static func member(_ resume: ClusterOnboardingResume, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, request: ClusterOnboardingRequest = .init()) -> Int32 { guard startService(operations, console) else { return 1 } for line in operations.status() { console.say(" " + line) } - let leader = ClusterOnboardingMacName.other(named: resume.leaderName ?? resume.peerName) if let port = resume.unsetCablePort { // The cable moved to a port that was never set up: the one thing that is this Mac's to do. console.say("") @@ -1172,8 +1169,7 @@ public enum ClusterOnboardingDriver { console.say(joinedLocalLine) return 1 } - console.say("This Mac's part runs by itself: nothing to do here.") - console.say("To test, change the model or stop: run `darkbloom cluster` on \(leader).") + console.say(memberNothingLine) return 0 } @@ -1213,11 +1209,11 @@ public enum ClusterOnboardingDriver { console.say(unsetPortLine(port)) items.append((.fixPort, fixPortItem)) } - if resume.serving { items.append((.test, "Test a response")) } - items.append((.model, resume.serving ? "Change model" : "Choose a model and serve")) - items.append((.scope, resume.scope.isLocalOnly ? "Serve through Darkbloom" : "Serve locally only (no coordinator)")) - if resume.serving { items.append((.stop, "Stop serving")) } - items.append((.verify, "Check both Macs released their memory")) + if resume.serving { items.append((.test, "Test")) } + items.append((.model, resume.serving ? "Change model" : "Choose a model")) + items.append((.scope, resume.scope.isLocalOnly ? "Serve through Darkbloom" : "Serve locally")) + if resume.serving { items.append((.stop, "Stop")) } + items.append((.verify, "Check memory is freed")) items.append((.quit, "Quit")) console.say("") guard let index = console.choose(items.map(\.1), selected: 0) else { return 0 } @@ -1250,11 +1246,10 @@ public enum ClusterOnboardingDriver { } } - /// The cable moved to a port that was never set up, and the one item that sets it up. - static func unsetPortLine(_ port: String) -> String { - "The cable is on \(port), which is not set up for the cluster, so the Macs cannot reach each other." - } - static let fixPortItem = "Set up the cable's port (macOS asks for your password)" + /// The cable moved to a port that was never set up (the Macs cannot reach each other there), and the one item that + /// sets it up (macOS asks for the password). + static func unsetPortLine(_ port: String) -> String { "The cable is on \(port), which isn't set up." } + static let fixPortItem = "Set up the cable port" /// Sets up the port the cable moved to (macOS asks once), and says how it went. static func fixPort(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> Int32 { @@ -1262,8 +1257,8 @@ public enum ClusterOnboardingDriver { if !result.ready, let script = result.manualScript, !console.closed, setUpPortWithSudo(script, operations, console) { result = checkLink(operations, console) } - console.say(result.ready ? "The cable's port is set up; the cluster re-forms by itself in a moment." - : "The port is not set up yet; run `darkbloom cluster` again to try once more.") + console.say(result.ready ? "\(done) Cable port set up. The Macs reconnect by themselves." + : "Cable port not set up. Run `darkbloom cluster` again.") return result.ready ? 0 : 1 } @@ -1271,7 +1266,7 @@ public enum ClusterOnboardingDriver { /// person typing this Mac's password into sudo. True when it exited 0. static func setUpPortWithSudo(_ script: String, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> Bool { - console.say(" macOS could not show its password window here. Type this Mac's password for sudo to set up the cable's port:") + console.say(" Type this Mac's password to set up the cable port.") return console.suspended { operations.runAsAdministrator(script) } } @@ -1283,15 +1278,18 @@ public enum ClusterOnboardingDriver { case .success: break case .failure(let failure): for line in failure.lines { console.say(" " + line) } - console.say("Nothing was changed.") + console.say("Nothing changed.") return 1 } console.say(wanted.line + ".") guard resume.serving else { - console.say("Not serving now: the next start serves this way.") + console.say("Takes effect at the next start.") return 0 } - return awaitReady(title: resume.modelName ?? "the model", operations, console) != nil ? 0 : 1 + let title = resume.modelName ?? "the model" + guard let ready = awaitReady(title: title, operations, console) else { return 1 } + console.say(" \(done) " + ready.summary(model: title) + servesWords(scope: wanted, ready: ready)) + return 0 } /// Each reason once, where it first appears. @@ -1300,21 +1298,13 @@ public enum ClusterOnboardingDriver { return reasons.filter { seen.insert($0).inserted } } - /// Both Macs in one line: "This Mac: Apple M5 Ultra, 256 GB · the other Mac: Apple M3 Ultra, 256 GB". - static func machinesLine(_ machines: [ClusterOnboardingMachine]) -> String { - let pair = machines.count == 2 - return ClusterOnboardingMacName.sentence(machines.map { machine in - "\(machine.here ? ClusterOnboardingMacName.this : pair ? ClusterOnboardingMacName.other : "a member"): \(machine.name)" - }.joined(separator: " · ")) - } - /// The choice, then the start. `scope` is how it will serve; `saveScope` saves it on the control leader first /// (`darkbloom cluster local`); `model` names the choice so the list is not asked; `privateImage`: a private image /// candidate, which never takes public traffic. static func chooseAndServe(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, scope: ClusterServingScope = .publicServing, saveScope: Bool = false, model: String? = nil, privateImage: Bool = false) -> Int32 { - console.heading("3 / 4 Choose a model") + console.heading("3/4 Model") var reached: [ClusterOnboardingMachine]? while reached == nil { switch busy(console, "Reading both Macs over the cable", operations.reachMembers) { @@ -1322,14 +1312,12 @@ public enum ClusterOnboardingDriver { case .failure(let failure): for line in failure.lines { console.say(line) } // Once paired, the other Mac's service may still wait for its Allow (both Macs ask at the same moment). - guard console.choose(["Try again", "Stop here"], selected: 0) == 0 else { - console.say("Run `darkbloom cluster` here again once the other Mac is on; nothing was changed.") + guard console.choose(["Try again", "Cancel"], selected: 0) == 0 else { + console.say("Nothing changed. Run `darkbloom cluster` again when the other Mac is on.") return 1 } } } - let machines = reached! - console.say(" " + machinesLine(machines)) if let notice = operations.developerNotice() { console.say(notice) } let choices: [ClusterOnboardingModelChoice] switch busy(console, "Planning each model for both Macs", operations.planModels) { @@ -1343,7 +1331,7 @@ public enum ClusterOnboardingDriver { let listed = choices.indices.filter { choices[$0].listed } let open = listed.filter { choices[$0].fitRemedy == nil } + listed.filter { choices[$0].fitRemedy != nil } guard !open.isEmpty else { - console.say("No model approved for clusters can run on these two Macs now.") + console.say("No approved model can run on these Macs now.") // One line per reason, the approved models it holds back named before it. let held = choices.indices.filter { choices[$0].validated != false && choices[$0].blocker != nil } for reason in reasonsInOrder(held.compactMap { choices[$0].blocker }) { @@ -1362,7 +1350,7 @@ public enum ClusterOnboardingDriver { chosen = index } else if let index = choices.indices.first(where: named) { console.say(choices[index].validated == false ? "\(choices[index].title) is not approved for clusters yet." - : "\(choices[index].title) is not offered on these Macs: \(choices[index].blocker ?? "it cannot be served here").") + : "\(choices[index].title) can't run on these Macs: \(choices[index].blocker ?? "not offered here").") return 1 } else { console.say("No model on the list is named \(model).") @@ -1371,23 +1359,19 @@ public enum ClusterOnboardingDriver { if chosen == nil { let titles = choices.map(\.title) let lines = open.map { index -> String in - let shared = titles.filter { $0 == choices[index].title }.count > 1 - var choice = choices[index] - guard choice.fitRemedy != nil else { return choice.listLine(sameTitleElsewhere: shared) } - // A model that does not fit now says so once: a tensor-parallel note saying only that is left out. - if choice.tensorParallelNote?.hasSuffix("does not fit now") == true { choice.tensorParallelNote = nil } - return choice.listLine(sameTitleElsewhere: shared) + " · does not fit now" + let line = choices[index].listLine(sameTitleElsewhere: titles.filter { $0 == choices[index].title }.count > 1) + return choices[index].fitRemedy == nil ? line : line + " · does not fit now" } guard let picked = console.choose(lines, selected: 0) else { - console.say("Nothing was changed. Run `darkbloom cluster` again to choose.") + console.say("Nothing changed.") return 0 } chosen = open[picked] } var choice = choices[chosen!] - // Whether public traffic may reach it, said at the choice (not when the cluster serves locally only): whether - // the pair can earn with it, and that a private image candidate never takes public traffic. - if !scope.isLocalOnly, let line = choice.publicTraffic { + // A private image candidate says at the choice that it never takes public traffic; whether the pair earns is + // said once it serves (`servesWords`). + if privateImage, let line = choice.publicTraffic { console.say(" " + ClusterOnboardingMacName.sentence(line) + (line.hasSuffix(".") ? "" : ".")) } if let offer = choice.provision { @@ -1399,12 +1383,12 @@ public enum ClusterOnboardingDriver { if offer.leaderDownloads { guard case .success(let again) = busy(console, "Planning \(choice.title)", operations.planModels), let index = again.firstIndex(where: { ($0.modelID ?? $0.title) == (choice.modelID ?? choice.title) }) else { - console.say("\(choice.title) could not be planned after the \(offer.fromOtherMac ? "copy" : "download"). " - + "Run `darkbloom cluster` here again.") + console.say("Couldn't plan \(choice.title) after the \(offer.fromOtherMac ? "copy" : "download"). " + + "Run `darkbloom cluster` again.") return 1 } if let blocker = again[index].blocker { - console.say("\(choice.title) is on this Mac now, but it cannot be served by these Macs: \(blocker)") + console.say("\(choice.title) can't run on these Macs: \(blocker)") return 1 } choice = again[index] @@ -1419,11 +1403,11 @@ public enum ClusterOnboardingDriver { } } } - console.heading("4 / 4 Start") + console.heading("4/4 Start") // Memory moves while the person reads: the fit is checked again right before anything starts. if let remedy = operations.recheckFit(chosen!) { - console.say("\(choice.title) does not fit in the Macs' free memory now: \(remedy)") - console.say("Nothing was changed. Run `darkbloom cluster` here again after that.") + console.say("\(choice.title) doesn't fit in free memory now: \(remedy)") + console.say("Nothing changed.") return 1 } let index = chosen! @@ -1448,33 +1432,33 @@ public enum ClusterOnboardingDriver { for line in failure.lines { console.say(" " + line) } return 1 } - console.say(" \(done) Setup sent to the other Mac.") guard let ready = awaitReady(title: choice.title, operations, console) else { return 1 } + console.say(" \(done) " + ready.summary(model: choice.title) + servesWords(scope: scope, ready: ready)) // A pair offered for pairing has no local API to test: its requests come through Darkbloom. if ready.offered != nil { console.say(ClusterOnboardingReady.offeredTestLine) } let tested = ready.offered != nil || test(operations, console) if tested, ready.offered == nil, !scope.isLocalOnly { register(title: choice.title, operations, console) } console.say("") guard tested else { - console.say("Setup saved, but the test request failed.") - console.say("Run `darkbloom cluster` to see the status and test again.") + console.say("Setup saved, but the test failed. Run `darkbloom cluster` to test again.") return 1 } - if !privateImage, let line = servesLine(scope: scope, ready: ready) { console.say(line) } if let restart = operations.afterRestart() { console.say(restart) } - console.say("Done. " + (operations.serviceOutlivesWindow() ? "You can close this window here and on the other Mac." - : "Keep this window and the other Mac's open: these Macs serve only while they stay open.")) - console.say("To test, change the model or stop: run `darkbloom cluster` on this Mac.") + console.say("Done. " + (operations.serviceOutlivesWindow() ? "You can close both windows." : "Keep both windows open.")) + console.say(againLine) return 0 } - /// The setup's word on how the pair serves, where nothing above said it: serving locally (local only, or a - /// coordinator without cluster support) already has its notice under the API line. - public static let earnsLine = "Serving through Darkbloom: the pair earns for the public requests it serves." - static func servesLine(scope: ClusterServingScope, ready: ClusterOnboardingReady) -> String? { - guard !scope.isLocalOnly else { return nil } - if let notice = ready.notice, !notice.hasPrefix(ClusterOnboardingReady.registeredNotice) { return nil } - return earnsLine + /// The leader's last line: `darkbloom cluster` again manages the cluster (its menu tests, changes the model, stops). + public static let againLine = "Run `darkbloom cluster` again to manage it." + + /// How the pair serves, at the end of the serving line: earning through Darkbloom, or local only (asked for, or a + /// coordinator without cluster support, which leaves its local-serving notice). + public static func servesWords(scope: ClusterServingScope, ready: ClusterOnboardingReady) -> String { + guard ready.offered == nil else { return "" } + if scope.isLocalOnly { return " (local only)" } + if let notice = ready.notice, !notice.hasPrefix(ClusterOnboardingReady.registeredNotice) { return " (local only)" } + return " (earning through Darkbloom)" } /// After the Test stage: registers the pair with the coordinator when it serves a cluster approval for this pair, @@ -1493,8 +1477,8 @@ public enum ClusterOnboardingDriver { _ = awaitReady(title: title, operations, console) } - /// Waits for the started cluster with its progress, then says where it serves; nil (with the last errors and the - /// diagnostics offer) when it did not become ready. + /// Waits for the started cluster with its progress (the caller says where it serves); nil (with the last errors + /// and the diagnostics offer) when it did not become ready. static func awaitReady(title: String, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> ClusterOnboardingReady? { let progress = ClusterOnboardingMailbox() @@ -1512,19 +1496,18 @@ public enum ClusterOnboardingDriver { console.settle() switch ready! { case .success(let where_): - for line in where_.lines(model: title) { console.say(" " + line + ".") } return where_ case .failure(let failure): for line in failure.lines { console.say(line) } offerDiagnostics(operations, console) - console.say("Both Macs keep trying by themselves; run `darkbloom cluster` here to see how it is going.") + console.say("Both Macs keep trying. Run `darkbloom cluster` to check.") return nil } } /// One choice to save a diagnostics file (redacted) after a start that did not finish. static func offerDiagnostics(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) { - guard console.choose(["Save a diagnostics file to send to Darkbloom", "Leave"], selected: 0) == 0 else { return } + guard console.choose(["Save diagnostics for Darkbloom", "Skip"], selected: 0) == 0 else { return } switch operations.saveDiagnostics() { case .success(let lines): for line in lines { console.say(" " + line) } case .failure(let failure): for line in failure.lines { console.say(" " + line) } @@ -1533,24 +1516,21 @@ public enum ClusterOnboardingDriver { enum ProvisionOutcome { case done, stopped, failed } - /// Says what has to move for the chosen model, asks once (the recommended way first), and moves it with progress. + /// Asks once how the chosen model reaches the Mac that lacks it (the recommended way first, the list saying what + /// moves), and moves it with progress. static func provision(_ offer: ClusterOnboardingProvisionOffer, title: String, index: Int, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> ProvisionOutcome { - console.say(" " + (offer.leaderDownloads ? "\(title) is not on this Mac yet:" : "\(title) is not on every Mac yet:")) - for line in offer.lines { console.say(" " + line) } if let blocker = offer.blocker { - console.say("It cannot start: \(blocker). Free some space and run `darkbloom cluster` here again.") + console.say("Can't start \(title): \(blocker). Free space, then run `darkbloom cluster` again.") return .failed } // Every copy is a choice from the list, the copy first so enter takes it; a short one says how long it takes // (2026-11-02 review: no key to press to do something, the same list as the rest of Darkbloom). - let get = offer.fromOtherMac ? "Copy it from the other Mac over the Thunderbolt cable" + (offer.quickSeconds.map { " (\(Self.duration($0)))" } ?? "") - : offer.leaderDownloads ? "Get it (download, then copy over the cable)" - : offer.quickSeconds.map { "Copy it over the Thunderbolt cable (\(Self.duration($0)))" } - ?? (offer.downloadAlternative ? "Copy it over the Thunderbolt cable (recommended)" : "Copy it over the Thunderbolt cable") - let options = [get] + (offer.downloadAlternative ? ["Download it from Darkbloom's catalog instead"] : []) + ["Stop here"] + let quick = offer.quickSeconds.map { " (\(Self.duration($0)))" } ?? "" + let get = offer.fromOtherMac ? "Copy from the other Mac" + quick : offer.leaderDownloads ? "Download" : "Copy to the other Mac" + quick + let options = [get] + (offer.downloadAlternative ? ["Download"] : []) + ["Cancel"] guard let answer = console.choose(options, selected: 0), answer != options.count - 1 else { - console.say("Nothing was copied or downloaded. Run `darkbloom cluster` here again to choose.") + console.say("Nothing changed.") return .stopped } return move(index: index, download: offer.downloadAlternative && answer == 1, operations, console) @@ -1598,7 +1578,7 @@ public enum ClusterOnboardingDriver { return .done case .failure(let failure): for line in failure.lines { console.say(" " + line) } - console.say("Run `darkbloom cluster` here again: a copy or download resumes where it stopped.") + console.say("Run `darkbloom cluster` again to resume.") return .failed } } @@ -1616,12 +1596,11 @@ public enum ClusterOnboardingDriver { } } - /// One test request; its answer on one line ("✓ Test response: …"), or what went wrong. + /// One test request; one line ("✓ Test response in 0.6 s, 120.0 tokens/s"), or what went wrong. static func test(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> Bool { switch busy(console, "Sending a test request", operations.testRequest) { case .success(let lines): - console.say(" \(done) Test response: " + (lines.first ?? "answered")) - for line in lines.dropFirst() { console.say(" " + line) } + console.say(" \(done) Test response" + (lines.first.flatMap { $0.isEmpty ? nil : " " + $0 } ?? "")) return true case .failure(let failure): for line in failure.lines { console.say(" " + line) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift index 57feea58e3..bc618a1cb4 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift @@ -338,12 +338,10 @@ final class OnboardingLive: @unchecked Sendable { last = report step = flow.observed(report) case .fix(let device): - // The one macOS approval; where no prompt can show (an SSH session has no window to show it in), one - // owner-only script, which the onboarding runs with sudo in this terminal (the person never has to - // find it, so the link flow's line telling them to run it by hand is not shown). - if !ClusterLocalNetworkAccess.overSSH() { - say("macOS asks for your password to set up the cable's port: approve it (once per Mac).") - } + // The one macOS approval (Connect's first line said macOS asks for the password; its window says + // what for); where no prompt can show (an SSH session has no window to show it in), one owner-only + // script, which the onboarding runs with sudo in this terminal (the person never has to find it, so + // the link flow's line telling them to run it by hand is not shown). let result = ClusterLinkRepair.fix(device: device, mode: .durable, dryRun: false) manualScript = result.manualScript step = flow.repaired(result) @@ -928,8 +926,8 @@ final class OnboardingLive: @unchecked Sendable { return .success(lines) } if let model = lock.withLock({ catalogChoices[index] }) { + // Its line ("✓ Downloaded …") is the download's own last report. folder = try downloadOnThisMac(model, store: store, progress: progress) - lines.append("\(model.id) is on this Mac now (downloaded from Darkbloom's catalog and verified, as `darkbloom` downloads models).") } let manifest = store.appendingPathComponent(folder).appendingPathComponent("manifest.json") guard let data = ClusterModelStore.readSmall(manifest) else { throw ClusterSetupFailure("this Mac's \(folder) has no readable manifest") } @@ -937,23 +935,23 @@ final class OnboardingLive: @unchecked Sendable { if let peer = lock.withLock({ peerReport }), peer.models.contains(where: { artifact.sameEntry(modelID: $0.modelID, version: $0.version, aggregate: $0.artifactSHA256) && ($0.filesSHA256 == nil || $0.filesSHA256 == artifact.filesDigest) }) { - lines.append("\(Self.sentence(there)) has it already (same catalog digest).") + lines.append("\(ClusterOnboardingDriver.done) \(Self.sentence(thereShort)) already has it") return .success(lines) } guard let pairing = try ClusterSetupLinkExchange.pairing() else { throw ClusterSetupFailure("This Mac is not paired.") } let selection = try context.linkSelection() - let name = there - let reports = ClusterTransferReports(label: "Copying \(artifact.modelID) to \(thereShort)", send: progress) + let reports = ClusterTransferReports(label: "Copying to \(thereShort)", send: progress) let outcome = try ClusterSetupLinkExchange.copyModel(pairing: pairing, selection: selection, peerAddress: nil, artifact: artifact, source: store.appendingPathComponent(folder), folder: folder) { sent, total in reports.report(done: sent, total: total) } if outcome.alreadyThere { - lines.append("\(Self.sentence(name)) has it already (same catalog digest).") + lines.append("\(ClusterOnboardingDriver.done) \(Self.sentence(thereShort)) already has it") } else { + // Every file matched the catalog manifest's SHA-256 (the copy fails otherwise). let rate = outcome.seconds > 0 ? Double(outcome.sentBytes) / outcome.seconds : 0 if rate > 0 { try? Data(String(format: "%.0f", rate).utf8).write(to: copyRateFile, options: .atomic) } - lines.append("Copied \(ClusterModelProvisioning.gigabytes(outcome.sentBytes)) to \(name) over the Thunderbolt cable in \(String(format: "%.1f", outcome.seconds)) s (\(String(format: "%.2f", rate / 1e9)) GB/s); every file matched the catalog manifest's SHA-256.") + lines.append("\(ClusterOnboardingDriver.done) Copied to \(thereShort) (\(ClusterModelProvisioning.gigabytes(outcome.sentBytes)), \(String(format: "%.1f", outcome.seconds)) s)") } // The member's answer now lists the model, so the plan and the start see it there. if case .reached(let report, _) = context.reachPeer() { lock.withLock { peerReport = report } } @@ -976,14 +974,15 @@ final class OnboardingLive: @unchecked Sendable { let deadline = started.addingTimeInterval(120 + Double(model.totalBytes) / 50e6) let staging = store.appendingPathComponent(".darkbloom-incoming-" + String(model.artifactSHA256.prefix(32))) var lastCheck = Date.distantPast - let reports = ClusterTransferReports(label: "Receiving \(model.modelID) from \(thereShort)", send: progress) + let reports = ClusterTransferReports(label: "Copying from \(thereShort)", send: progress) while Date() < deadline { if let data = ClusterModelStore.readSmall(store.appendingPathComponent(model.folder).appendingPathComponent("manifest.json")), let artifact = try? ClusterCatalogArtifact.parse(manifest: data), artifact.sameEntry(modelID: model.modelID, version: model.version, aggregate: model.artifactSHA256), model.filesSHA256 == nil || model.filesSHA256 == artifact.filesDigest { + // Every file matched the catalog manifest's SHA-256 (this Mac's service verified each one). let seconds = Date().timeIntervalSince(started) - return "\(Self.sentence(sender)) copied \(ClusterModelProvisioning.gigabytes(model.totalBytes)) of \(model.modelID) to \(hereShort) over the Thunderbolt cable in \(String(format: "%.1f", seconds)) s; every file matched the catalog manifest's SHA-256." + return "\(ClusterOnboardingDriver.done) Copied from \(thereShort) (\(ClusterModelProvisioning.gigabytes(model.totalBytes)), \(String(format: "%.1f", seconds)) s)" } if Date().timeIntervalSince(lastCheck) >= 1 { lastCheck = Date() @@ -1027,14 +1026,13 @@ final class OnboardingLive: @unchecked Sendable { // Written and verified uncached, like the copy over the cable: a download does not take memory from a model load. downloader.uncachedWrites = true let started = Date() - let reports = ClusterTransferReports(label: "Downloading \(model.id)", send: progress) + let reports = ClusterTransferReports(label: "Downloading", send: progress) let verifying = ClusterOnboardingMailbox() downloader.byteProgress = { done, total in guard done >= total else { reports.report(done: done, total: total); return } // Every byte is here; the downloader checks each file and the aggregate digest before it publishes. if verifying.take().isEmpty { - let checking = "Downloaded \(ClusterModelProvisioning.gigabytes(total)); checking every file against the catalog manifest" - progress(.live({ _ in checking }, logged: true)) + progress(.live({ _ in "Checking the download" }, logged: true)) } verifying.post(true) } @@ -1060,7 +1058,8 @@ final class OnboardingLive: @unchecked Sendable { guard case .complete(let folder) = ClusterModelStore.holding(store: store, artifact: installed.artifact) else { throw ClusterSetupFailure("\(model.id) could not be placed in the cluster's model store") } - progress(.line("Downloaded \(ClusterModelProvisioning.gigabytes(installed.artifact.totalBytes)) in \(String(format: "%.1f", Date().timeIntervalSince(started))) s; every file matched the catalog manifest.")) + // Every file matched the catalog manifest (the downloader checked each one before it published). + progress(.line("\(ClusterOnboardingDriver.done) Downloaded (\(ClusterModelProvisioning.gigabytes(installed.artifact.totalBytes)), \(String(format: "%.1f", Date().timeIntervalSince(started))) s)")) return folder } @@ -1518,12 +1517,9 @@ final class OnboardingLive: @unchecked Sendable { } } if let error = answer.error { return .failure(.init("The test request failed: \(error)")) } - let reply = answer.text.replacingOccurrences(of: "\n", with: " ").trimmingCharacters(in: .whitespaces) - var figures = "\(answer.tokens) tokens" - if let first = answer.firstTokenMilliseconds { figures += ", first token \(String(format: "%.2f", Double(first) / 1000)) s" } - if let rate = answer.tokensPerSecond { figures += ", \(String(format: "%.1f", rate)) tokens/s" } - if let finish = answer.finishReason { figures += ", finished: \(finish)" } - return .success(["\"\(text)\" -> \"\(String(reply.prefix(200)))\"", figures]) + if answer.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return .failure(.init("The test request got an empty answer.")) } + // One line for the screen: how fast it answered (its first token). + return .success([answer.firstTokenMilliseconds.map { "in \(String(format: "%.2f", Double($0) / 1000)) s" } ?? ""]) } func status() -> [String] { @@ -1552,38 +1548,33 @@ final class OnboardingLive: @unchecked Sendable { if let updating = ClusterService.publishedLive()?.updating { lines.append(updating) } let answering = self.answering if let control = ClusterService.published()?.control, ["alone", "cannotServe", "waiting"].contains(control.mode) { - lines.append((answering ? Self.sentence(here) + ": " : "") + control.line + ".") - lines.append("Commands typed here are handled by \(here).") + lines.append((answering ? Self.sentence(hereShort) + ": " : "") + control.line + ".") return lines } + // One line for the screen (the banner above says which Mac leads): what serves and where, or why it does not. let model = (leadership?.modelName).map(modelTitle) ?? "the chosen model" let now = session() if leadership?.serving != true { - lines.append("Not serving (stopped)\(leadership?.modelName.map { "; the last model was " + modelTitle($0) } ?? "").") + lines.append("Stopped\(leadership?.modelName.map { "; last model " + modelTitle($0) } ?? "").") if let scope = leadership?.scope, scope.isLocalOnly { lines.append("When it starts: " + scope.line + ".") } } else if let offered = offeredLine() { let ready = offeredReadiness(offered, own: ClusterService.published()?.child) - lines.append((ready.ready?.lines(model: model) ?? ["\(model): \(ready.line)"]).joined(separator: ". ") + ".") + lines.append((ready.ready?.summary(model: model) ?? "\(model): \(ready.line)") + ".") } else if let session = now.session, session.observed { if session.ready { - // The deployment first, then where the API is. - // The local-serving line is worded for the screen it lands on (`noticeLine`): a member's status says - // that Mac's API, as the API line above names it. let ready = ready(now, port: session.port ?? 0) - lines.append(ready.lines(model: model)[0] + ".") - lines.append(ready.apiLine + "; \(session.readyRanks) of \(session.ranks) parts ready.") - if let notice = ready.noticeLine { lines.append(notice + ".") } + lines.append(ready.summary(model: model) + + ClusterOnboardingDriver.servesWords(scope: leadership?.scope ?? .publicServing, ready: ready) + ".") // Why the pair serves locally although its coordinator offers a cluster approval (one line). if leadership?.scope.isLocalOnly != true, let note = (try? store.readRecord())?.approvalNote { lines.append(note + ".") } } else { - lines.append("\(model): \(session.readyRanks) of \(session.ranks) parts ready" + (session.detail.map { " (\($0))" } ?? "") + ".") + lines.append("Loading \(model): \(session.readyRanks) of \(session.ranks) parts ready" + (session.detail.map { " (\($0))" } ?? "") + ".") } } else if let error = now.error { - lines.append("\(Self.sentence(there)) does not answer over the cable now (\(error)); it rejoins by itself when it is back.") + lines.append("\(Self.sentence(thereShort)) doesn't answer over the cable (\(error)); it rejoins by itself.") } else { - lines.append("\(model) is starting (both Macs keep trying by themselves).") + lines.append("Starting \(model).") } - lines.append(answering ? "Leader: \(here). This Mac is a member." : "Member: \(there). This Mac leads.") return lines } @@ -1656,6 +1647,6 @@ final class OnboardingLive: @unchecked Sendable { let reason = (error as? ClusterSetupFailure)?.text ?? "\(error)" return .failure(.init("\(mac) stopped serving; \(there) did not answer (\(reason)). \(mac)'s cluster service tells it to stop as soon as it answers again.")) } - return .success(["Both Macs stop their parts now (each releases its memory first). Run `darkbloom cluster` here to serve again."]) + return .success(["Stopping both Macs. Run `darkbloom cluster` to serve again."]) } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingTerminal.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingTerminal.swift index 45b7aeb33d..e661e55a61 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingTerminal.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingTerminal.swift @@ -106,7 +106,7 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { // wraps, and the bloom's climb of `height` rows would leave the top // behind: such a window keeps the heading lines (and the meter). let widest = 2 + ClusterOnboardingBrand.width + 3 + (texts.map(\.count).max() ?? 0) - guard decorates, widest < columns else { heading(title); say(subtitle); return } + guard decorates, widest < columns else { heading(title); if !subtitle.isEmpty { say(subtitle) }; return } let beside = ["\u{1B}[1m\(texts[0])\u{1B}[0m", "\u{1B}[2m\(texts[1])\u{1B}[0m", "\u{1B}[2m\(texts[2])\u{1B}[0m", ""] func draw(_ revealed: Int) { @@ -139,9 +139,17 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { /// A copy's or download's report: the live line, laid out for its room, where /// one shows; in a transcript only the logged reports, as plain lines. public func progress(_ text: (_ width: Int?) -> String, logged: Bool) { - if decorates { working(text(liveRoom)) } else if logged { say(" " + text(nil)) } + guard decorates else { if logged { say(" " + text(nil)) }; return } + // Redrawn at most eight times a second: a copy or download reports more often than a person reads. + let now = DispatchTime.now().uptimeNanoseconds + let due = now &- progressDrawn >= 125_000_000 + if due { progressDrawn = now } + drawWorking(text(liveRoom), force: due) } + /// When the progress line was last redrawn (uptime, nanoseconds). + private var progressDrawn: UInt64 = 0 + /// One row only: the return and erase that replace the live line reach just /// the cursor's row, so a wrapped line would leave its start behind. /// Room: the indent, petal and space, the ellipsis and the last column. @@ -287,9 +295,11 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { /// presentation keeps one transcript. private func typedChoice(_ options: [String], _ start: Int, _ abandon: () -> Bool) -> Int? { for (index, option) in options.enumerated() { say(" \(index + 1)) \(option)") } - let prompt = " Choose 1-\(options.count) (enter = \(start + 1)): " + // Enter takes the first line unless another is the default, which the prompt then names. + let prompt = " Choose 1-\(options.count)" + (start == 0 ? "" : " (enter = \(start + 1))") + ": " + // The option taken, by its name: what the list said after its first " · " (a size, how it moves) is above. func finish(_ index: Int?) -> Int? { - write((index.map { options[$0] } ?? "") + "\n") + write((index.map { options[$0].components(separatedBy: " \u{00B7} ")[0] } ?? "") + "\n") return index } write(prompt) diff --git a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift index 474b5d49b8..d3df676ed0 100644 --- a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift +++ b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift @@ -138,7 +138,7 @@ import Darwin let count = Darwin.read(output[0], &buffer, buffer.count) let text = String(decoding: buffer.prefix(max(0, count)), as: UTF8.self) let listed = options.enumerated().map { " \($0.offset + 1)) \($0.element)\n" }.joined() - expect(text == "\nChoose a model\n" + listed + " Choose 1-13 (enter = 1): \n", + expect(text == "\nChoose a model\n" + listed + " Choose 1-13: \n", "pipe output has no colors, backspaces or echoed input: \(text)") } @@ -164,8 +164,8 @@ import Darwin expect(code == 0, "colour: exit 0, got \(String(describing: code))") let screen = visible(run.text) expect(ClusterOnboardingBrand.rows().allSatisfy { row in screen.contains { $0.contains(row) } }, "colour: the whole mark") - expect(screen.contains { $0.contains("Darkbloom") } && screen.contains { $0.contains(ClusterOnboardingDriver.setupSubtitle) }, - "colour: the name and the steps beside the mark") + expect(screen.contains { $0.contains("Darkbloom") } && !screen.contains { $0.contains("Two Macs, one model") }, + "colour: the name beside the mark, nothing more") let rows = stages.compactMap { stage in screen.firstIndex { $0.contains(stage) } } expect(rows.count == stages.count && rows == rows.sorted(), "colour: stages in order") for (index, stage) in stages.enumerated() { @@ -173,10 +173,10 @@ import Darwin expect(screen.contains { $0.contains(stage) && $0.contains(meter) }, "colour: \(stage) carries its meter") } // A taken choice folds to its one line: the ▸ and the option, the list and its hint erased. - expect(screen.contains(" \u{25B8} Yes, pair") && screen.contains(" \u{25B8} Qwen3.8-27B-4bit-mtp — 16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers"), + expect(screen.contains(" \u{25B8} Yes") && screen.contains(" \u{25B8} Qwen3.8-27B-4bit-mtp · 16.3 GB"), "colour: each choice folds to the chosen line") expect(run.text.contains("\u{1B}[3A\r\u{1B}[J"), "colour: the list is erased in place once chosen") - expect(screen.contains(" Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers."), + expect(screen.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom)"), "colour: the serving line reads plainly") for live in ["Checking the cable", "Reading both Macs over the cable", "Planning each model for both Macs", "Loading Qwen3.8-27B-4bit-mtp on both Macs", "Sending a test request"] { @@ -196,8 +196,10 @@ import Darwin && ClusterOnboardingBrand.bloom.count == ClusterOnboardingBrand.pixels.joined().filter { $0 == "#" }.count, "the bloom draws every pixel once") expect(ClusterOnboardingBrand.rows(revealed: 0).allSatisfy { $0.allSatisfy { $0 == " " } }, "an unopened bloom is blank") - expect(ClusterOnboardingBrand.meter("2 / 4 Pair") == "\u{25CF}\u{25CF}\u{25CB}\u{25CB}" - && ClusterOnboardingBrand.meter("Test a response") == nil && ClusterOnboardingBrand.meter("6 / 5 x") == nil, "the step meter") + expect(ClusterOnboardingBrand.meter("2/4 Pair") == "\u{25CF}\u{25CF}\u{25CB}\u{25CB}" + && ClusterOnboardingBrand.meter("2 / 4 Pair") == "\u{25CF}\u{25CF}\u{25CB}\u{25CB}" + && ClusterOnboardingBrand.meter("Test") == nil && ClusterOnboardingBrand.meter("6/5 x") == nil + && ClusterOnboardingBrand.meter("6 / 5 x") == nil, "the step meter") expect(!ClusterOnboardingBrand.drawsBlocks(["LANG": "C"]) && ClusterOnboardingBrand.drawsBlocks(["LC_ALL": "en_US.UTF-8"]), "blocks only where the locale is UTF-8") expect(ClusterOnboardingBrand.colour(["COLORTERM": "truecolor"]) == "38;2;20;86;255" && ClusterOnboardingBrand.colour([:]) == "38;5;27", @@ -240,11 +242,10 @@ import Darwin } } - /// A colour window narrower than the mark's widest row (the steps beside - /// the mark need 57 columns) keeps the meter and live lines without the - /// mark, so the bloom never climbs past a wrapped row; and a live line - /// wider than the window is cut to one row, so the line that replaces it - /// erases all of it. + /// A narrow colour window (45 columns) keeps the meter and live lines, and + /// the mark where its row fits (the setup's opening is the name alone); and + /// a live line wider than the window is cut to one row, so the line that + /// replaces it erases all of it. static func narrowColourWindowKeepsOneRowLines() { let recorder = Recorder() let run = TerminalRun(operations(recorder, pairEvents: leaderEvents, @@ -258,9 +259,9 @@ import Darwin let code = run.finish() expect(code == 0, "45 columns: exit 0, got \(String(describing: code))") let screen = visible(run.text) - expect(!run.text.contains("\u{2588}") && !run.text.contains("\u{1B}[\(ClusterOnboardingBrand.height)A"), - "45 columns: no mark and no bloom climb") - expect(screen.contains { $0.contains("1 / 4 Connect") && $0.contains("\u{25CF}\u{25CB}\u{25CB}\u{25CB}") }, + // The setup's opening is the name alone (2026-11-03), so the mark fits beside it at 45 columns too. + expect(run.text.contains("\u{2588}"), "45 columns: the short opening fits beside the mark") + expect(screen.contains { $0.contains("1/4 Connect") && $0.contains("\u{25CF}\u{25CB}\u{25CB}\u{25CB}") }, "45 columns: headings keep the meter") let wide = screen.filter { $0.contains("\u{25B8}") && $0.count > 45 } expect(wide.isEmpty, "45 columns: the list's rows fit the window: \(wide)") @@ -304,8 +305,8 @@ import Darwin expect(run.waitFor(prompt(2)), "failed test: choose model") run.type("\r") expect(run.finish() == 1, "failed test returns failure") - expect(run.text.contains("Setup saved, but the test request failed."), "failure is explicit") - expect(run.text.hasSuffix("Run `darkbloom cluster` to see the status and test again.\n"), "failure ends with its next action") + expect(run.text.hasSuffix("Setup saved, but the test failed. Run `darkbloom cluster` to test again.\n"), + "failure is explicit and ends with its next action") expect(!run.text.contains("Done."), "failed response never reports setup success") expect(recorder.all.suffix(3) == ["serve", "waitReady", "testRequest"], "readiness and actual test still run") } @@ -320,11 +321,11 @@ import Darwin resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: choices)) expect(run.waitFor(prompt(1)), "every family uses the same list") - expect(run.text.contains(" 1) MiMo — Fits these Macs\n"), "offered MiMo remains selectable") + expect(run.text.contains(" 1) MiMo · Fits these Macs\n"), "offered MiMo remains selectable") expect(!run.text.contains("GLM"), "a model that cannot be served here is not listed") run.type("q") expect(run.finish() == 0, "q cancels the choice") - expect(run.text.contains("Nothing was changed. Run `darkbloom cluster` again to choose."), "cancelled: said") + expect(run.text.contains("Nothing changed."), "cancelled: said") expect(!recorder.all.contains("adopt 0") && !recorder.all.contains("serve"), "presentation does not bypass start checks") } @@ -335,45 +336,47 @@ import Darwin "searching: a live line, no said line") let wait = machine.handle(.waitingAsLeader) expect(machine.role == .leader && machine.phase == .waiting, "listening makes this Mac the leader-to-be") - expect(wait.last == "Now run `darkbloom cluster` on the other Mac.", "the action is the last line, word for word: \(wait)") - expect(wait.first?.contains("q cancels") == true, "the cancel key is named") - expect(machine.working?.contains("run `darkbloom cluster` there") == true, "the live line repeats the action while it waits") + expect(wait == ["Run `darkbloom cluster` on the other Mac."], "the action is the one line, word for word: \(wait)") + expect(machine.working?.contains("run `darkbloom cluster` there") == true && machine.working?.contains("q cancels") == true, + "the live line repeats the action while it waits, and names the cancel key") expect(machine.handle(.waitingAsLeader).isEmpty, "the wait is announced once (idempotent)") expect(machine.handle(.connected).isEmpty, "connected: nothing said") let code = machine.handle(.code("123456", peer: ["Apple M5 Ultra, 256 GB", "macOS 27.0.1"])) expect(machine.asking == "123 456", "the code waits for an answer") - expect(code == ["The other Mac: Apple M5 Ultra, 256 GB", " macOS 27.0.1", "Code: 123 456", codeQuestion], - "the other Mac, the code and the question: \(code)") - expect(ClusterOnboardingPairing.codeAnswers == ["Yes, pair", "No"], "the two answers") + expect(code == ["Code 123 456. Same on the other Mac?"], "the code and its question, one line: \(code)") + expect(ClusterOnboardingPairing.codeAnswers == ["Yes", "No"], "the two answers") expect(machine.answered(true) == [ClusterOnboardingPairing.otherMacAnswerLine] && machine.working == "Waiting for the other Mac to confirm the code", "answer yes: the other Mac's turn, said, and the wait is live") expect(machine.answered(true).isEmpty, "a second answer answers nothing") var first = ClusterOnboardingPairing() _ = first.handle(.code("123456", peer: ["Apple M5 Ultra, 256 GB"])) - _ = first.handle(.peerDecided(true)) + expect(first.handle(.peerDecided(true)).isEmpty, "the other Mac's confirmation: no line") expect(first.answered(true).isEmpty, "the other Mac answered first: nothing more to do there") + var declined = ClusterOnboardingPairing() + _ = declined.handle(.code("123456", peer: [])) + expect(declined.handle(.peerDecided(false)) == ["The other Mac declined the code."], "the other Mac declined: said") expect(machine.finished(.paired(role: .leader, peerName: "Apple M5 Ultra, 256 GB")).last - == "\u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). This Mac leads.", "leader's paired line") + == "\u{2713} Paired. This Mac leads.", "leader's paired line") var joiner = ClusterOnboardingPairing() _ = joiner.handle(.searching) - expect(joiner.handle(.joining) == ["Found the other Mac on the cable: it leads, and this Mac joins it."], "a waiting leader is found") + expect(joiner.handle(.joining).isEmpty && joiner.working == "Exchanging keys with the other Mac", "a waiting leader is found: live only") expect(joiner.role == .member, "dialing a waiting Mac makes this one a member") expect(joiner.finished(.paired(role: .member, peerName: "Apple M3 Ultra, 256 GB")).last - == "\u{2713} Paired with the other Mac (Apple M3 Ultra, 256 GB). It leads; this Mac follows it.", "member's paired line, word for word") + == "\u{2713} Paired. The other Mac leads.", "member's paired line, word for word") var tie = ClusterOnboardingPairing() _ = tie.handle(.waitingAsLeader) - expect(tie.handle(.joining) == ["The other Mac started waiting at the same moment and leads; this Mac joins it."], "a tie is explained") + expect(tie.handle(.joining).isEmpty, "a tie: the paired line says which Mac leads") expect(tie.role == .member, "the Mac that yields joins") var declining = ClusterOnboardingPairing() _ = declining.handle(.code("123456", peer: [])) - expect(declining.answered(false) == ["Declined here: nothing is paired."], "answer no") + expect(declining.answered(false) == ["Declined: nothing paired."], "answer no") var failed = ClusterOnboardingPairing() expect(failed.finished(.failed(["The code was declined."])) == ["Not paired.", "The code was declined.", - "Run `darkbloom cluster` again to try again."], "a failed pairing says how to retry") + "Run `darkbloom cluster` again."], "a failed pairing says how to retry") expect(ClusterOnboardingPairing.spaced("654321") == "654 321", "code spacing") // A typed answer: enter, a number, or a letter only one option starts with. @@ -383,7 +386,7 @@ import Darwin && C.match("y", options: answers, selected: 0) == 0 && C.match("N", options: answers, selected: 0) == 1 && C.match("3", options: answers, selected: 0) == nil && C.match("x", options: answers, selected: 0) == nil, "typed answers") - expect(C.match("c", options: ["Change model", "Check both Macs released their memory"], selected: 0) == nil, + expect(C.match("c", options: ["Change model", "Check memory is freed"], selected: 0) == nil, "a letter two options start with picks neither") } @@ -403,9 +406,7 @@ import Darwin /// A copy's live report, logged for a transcript, then the line for the record. static let copyReports: [ClusterOnboardingProgress] = [ - .live({ _ in "Copying Qwen3.8-27B-4bit-mtp to the other Mac (Apple M3 Ultra, 256 GB) over the Thunderbolt cable: 8.2 of 16.3 GB, 2.40 GB/s, about 1 s left" }, - logged: true), - .line("Copied 16.3 GB in 6.9 s (2.36 GB/s); every file matched its manifest digest.")] + .live({ _ in "Copying to the other Mac: 8.2 of 16.3 GB, 2.40 GB/s, about 1 s left" }, logged: true)] final class Recorder: @unchecked Sendable { let lock = NSLock() @@ -420,7 +421,7 @@ import Darwin pairEvents: [ClusterOnboardingPairEvent], pairResult: ClusterOnboardingPairResult, choices: [ClusterOnboardingModelChoice] = choices, replanned: [ClusterOnboardingModelChoice]? = nil, - provisionResult: Result<[String], ClusterOnboardingFailure> = .success(["The other Mac (Apple M3 Ultra, 256 GB) has Qwen3.8-27B-4bit-mtp now: 12 files verified against the catalog manifest."]), + provisionResult: Result<[String], ClusterOnboardingFailure> = .success(["\u{2713} Copied to the other Mac (16.3 GB, 6.9 s)"]), provisionReports: [ClusterOnboardingProgress] = copyReports, provisionReportPause: useconds_t = 30_000, linkPorts: [String] = [], @@ -428,7 +429,7 @@ import Darwin recheck: String? = nil, afterRestart: String? = nil, developerNotice: String? = nil, - testResult: Result<[String], ClusterOnboardingFailure> = .success(["\"Red, Blue, Green\" (6 tokens, first token 0.61 s)"]), + testResult: Result<[String], ClusterOnboardingFailure> = .success(["in 0.61 s"]), machines: [ClusterOnboardingMachine] = leaderHardware, registerResult: Result<[String], ClusterOnboardingFailure> = .success([]), localNetwork: @escaping @Sendable (ClusterOnboardingLocalNetworkSubject) -> ClusterOnboardingLocalNetwork = { _ in .allowed }, @@ -454,7 +455,6 @@ import Darwin } if let linkScript, !recorder.all.contains("runAsAdministrator") { say("Cable found.") - say("macOS asks for your password to set up the cable's port: approve it (once per Mac).") return .init(ready: false, exitCode: 1, manualScript: linkScript) } if linkPorts.count > 1, chosenPort.all.isEmpty { @@ -510,11 +510,9 @@ import Darwin testRequest: { recorder.note("testRequest"); return testResult }, // Rank 0, which serves the API, is the Mac that leads: this Mac on the leader, the other Mac on a member. status: { recorder.note("status"); return resume.role == .member - ? ["Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, the other Mac 32 layers / this Mac 32 layers.", - "API at http://localhost:8000 on the other Mac (Apple M3 Ultra, 256 GB); 2 of 2 parts ready."] - : ["Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers.", - "API at http://localhost:8000 on this Mac; 2 of 2 parts ready."] }, - stop: { recorder.note("stop"); return .success(["Both Macs stopped serving."]) }, + ? ["Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 on the other Mac (earning through Darkbloom)."] + : ["Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom)."] }, + stop: { recorder.note("stop"); return .success(["Stopping both Macs. Run `darkbloom cluster` to serve again."]) }, provision: { index, download, progress in recorder.note("provision \(index) \(download ? "download" : "copy")") for report in provisionReports { @@ -565,7 +563,7 @@ import Darwin let leader = TerminalRun(operations(leaderRecorder, resume: .init(role: .leader), pairEvents: [], pairResult: .failed([]), choices: [choice], recheck: "Quit apps first."), request: request) expect(leader.finish() == 1, "qualification stops at the start's fit check here") - expect(leader.text.contains("MiMo private PNG does not fit in the Macs' free memory now: Quit apps first."), "leader reaches the start") + expect(leader.text.contains("MiMo private PNG doesn't fit in free memory now: Quit apps first."), "leader reaches the start") expect(leaderRecorder.all.contains("planModels"), "leader uses normal planning") expect(!leaderRecorder.all.contains("adopt 0") && !leaderRecorder.all.contains("serve"), "a stopped draft creates no saved plan or Ready") } @@ -694,13 +692,13 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, pairEvents: leaderEvents, pairResult: .paired(role: .leader, peerName: "Apple M3 Ultra, 256 GB"))) - expect(run.waitFor(" Now run `darkbloom cluster` on the other Mac.\n"), "leader: the one thing to do on the other Mac, on its own line") - expect(run.waitFor(codeQuestion + "\n 1) Yes, pair\n 2) No\n " + prompt(2)), "leader: the code question and its answers") + expect(run.waitFor(" Run `darkbloom cluster` on the other Mac.\n"), "leader: the one thing to do on the other Mac, on its own line") + expect(run.waitFor(" Code 123 456. " + codeQuestion + "\n 1) Yes\n 2) No\n " + prompt(2)), "leader: the code, its question and its answers") run.type("y") expect(run.waitFor(" " + prompt(2), count: 2), "leader: the model list") let listed = run.text - expect(listed.contains(" This Mac: Apple M5 Ultra, 256 GB \u{00B7} the other Mac: Apple M3 Ultra, 256 GB\n"), "leader: both Macs in one line") - expect(listed.contains(" 1) Qwen3.8-27B-4bit-mtp — 16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers\n"), "leader: one line per model: \(listed)") + expect(!listed.contains("This Mac: Apple"), "leader: no line of both Macs' hardware") + expect(listed.contains(" 1) Qwen3.8-27B-4bit-mtp · 16.3 GB\n 2) Z.ai: GLM-5.3-Flash · 181.8 GB\n"), "leader: one short line per model: \(listed)") expect(!listed.contains("rank 1 (decodes)"), "leader: the rest of a model's lines is not said") expect(!listed.contains("gpt-oss-20b"), "leader: a model these Macs cannot serve is not listed") run.type("\r") @@ -708,26 +706,28 @@ import Darwin expect(code == 0, "leader: exit 0, got \(String(describing: code))") let text = run.text for line in [ - " \(prompt(2))Yes, pair", - " \u{2713} Paired with the other Mac (Apple M3 Ultra, 256 GB). This Mac leads.", - " \(prompt(2))Qwen3.8-27B-4bit-mtp — 16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers", - " \u{2713} Setup sent to the other Mac.", - " Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers.", - " API at http://localhost:8000 on this Mac.", - " \u{2713} Test response: \"Red, Blue, Green\" (6 tokens, first token 0.61 s)", + " \(prompt(2))Yes", + " " + ClusterOnboardingPairing.otherMacAnswerLine, + " \u{2713} Paired. This Mac leads.", + " \(prompt(2))Qwen3.8-27B-4bit-mtp", + " \u{2713} Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom)", + " \u{2713} Test response in 0.61 s", ] { expect(text.contains(line + "\n"), "leader: \(line)") } // What is done, then the one thing to do next: the last line. - expect(text.hasSuffix("Done. You can close this window here and on the other Mac.\n" - + "To test, change the model or stop: run `darkbloom cluster` on this Mac.\n"), "leader: the last lines: \(text)") + expect(text.hasSuffix("Done. You can close both windows.\n" + ClusterOnboardingDriver.againLine + "\n"), "leader: the last lines: \(text)") + expect(!text.contains("Setup sent") && !text.contains("confirmed the code") && !text.contains("Cable found"), + "leader: no line repeats what another says") expect(!text.contains("127.0.0.1"), "leader: no bare loopback address") expect(!text.contains("Run `darkbloom cluster` on the other Mac too."), "leader: the link flow's own ending is not repeated") expect(!text.contains("press n to stop") && !text.contains("Options:"), "leader: no countdown and no options paragraph after the choice") let positions = stages.compactMap { text.range(of: $0)?.lowerBound } expect(positions.count == stages.count && positions == positions.sorted(), "setup stages stay in order") expect(!text.contains("\u{1B}"), "NO_COLOR transcript has no terminal escapes") - expect(visible(text).filter { !$0.isEmpty }.count <= 32, "leader: a short screen: \(visible(text).filter { !$0.isEmpty }.count) lines") + expect(visible(text).filter { !$0.isEmpty }.count <= 21, "leader: a short screen: \(visible(text).filter { !$0.isEmpty }.count) lines") + // 2026-11-03 (owner, from the customer's review): "less is better". The setup's screen keeps to a word budget. + expect(words(text) <= leaderWordBudget, "leader: at most \(leaderWordBudget) words, got \(words(text))") expect(run.keys == 2, "leader: two keys (y, enter), got \(run.keys)") expect(recorder.all == ["checkLink", "pair", "answer y", "ensureService", "reachMembers", "planModels", "recheckFit 0", "adopt 0", "serve", "waitReady", "testRequest", "register"], "leader: operations in order: \(recorder.all)") @@ -764,7 +764,7 @@ import Darwin } /// DEVELOPER ONLY (`DARKBLOOM_CLUSTER_FORCE_MODE` in a debug build): a forced mode is said loudly, in one line, on - /// the setup screen right under the line of both Macs; without the setting the screen has no such line. + /// the setup screen right under the model step's heading; without the setting the screen has no such line. static func forcedModeNoticeOnTheSetupScreen() { let notice = "Developer setting: tensor parallel forced (DARKBLOOM_CLUSTER_FORCE_MODE=tensor_parallel_v1; debug build only)." let recorder = Recorder() @@ -774,8 +774,7 @@ import Darwin run.type("y") expect(run.waitFor(prompt(2), count: 2), "forced mode: the model choice") let text = run.text - expect(text.contains(" This Mac: Apple M5 Ultra, 256 GB \u{00B7} the other Mac: Apple M3 Ultra, 256 GB\n" + notice + "\n"), - "forced mode: the notice in one line right under the Macs") + expect(text.contains("\n3/4 Model\n" + notice + "\n"), "forced mode: the notice in one line right under the heading") expect(text.components(separatedBy: "Developer setting:").count == 2, "forced mode: said once") run.type("\r") _ = run.finish() @@ -791,22 +790,25 @@ import Darwin _ = other.finish() } - /// The serving API listens on loopback on the Mac that runs rank 0: the line says which Mac that is. + /// The serving API listens on loopback on the Mac that runs rank 0: the line says when that is the other Mac, and + /// at its end how the pair serves (local only, asked for or a coordinator without cluster support; else earning). static func servingLineNamesTheMac() { - expect(ClusterOnboardingReady(servedBy: "this Mac", port: 8000).apiLine == "API at http://localhost:8000 on this Mac", "serving here") - expect(ClusterOnboardingReady(servedBy: "the other Mac (Apple M3 Ultra, 256 GB)", port: 8100).apiLine - == "API at http://localhost:8100 on the other Mac (Apple M3 Ultra, 256 GB)", "serving there: that Mac named") - expect(ClusterOnboardingReady(servedBy: "this Mac", port: 8000).lines(model: "Qwen3.5-9B") - == ["Serving Qwen3.5-9B across both Macs", "API at http://localhost:8000 on this Mac"], "no plan known: still one plain line") - // The local-serving line speaks of the Mac whose API serves: on the screen of the Mac that does not hold the - // API (a member's status, or a leader whose API moved) it is that Mac's API, never "this Mac's". + expect(ClusterOnboardingReady(servedBy: "this Mac", port: 8000).summary(model: "Qwen3.5-9B") + == "Serving Qwen3.5-9B at http://localhost:8000", "serving here") + expect(ClusterOnboardingReady(servedBy: "the other Mac (Apple M3 Ultra, 256 GB)", port: 8100).summary(model: "Qwen3.5-9B") + == "Serving Qwen3.5-9B at http://localhost:8100 on the other Mac", "serving there: that Mac said") + let D = ClusterOnboardingDriver.self let notice = "Serving locally on this Mac's API; public serving needs a coordinator with cluster support" - expect(ClusterOnboardingReady(servedBy: "this Mac", port: 8000, notice: notice).lines(model: "Qwen3.5-9B").last == notice, - "local serving here: this Mac's API") - let there = ClusterOnboardingReady(servedBy: "the other Mac (Apple M3 Ultra, 256 GB)", port: 8000, notice: notice).lines(model: "Qwen3.5-9B") - expect(there.last == "Serving locally on that Mac's API; public serving needs a coordinator with cluster support", - "local serving there: that Mac's API, got \(there)") - expect(!there.contains { $0.contains("this Mac's API") }, "local serving there: no line says this Mac's API") + expect(D.servesWords(scope: .publicServing, ready: .init(servedBy: "this Mac", port: 8000, notice: notice)) == " (local only)", + "serves: a coordinator without cluster support serves locally") + expect(D.servesWords(scope: .publicServing, ready: .init(servedBy: "this Mac", port: 8000)) == " (earning through Darkbloom)", + "serves: through Darkbloom") + expect(D.servesWords(scope: .publicServing, ready: .init(servedBy: "this Mac", port: 8000, + notice: ClusterOnboardingReady.registeredNotice + " for m")) == " (earning through Darkbloom)", "serves: registered as a cluster member") + expect(D.servesWords(scope: .localOnly(bind: "0.0.0.0"), ready: .init(servedBy: "this Mac", port: 8000)) == " (local only)", + "serves: local only, asked for") + expect(D.servesWords(scope: .publicServing, ready: .init(servedBy: "this Mac", port: 8000, offered: "offered")) == "", + "serves: offered for pairing says it itself") } /// The leader's cluster service keeps each member on the leader's serving state (serve or stop, and the model), @@ -832,19 +834,19 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, pairEvents: memberEvents, pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"))) - expect(run.waitFor("Found the other Mac on the cable: it leads, and this Mac joins it."), "member: finds the waiting leader by itself") expect(run.waitFor(codeQuestion), "member: the code question") run.type("y") let code = run.finish() expect(code == 0, "member: exit 0") let text = run.text - expect(text.contains(" \u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). It leads; this Mac follows it.\n"), - "member: who leads, word for word") - expect(text.hasSuffix("Done on this Mac. " + ClusterOnboardingDriver.closeWindowLine + "\n" + ClusterOnboardingDriver.joinedLine + "\n"), - "member: whether the window may close, then where to continue, last: \(text)") - expect(!text.contains("Now run `darkbloom cluster` on the other Mac."), "member: never told to run anything on another Mac") + expect(text.contains(" \u{2713} Paired. The other Mac leads.\n"), "member: who leads, word for word") + expect(text.hasSuffix(ClusterOnboardingDriver.joinedLine + " " + ClusterOnboardingDriver.closeWindowLine + "\n"), + "member: where to continue and whether the window may close, last: \(text)") + expect(!text.contains("Run `darkbloom cluster` on the other Mac."), "member: never told to run anything on another Mac") + expect(!text.contains("Found the other Mac"), "member: finding the leader stays on the live line") expect(!text.contains("cluster local"), "member: no `local` line for a plain join") - expect(visible(text).filter { !$0.isEmpty }.count <= 20, "member: a short screen: \(visible(text).filter { !$0.isEmpty }.count) lines") + expect(visible(text).filter { !$0.isEmpty }.count <= 12, "member: a short screen: \(visible(text).filter { !$0.isEmpty }.count) lines") + expect(words(text) <= memberWordBudget, "member: at most \(memberWordBudget) words, got \(words(text))") expect(run.keys == 1, "member: one key (y)") expect(recorder.all == ["checkLink", "pair", "answer y", "ensureService"], "member: operations \(recorder.all)") transcript("member-from-scratch", text, keys: run.keys) @@ -854,10 +856,9 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, pairEvents: [.searching, .waitingAsLeader, .joining, .code("111222", peer: ["Apple M3 Ultra, 256 GB"])], pairResult: .paired(role: .member, peerName: "Apple M3 Ultra, 256 GB"))) - expect(run.waitFor("The other Mac started waiting at the same moment and leads; this Mac joins it."), "tie: explained") - expect(run.waitFor("Code: 111 222"), "tie: code shown"); run.type("y") + expect(run.waitFor("Code 111 222"), "tie: code shown"); run.type("y") expect(run.finish() == 0, "tie: joins and ends") - expect(run.text.contains("Paired with the other Mac (Apple M3 Ultra, 256 GB). It leads; this Mac follows it."), "tie: follows the leader") + expect(run.text.contains("Paired. The other Mac leads."), "tie: follows the leader") } static func cancelWhileWaiting() { @@ -865,10 +866,10 @@ import Darwin let run = TerminalRun(operations(recorder, pairEvents: [.searching, .waitingAsLeader, .note("still waiting"), .note("still waiting"), .note("still waiting"), .note("still waiting"), .note("still waiting"), .note("still waiting"), .note("still waiting")] + Array(repeating: .note(""), count: 200), pairResult: .failed(["expired"]))) - expect(run.waitFor("q cancels"), "cancel: the wait is on screen") + expect(run.waitFor("Run `darkbloom cluster` on the other Mac."), "cancel: the wait is on screen") run.type("q") expect(run.finish() == 130, "cancel: q ends with 130") - expect(run.text.contains("Cancelled: nothing was paired. Run `darkbloom cluster` again to start over."), "cancel: says nothing was paired") + expect(run.text.contains("Cancelled: nothing paired."), "cancel: says nothing was paired") } static func declinedCode() { @@ -878,8 +879,8 @@ import Darwin expect(run.waitFor(codeQuestion), "declined: code shown"); run.type("n") expect(run.finish() == 1, "declined: exit 1") expect(run.text.contains(" " + prompt(2) + "No\n"), "declined: the answer on the prompt's line") - expect(run.text.contains("Declined here: nothing is paired."), "declined: said") - expect(run.text.contains("Run `darkbloom cluster` again to try again."), "declined: how to retry") + expect(run.text.contains("Declined: nothing paired."), "declined: said") + expect(run.text.contains("Run `darkbloom cluster` again.\n"), "declined: how to retry") expect(!recorder.all.contains("ensureService"), "declined: no service started") } @@ -887,7 +888,7 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, linkReady: false, pairEvents: [], pairResult: .failed([]))) expect(run.finish() == 1, "link not ready: stops") - expect(run.text.contains("The cable is not ready yet, so pairing waits."), "link not ready: said") + expect(run.text.contains("Cable not ready. Fix the step above, then run `darkbloom cluster` again."), "link not ready: said") expect(!run.text.contains("cluster link"), "link not ready: no developer command named") expect(recorder.all == ["checkLink"], "link not ready: nothing else ran") } @@ -908,13 +909,12 @@ import Darwin let run = TerminalRun(operations(recorder, resume: memberResume(), pairEvents: [], pairResult: .failed([]))) expect(run.finish() == 0, "member again: ends by itself") let text = run.text - expect(text.contains("This Mac follows the other Mac (Apple M3 Ultra, 256 GB)"), "member again: who leads, in the opening") + expect(text.contains("This Mac follows the other Mac\n"), "member again: who leads, in the opening") expect(!text.contains("derived") && !text.contains("term ") && !text.contains("rank 0"), "member again: no leadership jargon") - expect(text.contains(" Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, the other Mac 32 layers / this Mac 32 layers.\n"), "member again: the status") - expect(text.hasSuffix("This Mac's part runs by itself: nothing to do here.\n" - + "To test, change the model or stop: run `darkbloom cluster` on the other Mac (Apple M3 Ultra, 256 GB).\n"), - "member again: where to manage the cluster, last: \(text)") - expect(!text.contains("Change model") && !text.contains("Test a response") && !text.contains("Choose 1-"), "member again: no menu") + expect(text.contains(" Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 on the other Mac (earning through Darkbloom).\n"), + "member again: the status") + expect(text.hasSuffix(ClusterOnboardingDriver.memberNothingLine + "\n"), "member again: where to manage the cluster, last: \(text)") + expect(!text.contains("Change model") && !text.contains("Choose 1-"), "member again: no menu") expect(recorder.all == ["ensureService", "status"], "member again: its service and the status only: \(recorder.all)") expect(run.keys == 0, "member again: no key") transcript("member-again", text, keys: run.keys) @@ -926,7 +926,7 @@ import Darwin static func resumedMacsOpenWithTheMark() { let D = ClusterOnboardingDriver.self let resumes: [(String, ClusterOnboardingResume, String)] = [ - ("member", memberResume(), "This Mac follows the other Mac (Apple M3 Ultra, 256 GB)"), + ("member", memberResume(), "This Mac follows the other Mac"), ("leader", .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), D.leaderSubtitle), ] for (label, resume, subtitle) in resumes { @@ -969,11 +969,11 @@ import Darwin pairEvents: [], pairResult: .failed([]))) expect(run.waitFor(prompt(6)), "leader again: the menu") let menu = run.text - expect(menu.contains(" 1) Test a response\n 2) Change model\n 3) Serve locally only (no coordinator)\n 4) Stop serving\n" - + " 5) Check both Macs released their memory\n 6) Quit\n"), "leader again: every choice, one per line: \(menu)") + expect(menu.contains(" 1) Test\n 2) Change model\n 3) Serve locally\n 4) Stop\n 5) Check memory is freed\n 6) Quit\n"), + "leader again: every choice, one short line each: \(menu)") run.type("\r") expect(run.finish() == 0, "leader again: test request") - expect(run.text.contains(" \u{2713} Test response: \"Red, Blue, Green\""), "leader again: the answer") + expect(run.text.contains(" \u{2713} Test response in 0.61 s\n"), "leader again: the answer") expect(recorder.all == ["ensureService", "status", "testRequest"], "leader again: no pairing, no plan: \(recorder.all)") transcript("leader-again", run.text, keys: run.keys) } @@ -993,7 +993,7 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: [ClusterOnboardingModelChoice(title: "big", lines: [], blocker: "too large for this pair")])) expect(run.finish() == 1, "no model: exit 1") - expect(run.text.contains("No model approved for clusters can run on these two Macs now.\n big: too large for this pair\n"), + expect(run.text.contains("No approved model can run on these Macs now.\n big: too large for this pair\n"), "no model: said, with why: \(run.text)") } @@ -1014,13 +1014,12 @@ import Darwin expect(run.waitFor(prompt(2)), "copy: the choice") expect(!run.text.contains("needs: "), "copy: the list stays one line per model") run.type("\r") - expect(run.waitFor(" Qwen3.8-27B-4bit-mtp is not on every Mac yet:\n The other Mac (Apple M3 Ultra, 256 GB): copy from this Mac over the Thunderbolt cable (16.3 GB, about 7 s)\n"), - "copy: once chosen, what is missing, with size and time") - expect(run.waitFor(" 1) Copy it over the Thunderbolt cable (recommended)\n 2) Download it from Darkbloom's catalog instead\n 3) Stop here\n " + prompt(3)), - "copy: the cable first, as a list") + expect(run.waitFor(" 1) Copy to the other Mac\n 2) Download\n 3) Cancel\n " + prompt(3)), "copy: the cable first, as a list that says what moves") + expect(!run.text.contains("is not on every Mac yet") && run.text.contains(" 1) Qwen3.8-27B-4bit-mtp · 16.3 GB · copy\n"), + "copy: the model's line says a copy is needed, nothing more: \(run.text)") run.type("\r") - expect(run.waitFor(" Copying Qwen3.8-27B-4bit-mtp to the other Mac (Apple M3 Ultra, 256 GB) over the Thunderbolt cable: 8.2 of 16.3 GB, 2.40 GB/s, about 1 s left"), "copy: progress on the leader") - expect(run.waitFor("every file matched its manifest digest."), "copy: verified") + expect(run.waitFor(" Copying to the other Mac: 8.2 of 16.3 GB, 2.40 GB/s, about 1 s left"), "copy: progress on the leader") + expect(run.waitFor(" \u{2713} Copied to the other Mac (16.3 GB, 6.9 s)\n"), "copy: done, verified") expect(run.finish() == 0, "copy: served") 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)") @@ -1034,7 +1033,7 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: copyChoices)) expect(run.waitFor(prompt(2)), "catalog: the choice"); run.type("\r") - expect(run.waitFor("Download it from Darkbloom's catalog instead"), "catalog: the alternative is offered"); run.type("2") + expect(run.waitFor(" 2) Download\n"), "catalog: the alternative is offered"); run.type("2") expect(run.finish() == 0, "catalog: served after the download") expect(recorder.all.contains("provision 0 download") && recorder.all.contains("adopt 0"), "catalog: downloaded, then adopted: \(recorder.all)") } @@ -1044,13 +1043,14 @@ import Darwin let offer = ClusterOnboardingProvisionOffer(lines: ["This Mac: download from Darkbloom's catalog (16.3 GB)", "The other Mac (Apple M3 Ultra, 256 GB): copy from this Mac over the Thunderbolt cable (16.3 GB)"], downloadAlternative: false, leaderDownloads: true) - let before = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["not on these Macs yet: planned once it is on this Mac"], blocker: nil, provision: offer)] + let before = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · not on these Macs: downloaded from Darkbloom's catalog first"], + blocker: nil, provision: offer)] let after = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers", "rank 1 (decodes): Apple M5 Ultra, 256 GB (this Mac), layers 32-63"], blocker: nil)] let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: before, replanned: after)) expect(run.waitFor(prompt(1)), "download: a catalog model is offered"); run.type("\r") - expect(run.waitFor(" Qwen3.8-27B-4bit-mtp is not on this Mac yet:\n"), "download: said") - expect(run.waitFor(" 1) Get it (download, then copy over the cable)\n 2) Stop here\n"), "download: one choice"); run.type("\r") + expect(run.text.contains(" 1) Qwen3.8-27B-4bit-mtp · 16.3 GB · download\n"), "download: the model's line says it is downloaded first") + expect(run.waitFor(" 1) Download\n 2) Cancel\n"), "download: one choice"); run.type("\r") expect(run.finish() == 0, "download: served") 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)") @@ -1063,9 +1063,9 @@ import Darwin (0...100).map { percent in .live({ width in widths.note(width.map(String.init) ?? "plain") - return "Downloading Qwen3.8-27B-4bit-mtp \(percent)% \(String(format: "%.1f", 0.163 * Double(percent)))/16.3 GB" + return "Downloading \(percent)% \(String(format: "%.1f", 0.163 * Double(percent)))/16.3 GB" }, logged: percent % 25 == 0) - } + [.line("Downloaded 16.3 GB in 130.2 s; every file matched the catalog manifest.")] + } + [.line("\u{2713} Downloaded (16.3 GB, 130.2 s)")] } /// A download reports four times a second for minutes. A live terminal redraws its reports on one row, laid out @@ -1074,7 +1074,8 @@ import Darwin static func downloadProgressStaysOnOneLine() { let offer = ClusterOnboardingProvisionOffer(lines: ["This Mac: download from Darkbloom's catalog (16.3 GB)"], downloadAlternative: false, leaderDownloads: true) - let before = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["not on these Macs yet: planned once it is on this Mac"], blocker: nil, provision: offer)] + let before = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · not on these Macs: downloaded from Darkbloom's catalog first"], + blocker: nil, provision: offer)] let after = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers"], blocker: nil)] for colour in [true, false] { let label = colour ? "live download" : "plain download" @@ -1087,12 +1088,12 @@ import Darwin expect(run.waitFor(colour ? arrowHint : prompt(1)), "\(label): the choice"); run.type("\r") expect(run.waitFor(colour ? arrowHint : prompt(2), count: colour ? 2 : 1), "\(label): get it"); run.type("\r") expect(run.finish() == 0, "\(label): served after the download") - let rows = run.text.components(separatedBy: "\n").filter { $0.contains("Downloading Qwen3.8-27B-4bit-mtp") } + let rows = run.text.components(separatedBy: "\n").filter { $0.contains("Downloading ") } let screen = visible(run.text) - expect(screen.contains(" Downloaded 16.3 GB in 130.2 s; every file matched the catalog manifest."), "\(label): the line for the record") + expect(screen.contains(" \u{2713} Downloaded (16.3 GB, 130.2 s)"), "\(label): the line for the record") if colour { expect(rows.count == 1, "\(label): every report on one row, got \(rows.count) rows") - expect(!screen.contains { $0.contains("Downloading Qwen3.8-27B-4bit-mtp") }, "\(label): the line for the record took the live row") + expect(!screen.contains { $0.contains("Downloading ") }, "\(label): the line for the record took the live row") expect(!widths.all.isEmpty && Set(widths.all) == ["94"], "\(label): laid out for the live line's room: \(Set(widths.all))") } else { expect(rows.map { $0.split(separator: " ").first { $0.hasSuffix("%") }.map(String.init) } == ["0%", "25%", "50%", "75%", "100%"], @@ -1109,9 +1110,9 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: copyChoices)) expect(run.waitFor(prompt(2)), "declined copy: choice"); run.type("\r") - expect(run.waitFor("3) Stop here"), "declined copy: offer"); run.type("3") + expect(run.waitFor("3) Cancel"), "declined copy: offer"); run.type("3") expect(run.finish() == 0, "declined copy: exit 0") - expect(run.text.contains("Nothing was copied or downloaded. Run `darkbloom cluster` here again to choose."), "declined copy: said") + expect(run.text.hasSuffix("Nothing changed.\n"), "declined copy: said") expect(!recorder.all.contains { $0.hasPrefix("provision") || $0.hasPrefix("adopt") }, "declined copy: nothing moved or adopted") } @@ -1123,7 +1124,7 @@ import Darwin choices: blocked)) expect(run.waitFor(prompt(1)), "disk: choice"); run.type("\r") expect(run.finish() == 1, "disk: exit 1") - expect(run.text.contains("It cannot start: the other Mac (Apple M3 Ultra, 256 GB) has 3.0 GB free; the model needs 16.3 GB and 2.1 GB to spare. Free some space and run `darkbloom cluster` here again."), + expect(run.text.contains("Can't start Qwen3.8-27B-4bit-mtp: the other Mac (Apple M3 Ultra, 256 GB) has 3.0 GB free; the model needs 16.3 GB and 2.1 GB to spare. Free space, then run `darkbloom cluster` again."), "disk: the free-disk refusal in words") expect(!recorder.all.contains { $0.hasPrefix("provision") }, "disk: nothing started") } @@ -1133,9 +1134,9 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: copyChoices, provisionResult: .failure(.init("The copy to the other Mac (Apple M3 Ultra, 256 GB) stopped at 2.0 of 16.3 GB: the cable connection ended.")))) expect(run.waitFor(prompt(2)), "interrupted: choice"); run.type("\r") - expect(run.waitFor("3) Stop here"), "interrupted: offer"); run.type("\r") + expect(run.waitFor("3) Cancel"), "interrupted: offer"); run.type("\r") expect(run.finish() == 1, "interrupted: exit 1") - expect(run.text.contains("Run `darkbloom cluster` here again: a copy or download resumes where it stopped."), "interrupted: resumes next time") + expect(run.text.contains("Run `darkbloom cluster` again to resume."), "interrupted: resumes next time") expect(!recorder.all.contains("adopt 0"), "interrupted: no setup synced for a model a Mac lacks") } @@ -1153,7 +1154,7 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: choices)) expect(run.waitFor(prompt(1)), "short copy: the choice"); run.type("\r") - expect(run.waitFor(" 1) Copy it over the Thunderbolt cable (about 7 s)\n 2) Download it from Darkbloom's catalog instead\n 3) Stop here\n " + prompt(3)), + expect(run.waitFor(" 1) Copy to the other Mac (about 7 s)\n 2) Download\n 3) Cancel\n " + prompt(3)), "short copy: the copy first in the list, its time on it") usleep(300_000) expect(!recorder.all.contains { $0.hasPrefix("provision") }, "short copy: nothing starts by itself: \(recorder.all)") @@ -1168,7 +1169,7 @@ import Darwin /// The list's last item stops there, and so does q. static func shortCopyStopsFromItsList() { - for (label, key) in [("stop here", "3"), ("q", "q")] { + for (label, key) in [("cancel", "3"), ("q", "q")] { let recorder = Recorder() let choices = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: [], blocker: nil, provision: quickOffer)] let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), @@ -1176,7 +1177,7 @@ import Darwin expect(run.waitFor(prompt(1)), "short copy, \(label): choice"); run.type("\r") expect(run.waitFor(prompt(3)), "short copy, \(label): the list"); run.type(key) expect(run.finish() == 0, "short copy, \(label): exit 0") - expect(run.text.contains("Nothing was copied or downloaded. Run `darkbloom cluster` here again to choose."), "short copy, \(label): said") + expect(run.text.hasSuffix("Nothing changed.\n"), "short copy, \(label): said") expect(!recorder.all.contains { $0.hasPrefix("provision") || $0.hasPrefix("adopt") }, "short copy, \(label): nothing moved: \(recorder.all)") } } @@ -1216,14 +1217,14 @@ import Darwin gate.signal() expect(run.waitFor(codeQuestion), "cable: then pairing"); run.type("y") expect(run.finish() == 0, "cable: member done") - expect(run.text.contains(" Cable found.\n") && run.text.contains(" Cable ready.\n"), "cable: plain lines") + expect(!run.text.contains("Cable found") && run.text.contains(" \u{2713} Cable ready\n"), "cable: one done line") } static func twoCablesAreAskedOnScreen() { let recorder = Recorder() let run = TerminalRun(operations(recorder, pairEvents: [.searching, .joining, .code("123456", peer: ["Apple M5 Ultra, 256 GB"])], pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), linkPorts: ["en5", "en6"])) - expect(run.waitFor(" Two cables are connected. Which one goes to the other Mac?\n 1) en5\n 2) en6\n " + prompt(2)), "two cables: asked as a list") + expect(run.waitFor(" Which cable goes to the other Mac?\n 1) en5\n 2) en6\n " + prompt(2)), "two cables: asked as a list") run.type("2") expect(run.waitFor(codeQuestion), "two cables: pairing goes on"); run.type("y") expect(run.finish() == 0, "two cables: done") @@ -1241,8 +1242,8 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: choices)) expect(run.waitFor(prompt(2)), "fit: the choice") - expect(run.text.contains(" 1) Qwen3.8-27B-4bit-mtp — 16.3 GB · pipeline") && run.text.contains(" 2) Z.ai: GLM-5.3-Flash — 181.8 GB · tensor parallel"), "fit: the one that fits is 1") - expect(run.text.contains("M5 Ultra 50% · does not fit now\n"), "fit: the one that does not is marked on its line") + expect(run.text.contains(" 1) Qwen3.8-27B-4bit-mtp · 16.3 GB\n 2) Z.ai: GLM-5.3-Flash · 181.8 GB · does not fit now\n"), + "fit: the one that fits is 1, the one that does not is marked on its line: \(run.text)") run.type("\r") expect(run.finish() == 0, "fit: served") expect(recorder.all.contains("adopt 1") && !recorder.all.contains("adopt 0"), "fit: enter chose the fitting model: \(recorder.all)") @@ -1254,7 +1255,8 @@ import Darwin recheck: "Restart the other Mac (Apple M3 Ultra, 256 GB) to free memory.")) expect(run.waitFor(prompt(2)), "recheck: choice"); run.type("\r") expect(run.finish() == 1, "recheck: stops at once") - expect(run.text.contains("Qwen3.8-27B-4bit-mtp does not fit in the Macs' free memory now: Restart the other Mac (Apple M3 Ultra, 256 GB) to free memory."), "recheck: the same remedy line") + expect(run.text.contains("Qwen3.8-27B-4bit-mtp doesn't fit in free memory now: Restart the other Mac (Apple M3 Ultra, 256 GB) to free memory.\nNothing changed.\n"), + "recheck: the remedy, then that nothing changed") expect(!recorder.all.contains { $0.hasPrefix("adopt") || $0 == "serve" || $0 == "waitReady" }, "recheck: nothing adopted or started: \(recorder.all)") } @@ -1264,7 +1266,7 @@ import Darwin readyResult: .failure(.init(["The cluster did not report ready within 15 minutes.", "The other Mac (Apple M3 Ultra, 256 GB): its part ended: out of memory.", "This Mac: loading layers 16-31."])))) expect(run.waitFor(prompt(2)), "timeout: choice"); run.type("\r") - expect(run.waitFor(" 1) Save a diagnostics file to send to Darkbloom\n 2) Leave\n"), "timeout: one choice for diagnostics") + expect(run.waitFor(" 1) Save diagnostics for Darkbloom\n 2) Skip\n"), "timeout: one choice for diagnostics") run.type("1") expect(run.finish() == 1, "timeout: exit 1") expect(run.text.contains("The other Mac (Apple M3 Ultra, 256 GB): its part ended: out of memory."), "timeout: each Mac's last error on screen") @@ -1276,22 +1278,21 @@ import Darwin static func restartLineAtTheEnd() { let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), - afterRestart: "After a restart or power cut, this Mac serves again once someone logs in.")) + afterRestart: "After a restart, this Mac serves again once someone logs in.")) expect(run.waitFor(prompt(2)), "restart line: choice"); run.type("\r") expect(run.finish() == 0, "restart line: served") - expect(run.text.contains("After a restart or power cut, this Mac serves again once someone logs in.\nDone. "), + expect(run.text.contains("After a restart, this Mac serves again once someone logs in.\nDone. "), "restart line: what happens after a restart, from the service's real state, before Done") } /// What happens after a restart, from the Mac's own settings (A9): never a promise a FileVault Mac cannot keep. static func restartWords() { typealias R = ClusterOnboardingRestart - expect(R.line(mac: "this Mac", autoLogin: true, fileVault: false) - == "After a restart or power cut, this Mac comes back by itself and serves again (automatic login is on).", "restart: auto-login on") - expect(R.line(mac: "this Mac", autoLogin: false, fileVault: true) - == "After a restart or power cut, this Mac serves again once someone logs in (FileVault keeps the disk locked until then).", "restart: FileVault on") - expect(R.line(mac: "this Mac", autoLogin: false, fileVault: false).hasSuffix("To make it automatic, turn on automatic login (System Settings → Users & Groups; needs FileVault off)."), - "restart: auto-login off, the plain remedy") + expect(R.line(mac: "this Mac", autoLogin: true, fileVault: false) == "After a restart, this Mac serves again by itself.", "restart: auto-login on") + expect(R.line(mac: "this Mac", autoLogin: false, fileVault: true) == "After a restart, this Mac serves again once someone logs in.", + "restart: FileVault on") + expect(R.line(mac: "this Mac", autoLogin: false, fileVault: false) + == "After a restart, this Mac serves again once someone logs in (or turn on automatic login).", "restart: auto-login off, the plain remedy") expect(R.line(mac: "this Mac", autoLogin: false, fileVault: nil).contains("once someone logs in"), "restart: FileVault unknown, no promise") for line in [R.line(mac: "x", autoLogin: false, fileVault: true), R.line(mac: "x", autoLogin: false, fileVault: false)] { expect(!line.contains("by itself"), "restart: no 'by itself' promise without auto-login: \(line)") @@ -1376,7 +1377,7 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([]))) - expect(run.waitFor(" 1) Choose a model and serve\n 2) Serve locally only (no coordinator)\n 3) Check both Macs released their memory\n 4) Quit\n"), + expect(run.waitFor(" 1) Choose a model\n 2) Serve locally\n 3) Check memory is freed\n 4) Quit\n"), "stopped leader: the menu") run.type("3") expect(run.finish() == 0, "stopped leader: teardown checked") @@ -1429,9 +1430,8 @@ import Darwin run.type("\r") expect(run.finish() == 0, "local from scratch: exit 0") let text = run.text - expect(text.contains(" API at http://localhost:8000 on this Mac, and at port 8000 of its LAN or tailnet address.\n"), - "local from scratch: the API line names the network") - expect(text.contains(" Serving locally only on this Mac's API: no coordinator, no public traffic.\n"), "local from scratch: the local-only line") + expect(text.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 and on the network (local only)\n"), + "local from scratch: one serving line, the network and local only on it: \(text)") expect(recorder.all == ["checkLink", "pair", "answer y", "ensureService", "reachMembers", "planModels", "recheckFit 0", "adopt 0", "setScope local 0.0.0.0", "serve", "waitReady", "testRequest"], "local from scratch: scope saved after the adopt, before the start: \(recorder.all)") expect(run.keys == 2, "local from scratch: the same two keys (y, enter), got \(run.keys)") @@ -1459,7 +1459,8 @@ import Darwin expect(run.finish() == 0, "local switch: exit 0") let text = run.text expect(text.contains(ClusterServingScope.localOnly(bind: "0.0.0.0").line + ".\n"), "local switch: how it serves now") - expect(text.contains(" Serving locally only on this Mac's API: no coordinator, no public traffic.\n"), "local switch: ready again, local only") + expect(text.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 and on the network (local only)\n"), + "local switch: ready again, local only") expect(recorder.all == ["ensureService", "setScope local 0.0.0.0", "waitReady"], "local switch: \(recorder.all)") expect(run.keys == 0, "local switch: no key") } @@ -1482,7 +1483,7 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([]), readyResult: .success(localReady))) - expect(run.waitFor(" 3) Serve locally only (no coordinator)\n"), "menu: local only is offered") + expect(run.waitFor(" 3) Serve locally\n"), "menu: local only is offered") run.type("3") expect(run.finish() == 0, "menu local: exit 0") expect(recorder.all == ["ensureService", "status", "setScope local 0.0.0.0", "waitReady"], "menu local: \(recorder.all)") @@ -1500,11 +1501,11 @@ import Darwin let stopped = Recorder() let idle = TerminalRun(operations(stopped, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([]))) - expect(idle.waitFor(" 2) Serve locally only (no coordinator)\n"), "menu, stopped: local only is offered") + expect(idle.waitFor(" 2) Serve locally\n"), "menu, stopped: local only is offered") idle.type("2") expect(idle.finish() == 0, "menu local, stopped: exit 0") expect(stopped.all == ["ensureService", "status", "setScope local 0.0.0.0"], "menu local, stopped: saved, nothing started: \(stopped.all)") - expect(idle.text.contains("Not serving now: the next start serves this way."), "menu local, stopped: when it applies") + expect(idle.text.contains("Takes effect at the next start."), "menu local, stopped: when it applies") } /// `darkbloom cluster local `: the named model (id or title, any case) is chosen without the list. @@ -1524,7 +1525,7 @@ import Darwin let refused = TerminalRun(operations(blocked, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([])), request: request) expect(refused.finish() == 1, "named blocked model: exit 1") - expect(refused.text.contains("gpt-oss-20b is not offered on these Macs: not granted for this pair of chips.\n"), "named blocked model: why") + expect(refused.text.contains("gpt-oss-20b can't run on these Macs: not granted for this pair of chips.\n"), "named blocked model: why") expect(blocked.all == ["ensureService", "reachMembers", "planModels"], "named blocked model: nothing adopted: \(blocked.all)") let unknown = Recorder() @@ -1553,17 +1554,17 @@ import Darwin run.type("y") expect(run.finish() == 0, "\(label): exit 0 once paired") let text = run.text - expect(text.hasSuffix("Done on this Mac. " + ClusterOnboardingDriver.closeWindowLine + "\n" + ClusterOnboardingDriver.joinedLocalContinueLine + "\n"), + expect(text.hasSuffix(ClusterOnboardingDriver.joinedLocalContinueLine + " " + ClusterOnboardingDriver.closeWindowLine + "\n"), "\(label): one line for the other Mac, `local` in it, last: \(text)") expect(!text.contains(ClusterOnboardingDriver.joinedLine) && !text.contains(ClusterOnboardingDriver.joinedLocalLine), "\(label): no second instruction for the other Mac") - expect(!text.contains("3 / 4") && !text.contains("Choose a model") && !text.contains("Test a response"), + expect(!text.contains("3/4") && !text.contains("Choose a model") && !text.contains("Change model"), "\(label): no model list and no menu on the Mac that joined") expect(recorder.all == ["checkLink", "pair", "answer y", "ensureService"], "\(label): nothing after its service: \(recorder.all)") expect(run.keys == 1, "\(label): one key (y), got \(run.keys)") transcript(request.model == nil ? "member-joins-with-local" : "member-joins-with-local-model", text, keys: run.keys) } - expect(ClusterOnboardingDriver.joinedLocalLine.contains("run it on the other Mac"), "member local: the line says where to run it") + expect(ClusterOnboardingDriver.joinedLocalLine.contains("on the other Mac"), "member local: the line says where to run it") } /// Two Macs of one kind (2026-10-25: both "Apple M5 Ultra, 256 GB", and the API line named the Mac the screen was not @@ -1586,11 +1587,6 @@ import Darwin let three = ["mac-a": "Apple M5 Ultra, 256 GB", "mac-b": "Apple M5 Ultra, 256 GB", "mac-c": "Apple M4 Max, 128 GB"] expect(N.names(three, viewerID: "mac-a") == three, "names: among three Macs none is 'the other'") - let identical = [ClusterOnboardingMachine(name: "Apple M5 Ultra, 256 GB", memoryGB: 256, gpuCores: 80, leads: true, models: 2), - ClusterOnboardingMachine(name: "Apple M5 Ultra, 256 GB", memoryGB: 256, gpuCores: 80, leads: false, models: 2)] - expect(ClusterOnboardingDriver.machinesLine(identical) == "This Mac: Apple M5 Ultra, 256 GB \u{00B7} the other Mac: Apple M5 Ultra, 256 GB", - "machines: both in one line, each said which") - typealias D = ClusterOnboardingDeployment let tp = [D.Share(name: "Apple M5 Ultra, 256 GB", layers: 78, weightsBytes: 91, label: N.other), D.Share(name: "Apple M5 Ultra, 256 GB", layers: 78, weightsBytes: 91, label: N.this)] @@ -1614,12 +1610,9 @@ import Darwin expect(run.finish() == 0, "identical: exit 0") let text = run.text for line in [ - " \u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). This Mac leads.", - " This Mac: Apple M5 Ultra, 256 GB \u{00B7} the other Mac: Apple M5 Ultra, 256 GB", - " 1) Z.ai: GLM-5.3-Flash — 181.8 GB · tensor parallel · this Mac 50% / the other Mac 50%", - " Serving Z.ai: GLM-5.3-Flash across both Macs: tensor parallel, this Mac 50% / the other Mac 50%.", - " API at http://localhost:8000 on this Mac.", - " Serving locally only on this Mac's API: no coordinator, no public traffic.", + " \u{2713} Paired. This Mac leads.", + " 1) Z.ai: GLM-5.3-Flash · 181.8 GB", + " \u{2713} Serving Z.ai: GLM-5.3-Flash at http://localhost:8000 (local only)", ] { expect(text.contains(line + "\n"), "identical: \(line)") } @@ -1656,7 +1649,7 @@ import Darwin struct Flow { let name: String; let operations: (Recorder) -> ClusterOnboardingOperations; let request: ClusterOnboardingRequest; let keys: [(String, String)] } let flows = [ Flow(name: "identical Macs", operations: identicalOperations, request: .init(), - keys: [(codeQuestion, "y"), ("3 / 4 Choose a model", "\r")]), + keys: [(codeQuestion, "y"), ("3/4 Model", "\r")]), Flow(name: "member with local", operations: { recorder in operations(recorder, pairEvents: memberEvents, pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB")) }, request: localRequest, keys: [(codeQuestion, "y")]), @@ -1691,7 +1684,9 @@ import Darwin for (presentation, text) in plain.merging(["30 columns": visible(narrow.text).joined(separator: "\n")], uniquingKeysWith: { first, _ in first }) { if presentation != "30 columns" { expect(!text.contains("\u{1B}"), "\(flow.name), \(presentation): no terminal escape") } let lower = text.lowercased() - expect(!lower.contains("ssh") && !lower.contains(".local") && !lower.contains("bearer") && !lower.contains("password") + // "password" is said where macOS asks for it; never a password itself ("password=", "password:"). + expect(!lower.contains("ssh") && !lower.contains(".local") && !lower.contains("bearer") + && !lower.contains("password=") && !lower.contains("password:") && text.range(of: #"[0-9A-Fa-f]{32,}"#, options: .regularExpression) == nil && text.range(of: #"\b\d{1,3}(\.\d{1,3}){3}\b"#, options: .regularExpression) == nil, "\(flow.name), \(presentation): no credential, host name, address or SSH") @@ -1711,7 +1706,7 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Max, 128 GB"), pairEvents: [], pairResult: .failed([]), choices: twins), request: localRequest) expect(run.waitFor(prompt(2)), "twins: the list") - expect(run.text.contains(" 1) Gemma 4 26B (gemma-4-26b-qat-4bit) — 15.6 GB · pipeline") && run.text.contains(" 2) Gemma 4 26B (gemma-4-26b) — 28.0 GB"), + expect(run.text.contains(" 1) Gemma 4 26B (gemma-4-26b-qat-4bit) · 15.6 GB\n 2) Gemma 4 26B (gemma-4-26b) · 28.0 GB\n"), "twins: each names its id: \(run.text)") run.type("\r") expect(run.finish() == 0, "twins: served") @@ -1719,53 +1714,42 @@ import Darwin "twins: the list's line is what is said about a model") } - /// Why not tensor parallel, at the end of the model's one line (owner, 2026-10-15: one line per model): a few words - /// for a model with a tensor-parallel plan that the planner split otherwise, nothing for one without (no noise). A - /// note from another build that is too long or not plain text is not said. + /// The model's one line is its name and size (2026-11-03: less is better), with "copy" or "download" when it has + /// to reach a Mac first; how it is split and why not tensor parallel are the planner's, not said. An older Mac's + /// choice still decodes. static func tensorParallelNotesOnTheModelLine() { typealias C = ClusterOnboardingModelChoice - let notes = ["tensor parallel: slower here", "tensor parallel: about as fast", "tensor parallel: does not fit now", - "tensor parallel: does not fit", "tensor parallel: link unmeasured", "tensor parallel: failed a check", - "tensor parallel: pipeline kept", "tensor parallel: excluded here", "no tensor parallel for this model"] - func line(_ note: String?) -> String { - C(title: "m", lines: ["a"], blocker: nil, tensorParallelNote: note).listLine(sameTitleElsewhere: false) + for note in ["tensor parallel: slower here", "tensor parallel: does not fit now", "tensor parallel: \u{1B}[2J", ""] { + expect(C(title: "m", lines: ["6.1 GB · pipeline · M3 Ultra 16 layers / M5 Max 16 layers"], blocker: nil, + tensorParallelNote: note).listLine(sameTitleElsewhere: false) == "m · 6.1 GB", "model line: name and size, no note: \(note)") } - for note in notes { - expect(note.count <= C.tensorParallelNoteLimit && line(note) == "m — a · " + note, - "TP note: at the end of the model's line: \(note)") - } - expect(line(String(repeating: "x", count: C.tensorParallelNoteLimit + 1)) == "m — a", - "TP note: a note longer than the limit is not said") - expect(line("tensor parallel: \u{1B}[2J") == "m — a", "TP note: a note with terminal control characters is not said") - expect(line(nil) == "m — a" && line("") == "m — a", "TP note: no note, nothing added") + expect(C(title: "m", lines: [], blocker: nil).listLine(sameTitleElsewhere: false) == "m", "model line: no size known, the name") + expect(C(title: "m", lines: ["6.1 GB"], blocker: nil, modelID: "org/m").listLine(sameTitleElsewhere: true) == "m (org/m) · 6.1 GB", + "model line: a shared title says its id") + let copy = ClusterOnboardingProvisionOffer(lines: [], downloadAlternative: true, leaderDownloads: false) + let download = ClusterOnboardingProvisionOffer(lines: [], downloadAlternative: false, leaderDownloads: true) + let fromPeer = ClusterOnboardingProvisionOffer(lines: [], downloadAlternative: false, leaderDownloads: true, fromOtherMac: true) + expect(C(title: "m", lines: ["6.1 GB"], blocker: nil, provision: copy).listLine(sameTitleElsewhere: false) == "m · 6.1 GB · copy" + && C(title: "m", lines: ["6.1 GB · not on these Macs: downloaded from Darkbloom's catalog first"], blocker: nil, provision: download) + .listLine(sameTitleElsewhere: false) == "m · 6.1 GB · download" + && C(title: "m", lines: ["6.1 GB"], blocker: nil, provision: fromPeer).listLine(sameTitleElsewhere: false) == "m · 6.1 GB · copy", + "model line: what has to move first") let older = try? JSONDecoder().decode(C.self, from: Data(#"{"title":"m","lines":["a"]}"#.utf8)) - expect(older != nil && older?.tensorParallelNote == nil && older?.validated == nil, "TP note: an older Mac's choice decodes without it") + expect(older != nil && older?.tensorParallelNote == nil && older?.validated == nil, "model line: an older Mac's choice decodes") let listed = [ C(title: "Qwen3.5-9B", lines: ["6.1 GB · pipeline · M3 Ultra 16 layers / M5 Max 16 layers · about 92 tokens/s", "Pipeline: tensor parallel is predicted slower for requests of 1024 prompt and 256 answer tokens."], blocker: nil, tensorParallelNote: "tensor parallel: slower here"), - C(title: "Qwen3.8-27B", lines: ["16.3 GB · tensor parallel · M3 Ultra 40% / M5 Max 60% · about 41 tokens/s", - "Tensor parallel: pipeline is left out (Qwen3.8 27B keeps images, video and committed-token logprobs only in tensor parallel)."], - blocker: nil), C(title: "Bonsai 27B", lines: ["7.2 GB · pipeline · M3 Ultra 4 layers / M5 Max 60 layers"], blocker: nil, - fitRemedy: "Quit apps on the other Mac (Apple M5 Max, 128 GB) first."), - C(title: "Qwen3.6-35B-A3B", lines: ["19.5 GB · pipeline · M3 Ultra 4 layers / M5 Max 36 layers"], blocker: nil, fitRemedy: "Quit apps on the other Mac (Apple M5 Max, 128 GB) first.", tensorParallelNote: "tensor parallel: does not fit now")] - let recorder = Recorder() - let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M5 Max, 128 GB"), pairEvents: [], + let run = TerminalRun(operations(Recorder(), resume: .init(role: .leader, peerName: "Apple M5 Max, 128 GB"), pairEvents: [], pairResult: .failed([]), choices: listed), columns: 40) - expect(run.waitFor(prompt(4)), "TP note: the list") - let text = run.text - expect(text.contains(" 1) Qwen3.5-9B — 6.1 GB · pipeline · M3 Ultra 16 layers / M5 Max 16 layers · about 92 tokens/s" - + " · tensor parallel: slower here\n 2) Qwen3.8-27B — "), "TP note: at the end of the line it is about: \(text)") - expect(text.contains("about 41 tokens/s\n 3) Bonsai 27B — 7.2 GB · pipeline · M3 Ultra 4 layers / M5 Max 60 layers · does not fit now\n 4) Qwen3.6-35B-A3B — "), - "TP note: none for tensor parallel chosen or a model without it: \(text)") - expect(text.contains("M5 Max 36 layers · does not fit now\n"), - "TP note: a note that only says the model does not fit now is left to the fit mark, said once: \(text)") - expect(!text.contains("Tensor parallel: pipeline is left out") && !text.contains("Pipeline: tensor parallel is predicted slower"), - "TP note: the planner's full reasons are not said") + expect(run.waitFor(prompt(2)), "model line: the list") + expect(run.text.contains(" 1) Qwen3.5-9B · 6.1 GB\n 2) Bonsai 27B · 7.2 GB · does not fit now\n"), + "model line: name and size, a model that does not fit now said once: \(run.text)") + expect(!run.text.contains("tensor parallel") && !run.text.contains("layers"), "model line: no split, no planner reasons") run.type("\r") - expect(run.finish() == 0, "TP note: served") + expect(run.finish() == 0, "model line: served") } /// The scope's values: from the record, the bind addresses it takes, what reaches the network, and its line. @@ -1788,8 +1772,8 @@ import Darwin expect(S.localOnly(bind: "2001:db8::10").reachableFromNetwork, "an address reaches its network") for loopback in ["127.0.0.1", "::1", "localhost"] { expect(!S.localOnly(bind: loopback).reachableFromNetwork, "loopback stays on this Mac: \(loopback)") } expect(!S.publicServing.reachableFromNetwork && S.publicServing.bind == nil, "public: no local-only bind") - expect(S.localOnly(bind: "127.0.0.1").line.contains("the API listens on this Mac only (127.0.0.1)"), "line: loopback") - expect(S.localOnly(bind: "2001:db8::10").line.contains("the API listens at 2001:db8::10"), "line: an address") + expect(S.localOnly(bind: "127.0.0.1").line == "Local only, on this Mac only (127.0.0.1); API key: `darkbloom local`", "line: loopback") + expect(S.localOnly(bind: "2001:db8::10").line == "Local only, at 2001:db8::10; API key: `darkbloom local`", "line: an address") typealias Sync = ClusterOnboardingSync expect(Sync.action(leaderServing: true, leaderModel: "m", memberServing: true, memberModel: "m", leaderLocalOnly: true, memberLocalOnly: false) @@ -1800,16 +1784,26 @@ import Darwin == .none, "sync: an older member (no scope reported) is compared by model only") let here = ClusterOnboardingReady(servedBy: "this Mac", port: 8000, network: true) - expect(here.apiLine == "API at http://localhost:8000 on this Mac, and at port 8000 of its LAN or tailnet address", "ready: network, this Mac") + expect(here.summary(model: "m") == "Serving m at http://localhost:8000 and on the network", "ready: network, this Mac") let there = ClusterOnboardingReady(servedBy: "the other Mac (Apple M4 Max, 128 GB)", port: 8000, network: true) - expect(there.apiLine == "API at http://localhost:8000 on the other Mac (Apple M4 Max, 128 GB), and at port 8000 of that Mac's LAN or tailnet address; this Mac answers too (`darkbloom local` shows its address)", "ready: network, that Mac (this Mac's port passes to it)") - expect(ClusterOnboardingReady(servedBy: "this Mac", port: 8000).apiLine == "API at http://localhost:8000 on this Mac", "ready: loopback unchanged") + expect(there.summary(model: "m") == "Serving m at http://localhost:8000 on the other Mac and on the network", "ready: network, that Mac") + expect(ClusterOnboardingReady(servedBy: "this Mac", port: 8000).summary(model: "m") == "Serving m at http://localhost:8000", "ready: loopback unchanged") let older = try? JSONDecoder().decode(ClusterOnboardingReady.self, from: Data(#"{"servedBy":"this Mac","port":8000}"#.utf8)) expect(older?.network == nil, "ready: an older Mac's answer decodes without the network field") } /// The four steps, in order. - static let stages = ["1 / 4 Connect", "2 / 4 Pair", "3 / 4 Choose a model", "4 / 4 Start"] + static let stages = ["1/4 Connect", "2/4 Pair", "3/4 Model", "4/4 Start"] + + /// The words a person reads on a screen (escapes and redraws removed), as `wc -w` counts them. + static func words(_ text: String) -> Int { + visible(text).joined(separator: " ").split(whereSeparator: { $0.isWhitespace }).count + } + + /// The from-scratch screens' word budgets (2026-11-03: about 70% fewer words than the 2026-11-02 screens, 293 and + /// 148): a line that grows them back fails here. + static let leaderWordBudget = 100 + static let memberWordBudget = 60 static let codeQuestion = ClusterOnboardingPairing.codeQuestion @@ -1828,10 +1822,10 @@ import Darwin /// An arrow pressed while the setup waits (here for Allow) is no key: only q or a lone escape stops a wait. static func arrowKeysDoNotStopAWait() { let run = TerminalRun(operations(Recorder(), pairEvents: [], pairResult: .failed([]), localNetwork: refusedThenAllowed(3))) - expect(run.waitFor("click Allow."), "arrow in a wait: the prompt line") + expect(run.waitFor("Click Allow"), "arrow in a wait: the prompt line") run.type("\u{1B}[A") run.type("\u{1B}[B") - expect(run.waitFor(" \u{2713} Local network allowed for Terminal.\n"), "arrow in a wait: still waiting, then allowed") + expect(run.waitFor(" \u{2713} Allowed\n"), "arrow in a wait: still waiting, then allowed") _ = run.finish() expect(!run.text.contains("still off"), "arrow in a wait: not stopped: \(run.text)") } @@ -1847,7 +1841,7 @@ import Darwin expect(run.waitFor("Qwen3.8 27B"), "q, \(label): the list") run.type("q") expect(run.finish() == 0, "q, \(label): exit 0") - expect(run.text.contains("Nothing was changed. Run `darkbloom cluster` again to choose."), "q, \(label): cancelled") + expect(run.text.hasSuffix("Nothing changed.\n"), "q, \(label): cancelled") expect(!recorder.all.contains { $0.hasPrefix("adopt") || $0.hasPrefix("recheckFit") }, "q, \(label): nothing chosen: \(recorder.all)") } } @@ -1857,9 +1851,9 @@ import Darwin let run = TerminalRun(operations(Recorder(), pairEvents: [], pairResult: .failed([]), localNetwork: refusedThenAllowed(2), remote: true, commandApp: "sshd-keygen-wrapper")) expect(run.waitFor(" " + ClusterOnboardingDriver.approvalsLine(remote: true) + "\n"), "SSH: the approvals, where each is answered") - expect(run.waitFor(" macOS asks on this Mac's own screen (use Screen Sharing if it has no display) to let sshd-keygen-wrapper find devices on your local network: click Allow.\n"), + expect(run.waitFor(" Click Allow on the Local Network prompt for sshd-keygen-wrapper on this Mac's screen (Screen Sharing if headless).\n"), "SSH: the prompt is on the Mac's screen, and the program macOS names") - expect(run.waitFor(" \u{2713} Local network allowed for sshd-keygen-wrapper.\n"), "SSH: allowed") + expect(run.waitFor("for sshd-keygen-wrapper on this Mac's screen (Screen Sharing if headless).\n \u{2713} Allowed\n"), "SSH: allowed") _ = run.finish() } @@ -1872,7 +1866,7 @@ import Darwin expect(run.finish(seconds: 30) == 0, "unknown: the member's setup ends") expect(run.text.contains(" " + ClusterOnboardingDriver.localNetworkMaybeLine("Darkbloom") + " " + ClusterOnboardingDriver.otherMacAllowLine + "\n"), "unknown: the prompt's line as an if: \(run.text)") - expect(run.text.contains("Done on this Mac."), "unknown: nothing to wait for") + expect(run.text.contains(ClusterOnboardingDriver.joinedLine), "unknown: nothing to wait for") } /// The leader reads both Macs once paired; the other Mac's service may still wait for its Allow: a list to try @@ -1882,7 +1876,7 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), reachFailures: 1)) expect(run.waitFor("The other Mac did not answer over the cable.\n"), "try again: what happened") - expect(run.waitFor("1) Try again\n 2) Stop here\n"), "try again: the list") + expect(run.waitFor("1) Try again\n 2) Cancel\n"), "try again: the list") run.type("\r") expect(run.waitFor(prompt(2), count: 2), "try again: then the model list") run.type("\r") @@ -1890,8 +1884,8 @@ import Darwin expect(recorder.all.filter { $0 == "reachMembers" }.count == 2, "try again: read twice: \(recorder.all)") } - /// The setup's last word says how the pair serves: through Darkbloom (it earns), or locally (its notice says it). - /// The chosen model's public-traffic line is said at the choice. + /// The serving line says how the pair serves: earning through Darkbloom, or local only. Only a private image + /// candidate says at the choice that it takes no public traffic (2026-11-03: less is better). static func startSaysHowThePairServes() { let qualified = [ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers"], blocker: nil, publicTraffic: "qualified for public traffic in pipeline mode", validated: true)] @@ -1901,21 +1895,23 @@ import Darwin expect(run.waitFor(prompt(1)), "serves: the list"); run.type("\r") expect(run.finish() == 0, "serves: exit 0") let text = run.text - expect(text.contains(" Qualified for public traffic in pipeline mode.\n"), "serves: the public-traffic line at the choice: \(text)") - expect(text.contains("\n" + ClusterOnboardingDriver.earnsLine + "\n"), "serves: through Darkbloom, said at the end") + expect(!text.contains("public traffic in pipeline mode"), "serves: no public-traffic line at the choice: \(text)") + expect(text.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom)\n"), + "serves: through Darkbloom, on the serving line: \(text)") let local = TerminalRun(operations(Recorder(), resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: qualified, readyResult: .success(localReady)), request: localRequest) expect(local.waitFor(prompt(1)), "serves locally: the list"); local.type("\r") expect(local.finish() == 0, "serves locally: exit 0") - expect(!local.text.contains("public traffic in pipeline mode") && !local.text.contains(ClusterOnboardingDriver.earnsLine), - "serves locally: neither line; the notice says how it serves: \(local.text)") + expect(!local.text.contains("public traffic in pipeline mode") && !local.text.contains("earning"), + "serves locally: no public-traffic line, no earning: \(local.text)") + expect(local.text.contains("(local only)\n"), "serves locally: said on the serving line: \(local.text)") } /// The list's keys on a colour UTF-8 terminal. static let arrowHint = "\u{2191}\u{2193} move \u{00B7} enter select \u{00B7} q cancel" /// A plain transcript's choice prompt (enter takes the first option). - static func prompt(_ count: Int) -> String { "Choose 1-\(count) (enter = 1): " } + static func prompt(_ count: Int) -> String { "Choose 1-\(count): " } /// The leader's pairing: nobody waits on the cable, the other Mac joins, both confirm the code. static let leaderEvents: [ClusterOnboardingPairEvent] = [.searching, .waitingAsLeader, .connected, @@ -1931,14 +1927,13 @@ import Darwin pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), outlivesWindow: false)) expect(joined.waitFor(codeQuestion), "dev member: the code question"); joined.type("y") expect(joined.finish() == 0, "dev member: exit 0") - expect(joined.text.contains("Done on this Mac. " + ClusterOnboardingDriver.keepWindowLine + "\n"), "dev member: keep the window open") + expect(joined.text.contains(ClusterOnboardingDriver.joinedLine + " " + ClusterOnboardingDriver.keepWindowLine + "\n"), "dev member: keep the window open") let leader = Recorder() let led = TerminalRun(operations(leader, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), outlivesWindow: false)) expect(led.waitFor(prompt(2)), "dev leader: the list"); led.type("\r") expect(led.finish() == 0, "dev leader: exit 0") - expect(led.text.contains("Done. Keep this window and the other Mac's open: these Macs serve only while they stay open.\n"), - "dev leader: keep both windows open") + expect(led.text.contains("Done. Keep both windows open.\n"), "dev leader: keep both windows open") } /// The code's list ends by itself when the pairing does meanwhile (the other Mac declined): no answer is waited for. @@ -1948,7 +1943,7 @@ import Darwin pairResult: .failed(["The other Mac declined the code."]))) expect(run.waitFor(codeQuestion), "ended: the code shown") expect(run.finish(seconds: 15) == 1, "ended: exit 1 with no key") - expect(run.text.contains("The other Mac declined the code.") && run.text.contains("Run `darkbloom cluster` again to try again."), + expect(run.text.contains("The other Mac declined the code.") && run.text.contains("Run `darkbloom cluster` again.\n"), "ended: the pairing's own reason") expect(run.keys == 0, "ended: no key typed") } @@ -1959,8 +1954,7 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, pairEvents: memberEvents, pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), linkScript: "~/.darkbloom/cluster-device/link-fix.sh")) - expect(run.waitFor(" macOS could not show its password window here. Type this Mac's password for sudo to set up the cable's port:\n"), - "sudo: said before sudo asks") + expect(run.waitFor(" Type this Mac's password to set up the cable port.\n"), "sudo: said before sudo asks") expect(run.waitFor(codeQuestion), "sudo: then the cable is ready and pairing goes on"); run.type("y") expect(run.finish() == 0, "sudo: member done") expect(recorder.all.prefix(3) == ["checkLink", "runAsAdministrator", "checkLink"], "sudo: the script, then the cable again: \(recorder.all)") @@ -1971,8 +1965,8 @@ import Darwin let refused = TerminalRun(operations(failed, pairEvents: [], pairResult: .failed([]), linkScript: "~/.darkbloom/cluster-device/link-fix.sh", sudoSucceeds: false)) expect(refused.finish() == 1, "sudo failed: stops") - expect(refused.text.contains("The cable's port was not set up. Run `darkbloom cluster` again, or run: sudo sh ~/.darkbloom/cluster-device/link-fix.sh\n"), - "sudo failed: what to do, the script last") + expect(refused.text.hasSuffix("Cable port not set up. Run `darkbloom cluster` again.\n") && !refused.text.contains("link-fix.sh"), + "sudo failed: what to do, no script to run by hand") expect(!failed.all.contains("pair"), "sudo failed: no pairing") } @@ -1982,21 +1976,21 @@ import Darwin let recorder = Recorder() let run = TerminalRun(operations(recorder, pairEvents: memberEvents, pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), localNetwork: refusedThenAllowed(2, [.thisCommand, .service]))) - expect(run.waitFor(" macOS asks to let Terminal find devices on your local network: click Allow.\n"), "local network: this command's prompt, in Connect") - expect(run.waitFor(" \u{2713} Local network allowed for Terminal.\n"), "local network: allowed, then pairing") + expect(run.waitFor(" Click Allow on the Local Network prompt for Terminal.\n"), "local network: this command's prompt, in Connect") + expect(run.waitFor("prompt for Terminal.\n \u{2713} Allowed\n"), "local network: allowed, then pairing") expect(run.waitFor(codeQuestion), "local network: the code"); run.type("y") - expect(run.waitFor(" macOS asks to let Darkbloom find devices on your local network: click Allow. " + ClusterOnboardingDriver.otherMacAllowLine + "\n"), + expect(run.waitFor(" Click Allow on the Local Network prompt for Darkbloom. " + ClusterOnboardingDriver.otherMacAllowLine + "\n"), "local network: Darkbloom's, once paired, the other Mac's said too") expect(run.finish(seconds: 20) == 0, "local network: member done") let text = run.text - let order = ["1 / 4 Connect", "click Allow.", "Local network allowed for Terminal.", "2 / 4 Pair", "Paired with", "Darkbloom find devices", - "Local network allowed for Darkbloom.", "Done on this Mac."].compactMap { text.range(of: $0)?.lowerBound } - expect(order.count == 8 && order == order.sorted(), "local network: asked in order, each before the next step: \(text)") + let order = ["1/4 Connect", "prompt for Terminal.\n \u{2713} Allowed", "2/4 Pair", "Paired.", + "the other Mac too.\n \u{2713} Allowed", "Done here"].compactMap { text.range(of: $0)?.lowerBound } + expect(order.count == 6 && order == order.sorted(), "local network: asked in order, each before the next step: \(text)") transcript("member-local-network-prompts", text, keys: run.keys) // Refused and left so: q stops with where to turn it on. let blocked = TerminalRun(operations(Recorder(), pairEvents: [], pairResult: .failed([]), localNetwork: { _ in .blocked })) - expect(blocked.waitFor("click Allow."), "refused: the prompt line") + expect(blocked.waitFor("Click Allow"), "refused: the prompt line") blocked.type("q") expect(blocked.finish() == 1, "refused: stops") expect(blocked.text.hasSuffix("Turn it on in System Settings → Privacy & Security → Local Network, then run `darkbloom cluster` again.\n"), @@ -2022,10 +2016,10 @@ import Darwin run.type("\u{1B}[B") expect(run.waitFor("\u{25B8}\u{1B}[0m \u{1B}[1mChange model", seconds: 5), "arrows: ↓ moves the ▸ to the second item") run.type("\u{1B}[B") - expect(run.waitFor("\u{25B8}\u{1B}[0m \u{1B}[1mServe locally only", seconds: 5), "arrows: and to the third") + expect(run.waitFor("\u{25B8}\u{1B}[0m \u{1B}[1mServe locally", seconds: 5), "arrows: and to the third") run.type("\r") expect(run.finish() == 0, "arrows: exit 0") - expect(visible(run.text).contains(" \u{25B8} Serve locally only (no coordinator)"), "arrows: the list folds to the item taken") + expect(visible(run.text).contains(" \u{25B8} Serve locally"), "arrows: the list folds to the item taken") expect(recorder.all == ["ensureService", "status", "setScope local 0.0.0.0", "waitReady"], "arrows: the third item ran: \(recorder.all)") transcript("leader-again-arrows", run.text, keys: run.keys) } @@ -2046,7 +2040,7 @@ import Darwin choices: mixed)) expect(run.waitFor(prompt(2)), "approved: the list of two") let text = run.text - expect(text.contains(" 1) Z.ai: GLM-5.3-Flash — 181.8 GB · tensor parallel\n 2) Qwen3.8 27B — 16.3 GB · tensor parallel\n"), + expect(text.contains(" 1) Z.ai: GLM-5.3-Flash · 181.8 GB\n 2) Qwen3.8 27B · 16.3 GB\n"), "approved: only the approved models: \(text)") expect(!text.contains("Qwen 3.5 9B") && !text.contains("Gemma"), "approved: nothing else, not even as not offered") run.type("2") @@ -2063,7 +2057,7 @@ import Darwin let none = TerminalRun(operations(Recorder(), resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: [mixed[0], mixed[3]])) expect(none.finish() == 1, "approved: none approved stops") - expect(none.text.contains("No model approved for clusters can run on these two Macs now.\n"), "approved: said") + expect(none.text.contains("No approved model can run on these Macs now.\n"), "approved: said") expect(!none.text.contains("Qwen 3.5 9B"), "approved: an unapproved model is not named among the reasons") } @@ -2076,19 +2070,15 @@ import Darwin expect(D.shownName(nil) == nil && D.shownName(" ") == nil, "names: none given") expect(D.shownName("Studio\u{1B}[2J") == nil, "names: a control character is never said") expect(D.shownName(String(repeating: "x", count: 41)) == nil, "names: at most 40 characters") - expect(D.leaderSubtitle(named: "Studio A") == "This Mac (Studio A) leads the cluster", "names: the leader's opening") + expect(D.leaderSubtitle(named: "Studio A") == "This Mac (Studio A) leads", "names: the leader's opening") expect(D.leaderSubtitle(named: nil) == D.leaderSubtitle, "names: unknown, unchanged") - expect(D.followerSubtitle(memberResume(), named: "Studio B") == "This Mac (Studio B) follows the other Mac (Apple M3 Ultra, 256 GB)", - "names: the member's opening") - var waits = ClusterOnboardingPairing(named: "Studio A") - expect(waits.handle(.waitingAsLeader).first == "This Mac (Studio A) leads. It waits up to 10 minutes for the other Mac (q cancels).", - "names: the first Mac's wait") + expect(D.followerSubtitle(named: "Studio B") == "This Mac (Studio B) follows the other Mac", "names: the member's opening") var leads = ClusterOnboardingPairing() expect(leads.finished(.paired(role: .leader, peerName: "Apple M5 Ultra, 256 GB"), named: "Studio A").last - == "\u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). This Mac (Studio A) leads.", "names: the leader's paired line") + == "\u{2713} Paired. This Mac (Studio A) leads.", "names: the leader's paired line") var follows = ClusterOnboardingPairing() expect(follows.finished(.paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), named: "Studio B").last - == "\u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). It leads; this Mac (Studio B) follows it.", "names: the member's paired line") + == "\u{2713} Paired. The other Mac leads.", "names: the member's paired line") let mac = "Apple M5 Ultra, 256 GB" let paired = TerminalRun(operations(Recorder(), pairEvents: [.searching, .waitingAsLeader, .connected, .code("123456", peer: [mac]), @@ -2098,14 +2088,12 @@ import Darwin expect(paired.waitFor(codeQuestion), "names: the code question"); paired.type("y") expect(paired.waitFor(prompt(2), count: 2), "names: the model list"); paired.type("\r") expect(paired.finish() == 0, "names: served") - expect(paired.text.contains(" \u{2713} Paired with the other Mac (Apple M5 Ultra, 256 GB). This Mac (Studio A) leads.\n"), + expect(paired.text.contains(" \u{2713} Paired. This Mac (Studio A) leads.\n"), "names: identical Macs, this one named where it says it leads") - expect(paired.text.contains(" This Mac (Studio A) leads. It waits up to 10 minutes for the other Mac (q cancels).\n"), - "names: identical Macs, this one named where it starts waiting") for (label, resume, name, opening) in [ ("leader", ClusterOnboardingResume(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), - "Studio A", "This Mac (Studio A) leads the cluster"), - ("member", memberResume(), "Studio B", "This Mac (Studio B) follows the other Mac (Apple M3 Ultra, 256 GB)"), + "Studio A", "This Mac (Studio A) leads"), + ("member", memberResume(), "Studio B", "This Mac (Studio B) follows the other Mac"), ("unsayable", ClusterOnboardingResume(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp"), "Studio\u{07}", D.leaderSubtitle)] { let run = TerminalRun(operations(Recorder(), resume: resume, pairEvents: [], pairResult: .failed([]), thisMacName: name)) @@ -2130,18 +2118,17 @@ import Darwin let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: before, replanned: after)) expect(run.waitFor(prompt(1)), "from the other Mac: offered"); run.type("\r") - expect(run.waitFor(" Qwen3.8 27B is not on this Mac yet:\n"), "from the other Mac: said") - expect(run.waitFor(" 1) Copy it from the other Mac over the Thunderbolt cable (about 7 s)\n 2) Stop here\n"), - "from the other Mac: a copy, with its time: \(run.text)") - expect(!run.text.contains("download"), "from the other Mac: no download is mentioned") + expect(run.text.contains(" 1) Qwen3.8 27B · 16.3 GB · copy\n"), "from the other Mac: its line says a copy") + expect(run.waitFor(" 1) Copy from the other Mac (about 7 s)\n 2) Cancel\n"), "from the other Mac: a copy, with its time: \(run.text)") + expect(!run.text.lowercased().contains("download"), "from the other Mac: no download is mentioned") run.type("\r") expect(run.finish() == 0, "from the other Mac: served") expect(recorder.all.contains("provision 0 copy") && recorder.all.filter { $0 == "planModels" }.count == 2, "from the other Mac: copied, then planned here: \(recorder.all)") } - /// A model that does not fit now says so once at the end of its line: a tensor-parallel note that only says the - /// same is left out, any other note stays. + /// A model that does not fit now says so once, at the end of its line (the planner's tensor-parallel note, which + /// may say the same, is not said at all). static func modelThatDoesNotFitSaysSoOnce() { typealias C = ClusterOnboardingModelChoice let choices = [ @@ -2154,9 +2141,9 @@ import Darwin choices: choices)) expect(run.waitFor(prompt(3)), "fit: the list") let text = run.text - expect(text.contains(" 2) Z.ai: GLM-5.3-Flash — 181.8 GB · pipeline · does not fit now\n"), "fit: said once: \(text)") - expect(!text.contains("does not fit now · does not fit now") && !text.contains("tensor parallel: does not fit now"), "fit: never twice") - expect(text.contains(" 3) Gemma 4 31B — 58.2 GB · pipeline · tensor parallel: slower here · does not fit now\n"), "fit: another note stays") + expect(text.contains(" 1) Qwen3.8 27B · 16.3 GB\n 2) Z.ai: GLM-5.3-Flash · 181.8 GB · does not fit now\n" + + " 3) Gemma 4 31B · 58.2 GB · does not fit now\n"), "fit: said once on each line that does not fit: \(text)") + expect(!text.contains("does not fit now · does not fit now") && !text.contains("tensor parallel:"), "fit: never twice, no notes") run.type("1") expect(run.finish() == 0, "fit: the model that fits is served") } From 0215eed7a42812802dcafaf99fc3f0f169f7c2bf Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:11:04 -0800 Subject: [PATCH 0206/1441] docs(cluster): quote the shorter setup screens Every quote of the guided setup in two-mac-cluster.md and inference.md now matches the cut screens (29c84b6fbc): the step names, the Yes/No answer, the approvals and Local Network lines, both Macs' end lines, the six menu items, the serving and status lines and the setup table's rows 1-5. The model list no longer carries tensor-parallel notes; the setup table's row 4 points to `darkbloom cluster plan`, which still prints the planner's reasons (its examples, including "tensor parallel: not measured yet", are kept). The changelog fragment is shortened to match. Tested: docs-check 205 OK, docs-impact against origin/dev OK, changelog-check 17 valid; trial merges with every other open PR touching these files lose no PR line. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-onboarding-simple.md | 24 ++-- docs/architecture/inference.md | 40 +++--- docs/provider/two-mac-cluster.md | 165 ++++++++++++----------- 3 files changed, 117 insertions(+), 112 deletions(-) diff --git a/changelog.d/cluster-onboarding-simple.md b/changelog.d/cluster-onboarding-simple.md index 0a671f73bb..bc60a89691 100644 --- a/changelog.d/cluster-onboarding-simple.md +++ b/changelog.d/cluster-onboarding-simple.md @@ -1,18 +1,14 @@ ### Simpler two-Mac cluster setup -- `darkbloom cluster` setup is shorter: four steps (Connect, Pair, Choose a model, Start), one line for each thing that - happened, and the next thing to do as each screen's last line. Every choice, a short model copy included, is a list - moved with ↑↓ and taken with enter, as `darkbloom start` picks models (numbered in plain transcripts); q or Esc - cancels, and no prompt asks for a key to do something. +- `darkbloom cluster` setup says far less: four steps (Connect, Pair, Model, Start), a line per thing that happened, + and the next thing to do last. Every choice is a list (↑↓ and enter, as `darkbloom start` picks models; numbered in + plain transcripts); q or Esc cancels. - The model list shows only the models approved for clusters (GLM-5.3-Flash and Qwen3.8 27B) that the two Macs can - serve; a named model that is not approved is refused. -- The Mac you set up on leads and keeps leading: every plan puts rank 0 (the API and the coordinator's registration) - on it, the cluster service's own re-plans included, so a pair set up with 0.10.6 whose other Mac took over leading - moves back at its next plan. -- Connect names the macOS approvals each Mac asks for: the cable's port (with sudo in the terminal over SSH, instead of - a script to run by hand) and Darkbloom's Local Network access, which both Macs ask right after pairing; the setup - waits until Allow or q. -- Both Macs confirm the pairing code. The Mac that follows shows the status and where to manage the cluster; both Macs - say whether their window can close, and a pair served through Darkbloom says it earns for the public requests it - serves. + serve, each with its size. +- The Mac you set up on leads and keeps leading: every plan puts rank 0 on it, the cluster service's own re-plans + included, so a pair set up with 0.10.6 whose other Mac took over leading moves back at its next plan. +- macOS's password and Local Network prompts come at stated moments (sudo in the terminal over SSH); both Macs ask + about Darkbloom's Local Network access right after pairing, and the setup waits until Allow or q. +- Both Macs confirm the pairing code; the Mac that follows only shows the status. The serving line says whether the + pair earns through Darkbloom or serves locally only. - `darkbloom doctor` includes the cluster's checks on a Mac paired for a cluster. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index f3cb485cdf..f8dd09817a 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -246,14 +246,17 @@ serving intent or change model eligibility and placement. See the [guided two-Mac setup](../provider/two-mac-cluster.md) for operator steps. Lines name the two Macs for the screen that shows them -(`ClusterOnboardingMacName`): "this Mac" and "the other Mac ()", -because two Macs of one kind share the hardware name. The leader words an +(`ClusterOnboardingMacName`): "this Mac" and "the other Mac", with the hardware +name ("the other Mac ()") where a line must tell them apart, +because two Macs of one kind share it; only this Mac's own screen adds the name +System Settings gives it ("This Mac (Studio A) leads", +`ClusterOnboardingDriver.thisMac`). The leader words an answer to a command the other Mac forwarded for that Mac's screen (`OnboardingLive.answeringForwarded`, `here`, `there`), and the cluster service names members the same way in its control lines and refusals -(`ClusterOnboardingMacName.names`). A deployment line recorded for both Macs -keeps hardware names; lines shown now carry the screen's words -(`ClusterOnboardingDeployment.Share.label`). The Mac that joins ends its +(`ClusterOnboardingMacName.names`). The deployment line, recorded for both Macs +with hardware names, is no longer on the screens, which say one serving line +(`ClusterOnboardingReady.summary`, `ClusterOnboardingDriver.servesWords`). The Mac that joins ends its onboarding once paired, also for `darkbloom cluster local` (`ClusterOnboardingDriver.joinedLocalContinueLine`). The model list keeps one line per artifact and name (`OnboardingLive.presentedChoices`): a choice that cannot be @@ -275,14 +278,16 @@ such field and are listed as they come. A member's `darkbloom cluster` shows the status and where to manage the cluster, with a list only to set up a cable port that is not set up yet (`ClusterOnboardingDriver.member`, `fixPortItem`); the leader's is a list of the control operations (`ClusterOnboardingDriver.menu`). -Every copy of a missing model is a list as well, a short one with its -predicted time (`ClusterOnboardingDriver.provision`). Served through Darkbloom, -the chosen model's public-traffic line follows the choice -(`ClusterOnboardingModelChoice.publicTraffic`), and the start ends with -`ClusterOnboardingDriver.earnsLine`, except for a private image candidate and -where the pair serves locally, which a notice under the API line already says -(`servesLine`). When the other Mac does not answer over the -cable, the leader asks **Try again** or **Stop here** (`chooseAndServe`). +A model's list line is its name and size, then "copy" or "download" when it +must reach a Mac first (`ClusterOnboardingModelChoice.listLine`); its split, +speed and tensor-parallel note are planned and carried but not said. Every copy +of a missing model is a list as well, a short one with its predicted time +(`ClusterOnboardingDriver.provision`). The public-traffic line +(`ClusterOnboardingModelChoice.publicTraffic`) is said only for a private image +candidate; the serving line ends "(earning through Darkbloom)" or "(local +only)" (`ClusterOnboardingDriver.servesWords`). When the other Mac does not +answer over the cable, the leader asks **Try again** or **Cancel** +(`chooseAndServe`). The Mac the cluster was set up on leads. `LiveContext.plan` makes that Mac every plan's rank 0, whichever Mac plans (`ClusterControlDerivation.planLeader`, from @@ -297,8 +302,9 @@ prefers it among the members present (`ClusterControlDerivation.derive`, pin). A Mac that is away never leads, so failover is unchanged. macOS's permissions are asked at stated moments -(`ClusterOnboardingDriver.allowLocalNetwork`), and Connect's first line names -them (`ClusterOnboardingDriver.approvalsLine`). The command probes Local Network +(`ClusterOnboardingDriver.allowLocalNetwork`), and Connect's first line asks for +both ("Allow macOS's password and Local Network prompts.", +`ClusterOnboardingDriver.approvalsLine`). The command probes Local Network access in the Connect step (`ClusterLocalNetworkAccess.probe`: one datagram to the cable's subnet broadcast, refused with `EHOSTUNREACH` until allowed). macOS lets a command run from a terminal or over SSH through by itself (TN3179), so @@ -3775,8 +3781,8 @@ pair's own fresh, keyed, owner-only link record, and without one it keeps the running setup. The planner's own default, and the plan tool without `--tensor-parallel-first`, keep the speed comparison. -The setup's model list (`ClusterOnboardingModelChoice.listLine`) ends a model's -one line with a short note when its layout has a tensor-parallel plan and the +The planner records a short note, which the setup's model list no longer says +(`ClusterOnboardingModelChoice.listLine`), when a model's layout has a tensor-parallel plan and the planner splits it otherwise, for example `tensor parallel: slower here`, `about as fast` (inside the margin), `does not fit now`, `link unmeasured`, or `no tensor parallel for this model`. The note comes from the planner's own assessment diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 3bdbafa582..b55763396d 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -38,15 +38,15 @@ leader is derived as that Mac (`ClusterControlDerivation.derive`, `preferred`). The other Mac follows; you never go back to it (see [If a Mac goes away](#if-a-mac-goes-away)). -The screen follows four steps: **Connect**, **Pair**, **Choose a model** and +The screen follows four steps: **Connect**, **Pair**, **Model** and **Start**, one line for each thing that happened. Every choice is a list you move through with ↑ and ↓ and take with enter, as `darkbloom start` picks models: the answer to the pairing code, the model, how a missing model gets onto the Macs and, later, what to do with a running cluster. Where the screen has no color (`NO_COLOR`, `TERM=dumb`, a pipe), the same list is numbered and one key answers it: a number, enter for the first line, or a letter only one -line starts with (`y` for "Yes, pair"). q or Esc cancels any list, so q never -picks a line such as "Qwen3.8 27B". While the setup waits (for the other Mac, +line starts with (`y` for "Yes"). q or Esc cancels any list, so q never +picks a line such as "Qwen3.8-27B-4bit-mtp · 16.3 GB". While the setup waits (for the other Mac, for Allow), q or Esc stops it and an arrow key does nothing; no prompt asks for a key to do something. The model list shows only models approved for clusters (`ClusterPublicModels.declared`: GLM-5.3-Flash and @@ -54,9 +54,8 @@ Qwen3.8 27B) that these two Macs can serve; any other model is left out, and a model named on the command line that is not approved is refused. Each Mac asks for up to two macOS approvals, at stated moments while you are at -that Mac, and Connect's first line names them ("Up to two macOS approvals on -this Mac: the cable's port (now) and Local Network for Darkbloom (once -paired)."). Each prompt's line says what to click: +that Mac, and Connect's first line says so ("Allow macOS's password and Local +Network prompts."). Each prompt's line says what to click: - **Connect:** the cable's port, once per Mac (your password). macOS lets a command run from a terminal or over SSH onto the local network by itself @@ -67,29 +66,33 @@ paired)."). Each prompt's line says what to click: - **Right after pairing:** Local Network access for Darkbloom, which this Mac's cluster service (a launchd agent, which macOS does ask about) asks for as it starts (`ClusterLocalNetworkAccess.startServiceProbe`). Pairing ends on both - Macs at once, so both ask at the same moment: "macOS asks to let Darkbloom - find devices on your local network: click Allow. The other Mac may ask too: - click Allow there as well." The setup waits until Allow, however long you + Macs at once, so both ask at the same moment: "Click Allow on the Local + Network prompt for Darkbloom. Allow it on the other Mac too." The setup + waits until Allow ("✓ Allowed"), however long you take at the other Mac, or until q; after 15 s it also names the switch in System Settings → Privacy & Security → Local Network. A cluster service that reports no probe within 10 s (an older build) gets the line as an "if", and the setup goes on. When macOS cannot show its password window (an SSH session with no desktop), -the setup runs the same commands with `sudo` in that terminal: you type this -Mac's password into sudo, not into Darkbloom, and the setup goes on. Only when -sudo fails does it name the script to run yourself. Over SSH, Darkbloom's Local +the setup runs the same commands with `sudo` in that terminal ("Type this Mac's +password to set up the cable port."): you type this Mac's password into sudo, +not into Darkbloom, and the setup goes on; if sudo fails, it says "Cable port +not set up. Run `darkbloom cluster` again." Over SSH, Darkbloom's Local Network prompt still appears on the Mac's own screen, and its line says so -("use Screen Sharing if it has no display"). - -The Mac that joins ends once paired: it says it follows the other Mac, whether -its window can close (a signed Darkbloom.app's login agent keeps serving; -without one, as for a development build, the Mac serves only while the window -stays open), and, last, to continue on the other -Mac (with `darkbloom cluster local` when it was started that way). The leader -ends the same way: what serves (served through Darkbloom, "Serving through -Darkbloom: the pair earns for the public requests it serves."), whether the -windows can close, and, last, the command to manage it. +("on this Mac's screen (Screen Sharing if headless)"). + +The Mac that joins ends once paired ("✓ Paired. The other Mac leads.") with one +line: what comes next and whether its window can close ("Done here: the other +Mac chooses the model. You can close this window."; started with +`darkbloom cluster local`, "Done here: run `darkbloom cluster local` on the +other Mac."). A signed Darkbloom.app's login agent keeps serving; without one, +as for a development build, the line ends "Keep this window open." and the Mac +serves only while the window stays open. The leader ends with what serves and +how ("✓ Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through +Darkbloom)", or "(local only)"), the test ("✓ Test response in 0.61 s"), +whether the windows can close ("Done. You can close both windows.") and, last, +"Run `darkbloom cluster` again to manage it." On a color terminal with a UTF-8 locale and at least 40 columns, setup opens with the Darkbloom mark, which blooms in pixel by pixel. Each step's heading @@ -107,15 +110,15 @@ names `darkbloom local`, which shows it. Setup reports completion only after the test response succeeds. If that request fails, the saved setup remains available: run `darkbloom cluster` on the leader, -check its status, and choose **Test a response** to try again. - -`darkbloom cluster` run again shows the cluster's status and, on the leader, a -list: **Test a response**, **Change model** (**Choose a model and serve** when -stopped), **Serve locally only** or **Serve through Darkbloom**, **Stop -serving**, **Check both Macs released their memory** and **Quit**, with **Set -up the cable's port** first when the cable moved to a port not set up yet. On -the other Mac it shows the status and where to manage the cluster: its part -runs by itself, and setting up such a port is the only choice it offers +check its status, and choose **Test** to try again. + +`darkbloom cluster` run again shows the cluster's status in one line and, on +the leader, a list: **Test**, **Change model** (**Choose a model** when +stopped), **Serve locally** or **Serve through Darkbloom**, **Stop**, **Check +memory is freed** and **Quit**, with **Set up the cable port** first when the +cable moved to a port not set up yet. On the other Mac it shows the status and +"Nothing to do here: manage it on the other Mac (`darkbloom cluster`).": its +part runs by itself, and setting up such a port is the only choice it offers ([below](#when-something-is-in-the-way)). The planner picks tensor parallel or pipeline for your Macs by itself. Phase @@ -123,8 +126,8 @@ split is off. A model whose artifact ships a speculative (MTP) head can also decode as speculative rounds across the pipeline, and does by default where its own cross-cable qualification records passed and measured the rounds faster than the plain pipeline of the same placement (this build: Qwen3.8 27B, Qwen3.5 -9B and MiMo V2.6 Flash). The onboarding then says "pipeline with speculative -decoding". A draft is kept only when it is the model's own choice at that +9B and MiMo V2.6 Flash). The plan (`darkbloom cluster plan`) then names the mode +"pipeline with speculative decoding". A draft is kept only when it is the model's own choice at that position, as the verify window computes it; the window's arithmetic differs in its last bits from one-token decode, so, as with the pipeline itself, output matches a single Mac's up to near ties. Your pair's own measured speed-up @@ -152,7 +155,7 @@ coordinator never carries it. So, with the default `[backend] mtp_mode` of With `mtp_mode = "on"`, `darkbloom cluster` keeps the assistant too. That pair is then not offered to the coordinator: its plan says "not offered for public traffic", and it serves on the leader's local API. A serving cluster switched -with **Serve locally only** or **Serve through Darkbloom** keeps the setup it +with **Serve locally** or **Serve through Darkbloom** keeps the setup it has; choose **Change model** to plan the model again for the new way of serving. Public speculative decoding for Qwen pairs needs qualification evidence of its own, which no record holds yet. Rules: [Qwen27 TP assistant policy](../reference/configuration.md#qwen27-tp-assistant-policy). @@ -169,32 +172,33 @@ format instruction only, as on one Mac | # | Where | What you do | What it asks | |---|---|---|---| -| 1 | the first Mac | Run `darkbloom cluster`. Its first line names the approvals this Mac may ask for. It checks the Thunderbolt cable ("Cable found.", "Cable ready.") and Local Network access. Nobody waits on the cable yet, so this Mac leads; its last line is **"Now run `darkbloom cluster` on the other Mac."**, and it waits (q cancels). With two cables it asks which one to use. | the cable's port, once (your password; sudo in this terminal where macOS shows no window); Local Network access for the terminal app only where macOS blocks it | -| 2 | the other Mac | Run `darkbloom cluster`. The same checks; then it finds the waiting Mac on the cable by itself (no address, no host name). Both screens show the same six-digit code and "Does the other Mac show the same code? Answer on both Macs."; a Mac that answered first says "Now choose “Yes, pair” on the other Mac too." | the same as the first Mac; **Yes, pair** on each Mac when the codes match | -| 3 | both Macs | Each says it is paired; the other Mac: **"Paired with the other Mac (). It leads; this Mac follows it."** Both cluster services now run, and macOS asks on both Macs at the same moment to let Darkbloom find devices on your local network: click Allow on each; each screen waits for its own. Nothing else is ever asked on the other Mac; its last line says to continue on the other Mac (with `darkbloom cluster local` when it was started that way). | Local Network access for Darkbloom, once on each Mac | -| 4 | the leader | It shows both Macs in one line ("This Mac: … · the other Mac: …") and every model approved for clusters that the pair can serve (held by both Macs, by one of them, or in Darkbloom's catalog), one line each: size, how it is split, each Mac's share ("this Mac 50% / the other Mac 50%") and the expected speed. A model a Mac holds twice (a catalog download beside the cluster's own copy) is listed once. A model that has tensor parallel but is split otherwise says why at the end of its line (for example "tensor parallel: slower here", "tensor parallel: not measured yet" or "tensor parallel: link unmeasured"). Models that fit in the Macs' free memory now come first; one that does not ends with "does not fit now". Choose the model with ↑↓ and enter (enter takes the first). Served through Darkbloom, a line under the choice says whether public traffic may reach the model ("Not yet qualified for public traffic."). A model the other Mac lacks says how it gets there ("copy ... over the Thunderbolt cable (6.1 GB)"). If the other Mac does not answer over the cable (its Darkbloom prompt may still wait for Allow), it offers **Try again** or **Stop here**. | the copy first in a list; a short one says its time ("Copy it over the Thunderbolt cable (about 7 s)") | -| 5 | — | Choosing is starting: the leader saves the setup, sends it to the other Mac over the cable, starts both Macs, waits until both are loaded and answers one test request, each said in one line. Served through Darkbloom, it ends with "Serving through Darkbloom: the pair earns for the public requests it serves." | nothing | +| 1 | the first Mac | Run `darkbloom cluster`. Its first line is "Allow macOS's password and Local Network prompts." It checks the Thunderbolt cable ("✓ Cable ready") and Local Network access. Nobody waits on the cable yet, so this Mac leads; its last line is **"Run `darkbloom cluster` on the other Mac."**, and it waits (q cancels). With two cables it asks "Which cable goes to the other Mac?" | the cable's port, once (your password; sudo in this terminal where macOS shows no window); Local Network access for the terminal app only where macOS blocks it | +| 2 | the other Mac | Run `darkbloom cluster`. The same checks; then it finds the waiting Mac on the cable by itself (no address, no host name). Both screens show the same six-digit code ("Code 123 456. Same on the other Mac?"); a Mac that answered first says "Now confirm on the other Mac." | the same as the first Mac; **Yes** on each Mac when the codes match | +| 3 | both Macs | Each says it is paired ("✓ Paired. This Mac leads." on the leader, "✓ Paired. The other Mac leads." on the other Mac). Both cluster services now run, and macOS asks on both Macs at the same moment to let Darkbloom find devices on your local network: click Allow on each; each screen waits for its own ("✓ Allowed"). Nothing else is ever asked on the other Mac; its last line is "Done here: the other Mac chooses the model. You can close this window." | Local Network access for Darkbloom, once on each Mac | +| 4 | the leader | It lists every model approved for clusters that the pair can serve (held by both Macs, by one of them, or in Darkbloom's catalog), one line each with its size ("Qwen3.8-27B-4bit-mtp · 16.3 GB"), ending "copy" or "download" when the model must reach a Mac first. A model a Mac holds twice (a catalog download beside the cluster's own copy) is listed once. The planner records why a model that has tensor parallel is split otherwise (for example "tensor parallel: slower here", "tensor parallel: not measured yet" or "tensor parallel: link unmeasured"); `darkbloom cluster plan` gives the full reason under "Tensor parallel or pipeline". Models that fit in the Macs' free memory now come first; one that does not ends with "does not fit now". Choose the model with ↑↓ and enter (enter takes the first). If the other Mac does not answer over the cable (its Darkbloom prompt may still wait for Allow), it offers **Try again** or **Cancel**. | the copy first in a list; a short one says its time ("Copy to the other Mac (about 7 s)") | +| 5 | — | Choosing is starting: the leader saves the setup, sends it to the other Mac over the cable and starts both Macs; once both are loaded it says where the pair serves ("✓ Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom)", or "(local only)") and answers one test request ("✓ Test response in 0.61 s"). | nothing | -When it serves, the screen says how in one line, for example: +When it serves, the screen says where in one line, for example: ``` -Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers. -API at http://localhost:8000 on this Mac. +✓ Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom) ``` Every screen names the Macs from where it is shown: "this Mac" is the Mac the -screen is on and "the other Mac (Apple M3 Ultra, 256 GB)" the other one, by the -hardware name pairing showed (never a host or computer name). Two Macs of one -kind share that name, so it never stands alone. A Mac that does not lead shows -the leader's answers in the same words for its own screen. +screen is on and "the other Mac" the other one. A line that must tell them +apart adds the hardware name pairing showed ("the other Mac (Apple M3 Ultra, +256 GB)"), never its host or computer name; only this Mac's own screen names it +as System Settings does ("This Mac (Studio A) leads"). A Mac that does not lead +shows the leader's answers in the same words for its own screen. When the coordinator in your provider configuration cannot take a cluster member yet (it is unreachable, or it has no cluster support), the pair still serves, on the leader's local API only, with the same local token as -`darkbloom start --local`, and a third line says so: +`darkbloom start --local`, and its serving line ends "(local only)" instead of +"(earning through Darkbloom)". The leader's part logs why: ``` -Serving locally on this Mac's API; public serving needs a coordinator with cluster support. +Notice: Serving locally on this Mac's API; public serving needs a coordinator with cluster support ``` Nothing to do: the next start registers with the coordinator once it supports @@ -230,14 +234,14 @@ A tensor-parallel pair registers like a pipeline one; its plan names no cut. ([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: +2. Read the end of the setup screen. After the test response it says: ``` Registered with the coordinator as a cluster member: approval , until . ``` - There is no local API in this mode. `darkbloom cluster` status shows the - same line. + There is no local API in this mode. `darkbloom cluster` status says it after + the model: `Serving : Registered with the coordinator as a cluster member: approval , until .` An approval ends at its `not_after`, which the operator sets; one derived from a release ends 90 days after that release registered @@ -268,32 +272,33 @@ What `darkbloom cluster` status says in each mode: | Mode | Status line | |---|---| -| Registered | `Registered with the coordinator as a cluster member: approval , until .` | -| Coordinator gave no answer for the grace | The API line, then `The coordinator has not answered for 10 minutes: the pair serves on the leader's local API until it answers again, then it is offered again with approval .` | -| Approval no longer listed | The API line, then `The coordinator no longer lists cluster approval : the pair serves on the leader's local API until it lists a matching one again.` | -| Parts kept ending | The API line, then `The coordinator-paired parts ended 3 times in a row right after starting with cluster approval : the pair serves on the leader's local API for 60 minutes, then it is offered again with it, or sooner with a later one the coordinator lists.` | -| Approval ended | The API line, then one line that says the cluster approval `` expired and the pair serves on the leader's local API | -| No approval (staging, production before its coordinator derives approvals from releases, no matching entry) | The API line, then (only after a refusal) `Not offered for pairing: .` | +| Registered | `Serving : Registered with the coordinator as a cluster member: approval , until .` | +| Coordinator gave no answer for the grace | The serving line, then `The coordinator has not answered for 10 minutes: the pair serves on the leader's local API until it answers again, then it is offered again with approval .` | +| Approval no longer listed | The serving line, then `The coordinator no longer lists cluster approval : the pair serves on the leader's local API until it lists a matching one again.` | +| Parts kept ending | The serving line, then `The coordinator-paired parts ended 3 times in a row right after starting with cluster approval : the pair serves on the leader's local API for 60 minutes, then it is offered again with it, or sooner with a later one the coordinator lists.` | +| Approval ended | The serving line, then one line that says the cluster approval `` expired and the pair serves on the leader's local API | +| No approval (staging, production before its coordinator derives approvals from releases, no matching entry) | The serving line, then (only after a refusal) `Not offered for pairing: .` | Approval sources, checks and saved fields: [coordinator-paired member](../reference/configuration.md#coordinator-paired-member). -Counting every key: enter for **Yes, pair** on each Mac and enter for the first +Counting every key: enter for **Yes** on each Mac and enter for the first model on the leader (three keys), plus the macOS prompts [above](#the-steps-once). Running `darkbloom cluster` again on either Mac opens with the same Darkbloom -mark, beside "Darkbloom cluster" and the part this Mac plays ("This Mac leads -the cluster", or "This Mac follows the other Mac (…)"; with the name System -Settings gives this Mac, "This Mac (Studio A) leads the cluster", so two -identical Macs each say which they are), then shows the -cluster's state (the deployment line first) and, on the leader, the list -[above](#the-steps-once). The other Mac ends with where to manage the cluster -("To test, change the model or stop: run `darkbloom cluster` on the other Mac -(…)."), or, when the cable moved to a port not set up yet, offers to set it up -([below](#when-something-is-in-the-way)). +mark, beside "Darkbloom cluster" and the part this Mac plays ("This Mac leads", +or "This Mac follows the other Mac"; with the name System Settings gives this +Mac, "This Mac (Studio A) leads", so two identical Macs each say which they +are), then shows the cluster's state in one line ("Serving +Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom).", +or "Stopped; last model …") and, on the leader, the list +[above](#the-steps-once). The other Mac ends with "Nothing to do here: manage +it on the other Mac (`darkbloom cluster`).", or, when the cable moved to a port +not set up yet, offers to set it up ([below](#when-something-is-in-the-way)). If both Macs start waiting at the same moment, the pairing's own rule picks one -to keep waiting (it leads) and the other says so and joins it. +to keep waiting (it leads) and the other joins it ("✓ Paired. The other Mac +leads."). ## Serving locally only @@ -320,8 +325,7 @@ decodes with its speculative assistant under the default `mtp_mode` 2. Read the API's place from the ready screen: ``` - API at http://localhost:8000 on this Mac, and at port 8000 of its LAN or tailnet address. - Serving locally only on this Mac's API: no coordinator, no public traffic. + ✓ Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 and on the network (local only) ``` 3. Get the key: `darkbloom local` on the Mac the screen names prints the base @@ -337,7 +341,7 @@ may ask once to let Darkbloom accept incoming connections. The choice is kept: after a restart or reboot both Macs serve locally only again, until you switch back. In `darkbloom cluster` on the leader, **Serve -through Darkbloom** serves through Darkbloom again and **Serve locally only** +through Darkbloom** serves through Darkbloom again and **Serve locally** serves locally only; on a serving cluster the leading Mac's part restarts that way and the screen waits for it. The model list still reads Darkbloom's catalog when the network is up (to download a model neither @@ -426,8 +430,7 @@ under the near-tie rule) do two things only: public placement. A model or mode with no passing record is served for you, and the plan says in -one line, as the setup does under the chosen model when the pair serves -through Darkbloom: "not yet qualified for public traffic". +one line: "not yet qualified for public traffic". Time budgets (startup, first token, stop) are derived from the setup and the installed artifact, not from a per-model table: @@ -663,9 +666,9 @@ drained for an update yet: its update waits while it serves (the log says - **No macOS prompt can be shown** (for example with no one logged in to the desktop): the check writes the exact commands the prompt would run to an owner-only script, and the setup runs it with `sudo` in the same terminal (type this - Mac's password into sudo). Only when that fails does it print the line to run - once as an administrator, `sudo sh ~/.darkbloom/cluster-device/link-fix.sh`; - then run `darkbloom cluster` again. A port an administrator already isolated this way + Mac's password into sudo). If that fails, it says "Cable port not set up. Run + `darkbloom cluster` again."; an administrator can also run the script once, + `sudo sh ~/.darkbloom/cluster-device/link-fix.sh`, then `darkbloom cluster` again. A port an administrator already isolated this way is recognised and recorded (no change, no prompt). - **Internet Sharing shares to the cluster port itself**: the check says so and stops before any prompt. Turn the cluster port off under System Settings → @@ -673,7 +676,7 @@ drained for an update yet: its update waits while it serves (the log says `darkbloom cluster` again. - **The cable moved to another Thunderbolt port**: an already configured port is reused without another configuration prompt. For a port not yet configured, - run `darkbloom cluster` and choose **Set up the cable's port** when offered; macOS asks for administrator + run `darkbloom cluster` and choose **Set up the cable port** when offered; macOS asks for administrator approval to configure that port. Recovery RDMA enablement and Local Network privacy permission remain separate steps. - **The Macs were paired again** while their cluster services ran @@ -685,18 +688,18 @@ drained for an update yet: its update waits while it serves (the log says restart its service, since one an earlier release started keeps the earlier pairing: on that Mac, run `darkbloom cluster stop`, then `darkbloom cluster`. - **A part keeps ending the same way**: after three identical ends the screen - says it and offers **Save a diagnostics file to send to Darkbloom**; both Macs + says it and offers **Save diagnostics for Darkbloom**; both Macs keep trying by themselves. - **The leader cannot reach the other Mac**: make sure the other Mac is on and logged in; it rejoins by itself. During setup the leader offers **Try again** - and **Stop here**, since the other Mac's Darkbloom prompt may still be waiting + and **Cancel**, since the other Mac's Darkbloom prompt may still be waiting for Allow. If you denied the Local Network prompt there, allow Darkbloom in System Settings → Privacy & Security → Local Network, then run `darkbloom cluster` again. - **A model is not offered**: the list leaves out every model that is not approved for clusters or that these Macs cannot serve, with no reason beside it. A model named on the command line says why ("… is not approved for - clusters yet.", or "… is not offered on these Macs: "). When no + clusters yet.", or "… can't run on these Macs: ."). When no approved model can run, the screen says so and gives each reason once, after the models it holds back, for example "supported on a cluster, but this Mac's cluster worker does not take this copy of it"; a model is listed once when @@ -706,7 +709,7 @@ drained for an update yet: its update waits while it serves (the log says first.") is said, and nothing starts, if it still does not fit when checked again right before the start. - **The start does not finish**: the screen shows each Mac's last error and - offers **Save a diagnostics file to send to Darkbloom**, which writes one to + offers **Save diagnostics for Darkbloom**, which writes a file to your home folder (no keys, addresses or names in it; nothing is written if any would remain). From 63b3ee96da87ebdc2747df7013c70e243c12caa1 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 05:32:39 -0600 Subject: [PATCH 0207/1441] ci: build the cluster package's test products in the provider CI action Adds a cluster lane to provider-ci-build and its cache keys, and a temporary discovery job that learns which cluster tests the Blacksmith macOS VM can run. Co-Authored-By: Claude Opus 5.5 --- .github/actions/provider-ci-build/action.yml | 27 +++-- .github/workflows/ci.yml | 113 +++++++++++++++++++ scripts/provider-ci-cache.py | 3 +- 3 files changed, 133 insertions(+), 10 deletions(-) diff --git a/.github/actions/provider-ci-build/action.yml b/.github/actions/provider-ci-build/action.yml index 0adbe70dfe..946862daf7 100644 --- a/.github/actions/provider-ci-build/action.yml +++ b/.github/actions/provider-ci-build/action.yml @@ -2,7 +2,7 @@ name: Provider CI Build description: Build full debug test products with lane-specific caches and source-matched Metal inputs: lane: - description: provider or sdk; each owns independent build outputs + description: provider, sdk or cluster; each owns independent build outputs required: true runs: using: composite @@ -13,7 +13,7 @@ runs: LANE: ${{ inputs.lane }} run: | case "$LANE" in - provider|sdk) ;; + provider|sdk|cluster) ;; *) echo "Unknown provider CI lane: $LANE" >&2; exit 2 ;; esac - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 @@ -41,13 +41,14 @@ runs: path: | provider-swift/.build libs/mlx-swift-lm/.build + libs/darkbloom-cluster/.build key: ${{ steps.keys.outputs.swift-key }} restore-keys: ${{ steps.keys.outputs.swift-prefix }} - name: Revalidate source timestamps and discard cached runtime resources shell: bash run: | python3 scripts/provider-release-cache.py restore-mtimes - for root in provider-swift/.build libs/mlx-swift-lm/.build; do + for root in provider-swift/.build libs/mlx-swift-lm/.build libs/darkbloom-cluster/.build; do [ -d "$root" ] || continue find "$root" -type f -name mlx.metallib -delete find "$root" -mindepth 3 -maxdepth 3 -type d \ @@ -72,8 +73,14 @@ runs: swift package unedit --force mlx-swift >/dev/null 2>&1 || true swift package edit --path ../mlx-swift mlx-swift swift build --build-tests + - name: Build all cluster test products + if: inputs.lane == 'cluster' + id: cluster-build + shell: bash + working-directory: libs/darkbloom-cluster + run: swift build --build-tests - name: Record timestamps for successfully built sources - if: ${{ !cancelled() && (steps.provider-build.outcome == 'success' || steps.sdk-build.outcome == 'success') }} + if: ${{ !cancelled() && (steps.provider-build.outcome == 'success' || steps.sdk-build.outcome == 'success' || steps.cluster-build.outcome == 'success') }} id: timestamps shell: bash run: python3 scripts/provider-release-cache.py snapshot-mtimes @@ -84,6 +91,7 @@ runs: path: | provider-swift/.build libs/mlx-swift-lm/.build + libs/darkbloom-cluster/.build key: ${{ steps.keys.outputs.swift-key }} - name: Restore source-matched Metal cache id: metallib-cache @@ -99,11 +107,12 @@ runs: METALLIB_CACHE_DIR: ${{ runner.temp }}/metallib-cache run: | cmake --version - if [ "$LANE" = sdk ]; then - bin=$(swift build --package-path libs/mlx-swift-lm --show-bin-path) - else - bin=$(swift build --package-path provider-swift --show-bin-path) - fi + case "$LANE" in + sdk) package=libs/mlx-swift-lm ;; + cluster) package=libs/darkbloom-cluster ;; + *) package=provider-swift ;; + esac + bin=$(swift build --package-path "$package" --show-bin-path) ./scripts/stage-test-metallib.sh "$bin" - name: Save validated source-matched Metal cache if: ${{ !cancelled() && steps.metallib.outcome == 'success' && steps.metallib-cache.outputs.cache-hit != 'true' }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d16d575f9c..4acbb90c2b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -767,6 +767,119 @@ jobs: if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} run: bash provider-swift/Tests/ClusterOnboardingChecks/run.sh + cluster-discovery: + # TEMPORARY discovery job: learn what the Blacksmith macOS VM can run. + name: Cluster discovery (${{ matrix.part }}) + needs: [changes] + runs-on: blacksmith-12vcpu-macos-27 + timeout-minutes: 170 + strategy: + fail-fast: false + matrix: + part: ['1/4', '2/4', '3/4', '4/4', runners] + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + submodules: recursive + - name: Describe the VM + run: | + sysctl hw.memsize hw.ncpu machdep.cpu.brand_string || true + sw_vers || true + system_profiler SPDisplaysDataType || true + - name: Build cluster test products + id: provider-ci-build + if: ${{ matrix.part != 'runners' }} + uses: ./.github/actions/provider-ci-build + with: + lane: cluster + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + if: ${{ matrix.part == 'runners' }} + with: + python-version: '3.12.10' + - name: Select SDK 27 provider toolchain + if: ${{ matrix.part == 'runners' }} + run: ./scripts/prepare-provider-release-toolchain.sh + - name: Discover + if: ${{ !cancelled() }} + env: + PART: ${{ matrix.part }} + DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS: '12' + run: | + out="$RUNNER_TEMP/discovery" + mkdir -p "$out/logs" + python3 - "$out" <<'PY' + import json, os, re, subprocess, sys, time + from pathlib import Path + out = Path(sys.argv[1]); part = os.environ["PART"] + gates = {name: "1" for name in ( + "QWEN_TP_MTP_GPU", "QWEN_TP_BATCH_GPU", "QWEN_TP_AQV_GPU", "QWEN_TP_REAL_GEOMETRY_GPU", + "QWEN_TP_SHARE_PROBE_GPU", "QWEN_TP_MOE_GPU", "QWEN_TP_MOE_GPU_DIAG", "GLM53_DEPTH_INVARIANCE", + "GLM53_PAGED_KV", "GLM53_PREFIX_SSD", "GLM53_WINDOW_CENSUS", "GLM53_ROW_INVARIANCE", + "DARKBLOOM_PAGED_BENCH", "QWEN_TP_AQV_BENCH", "QWEN_TP_WIDE_BENCH", "PREFIX_RECORD_ENCODE_BENCH")} + def run(name, argv, cwd, env, timeout): + log = out / "logs" / (re.sub(r"[^A-Za-z0-9_.-]", "_", name) + ".log") + start = time.time(); status = None + with open(log, "w") as handle: + try: + status = subprocess.run(argv, cwd=cwd, env=env, stdout=handle, stderr=subprocess.STDOUT, + timeout=timeout).returncode + except subprocess.TimeoutExpired: + status = "timeout" + text = log.read_text(errors="replace") + record = {"name": name, "status": status, "seconds": round(time.time() - start, 1)} + record["passed"] = sum(int(n) for n in re.findall(r"Test run with (\d+) tests? (?:in \d+ suites? )?passed", text)) + record["failed_lines"] = [l.strip()[:300] for l in text.splitlines() + if re.search(r"(✘|error:|failed|Fatal error|signal)", l)][:40] + record["skipped"] = len(re.findall(r"(?m)^[^A-Za-z0-9]*(?:Test|Suite) .+ skipped", text)) + record["xctest"] = re.findall(r"Executed \d+ tests?, with .*", text)[-1:] + record["summary"] = re.findall(r"Test run with .*", text)[-1:] + print(json.dumps(record), flush=True) + return record + results = [] + base = dict(os.environ) + if part == "runners": + tests = Path("libs/darkbloom-cluster/Tests") + for directory in sorted(tests.iterdir()): + if (directory / "run.sh").is_file(): + argv = ["bash", str(directory / "run.sh")] + elif (directory / "run.py").is_file(): + argv = ["python3", str(directory / "run.py"), "--output", str(out / ("runner-" + directory.name))] + else: + continue + results.append(run("runner-" + directory.name, argv, None, base, 1500)) + else: + index, total = map(int, part.split("/")) + package = "libs/darkbloom-cluster" + listed = subprocess.run(["swift", "test", "list", "--skip-build"], cwd=package, + capture_output=True, text=True) + (out / "list.txt").write_text(listed.stdout + listed.stderr) + suites = sorted({f"{m.group(1)}.{m.group(2)}" for line in listed.stdout.splitlines() + if (m := re.match(r"^([^./]+)[./]([^./ ]+)", line.strip()))}) + print(f"{len(suites)} suites", flush=True) + mine = suites[index - 1::total] + for suite in mine: + module, name = suite.split(".", 1) + selector = f"^{module}[./]{name}([./]|$)" + record = run(suite, ["swift", "test", "--skip-build", "--filter", selector], package, base, 1200) + record["mode"] = "default"; results.append(record) + if record["skipped"]: + gated = run(suite + "-gated", ["swift", "test", "--skip-build", "--filter", selector], + package, {**base, **gates}, 1800) + gated["mode"] = "gated"; results.append(gated) + (out / "results.json").write_text(json.dumps(results, indent=1)) + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: + summary.write("| name | status | seconds | passed | skipped | summary |\n|---|---|---|---|---|---|\n") + for r in results: + summary.write(f"| {r['name']} | {r['status']} | {r['seconds']} | {r['passed']} | {r['skipped']} | {(r['summary'] or r['xctest'] or [''])[0][:120]} |\n") + PY + - name: Upload discovery + if: ${{ !cancelled() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: cluster-discovery-${{ strategy.job-index }} + path: ${{ runner.temp }}/discovery + retention-days: 7 + provider-test-gate: name: Provider Tests runs-on: ubuntu-24.04 diff --git a/scripts/provider-ci-cache.py b/scripts/provider-ci-cache.py index f52f8a57f1..521d57d1a2 100644 --- a/scripts/provider-ci-cache.py +++ b/scripts/provider-ci-cache.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Emit compatible cache keys for provider and nested SDK CI. -Run `keys --lane provider|sdk` after Metal toolchain setup. +Run `keys --lane provider|sdk|cluster` after Metal toolchain setup. Redirect scalar stdout to GITHUB_OUTPUT. Swift restore prefixes retain all compatibility boundaries; the shared metallib key is exact-only. Cache hits never authorize skipping tests @@ -22,6 +22,7 @@ LANE_PURPOSES = { "provider": "provider-debug-tests", "sdk": "sdk-nested-debug-tests", + "cluster": "cluster-runtime-debug-tests", } MLX_SOURCE = "libs/mlx-swift/Source/Cmlx/mlx" SWIFT_WRAPPER = Path(__file__).resolve().with_name("provider-release-swift.sh") From 1e723c2e0aea01862945380fb401bec8f97699c0 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 05:33:43 -0600 Subject: [PATCH 0208/1441] test(provider): reproduce R4-1729-A: cluster and provider changes during the rollback prompt The rollback checks cluster membership and the provider before the prompt only. These tests change both while the prompt is open and expect a refusal with nothing changed. They fail on this head: the rollback drains and swaps. Co-Authored-By: Claude Opus 5.5 --- .../UpdateRollbackCommandTests.swift | 45 ++++++++++++++++++- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift index 8c95cff765..788a67ef00 100644 --- a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift @@ -147,6 +147,43 @@ struct UpdateRollbackCommandTests { #expect(try install.store.loadState().quarantine?.version == "2.0.0") #expect(stopped.said.last == "The provider is not running; `darkbloom start` starts v1.0.0.") } + + // R4-1729-A: the cluster check and the provider check ran before the + // prompt only. Both are decided again under the update lease, before the + // drain, and nothing is changed when either changed during the prompt. + + @Test("a Mac that joins a cluster pair during the prompt is refused under the lease, with nothing changed", + arguments: [true, false]) + func clusterMembershipChangesDuringThePrompt(loaded: Bool) async throws { + let install = try RollbackInstall() + defer { install.remove() } + let host = RecordingHost(install: install, loaded: loaded, answer: "y", inClusterOnceAnswered: true) + + let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: host, yes: false) } + + #expect(error?.description == UpdateRollback.clusterRefusal) + #expect(host.events.isEmpty) + #expect(try install.liveBinary() == "2.0.0-darkbloom") + let state = try install.store.loadState() + #expect(state.current?.version == "2.0.0") + #expect(state.quarantine == nil) + try install.updater.beginUpdateSession(operation: "lease-check").release() + } + + @Test("a service provider replaced by a foreground provider during the prompt is refused before any drain") + func serviceReplacedByForegroundDuringThePrompt() async throws { + let install = try RollbackInstall() + defer { install.remove() } + let host = RecordingHost(install: install, loaded: true, answer: "y", providerOnceAnswered: .foreground) + + let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: host, yes: false) } + + #expect(error?.description == UpdateRollback.foregroundRefusal) + #expect(host.events.isEmpty) + #expect(try install.liveBinary() == "2.0.0-darkbloom") + #expect(try install.store.loadState().quarantine == nil) + try install.updater.beginUpdateSession(operation: "lease-check").release() + } } /// v1 installed, then v2 installed and promoted by the updater, in a temporary root. @@ -230,6 +267,7 @@ private final class RecordingHost: @unchecked Sendable { var events: [String] = [] var lines: [String] = [] var provider: UpdateRollback.Provider = .stopped + var inCluster = false } private let log: Log @@ -238,19 +276,22 @@ private final class RecordingHost: @unchecked Sendable { var said: [String] { log.lock.withLock { log.lines } } /// `providerOnceAnswered` is the provider's state from the prompt's answer on. + /// `inClusterOnceAnswered`: this Mac joins a cluster pair while the prompt is open. init(install: RollbackInstall, loaded: Bool, foreground: Bool = false, inCluster: Bool = false, canAsk: Bool = true, answer: String? = nil, providerOnceAnswered: UpdateRollback.Provider? = nil, - beforeDrain: @escaping () throws -> Void = {}) { + inClusterOnceAnswered: Bool? = nil, beforeDrain: @escaping () throws -> Void = {}) { let log = Log() log.provider = loaded ? .service : foreground ? .foreground : .stopped + log.inCluster = inCluster self.log = log let record = { (event: String) in log.lock.withLock { log.events.append(event) } } host = UpdateRollback.Host( - servesInCluster: { inCluster }, + servesInCluster: { log.lock.withLock { log.inCluster } }, provider: { log.lock.withLock { log.provider } }, canAsk: { canAsk }, readAnswer: { if let providerOnceAnswered { log.lock.withLock { log.provider = providerOnceAnswered } } + if let inClusterOnceAnswered { log.lock.withLock { log.inCluster = inClusterOnceAnswered } } return answer }, drain: { From 8a3f0c72d07b1d60a94649afef2734456b4daaac Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 05:36:36 -0600 Subject: [PATCH 0209/1441] fix(provider): `update --rollback` decides the cluster and provider checks under the update lease (R4-1729-A) The plan and the prompt run without a lock, and the cluster check and the provider check were made only before them. A Mac that joined a pair, or a service replaced by a foreground provider while the prompt was open, was drained and swapped. Now the command takes the update lease first and decides again under it, before anything changes: - it holds the cluster service lock until the swap is done and refuses when this Mac serves in a pair (a running service, a loaded login agent or a cluster-member job); a cluster service starts without the update lease; - it reads the provider again: a foreground provider and one started since the plan are refused before the drain; a stopped one is held out of starting (provider instance lock) until the swap is done; - it drains the service under that same lease (ServiceDrain.drain, split from prepare). The update lease is the one a pair's coordinated update holds for its whole cycle, so a rollback and a pair update never interleave. Tests cover both directions, the holds, and adapt the stopped-during-prompt case: a provider read as stopped under the lease is no longer drained. Co-Authored-By: Claude Opus 5.5 --- docs/provider/cli-reference.md | 17 +++- docs/threat-model.yaml | 5 + .../Onboarding/ClusterService.swift | 10 ++ .../Service/ProcessLifecycle.swift | 8 ++ .../Update/UpdateProcessLock.swift | 9 ++ .../Sources/darkbloom/ServiceDrain.swift | 96 ++++++++++--------- .../Sources/darkbloom/UpdateRollback.swift | 91 +++++++++++++++--- .../UpdateRollbackCommandTests.swift | 95 +++++++++++++++++- .../UpdateRollbackEndToEndTests.swift | 9 +- .../Service/ProcessLifecycleTests.swift | 13 +++ 10 files changed, 284 insertions(+), 69 deletions(-) diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index bc540c8dde..7e6bfd69fc 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -758,11 +758,18 @@ provider is restarted and the watchdog rearmed, as for an installed update; a stopped provider, or one stopped while the prompt was open, is only swapped (`provider-swift/Sources/darkbloom/UpdateRollback.swift`, `UpdateRollback`; `provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift`, -`rollbackPlan`, `rollBackToPredecessor`). It exits 1 and changes nothing when -this Mac serves in a `darkbloom cluster` pair (a running cluster service or a -loaded cluster-member provider job), a provider runs outside launchd -(`darkbloom start --foreground`) or started after the plan was shown, another -update or recovery holds the lease, +`rollbackPlan`, `rollBackToPredecessor`). The prompt runs without a lock, so +the command decides the cluster and provider checks again once it holds the +update lease, before the drain, and keeps them true until the swap is done: it +holds the cluster service lock so no cluster service starts, and, for a stopped +provider, the provider instance lock so no provider starts. The update lease is +the one a pair's coordinated update holds for its whole cycle, so a rollback and +a pair update never interleave. It exits 1 and changes nothing when +this Mac serves in a `darkbloom cluster` pair (a running cluster service, a +loaded cluster service login agent, or a loaded cluster-member provider job), a +provider runs outside launchd (`darkbloom start --foreground`, also when it +replaced the service while the prompt was open) or started after the plan was +shown, another update or recovery holds the lease, no release is kept for rollback, the installed release is already that release, the installed `Darkbloom.app` is not the recorded release, or the kept release fails its hash or signature check (`RollbackRefusal`). Steps are in diff --git a/docs/threat-model.yaml b/docs/threat-model.yaml index 74f59881c9..901638c936 100644 --- a/docs/threat-model.yaml +++ b/docs/threat-model.yaml @@ -1889,6 +1889,11 @@ threats: predecessor verification and the same single-slot exact-version quarantine; it also refuses an installed bundle that differs from the recorded release and never rolls back one Mac of a cluster pair. + Cluster membership and the provider's state are decided under the + update lease (the lease a pair's coordinated update holds), and the + cluster service lock and, for a stopped provider, the provider + instance lock are held until the swap is done, so neither a cluster + service nor a foreground provider can start mid-swap. status: implemented - description: > Bounded watchdog network I/O (URLSession request/resource timeouts) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index 9f3dd5d8e6..5ef8ad4b8d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -207,6 +207,16 @@ public final class ClusterService: @unchecked Sendable { return running(in: directory) == true } + /// Holds this home's service lock, so no cluster service starts here until the hold is released (a start fails as + /// "already running", and its login agent retries). Nil when a service holds the lock; throws when the lock + /// cannot be opened. `darkbloom update --rollback` holds it across its swap, so this Mac cannot join a pair while + /// its release changes. + public static func holdStopped(operation: String) throws -> UpdateProcessLock? { + let lockFile = try paths().lock + try ClusterConfigurationFiles.ensureDirectory(lockFile.deletingLastPathComponent(), create: true, privateMode: true) + return try UpdateProcessLock.acquireUnlessBusy(at: lockFile, operation: operation) + } + private static func running(in directory: URL) -> Bool? { let lockFile = files(in: directory).lock let fd = open(lockFile.path, O_RDONLY | O_CLOEXEC) diff --git a/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift b/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift index dc0f8b01e0..9eb0daedfb 100644 --- a/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift +++ b/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift @@ -65,6 +65,14 @@ public enum ProcessLifecycle { } } + /// Holds the provider instance lock without becoming the provider, so no provider (launchd or foreground) starts + /// until the hold is released: its `acquireSingleInstanceLock` fails as busy. Nil when a provider holds it; + /// throws when the lock cannot be opened. + public static func holdStartsOut(operation: String, + at pidFile: URL = ProcessLifecycle.defaultPIDFile()) throws -> UpdateProcessLock? { + try UpdateProcessLock.acquireUnlessBusy(at: pidFile.appendingPathExtension("lock"), operation: operation) + } + public static func existingPID(at pidFile: URL = ProcessLifecycle.defaultPIDFile()) -> Int32? { readPID(at: pidFile) } diff --git a/provider-swift/Sources/ProviderCore/Update/UpdateProcessLock.swift b/provider-swift/Sources/ProviderCore/Update/UpdateProcessLock.swift index e87a324e32..43ac537783 100644 --- a/provider-swift/Sources/ProviderCore/Update/UpdateProcessLock.swift +++ b/provider-swift/Sources/ProviderCore/Update/UpdateProcessLock.swift @@ -136,6 +136,15 @@ public final class UpdateProcessLock: @unchecked Sendable { return UpdateProcessLock(descriptor: descriptor, path: path, owner: owner) } + /// One try: nil when another process holds the lock, thrown otherwise. + public static func acquireUnlessBusy(at path: URL, operation: String) throws -> UpdateProcessLock? { + do { + return try acquire(at: path, operation: operation) + } catch LockError.busy { + return nil + } + } + /// Owner-local check that this object's retained kernel lock still names /// the canonical file. A path snapshot alone cannot prove descriptor custody. func requireHeld() throws { diff --git a/provider-swift/Sources/darkbloom/ServiceDrain.swift b/provider-swift/Sources/darkbloom/ServiceDrain.swift index c89b399a69..cd6d30f726 100644 --- a/provider-swift/Sources/darkbloom/ServiceDrain.swift +++ b/provider-swift/Sources/darkbloom/ServiceDrain.swift @@ -22,50 +22,7 @@ enum ServiceDrain { let updater = SelfUpdater(coordinatorBaseURL: state?.coordinatorUrl ?? BuildEnvironment.current.coordinatorHTTPURL) let session = try updater.beginUpdateSession(operation: "provider-lifecycle", timeout: 0) do { - let identity = WatchdogProbe.providerIdentity(daemonState: state, launchSnapshotProcess: LaunchAgent.launchSnapshot()?.process) - if let identity, identity.isCurrent(), !options.force { - guard state?.processIdentity == identity, state?.lifecycle != nil else { - throw ValidationError("This running provider does not expose graceful-drain control. Upgrade it, or explicitly use --force to interrupt it.") - } - } - let hasControl = identity?.isCurrent() == true && state?.processIdentity == identity && state?.lifecycle != nil - if !hasControl && !options.force && LaunchAgent.launchSnapshot()?.process != nil { - throw ValidationError("Cannot confirm the running provider identity. No process or recovery setting was changed.") - } - let request = identity.flatMap { hasControl ? ProviderDrainRequest(target: $0, timeoutSeconds: options.timeout, force: options.force) : nil } - let mailbox = identity.map { LifecycleMailbox(identity: $0) } - let recovery = try ServiceRecoverySnapshot.capture() - try withConfigurationChange { - try publishWithRecoveryRollback(disable: { - try WatchdogAgent.stop() - try LaunchAgent.disableAutomaticStartup() - }, publish: { - if let request, let mailbox { try mailbox.writeRequest(request) } - }, restore: { try recovery.restore() }) - } - // Only a published request (or a confirmed stopped process) may - // discard prior recovery history. Later drain timeouts stay fenced. - try? FileManager.default.removeItem(at: WatchdogStateStore.path()) - - if let request, let mailbox { - print("Draining accepted requests (deadline: \(options.timeout)s). New work is refused by the running provider.") - do { - let result = try await wait(request: request, mailbox: mailbox) - let confirmation = result.coordinatorAcknowledged ? "received" : (result.outcome == .drained ? "not needed (no coordinator connection)" : "unconfirmed") - print("Drain \(result.outcome.rawValue): \(result.remaining) unfinished request(s); coordinator acknowledgement: \(confirmation).") - } catch { - guard options.force else { throw error } - print("Forced stop: drain acknowledgement unavailable; unfinished work will be interrupted.") - } - } else if options.force { - print("Forced lifecycle requested: unfinished work may be interrupted; completion is unconfirmed.") - - } - if options.force, let identity, identity.isCurrent() { - guard ProcessLifecycle.terminate(identity, gracePeriod: 1) else { - throw ValidationError("Forced termination did not finish; the service remains disabled.") - } - } + try await drain(options: options, state: state, withConfigurationChange: withConfigurationChange) return session } catch { session.release() @@ -73,6 +30,57 @@ enum ServiceDrain { } } + /// `prepare`'s drain, for a caller that already holds the update lease and decided under it that the provider + /// service is to be drained (`darkbloom update --rollback`). + static func drain(options: DrainOptions, + state: DaemonState? = DaemonStateFile.read(), + withConfigurationChange: (_ setup: () throws -> Void) throws -> Void = { try $0() }) async throws { + let identity = WatchdogProbe.providerIdentity(daemonState: state, launchSnapshotProcess: LaunchAgent.launchSnapshot()?.process) + if let identity, identity.isCurrent(), !options.force { + guard state?.processIdentity == identity, state?.lifecycle != nil else { + throw ValidationError("This running provider does not expose graceful-drain control. Upgrade it, or explicitly use --force to interrupt it.") + } + } + let hasControl = identity?.isCurrent() == true && state?.processIdentity == identity && state?.lifecycle != nil + if !hasControl && !options.force && LaunchAgent.launchSnapshot()?.process != nil { + throw ValidationError("Cannot confirm the running provider identity. No process or recovery setting was changed.") + } + let request = identity.flatMap { hasControl ? ProviderDrainRequest(target: $0, timeoutSeconds: options.timeout, force: options.force) : nil } + let mailbox = identity.map { LifecycleMailbox(identity: $0) } + let recovery = try ServiceRecoverySnapshot.capture() + try withConfigurationChange { + try publishWithRecoveryRollback(disable: { + try WatchdogAgent.stop() + try LaunchAgent.disableAutomaticStartup() + }, publish: { + if let request, let mailbox { try mailbox.writeRequest(request) } + }, restore: { try recovery.restore() }) + } + // Only a published request (or a confirmed stopped process) may + // discard prior recovery history. Later drain timeouts stay fenced. + try? FileManager.default.removeItem(at: WatchdogStateStore.path()) + + if let request, let mailbox { + print("Draining accepted requests (deadline: \(options.timeout)s). New work is refused by the running provider.") + do { + let result = try await wait(request: request, mailbox: mailbox) + let confirmation = result.coordinatorAcknowledged ? "received" : (result.outcome == .drained ? "not needed (no coordinator connection)" : "unconfirmed") + print("Drain \(result.outcome.rawValue): \(result.remaining) unfinished request(s); coordinator acknowledgement: \(confirmation).") + } catch { + guard options.force else { throw error } + print("Forced stop: drain acknowledgement unavailable; unfinished work will be interrupted.") + } + } else if options.force { + print("Forced lifecycle requested: unfinished work may be interrupted; completion is unconfirmed.") + + } + if options.force, let identity, identity.isCurrent() { + guard ProcessLifecycle.terminate(identity, gracePeriod: 1) else { + throw ValidationError("Forced termination did not finish; the service remains disabled.") + } + } + } + /// Stop only a confirmed drained owner. A PID file alone never authorizes /// signalling a process, and ordinary replacement never escalates to SIGKILL. static func stopDrainedProvider(unloadService: Bool = true) async throws { diff --git a/provider-swift/Sources/darkbloom/UpdateRollback.swift b/provider-swift/Sources/darkbloom/UpdateRollback.swift index 24f2c4e220..c9a2b244d2 100644 --- a/provider-swift/Sources/darkbloom/UpdateRollback.swift +++ b/provider-swift/Sources/darkbloom/UpdateRollback.swift @@ -6,8 +6,28 @@ import ProviderCore /// one Mac. It restores the release kept for rollback through the watchdog's /// journaled rollback (`SelfUpdater.rollBackToPredecessor`) and quarantines the /// installed one, between the drain and restart `darkbloom update` uses: the -/// running provider drains first (the drain holds the update lease), the -/// layout is swapped, then the provider restarts. +/// running provider drains first, the layout is swapped, then the provider +/// restarts. +/// +/// Exclusion (R4-1729-A). The plan and the prompt run without any lock, so +/// everything they checked is decided again once the command holds the update +/// lease, before anything changes, and stays true until the swap is done: +/// - The update lease (`SelfUpdater.beginUpdateSession`) is the one every +/// install mutation takes: a pair's coordinated update for its whole cycle +/// (`ClusterPairUpdateCycle`, "cluster-auto-update") and its candidate +/// recovery, the watchdog, the in-process auto-update, `darkbloom update`, +/// and every `start`, `stop` and `restart` drain, including the one that +/// installs a cluster member job. A rollback and a pair update never +/// interleave: whichever takes the lease second is refused or waits for the +/// next update slot. +/// - A cluster service starts without the update lease, so under the lease the +/// command also holds the cluster service lock (`ClusterService.holdStopped`) +/// until the swap is done, and refuses when this Mac serves in a pair. +/// - The provider is read again under the lease. One started since the plan, +/// or replaced by a foreground provider (service to foreground), is refused +/// before the drain. A provider that is not running is kept from starting +/// until the swap is done (`ProcessLifecycle.holdStartsOut`); a foreground +/// start takes no update lease. struct UpdateRollback { /// This Mac's provider service, injected so tests never reach launchd. enum Provider { @@ -19,13 +39,19 @@ struct UpdateRollback { } struct Host { - /// A `darkbloom cluster` service runs, or the provider job runs a cluster member. + /// A `darkbloom cluster` service runs or its login agent is loaded, or the provider job runs a cluster member. var servesInCluster: () -> Bool + /// Called under the update lease: holds this Mac's cluster service from starting until released, or nil when + /// this Mac serves in a cluster pair (as `servesInCluster`). + var holdClusterOut: () throws -> UpdateProcessLock? var provider: () -> Provider + /// Called under the update lease for a provider that is not running: holds every provider start (launchd or + /// foreground) out until released, or nil when a provider holds its instance lock. + var holdProviderStartsOut: () throws -> UpdateProcessLock? var canAsk: () -> Bool var readAnswer: () -> String? - /// Drains the running provider and returns the update lease the drain holds. - var drain: () async throws -> SelfUpdater.UpdateSession + /// Drains the running provider service. Called while the command holds the update lease. + var drain: () async throws -> Void /// Relaunches the drained provider and rearms the watchdog. var restart: () async throws -> Void /// Waits until the relaunched provider is freshly authorized. @@ -60,6 +86,9 @@ struct UpdateRollback { private static var cli: String { BuildEnvironment.current.cliName } + /// The update lease's operation, and the owner the cluster service and provider holds name. + static let operation = "operator-rollback" + func run(skipConfirmation: Bool) async throws { guard !host.servesInCluster() else { throw Failure(description: Self.clusterRefusal) } let provider = host.provider() @@ -80,16 +109,32 @@ struct UpdateRollback { } let session = try await refusingClearly { - if loaded { return try await host.drain() } - return try updater.beginUpdateSession(operation: "operator-rollback", timeout: 0) + try updater.beginUpdateSession(operation: Self.operation, timeout: 0) } defer { session.release() } - // The plan and prompt ran without the lease: a provider started since - // is not swapped under, and one stopped since is not restarted. + // Under the lease, before anything changes: the plan and the prompt ran + // without it. Each hold lasts until the swap is done. + guard let clusterHold = try heldOrRefused({ try host.holdClusterOut() }) else { + throw Failure(description: Self.clusterRefusal) + } + defer { clusterHold.release() } let providerNow = host.provider() + guard providerNow != .foreground else { throw Failure(description: Self.foregroundRefusal) } guard loaded || providerNow == .stopped else { throw Failure(description: Self.startedRefusal) } - let restarts = loaded && providerNow == .service + // A provider stopped since the plan is swapped without a restart. + let restarts = providerNow == .service + var startsHold: UpdateProcessLock? + if restarts { + try await host.drain() + } else { + guard let hold = try heldOrRefused({ try host.holdProviderStartsOut() }) else { + throw Failure(description: Self.startedRefusal) + } + startsHold = hold + } let outcome = Result { try updater.rollBackToPredecessor(session: session, plan: plan) } + startsHold?.release() + clusterHold.release() // A drained provider restarts whether or not the rollback completed: // the layout is always one complete release (the journal guarantees it). var restartFailure: Error? @@ -137,6 +182,15 @@ struct UpdateRollback { ] } + /// A hold that could not be taken for another reason than contention refuses with nothing changed. + private func heldOrRefused(_ take: () throws -> UpdateProcessLock?) throws -> UpdateProcessLock? { + do { + return try take() + } catch { + throw Failure(description: "The rollback could not lock out a concurrent start (\(error)). Nothing was changed.") + } + } + /// Lease contention and every rollback refusal print as one plain line. private func refusingClearly(_ body: () async throws -> Value) async throws -> Value { do { @@ -152,17 +206,28 @@ struct UpdateRollback { extension UpdateRollback.Host { static func live(drain options: DrainOptions, configPath: String?) -> Self { let previous = LaunchAgent.launchSnapshot()?.process + // Configured to serve in a pair even while its service is not running: `darkbloom cluster stop` unloads + // the login agent, and the member job runs under the provider's own label. + let configuredInCluster = { + ClusterServiceAgent.installedLabels().contains { ClusterServiceAgent.isLoaded(label: $0) } + || (LaunchAgent.isLoaded() && LaunchAgent.installedJobIsClusterMember()) + } return Self( - servesInCluster: { - ClusterService.running() || (LaunchAgent.isLoaded() && LaunchAgent.installedJobIsClusterMember()) + servesInCluster: { ClusterService.running() || configuredInCluster() }, + holdClusterOut: { + // The service lock first: once it is held, no service starts, so the configuration read after it holds. + guard let hold = try ClusterService.holdStopped(operation: UpdateRollback.operation) else { return nil } + guard !configuredInCluster() else { hold.release(); return nil } + return hold }, provider: { if LaunchAgent.isLoaded() { return .service } return DaemonStateFile.read()?.processIdentity?.isCurrent() == true ? .foreground : .stopped }, + holdProviderStartsOut: { try ProcessLifecycle.holdStartsOut(operation: UpdateRollback.operation) }, canAsk: { isatty(STDIN_FILENO) != 0 }, readAnswer: { readLine() }, - drain: { try await ServiceDrain.prepare(options: options) }, + drain: { try await ServiceDrain.drain(options: options) }, restart: { try await ServiceDrain.stopDrainedProvider(unloadService: false) try LaunchAgent.restartAfterDrain() diff --git a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift index 788a67ef00..da6618b9c8 100644 --- a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift @@ -140,9 +140,10 @@ struct UpdateRollbackCommandTests { #expect(try install.liveBinary() == "2.0.0-darkbloom") #expect(try install.store.loadState().quarantine == nil) + // Read under the lease before any drain: a provider that stopped is not drained either. let stopped = RecordingHost(install: install, loaded: true, answer: "y", providerOnceAnswered: .stopped) try await install.rollback(host: stopped, yes: false) - #expect(stopped.events == ["drain"]) + #expect(stopped.events.isEmpty) #expect(try install.liveBinary() == "1.0.0-darkbloom") #expect(try install.store.loadState().quarantine?.version == "2.0.0") #expect(stopped.said.last == "The provider is not running; `darkbloom start` starts v1.0.0.") @@ -184,6 +185,66 @@ struct UpdateRollbackCommandTests { #expect(try install.store.loadState().quarantine == nil) try install.updater.beginUpdateSession(operation: "lease-check").release() } + + @Test("the rollback and a pair's coordinated update exclude each other through the update lease") + func sharedExclusionWithThePairUpdate() async throws { + let install = try RollbackInstall() + defer { install.remove() } + + // A pair update cycle holds the lease (`ClusterPairUpdateCycle.claim`): the rollback is refused. + let cycle = try install.updater.beginUpdateSession(operation: "cluster-auto-update") + let refused = RecordingHost(install: install, loaded: true, answer: "y") + let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: refused, yes: true) } + #expect(error?.description.contains("cluster-auto-update") == true) + #expect(refused.events.isEmpty) + cycle.release() + + // The rollback holds the lease from the drain to the swap: a pair update cycle cannot claim it, and no + // cluster service can start. + let probe = Probe() + let host = RecordingHost(install: install, loaded: true, answer: "y", beforeDrain: { + probe.cycleRefused = (try? install.updater.beginUpdateSession(operation: "cluster-auto-update")) == nil + probe.serviceHeldOut = try !install.isFree(install.clusterServiceLock) + }) + try await install.rollback(host: host, yes: true) + #expect(probe.cycleRefused && probe.serviceHeldOut) + #expect(try install.liveBinary() == "1.0.0-darkbloom") + #expect(try install.isFree(install.clusterServiceLock)) + try install.updater.beginUpdateSession(operation: "lease-check").release() + } + + @Test("a stopped provider is held out of starting over the swap, and a provider holding its lock refuses the rollback") + func stoppedProviderStartsAreHeldOut() async throws { + let install = try RollbackInstall() + defer { install.remove() } + + let racing = RecordingHost(install: install, loaded: false, providerHoldsInstanceLock: true) + let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: racing, yes: true) } + #expect(error?.description == UpdateRollback.startedRefusal) + #expect(try install.liveBinary() == "2.0.0-darkbloom") + #expect(try install.store.loadState().quarantine == nil) + + let stopped = RecordingHost(install: install, loaded: false) + try await install.rollback(host: stopped, yes: true) + #expect(try install.liveBinary() == "1.0.0-darkbloom") + #expect(try install.isFree(install.providerInstanceLock)) + #expect(try install.isFree(install.clusterServiceLock)) + } + + @Test("a hold that cannot be taken refuses with nothing changed") + func unopenableHoldRefuses() async throws { + let install = try RollbackInstall() + defer { install.remove() } + // A directory where the lock file belongs cannot be opened as a lock. + try FileManager.default.createDirectory(at: install.clusterServiceLock, withIntermediateDirectories: true) + let host = RecordingHost(install: install, loaded: true, answer: "y") + + let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: host, yes: true) } + + #expect(error?.description.contains("could not lock out a concurrent start") == true) + #expect(host.events.isEmpty) + #expect(try install.liveBinary() == "2.0.0-darkbloom") + } } /// v1 installed, then v2 installed and promoted by the updater, in a temporary root. @@ -240,6 +301,17 @@ private struct RollbackInstall { var store: UpdateRecoveryStore { UpdateRecoveryStore(installRoot: root, verifyCodeSignatures: false) } + /// Stand-ins for the cluster service lock and the provider instance lock, which the rollback holds over its swap. + var clusterServiceLock: URL { scratch.appendingPathComponent("cluster-setup/service.lock") } + var providerInstanceLock: URL { scratch.appendingPathComponent("provider.pid.lock") } + + /// Whether `lock` is free now (taken and released at once). + func isFree(_ lock: URL) throws -> Bool { + guard let held = try UpdateProcessLock.acquireUnlessBusy(at: lock, operation: "lock-check") else { return false } + held.release() + return true + } + func rollback(host: RecordingHost, yes: Bool) async throws { try await UpdateRollback(updater: updater, host: host.host, say: host.say).run(skipConfirmation: yes) } @@ -268,6 +340,7 @@ private final class RecordingHost: @unchecked Sendable { var lines: [String] = [] var provider: UpdateRollback.Provider = .stopped var inCluster = false + var providerHoldsInstanceLock = false } private let log: Log @@ -277,17 +350,28 @@ private final class RecordingHost: @unchecked Sendable { /// `providerOnceAnswered` is the provider's state from the prompt's answer on. /// `inClusterOnceAnswered`: this Mac joins a cluster pair while the prompt is open. + /// `providerHoldsInstanceLock`: a provider holds its instance lock without showing in the state file yet. init(install: RollbackInstall, loaded: Bool, foreground: Bool = false, inCluster: Bool = false, canAsk: Bool = true, answer: String? = nil, providerOnceAnswered: UpdateRollback.Provider? = nil, - inClusterOnceAnswered: Bool? = nil, beforeDrain: @escaping () throws -> Void = {}) { + inClusterOnceAnswered: Bool? = nil, providerHoldsInstanceLock: Bool = false, + beforeDrain: @escaping () throws -> Void = {}) { let log = Log() log.provider = loaded ? .service : foreground ? .foreground : .stopped log.inCluster = inCluster + log.providerHoldsInstanceLock = providerHoldsInstanceLock self.log = log let record = { (event: String) in log.lock.withLock { log.events.append(event) } } host = UpdateRollback.Host( servesInCluster: { log.lock.withLock { log.inCluster } }, + holdClusterOut: { + guard !log.lock.withLock({ log.inCluster }) else { return nil } + return try UpdateProcessLock.acquireUnlessBusy(at: install.clusterServiceLock, operation: UpdateRollback.operation) + }, provider: { log.lock.withLock { log.provider } }, + holdProviderStartsOut: { + guard !log.lock.withLock({ log.providerHoldsInstanceLock }) else { return nil } + return try UpdateProcessLock.acquireUnlessBusy(at: install.providerInstanceLock, operation: UpdateRollback.operation) + }, canAsk: { canAsk }, readAnswer: { if let providerOnceAnswered { log.lock.withLock { log.provider = providerOnceAnswered } } @@ -297,7 +381,6 @@ private final class RecordingHost: @unchecked Sendable { drain: { record("drain") try beforeDrain() - return try install.updater.beginUpdateSession(operation: "provider-lifecycle", timeout: 0) }, restart: { record("restart") }, waitForRestart: { record("wait") }) @@ -305,3 +388,9 @@ private final class RecordingHost: @unchecked Sendable { func say(_ line: String) { log.lock.withLock { log.lines.append(line) } } } + +/// What a hook observed while the rollback held its locks. +private final class Probe: @unchecked Sendable { + var cycleRefused = false + var serviceHeldOut = false +} diff --git a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift index 5e56325cd8..c6a9bb91d3 100644 --- a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift @@ -83,13 +83,14 @@ struct UpdateRollbackEndToEndTests { let log = EndToEndLog() let host = UpdateRollback.Host( servesInCluster: { false }, + holdClusterOut: { + try UpdateProcessLock.acquireUnlessBusy(at: scratch.appendingPathComponent("service.lock"), operation: "operator-rollback") + }, provider: { .service }, + holdProviderStartsOut: { nil }, canAsk: { false }, readAnswer: { nil }, - drain: { - log.record("drain") - return try updater.beginUpdateSession(operation: "provider-lifecycle", timeout: 0) - }, + drain: { log.record("drain") }, restart: { log.record("restart") }, waitForRestart: { log.record("wait") }) try await UpdateRollback(updater: updater, host: host, say: { log.say($0) }).run(skipConfirmation: command.yes) diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift index 2cf1dc1f52..dcdffc057e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift @@ -48,6 +48,19 @@ struct ProcessLifecycleTests { #expect(written == "\(ProcessInfo.processInfo.processIdentifier)") } + @Test("a rollback's start hold keeps every provider start out until it is released") + func startHoldExcludesProviderStart() throws { + let pidFile = tempPIDFile() + defer { ProcessLifecycle.releaseSingleInstanceLock(at: pidFile) } + + let hold = try #require(try ProcessLifecycle.holdStartsOut(operation: "operator-rollback", at: pidFile)) + #expect(throws: UpdateProcessLock.LockError.self) { try ProcessLifecycle.acquireSingleInstanceLock(at: pidFile) } + hold.release() + try ProcessLifecycle.acquireSingleInstanceLock(at: pidFile) + // A running provider keeps the rollback's hold out in turn. + #expect(try ProcessLifecycle.holdStartsOut(operation: "operator-rollback", at: pidFile) == nil) + } + @Test("acquire is idempotent for the running process") func acquireIdempotent() throws { let pidFile = tempPIDFile() From c1ed803dcb10c4758e89462c21aa4373dc5ccd6d Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 05:44:34 -0600 Subject: [PATCH 0210/1441] Pin libs/mlx-swift-lm to SDK main 2311af6e SDK main 2311af6e contains SDK #383 (ad856be1, the pin this branch had) and the other 0.10.7 SDK merges (#370, #371, #377, #382, #384, #375, #376). Co-Authored-By: Claude Opus 5.5 --- libs/mlx-swift-lm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index ad856be115..2311af6e67 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit ad856be1151d20c28a354eda81ce71ba68044d79 +Subproject commit 2311af6e67c2d79b6b7b59504978af67fe6857e0 From f5417945ed8c3746ec60f4079386b193ab5bdea9 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 05:46:54 -0600 Subject: [PATCH 0211/1441] docs: the saved Qwen TP widths after the per-lane prefix capture The width table, the eight-lane byte figures and the changelog were computed before #1720 charged each lane's prompt-prefix capture in the LOAD quote. The merged head's ClusterPlacementTensorWidthRegisteredTests prints the new figures: a rank of an equal split reserves 40,544,616,448 bytes at eight lanes without the assistant (was 28,555,198,464) and 60,367,765,504 with it (was 48,378,347,520). Idle pairs now save 2/2/4/8/8 without the assistant and 1/1/2/4/8 with it at 32/36/48/64/96+ GiB a Mac. The sizing code is unchanged; it reads the live quotes. Co-Authored-By: Claude Opus 5.5 --- changelog.d/qwen27-tp-default-lanes.md | 6 +++--- docs/architecture/inference.md | 18 ++++++++++-------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/changelog.d/qwen27-tp-default-lanes.md b/changelog.d/qwen27-tp-default-lanes.md index 14f85a899c..beaec56878 100644 --- a/changelog.d/qwen27-tp-default-lanes.md +++ b/changelog.d/qwen27-tp-default-lanes.md @@ -6,9 +6,9 @@ load. Before, it served one at a time: a local pair widened only after a burst, through a reload the burst waited for, and a pair serving Darkbloom traffic never widened. -- On two idle Macs, Qwen3.8-27B serves 8 at once from 48 GB a Mac without the - speculative assistant (4 at 32 or 36 GB), and 8 from 96 GB a Mac with it - (local clusters only); smaller Macs serve fewer. Two M5 Ultras serve 8 either +- On two idle Macs, Qwen3.8-27B serves 8 at once from 64 GB a Mac without the + speculative assistant (4 at 48 GB, 2 at 32 or 36 GB), and 8 from 96 GB a Mac + with it (local clusters only); smaller Macs serve fewer. Two M5 Ultras serve 8 either way. When not even 2 fit, the pair serves one request at a time, as before. - Memory safety is unchanged: both Macs reserve that many requests' full memory when the model loads and admit each request alone. A local pair set up diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 38339256ec..684ada8cf1 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-11-01 +> Last updated: 2026-11-03 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -5361,15 +5361,17 @@ the served layout; `ClusterPlacementTensorWidthRegisteredTests`): | Each Mac | Without the assistant (served through Darkbloom) | With the depth-3 assistant (local) | |---|---|---| -| 32 GiB | 4 | 1 | -| 36 GiB | 4 | 2 | -| 48 GiB | 8 | 4 | -| 64 GiB | 8 | 6 | +| 32 GiB | 2 | 1 | +| 36 GiB | 2 | 1 | +| 48 GiB | 4 | 2 | +| 64 GiB | 8 | 4 | | 96 GiB and larger | 8 | 8 | -At eight lanes, each rank of an equal split reserves 28,555,198,464 bytes at -LOAD without the assistant and 48,378,347,520 bytes with it; with its weights -and loading headroom it needs 42,084,887,040 and 65,642,146,304 bytes. Every +At eight lanes, each rank of an equal split reserves 40,544,616,448 bytes at +LOAD without the assistant and 60,367,765,504 bytes with it, each lane's +prompt-prefix capture included ([prefix ownership](hardware-support.md#qwen27-tp-batch-prefix-ownership)); +with its weights and loading headroom it needs 54,074,305,024 and +77,631,564,288 bytes. Every registered Qwen TP row is sized the same way from its own quotes. GLM keeps its eight lanes and other families keep their defaults. From 9dd1501d581bee9eaa50cf76eea3e96acfe13540 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 05:49:23 -0600 Subject: [PATCH 0212/1441] fix(provider): `update --rollback` decides again at the swap what the drain could change (review of R4-1729-A) Independent security review findings, fixed: - M1: after a forced or self-ended drain nothing held the provider instance lock over the swap. The instance lock is now taken at the swap for every path, or left with the drained service process when the lock's recorded owner is that process. Any other holder refuses the rollback; that process is never signalled (no restart), and the service stays drained. - M2: a loaded but dead launchd job beside a foreground provider counted as the service. The provider is classified by process identity (UpdateRollback.classify). - M3: the cluster service lock was held through the whole drain. Membership is now decided under the lease before the drain, and the lock is held only over the swap, where it is checked again; a pair formed during the drain refuses there and the drained provider restarts. - L1: a plan that changed during the prompt is refused before the drain (SelfUpdater.confirmRollbackPlan). - L2: docs no longer claim the pair cycle holds the lease through its restart; its loaded login agent covers that window. - L3: refused as root, whose lock files the user's processes could not take. - L4: a held instance lock names its owner's pid. Co-Authored-By: Claude Opus 5.5 --- docs/provider/cli-reference.md | 23 ++- docs/threat-model.yaml | 14 +- .../Onboarding/ClusterService.swift | 7 +- .../Service/ProcessLifecycle.swift | 8 +- .../Update/SelfUpdater+Rollback.swift | 17 +- .../Update/UpdateProcessLock.swift | 22 ++- .../Sources/darkbloom/UpdateCommand.swift | 5 + .../Sources/darkbloom/UpdateRollback.swift | 148 ++++++++++++------ .../UpdateRollbackCommandTests.swift | 100 +++++++++++- .../UpdateRollbackEndToEndTests.swift | 7 +- .../Service/ProcessLifecycleTests.swift | 10 +- .../Update/UpdateRollbackPlanTests.swift | 38 +++++ 12 files changed, 314 insertions(+), 85 deletions(-) diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 7e6bfd69fc..b3e543f2ad 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -759,20 +759,27 @@ stopped provider, or one stopped while the prompt was open, is only swapped (`provider-swift/Sources/darkbloom/UpdateRollback.swift`, `UpdateRollback`; `provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift`, `rollbackPlan`, `rollBackToPredecessor`). The prompt runs without a lock, so -the command decides the cluster and provider checks again once it holds the -update lease, before the drain, and keeps them true until the swap is done: it -holds the cluster service lock so no cluster service starts, and, for a stopped -provider, the provider instance lock so no provider starts. The update lease is -the one a pair's coordinated update holds for its whole cycle, so a rollback and -a pair update never interleave. It exits 1 and changes nothing when +the command decides every check again once it holds the update lease, before +the drain, and again at the swap for what the drain could let change. Over the +swap it holds the cluster service lock, so no cluster service starts, and the +provider instance lock (or leaves it with the drained service process), so no +other provider starts. A pair's coordinated update holds the same lease from +its check through its install, and its cluster service login agent stays +loaded through its restart, so a rollback and a pair update never interleave. +It runs only as the user the provider runs as, not as root. It exits 1 and +changes nothing when this Mac serves in a `darkbloom cluster` pair (a running cluster service, a loaded cluster service login agent, or a loaded cluster-member provider job), a provider runs outside launchd (`darkbloom start --foreground`, also when it replaced the service while the prompt was open) or started after the plan was -shown, another update or recovery holds the lease, +shown, the installed release changed after the plan was shown, another update +or recovery holds the lease, no release is kept for rollback, the installed release is already that release, the installed `Darkbloom.app` is not the recorded release, or the kept -release fails its hash or signature check (`RollbackRefusal`). Steps are in +release fails its hash or signature check (`RollbackRefusal`). A refusal at +the swap, after the drain, restarts the drained provider on the installed +release; when another provider took the instance lock during the drain, it is +not signalled and the service stays drained. Steps are in [installation → Roll back to the previous release](./installation.md#roll-back-to-the-previous-release). See [installation → Update](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/docs/provider/installation.md). diff --git a/docs/threat-model.yaml b/docs/threat-model.yaml index 901638c936..71365b34b2 100644 --- a/docs/threat-model.yaml +++ b/docs/threat-model.yaml @@ -1889,11 +1889,15 @@ threats: predecessor verification and the same single-slot exact-version quarantine; it also refuses an installed bundle that differs from the recorded release and never rolls back one Mac of a cluster pair. - Cluster membership and the provider's state are decided under the - update lease (the lease a pair's coordinated update holds), and the - cluster service lock and, for a stopped provider, the provider - instance lock are held until the swap is done, so neither a cluster - service nor a foreground provider can start mid-swap. + Cluster membership (a running cluster service, a loaded cluster + service login agent, a cluster member job), the provider's state + (by process identity) and the plan are decided under the update + lease, the lease a pair's coordinated update holds from its check + through its install, before the drain. At the swap the cluster + service lock and the provider instance lock are held (or the latter + stays with the drained service process) until the swap is done, so + neither a cluster service nor another provider can start mid-swap; + another holder refuses the rollback without signalling it. status: implemented - description: > Bounded watchdog network I/O (URLSession request/resource timeouts) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index 5ef8ad4b8d..6abb81a8e8 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -212,9 +212,12 @@ public final class ClusterService: @unchecked Sendable { /// cannot be opened. `darkbloom update --rollback` holds it across its swap, so this Mac cannot join a pair while /// its release changes. public static func holdStopped(operation: String) throws -> UpdateProcessLock? { - let lockFile = try paths().lock + try holdStopped(operation: operation, lockFile: try paths().lock) + } + + static func holdStopped(operation: String, lockFile: URL) throws -> UpdateProcessLock? { try ClusterConfigurationFiles.ensureDirectory(lockFile.deletingLastPathComponent(), create: true, privateMode: true) - return try UpdateProcessLock.acquireUnlessBusy(at: lockFile, operation: operation) + return try UpdateProcessLock.attempt(at: lockFile, operation: operation).lock } private static func running(in directory: URL) -> Bool? { diff --git a/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift b/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift index 9eb0daedfb..4ab6f10850 100644 --- a/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift +++ b/provider-swift/Sources/ProviderCore/Service/ProcessLifecycle.swift @@ -66,11 +66,11 @@ public enum ProcessLifecycle { } /// Holds the provider instance lock without becoming the provider, so no provider (launchd or foreground) starts - /// until the hold is released: its `acquireSingleInstanceLock` fails as busy. Nil when a provider holds it; - /// throws when the lock cannot be opened. + /// until the hold is released: its `acquireSingleInstanceLock` fails as busy. Busy, with the provider that holds + /// it, while one runs; throws when the lock cannot be opened. public static func holdStartsOut(operation: String, - at pidFile: URL = ProcessLifecycle.defaultPIDFile()) throws -> UpdateProcessLock? { - try UpdateProcessLock.acquireUnlessBusy(at: pidFile.appendingPathExtension("lock"), operation: operation) + at pidFile: URL = ProcessLifecycle.defaultPIDFile()) throws -> UpdateProcessLock.Attempt { + try UpdateProcessLock.attempt(at: pidFile.appendingPathExtension("lock"), operation: operation) } public static func existingPID(at pidFile: URL = ProcessLifecycle.defaultPIDFile()) -> Int32? { diff --git a/provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift b/provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift index 422c48f1a0..dfd8d25c86 100644 --- a/provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift +++ b/provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift @@ -104,17 +104,22 @@ extension SelfUpdater { generation: generation) } - /// Carries out a confirmed `plan` while the caller holds `session` (for a - /// running provider, the lease its drain took). Returns the restored version. - @discardableResult - public func rollBackToPredecessor(session: UpdateSession, plan: RollbackPlan) throws -> String { + /// Under `session`: `plan`, confirmed without the lease, still holds. A + /// promotion since then is the same rollback; any other install or + /// rollback is not (`changedSinceConfirmation`). + public func confirmRollbackPlan(_ plan: RollbackPlan, session: UpdateSession) throws { try session.recover(now: now()) - // The plan was confirmed without the lease. A promotion since then is - // the same rollback; any other install or rollback is not. let current = try rollbackPlan(session: session) guard current.from == plan.from, current.to == plan.to, current.generation == plan.generation else { throw RollbackRefusal.changedSinceConfirmation(installed: current.from, predecessor: current.to) } + } + + /// Carries out a confirmed `plan` while the caller holds `session` (for a + /// running provider, the lease its drain took). Returns the restored version. + @discardableResult + public func rollBackToPredecessor(session: UpdateSession, plan: RollbackPlan) throws -> String { + try confirmRollbackPlan(plan, session: session) let reason = "rolled back by the operator to v\(plan.to) (\(BuildEnvironment.current.cliName) update --rollback)" do { return try session.rollback(now: now(), reason: reason) diff --git a/provider-swift/Sources/ProviderCore/Update/UpdateProcessLock.swift b/provider-swift/Sources/ProviderCore/Update/UpdateProcessLock.swift index 43ac537783..af0b86b885 100644 --- a/provider-swift/Sources/ProviderCore/Update/UpdateProcessLock.swift +++ b/provider-swift/Sources/ProviderCore/Update/UpdateProcessLock.swift @@ -136,15 +136,27 @@ public final class UpdateProcessLock: @unchecked Sendable { return UpdateProcessLock(descriptor: descriptor, path: path, owner: owner) } - /// One try: nil when another process holds the lock, thrown otherwise. - public static func acquireUnlessBusy(at path: URL, operation: String) throws -> UpdateProcessLock? { - do { - return try acquire(at: path, operation: operation) - } catch LockError.busy { + /// One try at the lock: acquired, or busy with the owner the holder recorded. + public enum Attempt: Sendable { + case acquired(UpdateProcessLock) + case busy(Owner?) + + /// The lock when acquired; nil when another process holds it. + public var lock: UpdateProcessLock? { + if case .acquired(let lock) = self { return lock } return nil } } + /// One try: thrown only when the lock cannot be opened or taken for another reason than contention. + public static func attempt(at path: URL, operation: String) throws -> Attempt { + do { + return .acquired(try acquire(at: path, operation: operation)) + } catch LockError.busy(let owner) { + return .busy(owner) + } + } + /// Owner-local check that this object's retained kernel lock still names /// the canonical file. A path snapshot alone cannot prove descriptor custody. func requireHeld() throws { diff --git a/provider-swift/Sources/darkbloom/UpdateCommand.swift b/provider-swift/Sources/darkbloom/UpdateCommand.swift index 21d47d60a5..1044fffe80 100644 --- a/provider-swift/Sources/darkbloom/UpdateCommand.swift +++ b/provider-swift/Sources/darkbloom/UpdateCommand.swift @@ -67,6 +67,11 @@ struct Update: AsyncParsableCommand { let updater = SelfUpdater(coordinatorBaseURL: coordinatorURL) if rollback { + // Run as root, the locks it creates in this home would be root's, and the user's provider and cluster + // service could no longer take them. + guard geteuid() != 0 else { + throw ValidationError("Run `\(BuildEnvironment.current.cliName) update --rollback` as the user the provider runs as, not as root.") + } try await UpdateRollback( updater: updater, host: .live(drain: drain, configPath: configOptions.config), diff --git a/provider-swift/Sources/darkbloom/UpdateRollback.swift b/provider-swift/Sources/darkbloom/UpdateRollback.swift index c9a2b244d2..7889e6d744 100644 --- a/provider-swift/Sources/darkbloom/UpdateRollback.swift +++ b/provider-swift/Sources/darkbloom/UpdateRollback.swift @@ -10,24 +10,28 @@ import ProviderCore /// restarts. /// /// Exclusion (R4-1729-A). The plan and the prompt run without any lock, so -/// everything they checked is decided again once the command holds the update -/// lease, before anything changes, and stays true until the swap is done: +/// once the command holds the update lease it decides everything again: /// - The update lease (`SelfUpdater.beginUpdateSession`) is the one every -/// install mutation takes: a pair's coordinated update for its whole cycle -/// (`ClusterPairUpdateCycle`, "cluster-auto-update") and its candidate -/// recovery, the watchdog, the in-process auto-update, `darkbloom update`, -/// and every `start`, `stop` and `restart` drain, including the one that -/// installs a cluster member job. A rollback and a pair update never -/// interleave: whichever takes the lease second is refused or waits for the -/// next update slot. -/// - A cluster service starts without the update lease, so under the lease the -/// command also holds the cluster service lock (`ClusterService.holdStopped`) -/// until the swap is done, and refuses when this Mac serves in a pair. -/// - The provider is read again under the lease. One started since the plan, -/// or replaced by a foreground provider (service to foreground), is refused -/// before the drain. A provider that is not running is kept from starting -/// until the swap is done (`ProcessLifecycle.holdStartsOut`); a foreground -/// start takes no update lease. +/// install mutation takes: a pair's coordinated update from its check +/// through its install (`ClusterPairUpdateCycle`, "cluster-auto-update") and +/// its candidate recovery, the watchdog, the in-process auto-update, +/// `darkbloom update`, and every `start`, `stop` and `restart` drain, +/// including the one that installs a cluster member job. A rollback and a +/// pair update never mutate the install at once. +/// - Before the drain, under the lease, every refusal leaves the Mac as it +/// was: this Mac serves in a pair (a running cluster service, a loaded +/// cluster service login agent, which also covers a pair cycle's restart +/// after it gave the lease back, or a cluster member job); a provider runs +/// outside its launchd service, also one that replaced the service while the +/// prompt was open (classified by process identity, `classify`); a provider +/// started since the plan; or the installed release changed since the plan. +/// - At the swap, the command decides again what the drain could have let +/// change, and holds it until the swap is done: the cluster service lock +/// (`ClusterService.holdStopped`; a cluster service starts without the +/// lease) and the provider instance lock (`ProcessLifecycle.holdStartsOut`; +/// a foreground start takes no lease). The instance lock may instead stay +/// with the drained service process itself; held by any other process, the +/// rollback is refused and that process is never signalled. struct UpdateRollback { /// This Mac's provider service, injected so tests never reach launchd. enum Provider { @@ -41,13 +45,15 @@ struct UpdateRollback { struct Host { /// A `darkbloom cluster` service runs or its login agent is loaded, or the provider job runs a cluster member. var servesInCluster: () -> Bool - /// Called under the update lease: holds this Mac's cluster service from starting until released, or nil when - /// this Mac serves in a cluster pair (as `servesInCluster`). + /// At the swap, under the update lease: holds this Mac's cluster service from starting until released, or nil + /// when this Mac serves in a cluster pair (as `servesInCluster`). var holdClusterOut: () throws -> UpdateProcessLock? var provider: () -> Provider - /// Called under the update lease for a provider that is not running: holds every provider start (launchd or - /// foreground) out until released, or nil when a provider holds its instance lock. - var holdProviderStartsOut: () throws -> UpdateProcessLock? + /// The launchd provider service's process, which the drain drains (nil when none runs). + var serviceProcess: () -> ProcessIdentity? + /// At the swap, under the update lease: one try at the provider instance lock, which keeps every provider + /// start (launchd or foreground) out while held. + var holdProviderStartsOut: () throws -> UpdateProcessLock.Attempt var canAsk: () -> Bool var readAnswer: () -> String? /// Drains the running provider service. Called while the command holds the update lease. @@ -84,7 +90,7 @@ struct UpdateRollback { `\(cli) update --rollback` again to drain and restart it. """ - private static var cli: String { BuildEnvironment.current.cliName } + fileprivate static var cli: String { BuildEnvironment.current.cliName } /// The update lease's operation, and the owner the cluster service and provider holds name. static let operation = "operator-rollback" @@ -112,29 +118,31 @@ struct UpdateRollback { try updater.beginUpdateSession(operation: Self.operation, timeout: 0) } defer { session.release() } - // Under the lease, before anything changes: the plan and the prompt ran - // without it. Each hold lasts until the swap is done. - guard let clusterHold = try heldOrRefused({ try host.holdClusterOut() }) else { - throw Failure(description: Self.clusterRefusal) - } - defer { clusterHold.release() } + // Under the lease, before anything changes: every refusal here leaves the Mac as it was. + guard !host.servesInCluster() else { throw Failure(description: Self.clusterRefusal) } let providerNow = host.provider() guard providerNow != .foreground else { throw Failure(description: Self.foregroundRefusal) } guard loaded || providerNow == .stopped else { throw Failure(description: Self.startedRefusal) } + try await refusingClearly { try updater.confirmRollbackPlan(plan, session: session) } // A provider stopped since the plan is swapped without a restart. let restarts = providerNow == .service - var startsHold: UpdateProcessLock? - if restarts { - try await host.drain() - } else { - guard let hold = try heldOrRefused({ try host.holdProviderStartsOut() }) else { - throw Failure(description: Self.startedRefusal) - } - startsHold = hold + let drained = restarts ? host.serviceProcess() : nil + if restarts { try await host.drain() } + + // At the swap: what the drain let change is decided again and held until the swap is done. + let outcome: Result + do { + let holds = try holdStartsOut(drained: drained, drainedService: restarts) + defer { holds.forEach { $0.release() } } + outcome = Result { try updater.rollBackToPredecessor(session: session, plan: plan) } + } catch let refusal as ForeignStart { + throw Failure(description: refusal.description) + } catch let refusal where !restarts { + // Nothing was drained: the refusal stands as it is. + throw refusal + } catch { + outcome = .failure(error) } - let outcome = Result { try updater.rollBackToPredecessor(session: session, plan: plan) } - startsHold?.release() - clusterHold.release() // A drained provider restarts whether or not the rollback completed: // the layout is always one complete release (the journal guarantees it). var restartFailure: Error? @@ -182,15 +190,63 @@ struct UpdateRollback { ] } - /// A hold that could not be taken for another reason than contention refuses with nothing changed. - private func heldOrRefused(_ take: () throws -> UpdateProcessLock?) throws -> UpdateProcessLock? { + /// Another process took the provider instance lock while the service drained. Nothing is swapped, and the + /// drained service is not restarted: its restart would signal that process. + struct ForeignStart: Error, CustomStringConvertible { + let owner: String + var description: String { + "\(owner) started outside the provider service while it drained. Nothing was swapped. The service stays " + + "drained with automatic restart off; stop that process, then run `\(UpdateRollback.cli) restart` or " + + "`\(UpdateRollback.cli) update --rollback` again." + } + } + + /// At the swap, under the update lease: holds the cluster service lock and, unless the drained service process + /// still holds it, the provider instance lock. Every hold is released by the caller once the swap is done. + private func holdStartsOut(drained: ProcessIdentity?, drainedService: Bool) throws -> [UpdateProcessLock] { + guard let cluster = try heldOrRefused({ try host.holdClusterOut() }) else { + throw Failure(description: drainedService + ? "This Mac started serving in a two-Mac cluster while the provider drained. Nothing was swapped." + : Self.clusterRefusal) + } + let starts: UpdateProcessLock.Attempt + do { + starts = try heldOrRefused({ try host.holdProviderStartsOut() }) + } catch { + cluster.release() + throw error + } + switch starts { + case .acquired(let hold): + return [cluster, hold] + case .busy(let owner): + // The drained service still runs and holds its instance lock: no other provider can start either. + if drainedService, let drained, owner?.processIdentity == drained { return [cluster] } + cluster.release() + let holder = owner.map { "A provider (pid \($0.pid))" } ?? "A provider" + if drainedService { throw ForeignStart(owner: holder) } + throw Failure(description: "\(holder) holds the provider instance lock. Nothing was changed; stop it, then " + + "run `\(Self.cli) update --rollback` again.") + } + } + + /// A hold that could not be taken for another reason than contention refuses before the swap. + private func heldOrRefused(_ take: () throws -> Value) throws -> Value { do { return try take() } catch { - throw Failure(description: "The rollback could not lock out a concurrent start (\(error)). Nothing was changed.") + throw Failure(description: "The rollback could not lock out a concurrent start (\(error)). Nothing was swapped.") } } + /// The provider as the rollback treats it: a live process recorded in the daemon state that is not the launchd + /// job's process runs in the foreground, even beside a loaded job (a crashed job stays loaded; `start + /// --foreground` does not unload it). Otherwise a loaded job is the service, and nothing else runs. + static func classify(loaded: Bool, recorded: ProcessIdentity?, launch: ProcessIdentity?) -> Provider { + if let recorded, recorded != launch { return .foreground } + return loaded ? .service : .stopped + } + /// Lease contention and every rollback refusal print as one plain line. private func refusingClearly(_ body: () async throws -> Value) async throws -> Value { do { @@ -221,9 +277,11 @@ extension UpdateRollback.Host { return hold }, provider: { - if LaunchAgent.isLoaded() { return .service } - return DaemonStateFile.read()?.processIdentity?.isCurrent() == true ? .foreground : .stopped + let recorded = DaemonStateFile.read()?.processIdentity.flatMap { $0.isCurrent() ? $0 : nil } + return UpdateRollback.classify(loaded: LaunchAgent.isLoaded(), recorded: recorded, + launch: LaunchAgent.launchSnapshot()?.process) }, + serviceProcess: { LaunchAgent.launchSnapshot()?.process }, holdProviderStartsOut: { try ProcessLifecycle.holdStartsOut(operation: UpdateRollback.operation) }, canAsk: { isatty(STDIN_FILENO) != 0 }, readAnswer: { readLine() }, diff --git a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift index da6618b9c8..81e7643d06 100644 --- a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift @@ -220,7 +220,7 @@ struct UpdateRollbackCommandTests { let racing = RecordingHost(install: install, loaded: false, providerHoldsInstanceLock: true) let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: racing, yes: true) } - #expect(error?.description == UpdateRollback.startedRefusal) + #expect(error?.description.contains("holds the provider instance lock. Nothing was changed") == true) #expect(try install.liveBinary() == "2.0.0-darkbloom") #expect(try install.store.loadState().quarantine == nil) @@ -242,9 +242,90 @@ struct UpdateRollbackCommandTests { let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: host, yes: true) } #expect(error?.description.contains("could not lock out a concurrent start") == true) + #expect(host.events == ["drain", "restart"], "decided at the swap: the drained provider restarts") + #expect(try install.liveBinary() == "2.0.0-darkbloom") + } + + // Independent review of R4-1729-A: what the drain could let change is decided again at the swap. + + @Test("a cluster pair that forms during the drain is refused at the swap, and the drained provider restarts") + func clusterFormsDuringTheDrain() async throws { + let install = try RollbackInstall() + defer { install.remove() } + let probe = Probe() + let host = RecordingHost(install: install, loaded: true, answer: "y", beforeDrain: { probe.joinCluster?() }) + probe.joinCluster = { host.joinCluster() } + + let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: host, yes: true) } + + #expect(error?.description.contains("started serving in a two-Mac cluster while the provider drained") == true) + #expect(host.events == ["drain", "restart"]) + #expect(try install.liveBinary() == "2.0.0-darkbloom") + #expect(try install.store.loadState().quarantine == nil) + } + + @Test("the drained service may keep its instance lock over the swap; any other holder refuses without a restart") + func instanceLockAfterTheDrain() async throws { + let me = try #require(ProcessIdentity.current()) + + // The drained service still runs and holds its instance lock: the swap goes on under it. + let kept = try RollbackInstall() + defer { kept.remove() } + let serviceLock = Probe() + let drainedHolds = RecordingHost(install: kept, loaded: true, serviceProcess: me, beforeDrain: { + serviceLock.lock = try UpdateProcessLock.attempt(at: kept.providerInstanceLock, operation: "provider-instance").lock + }) + try await kept.rollback(host: drainedHolds, yes: true) + #expect(serviceLock.lock != nil) + #expect(drainedHolds.events == ["drain", "restart", "wait"]) + #expect(try kept.liveBinary() == "1.0.0-darkbloom") + serviceLock.lock?.release() + + // Another process took the lock while the service drained (here: the service is a different process). + let raced = try RollbackInstall() + defer { raced.remove() } + let foreignLock = Probe() + let foreign = RecordingHost(install: raced, loaded: true, serviceProcess: nil, beforeDrain: { + foreignLock.lock = try UpdateProcessLock.attempt(at: raced.providerInstanceLock, operation: "provider-instance").lock + }) + let error = await #expect(throws: UpdateRollback.Failure.self) { try await raced.rollback(host: foreign, yes: true) } + #expect(error?.description.contains("started outside the provider service while it drained. Nothing was swapped") == true) + #expect(foreign.events == ["drain"], "its restart would signal the other process") + #expect(try raced.liveBinary() == "2.0.0-darkbloom") + #expect(try raced.isFree(raced.clusterServiceLock)) + foreignLock.lock?.release() + try raced.updater.beginUpdateSession(operation: "lease-check").release() + } + + @Test("an install that changed during the prompt is refused before the drain") + func planChangedDuringThePromptIsRefusedBeforeTheDrain() async throws { + let install = try RollbackInstall() + defer { install.remove() } + let host = RecordingHost(install: install, loaded: true, answer: "y", onceAnswered: { + var state = try install.store.loadState() + state.installGeneration += 1 + try install.store.writeState(state) + }) + + let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: host, yes: false) } + + #expect(error?.description.contains("changed after the rollback was confirmed") == true) #expect(host.events.isEmpty) #expect(try install.liveBinary() == "2.0.0-darkbloom") } + + @Test("a foreground provider beside a loaded but dead service job is classed as foreground") + func providerClassification() throws { + let service = ProcessIdentity(pid: 100, startTimeMicros: 1) + let foreground = ProcessIdentity(pid: 200, startTimeMicros: 2) + #expect(UpdateRollback.classify(loaded: true, recorded: service, launch: service) == .service) + #expect(UpdateRollback.classify(loaded: true, recorded: nil, launch: service) == .service) + #expect(UpdateRollback.classify(loaded: true, recorded: nil, launch: nil) == .service) + #expect(UpdateRollback.classify(loaded: true, recorded: foreground, launch: nil) == .foreground) + #expect(UpdateRollback.classify(loaded: true, recorded: foreground, launch: service) == .foreground) + #expect(UpdateRollback.classify(loaded: false, recorded: foreground, launch: nil) == .foreground) + #expect(UpdateRollback.classify(loaded: false, recorded: nil, launch: nil) == .stopped) + } } /// v1 installed, then v2 installed and promoted by the updater, in a temporary root. @@ -307,7 +388,7 @@ private struct RollbackInstall { /// Whether `lock` is free now (taken and released at once). func isFree(_ lock: URL) throws -> Bool { - guard let held = try UpdateProcessLock.acquireUnlessBusy(at: lock, operation: "lock-check") else { return false } + guard let held = try UpdateProcessLock.attempt(at: lock, operation: "lock-check").lock else { return false } held.release() return true } @@ -351,9 +432,11 @@ private final class RecordingHost: @unchecked Sendable { /// `providerOnceAnswered` is the provider's state from the prompt's answer on. /// `inClusterOnceAnswered`: this Mac joins a cluster pair while the prompt is open. /// `providerHoldsInstanceLock`: a provider holds its instance lock without showing in the state file yet. + /// `serviceProcess`: the launchd service's process, which the drain drains. init(install: RollbackInstall, loaded: Bool, foreground: Bool = false, inCluster: Bool = false, canAsk: Bool = true, answer: String? = nil, providerOnceAnswered: UpdateRollback.Provider? = nil, inClusterOnceAnswered: Bool? = nil, providerHoldsInstanceLock: Bool = false, + serviceProcess: ProcessIdentity? = nil, onceAnswered: @escaping () throws -> Void = {}, beforeDrain: @escaping () throws -> Void = {}) { let log = Log() log.provider = loaded ? .service : foreground ? .foreground : .stopped @@ -365,17 +448,19 @@ private final class RecordingHost: @unchecked Sendable { servesInCluster: { log.lock.withLock { log.inCluster } }, holdClusterOut: { guard !log.lock.withLock({ log.inCluster }) else { return nil } - return try UpdateProcessLock.acquireUnlessBusy(at: install.clusterServiceLock, operation: UpdateRollback.operation) + return try UpdateProcessLock.attempt(at: install.clusterServiceLock, operation: UpdateRollback.operation).lock }, provider: { log.lock.withLock { log.provider } }, + serviceProcess: { serviceProcess }, holdProviderStartsOut: { - guard !log.lock.withLock({ log.providerHoldsInstanceLock }) else { return nil } - return try UpdateProcessLock.acquireUnlessBusy(at: install.providerInstanceLock, operation: UpdateRollback.operation) + guard !log.lock.withLock({ log.providerHoldsInstanceLock }) else { return .busy(nil) } + return try UpdateProcessLock.attempt(at: install.providerInstanceLock, operation: UpdateRollback.operation) }, canAsk: { canAsk }, readAnswer: { if let providerOnceAnswered { log.lock.withLock { log.provider = providerOnceAnswered } } if let inClusterOnceAnswered { log.lock.withLock { log.inCluster = inClusterOnceAnswered } } + try? onceAnswered() return answer }, drain: { @@ -387,10 +472,15 @@ private final class RecordingHost: @unchecked Sendable { } func say(_ line: String) { log.lock.withLock { log.lines.append(line) } } + + /// This Mac starts serving in a cluster pair from now on. + func joinCluster() { log.lock.withLock { log.inCluster = true } } } /// What a hook observed while the rollback held its locks. private final class Probe: @unchecked Sendable { var cycleRefused = false var serviceHeldOut = false + var joinCluster: (() -> Void)? + var lock: UpdateProcessLock? } diff --git a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift index c6a9bb91d3..7a5a05b748 100644 --- a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift @@ -84,10 +84,13 @@ struct UpdateRollbackEndToEndTests { let host = UpdateRollback.Host( servesInCluster: { false }, holdClusterOut: { - try UpdateProcessLock.acquireUnlessBusy(at: scratch.appendingPathComponent("service.lock"), operation: "operator-rollback") + try UpdateProcessLock.attempt(at: scratch.appendingPathComponent("service.lock"), operation: "operator-rollback").lock }, provider: { .service }, - holdProviderStartsOut: { nil }, + serviceProcess: { nil }, + holdProviderStartsOut: { + try UpdateProcessLock.attempt(at: scratch.appendingPathComponent("provider.pid.lock"), operation: "operator-rollback") + }, canAsk: { false }, readAnswer: { nil }, drain: { log.record("drain") }, diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift index dcdffc057e..add18bc74f 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProcessLifecycleTests.swift @@ -53,12 +53,16 @@ struct ProcessLifecycleTests { let pidFile = tempPIDFile() defer { ProcessLifecycle.releaseSingleInstanceLock(at: pidFile) } - let hold = try #require(try ProcessLifecycle.holdStartsOut(operation: "operator-rollback", at: pidFile)) + let hold = try #require(try ProcessLifecycle.holdStartsOut(operation: "operator-rollback", at: pidFile).lock) #expect(throws: UpdateProcessLock.LockError.self) { try ProcessLifecycle.acquireSingleInstanceLock(at: pidFile) } hold.release() try ProcessLifecycle.acquireSingleInstanceLock(at: pidFile) - // A running provider keeps the rollback's hold out in turn. - #expect(try ProcessLifecycle.holdStartsOut(operation: "operator-rollback", at: pidFile) == nil) + // A running provider keeps the rollback's hold out in turn, and names itself. + guard case .busy(let owner) = try ProcessLifecycle.holdStartsOut(operation: "operator-rollback", at: pidFile) else { + Issue.record("the rollback took a running provider's instance lock"); return + } + #expect(owner?.processIdentity == ProcessIdentity.current()) + #expect(owner?.operation == "provider-instance") } @Test("acquire is idempotent for the running process") diff --git a/provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackPlanTests.swift b/provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackPlanTests.swift index ddd147086b..b54bb87970 100644 --- a/provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackPlanTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackPlanTests.swift @@ -1,6 +1,7 @@ /// The operator rollback API behind `darkbloom update --rollback`: its plan, /// each refusal, and a failure finished under the same lease. +import Darwin import Foundation import Testing @testable import ProviderCore @@ -21,6 +22,43 @@ struct UpdateRollbackPlanTests { } } + @Test("the rollback's cluster hold keeps a cluster service out of its lock, taken as `ClusterService.run` takes it") + func clusterHoldKeepsTheServiceOut() throws { + // The resolved path: the directory check refuses a link in any component (`/var` is one). + let temporary = try #require(realpath(FileManager.default.temporaryDirectory.path, nil)) + defer { free(temporary) } + let directory = URL(fileURLWithPath: String(cString: temporary), isDirectory: true) + .appendingPathComponent("cluster-hold-\(UUID().uuidString)/cluster-setup", isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory.deletingLastPathComponent()) } + let lockFile = directory.appendingPathComponent("service.lock") + + let hold = try #require(try ClusterService.holdStopped(operation: "operator-rollback", lockFile: lockFile)) + let service = open(lockFile.path, O_RDWR | O_CREAT | O_CLOEXEC, 0o600) + #expect(service >= 0) + defer { close(service) } + #expect(flock(service, LOCK_EX | LOCK_NB) != 0, "no cluster service starts while the rollback holds it") + hold.release() + #expect(flock(service, LOCK_EX | LOCK_NB) == 0) + #expect(try ClusterService.holdStopped(operation: "operator-rollback", lockFile: lockFile) == nil, + "a running cluster service keeps the rollback out") + _ = flock(service, LOCK_UN) + } + + @Test("a plan confirmed before the lease must still hold under it") + func confirmedPlanMustStillHold() async throws { + let installed = try await InstalledUpdate.make(promote: true) + defer { Task { await installed.shutdown() } } + let plan = try installed.updater.rollbackPlan() + let session = try installed.updater.beginUpdateSession(operation: "operator-rollback") + defer { session.release() } + try installed.updater.confirmRollbackPlan(plan, session: session) + var state = try installed.store.loadState() + state.installGeneration += 1 + try installed.store.writeState(state) + #expect(throws: SelfUpdater.RollbackRefusal.self) { try installed.updater.confirmRollbackPlan(plan, session: session) } + #expect(try installed.store.loadState().quarantine == nil) + } + @Test("rolling back a pending candidate quarantines it with its failed starts") func pendingCandidateRollsBack() async throws { let installed = try await InstalledUpdate.make(promote: false) From 4d3528d08f00a14c6d458b0b84240a4baa658e5d Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 05:56:11 -0600 Subject: [PATCH 0213/1441] fix(provider): `update --rollback` drains and restarts only the service process (re-review R1, R2) - R2: the drain is told the service process captured under the lease and refuses any other running provider before anything changes (ServiceDrain.drain accepts:). - R1: the provider instance hold, when the command took it, lasts until just before the launchd relaunch, and then nothing is stopped (no provider runs). When the drained service kept the lock, its owner is checked again after the swap: if the service ended, the lock is taken then; another holder is not signalled and the service is not restarted. The relaunch never signals a process other than the drained one. Co-Authored-By: Claude Opus 5.5 --- .../Sources/darkbloom/ServiceDrain.swift | 7 +- .../Sources/darkbloom/UpdateRollback.swift | 87 ++++++++++++++----- .../UpdateRollbackCommandTests.swift | 34 +++++++- .../UpdateRollbackEndToEndTests.swift | 4 +- 4 files changed, 106 insertions(+), 26 deletions(-) diff --git a/provider-swift/Sources/darkbloom/ServiceDrain.swift b/provider-swift/Sources/darkbloom/ServiceDrain.swift index cd6d30f726..bc68588cc6 100644 --- a/provider-swift/Sources/darkbloom/ServiceDrain.swift +++ b/provider-swift/Sources/darkbloom/ServiceDrain.swift @@ -31,11 +31,16 @@ enum ServiceDrain { } /// `prepare`'s drain, for a caller that already holds the update lease and decided under it that the provider - /// service is to be drained (`darkbloom update --rollback`). + /// service is to be drained (`darkbloom update --rollback`). `accepts` decides whether a running provider is the + /// one the caller means to drain; any other is refused before anything changes. static func drain(options: DrainOptions, state: DaemonState? = DaemonStateFile.read(), + accepts: (ProcessIdentity) -> Bool = { _ in true }, withConfigurationChange: (_ setup: () throws -> Void) throws -> Void = { try $0() }) async throws { let identity = WatchdogProbe.providerIdentity(daemonState: state, launchSnapshotProcess: LaunchAgent.launchSnapshot()?.process) + if let identity, identity.isCurrent(), !accepts(identity) { + throw ValidationError("Provider process \(identity.pid) is not the provider service's process. No process or recovery setting was changed.") + } if let identity, identity.isCurrent(), !options.force { guard state?.processIdentity == identity, state?.lifecycle != nil else { throw ValidationError("This running provider does not expose graceful-drain control. Upgrade it, or explicitly use --force to interrupt it.") diff --git a/provider-swift/Sources/darkbloom/UpdateRollback.swift b/provider-swift/Sources/darkbloom/UpdateRollback.swift index 7889e6d744..100ab6a57b 100644 --- a/provider-swift/Sources/darkbloom/UpdateRollback.swift +++ b/provider-swift/Sources/darkbloom/UpdateRollback.swift @@ -56,10 +56,12 @@ struct UpdateRollback { var holdProviderStartsOut: () throws -> UpdateProcessLock.Attempt var canAsk: () -> Bool var readAnswer: () -> String? - /// Drains the running provider service. Called while the command holds the update lease. - var drain: () async throws -> Void - /// Relaunches the drained provider and rearms the watchdog. - var restart: () async throws -> Void + /// Drains the running provider service, whose process is `drained` (nil when none runs); any other running + /// provider is refused before anything changes. Called while the command holds the update lease. + var drain: (_ drained: ProcessIdentity?) async throws -> Void + /// Relaunches the drained provider and rearms the watchdog. Only `drained` may be stopped. `startsHold`: the + /// provider instance lock the command holds (no provider runs), released just before the relaunch. + var restart: (_ drained: ProcessIdentity?, _ startsHold: UpdateProcessLock?) async throws -> Void /// Waits until the relaunched provider is freshly authorized. var waitForRestart: () async throws -> Void } @@ -127,14 +129,28 @@ struct UpdateRollback { // A provider stopped since the plan is swapped without a restart. let restarts = providerNow == .service let drained = restarts ? host.serviceProcess() : nil - if restarts { try await host.drain() } + if restarts { try await host.drain(drained) } - // At the swap: what the drain let change is decided again and held until the swap is done. + // At the swap: what the drain let change is decided again and held until the swap is done. The provider + // instance hold lasts until the relaunch, so no other provider starts and none is signalled. let outcome: Result + var startsHold: UpdateProcessLock? do { let holds = try holdStartsOut(drained: drained, drainedService: restarts) - defer { holds.forEach { $0.release() } } - outcome = Result { try updater.rollBackToPredecessor(session: session, plan: plan) } + defer { holds.cluster.release() } + let swapped = Result { try updater.rollBackToPredecessor(session: session, plan: plan) } + if let starts = holds.starts { + startsHold = starts + } else { + do { + startsHold = try afterTheSwap(drained: drained, swapped: swapped) + } catch let foreign as ForeignStart { + throw foreign + } catch { + // The lock could not be opened: the restart still signals only the drained process. + } + } + outcome = swapped } catch let refusal as ForeignStart { throw Failure(description: refusal.description) } catch let refusal where !restarts { @@ -143,11 +159,13 @@ struct UpdateRollback { } catch { outcome = .failure(error) } + if !restarts { startsHold?.release() } // A drained provider restarts whether or not the rollback completed: // the layout is always one complete release (the journal guarantees it). var restartFailure: Error? if restarts { - do { try await host.restart() } catch { restartFailure = error } + do { try await host.restart(drained, startsHold) } catch { restartFailure = error } + startsHold?.release() } session.release() let notRestarted = restartFailure.map { @@ -190,20 +208,38 @@ struct UpdateRollback { ] } - /// Another process took the provider instance lock while the service drained. Nothing is swapped, and the - /// drained service is not restarted: its restart would signal that process. + /// Another process took the provider instance lock while the service drained, or during the swap. The drained + /// service is not restarted: its restart would signal that process. struct ForeignStart: Error, CustomStringConvertible { let owner: String + /// The restored version when the swap had completed. + var restored: String? var description: String { - "\(owner) started outside the provider service while it drained. Nothing was swapped. The service stays " - + "drained with automatic restart off; stop that process, then run `\(UpdateRollback.cli) restart` or " - + "`\(UpdateRollback.cli) update --rollback` again." + let what = restored.map { "Rolled back to v\($0), but \(owner.prefix(1).lowercased() + owner.dropFirst()) started outside " + + "the provider service during the swap." } + ?? "\(owner) started outside the provider service while it drained. Nothing was swapped." + return what + " The service stays drained with automatic restart off; stop that process, then run " + + "`\(UpdateRollback.cli) restart`" + (restored == nil ? " or `\(UpdateRollback.cli) update --rollback` again." : ".") + } + } + + /// The drained service kept its instance lock over the swap. If it ended meanwhile, the lock is taken now and + /// held until the relaunch; held by another process, that process is not signalled (`ForeignStart`). + private func afterTheSwap(drained: ProcessIdentity?, swapped: Result) throws -> UpdateProcessLock? { + switch try heldOrRefused({ try host.holdProviderStartsOut() }) { + case .acquired(let hold): + return hold + case .busy(let owner): + if let drained, owner?.processIdentity == drained { return nil } + throw ForeignStart(owner: owner.map { "A provider (pid \($0.pid))" } ?? "A provider", + restored: try? swapped.get()) } } /// At the swap, under the update lease: holds the cluster service lock and, unless the drained service process - /// still holds it, the provider instance lock. Every hold is released by the caller once the swap is done. - private func holdStartsOut(drained: ProcessIdentity?, drainedService: Bool) throws -> [UpdateProcessLock] { + /// still holds it, the provider instance lock (`starts`, nil when the drained process keeps it). + private func holdStartsOut(drained: ProcessIdentity?, drainedService: Bool) + throws -> (cluster: UpdateProcessLock, starts: UpdateProcessLock?) { guard let cluster = try heldOrRefused({ try host.holdClusterOut() }) else { throw Failure(description: drainedService ? "This Mac started serving in a two-Mac cluster while the provider drained. Nothing was swapped." @@ -218,10 +254,10 @@ struct UpdateRollback { } switch starts { case .acquired(let hold): - return [cluster, hold] + return (cluster, hold) case .busy(let owner): // The drained service still runs and holds its instance lock: no other provider can start either. - if drainedService, let drained, owner?.processIdentity == drained { return [cluster] } + if drainedService, let drained, owner?.processIdentity == drained { return (cluster, nil) } cluster.release() let holder = owner.map { "A provider (pid \($0.pid))" } ?? "A provider" if drainedService { throw ForeignStart(owner: holder) } @@ -285,9 +321,18 @@ extension UpdateRollback.Host { holdProviderStartsOut: { try ProcessLifecycle.holdStartsOut(operation: UpdateRollback.operation) }, canAsk: { isatty(STDIN_FILENO) != 0 }, readAnswer: { readLine() }, - drain: { try await ServiceDrain.drain(options: options) }, - restart: { - try await ServiceDrain.stopDrainedProvider(unloadService: false) + drain: { drained in try await ServiceDrain.drain(options: options, accepts: { $0 == drained }) }, + restart: { drained, startsHold in + // A held instance lock means no provider runs: there is nothing to stop. + if startsHold == nil { + let target = WatchdogProbe.providerIdentity(daemonState: DaemonStateFile.read(), + launchSnapshotProcess: LaunchAgent.launchSnapshot()?.process) + if let target, target.isCurrent(), target != drained { + throw ValidationError("provider process \(target.pid) is not the drained service's process; it was not signalled") + } + try await ServiceDrain.stopDrainedProvider(unloadService: false) + } + startsHold?.release() try LaunchAgent.restartAfterDrain() ServiceDrain.rearmWatchdog(explicitConfig: configPath) }, diff --git a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift index 81e7643d06..c3efd0f07e 100644 --- a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift @@ -297,6 +297,23 @@ struct UpdateRollbackCommandTests { try raced.updater.beginUpdateSession(operation: "lease-check").release() } + @Test("the drain is told which process it drains, and with no provider left the relaunch is asked under the start hold") + func drainedIdentityAndHoldThroughTheRelaunch() async throws { + let install = try RollbackInstall() + defer { install.remove() } + let service = ProcessIdentity(pid: 4242, startTimeMicros: 7) + // The drained service ended (a forced drain, or it exited): nothing holds the instance lock after the drain. + let host = RecordingHost(install: install, loaded: true, serviceProcess: service) + + try await install.rollback(host: host, yes: true) + + #expect(host.drainedProcess == service) + #expect(host.events == ["drain", "restart", "wait"]) + #expect(host.restartHeldStartsOut, "no provider can start between the swap and the relaunch") + #expect(try install.isFree(install.providerInstanceLock), "released once the relaunch was asked for") + #expect(try install.liveBinary() == "1.0.0-darkbloom") + } + @Test("an install that changed during the prompt is refused before the drain") func planChangedDuringThePromptIsRefusedBeforeTheDrain() async throws { let install = try RollbackInstall() @@ -422,12 +439,18 @@ private final class RecordingHost: @unchecked Sendable { var provider: UpdateRollback.Provider = .stopped var inCluster = false var providerHoldsInstanceLock = false + var drained: ProcessIdentity? + var restartHeldStartsOut = false } private let log: Log let host: UpdateRollback.Host var events: [String] { log.lock.withLock { log.events } } var said: [String] { log.lock.withLock { log.lines } } + /// The process the drain was told it drains. + var drainedProcess: ProcessIdentity? { log.lock.withLock { log.drained } } + /// The relaunch was asked for while the command still held the provider instance lock. + var restartHeldStartsOut: Bool { log.lock.withLock { log.restartHeldStartsOut } } /// `providerOnceAnswered` is the provider's state from the prompt's answer on. /// `inClusterOnceAnswered`: this Mac joins a cluster pair while the prompt is open. @@ -463,11 +486,18 @@ private final class RecordingHost: @unchecked Sendable { try? onceAnswered() return answer }, - drain: { + drain: { drained in record("drain") + log.lock.withLock { log.drained = drained } try beforeDrain() }, - restart: { record("restart") }, + restart: { _, startsHold in + record("restart") + // Whether the command still held every provider start out when it asked for the relaunch. + let held = startsHold != nil + && (try? UpdateProcessLock.attempt(at: install.providerInstanceLock, operation: "lock-check").lock) == nil + log.lock.withLock { log.restartHeldStartsOut = held } + }, waitForRestart: { record("wait") }) } diff --git a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift index 7a5a05b748..c5ba057bdb 100644 --- a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift @@ -93,8 +93,8 @@ struct UpdateRollbackEndToEndTests { }, canAsk: { false }, readAnswer: { nil }, - drain: { log.record("drain") }, - restart: { log.record("restart") }, + drain: { _ in log.record("drain") }, + restart: { _, _ in log.record("restart") }, waitForRestart: { log.record("wait") }) try await UpdateRollback(updater: updater, host: host, say: { log.say($0) }).run(skipConfirmation: command.yes) From a2d338bff08dd56609c149089cc9bb3a6dad5571 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 05:58:29 -0600 Subject: [PATCH 0214/1441] fix(provider): the rollback's relaunch signals only the drained process; tests for the new branches - ServiceDrain.stopDrainedProvider takes the drain's accepts check (ServiceDrain.requireAccepted), so the rollback's relaunch can stop only the drained service process. - ForeignStart says what the swap did when the other provider was found after it, including a failed swap's error. - Tests: a provider that takes the instance lock during the swap (no restart, not signalled), and the accepts check for the drain and the relaunch. Co-Authored-By: Claude Opus 5.5 --- .../Sources/darkbloom/ServiceDrain.swift | 16 +++++-- .../Sources/darkbloom/UpdateRollback.swift | 30 +++++++------ .../UpdateRollbackCommandTests.swift | 43 ++++++++++++++++++- 3 files changed, 70 insertions(+), 19 deletions(-) diff --git a/provider-swift/Sources/darkbloom/ServiceDrain.swift b/provider-swift/Sources/darkbloom/ServiceDrain.swift index bc68588cc6..d1926e015c 100644 --- a/provider-swift/Sources/darkbloom/ServiceDrain.swift +++ b/provider-swift/Sources/darkbloom/ServiceDrain.swift @@ -38,9 +38,7 @@ enum ServiceDrain { accepts: (ProcessIdentity) -> Bool = { _ in true }, withConfigurationChange: (_ setup: () throws -> Void) throws -> Void = { try $0() }) async throws { let identity = WatchdogProbe.providerIdentity(daemonState: state, launchSnapshotProcess: LaunchAgent.launchSnapshot()?.process) - if let identity, identity.isCurrent(), !accepts(identity) { - throw ValidationError("Provider process \(identity.pid) is not the provider service's process. No process or recovery setting was changed.") - } + try requireAccepted(identity, accepts) if let identity, identity.isCurrent(), !options.force { guard state?.processIdentity == identity, state?.lifecycle != nil else { throw ValidationError("This running provider does not expose graceful-drain control. Upgrade it, or explicitly use --force to interrupt it.") @@ -88,10 +86,13 @@ enum ServiceDrain { /// Stop only a confirmed drained owner. A PID file alone never authorizes /// signalling a process, and ordinary replacement never escalates to SIGKILL. - static func stopDrainedProvider(unloadService: Bool = true) async throws { + /// `accepts`: as for `drain`; any other running provider is refused before it is signalled. + static func stopDrainedProvider(unloadService: Bool = true, + accepts: (ProcessIdentity) -> Bool = { _ in true }) async throws { let launchIdentity = LaunchAgent.launchSnapshot()?.process let identity = WatchdogProbe.providerIdentity(daemonState: DaemonStateFile.read(), launchSnapshotProcess: LaunchAgent.launchSnapshot()?.process) + try requireAccepted(identity, accepts) // Restart must keep the service loaded until restartAfterDrain reloads // its plist. if !unloadService && identity == launchIdentity { return } @@ -109,6 +110,13 @@ enum ServiceDrain { } } + /// A running provider the caller did not mean is refused: it is neither drained nor signalled. + static func requireAccepted(_ identity: ProcessIdentity?, _ accepts: (ProcessIdentity) -> Bool, + isCurrent: (ProcessIdentity) -> Bool = { $0.isCurrent() }) throws { + guard let identity, isCurrent(identity), !accepts(identity) else { return } + throw ValidationError("Provider process \(identity.pid) is not the provider service's process; it was not drained or signalled.") + } + static func prepareForegroundReplacement(options: DrainOptions) async throws { guard let pid = ProcessLifecycle.existingPID(), pid != ProcessInfo.processInfo.processIdentifier, ProcessIdentity.read(pid: pid) != nil else { return } diff --git a/provider-swift/Sources/darkbloom/UpdateRollback.swift b/provider-swift/Sources/darkbloom/UpdateRollback.swift index 100ab6a57b..770a9533c1 100644 --- a/provider-swift/Sources/darkbloom/UpdateRollback.swift +++ b/provider-swift/Sources/darkbloom/UpdateRollback.swift @@ -212,14 +212,22 @@ struct UpdateRollback { /// service is not restarted: its restart would signal that process. struct ForeignStart: Error, CustomStringConvertible { let owner: String - /// The restored version when the swap had completed. - var restored: String? + /// The swap's result when the other process was found after it; nil when found before it. + var swapped: Result? var description: String { - let what = restored.map { "Rolled back to v\($0), but \(owner.prefix(1).lowercased() + owner.dropFirst()) started outside " - + "the provider service during the swap." } - ?? "\(owner) started outside the provider service while it drained. Nothing was swapped." + let what: String + switch swapped { + case nil: + what = "\(owner) started outside the provider service while it drained. Nothing was swapped." + case .success(let restored)?: + what = "Rolled back to v\(restored), but \(owner.lowercased()) started outside the provider service " + + "during the swap." + case .failure(let error)?: + what = "\(owner) started outside the provider service during the swap, and the rollback did not " + + "complete: \(error)." + } return what + " The service stays drained with automatic restart off; stop that process, then run " - + "`\(UpdateRollback.cli) restart`" + (restored == nil ? " or `\(UpdateRollback.cli) update --rollback` again." : ".") + + "`\(UpdateRollback.cli) restart`" + (swapped == nil ? " or `\(UpdateRollback.cli) update --rollback` again." : ".") } } @@ -231,8 +239,7 @@ struct UpdateRollback { return hold case .busy(let owner): if let drained, owner?.processIdentity == drained { return nil } - throw ForeignStart(owner: owner.map { "A provider (pid \($0.pid))" } ?? "A provider", - restored: try? swapped.get()) + throw ForeignStart(owner: owner.map { "A provider (pid \($0.pid))" } ?? "A provider", swapped: swapped) } } @@ -325,12 +332,7 @@ extension UpdateRollback.Host { restart: { drained, startsHold in // A held instance lock means no provider runs: there is nothing to stop. if startsHold == nil { - let target = WatchdogProbe.providerIdentity(daemonState: DaemonStateFile.read(), - launchSnapshotProcess: LaunchAgent.launchSnapshot()?.process) - if let target, target.isCurrent(), target != drained { - throw ValidationError("provider process \(target.pid) is not the drained service's process; it was not signalled") - } - try await ServiceDrain.stopDrainedProvider(unloadService: false) + try await ServiceDrain.stopDrainedProvider(unloadService: false, accepts: { $0 == drained }) } startsHold?.release() try LaunchAgent.restartAfterDrain() diff --git a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift index c3efd0f07e..bfd3d8159b 100644 --- a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift @@ -314,6 +314,41 @@ struct UpdateRollbackCommandTests { #expect(try install.liveBinary() == "1.0.0-darkbloom") } + @Test("a provider that takes the instance lock during the swap is not signalled, and the service is not restarted") + func foreignStartDuringTheSwap() async throws { + let install = try RollbackInstall() + defer { install.remove() } + let service = ProcessIdentity(pid: 4242, startTimeMicros: 7) + let foreign = ProcessIdentity(pid: 9, startTimeMicros: 1) + func owner(_ identity: ProcessIdentity) -> UpdateProcessLock.Owner { + .init(pid: identity.pid, processIdentity: identity, operation: "provider-instance", acquiredAt: 1) + } + // At the swap the drained service holds its lock; after it, another provider does. + let host = RecordingHost(install: install, loaded: true, serviceProcess: service, + scriptedStarts: [.busy(owner(service)), .busy(owner(foreign))]) + + let error = await #expect(throws: UpdateRollback.Failure.self) { try await install.rollback(host: host, yes: true) } + + #expect(error?.description.hasPrefix("Rolled back to v1.0.0, but a provider (pid 9) started outside the provider service during the swap.") == true) + #expect(host.events == ["drain"], "no restart: it would signal pid 9") + #expect(try install.liveBinary() == "1.0.0-darkbloom") + #expect(try install.isFree(install.clusterServiceLock)) + try install.updater.beginUpdateSession(operation: "lease-check").release() + } + + @Test("the drain and the relaunch refuse a running provider they were not told of, and act on the one they were") + func drainAndRelaunchTouchOnlyTheDrainedProcess() throws { + let service = ProcessIdentity(pid: 4242, startTimeMicros: 7) + let other = ProcessIdentity(pid: 9, startTimeMicros: 1) + let accepts = { (identity: ProcessIdentity) in identity == service } + #expect(throws: ValidationError.self) { try ServiceDrain.requireAccepted(other, accepts, isCurrent: { _ in true }) } + try ServiceDrain.requireAccepted(service, accepts, isCurrent: { _ in true }) + try ServiceDrain.requireAccepted(other, accepts, isCurrent: { _ in false }) + try ServiceDrain.requireAccepted(nil, accepts) + // The default of every other caller accepts any provider. + try ServiceDrain.requireAccepted(other, { _ in true }, isCurrent: { _ in true }) + } + @Test("an install that changed during the prompt is refused before the drain") func planChangedDuringThePromptIsRefusedBeforeTheDrain() async throws { let install = try RollbackInstall() @@ -441,6 +476,7 @@ private final class RecordingHost: @unchecked Sendable { var providerHoldsInstanceLock = false var drained: ProcessIdentity? var restartHeldStartsOut = false + var scriptedStarts: [UpdateProcessLock.Attempt] = [] } private let log: Log @@ -459,12 +495,14 @@ private final class RecordingHost: @unchecked Sendable { init(install: RollbackInstall, loaded: Bool, foreground: Bool = false, inCluster: Bool = false, canAsk: Bool = true, answer: String? = nil, providerOnceAnswered: UpdateRollback.Provider? = nil, inClusterOnceAnswered: Bool? = nil, providerHoldsInstanceLock: Bool = false, - serviceProcess: ProcessIdentity? = nil, onceAnswered: @escaping () throws -> Void = {}, + serviceProcess: ProcessIdentity? = nil, scriptedStarts: [UpdateProcessLock.Attempt] = [], + onceAnswered: @escaping () throws -> Void = {}, beforeDrain: @escaping () throws -> Void = {}) { let log = Log() log.provider = loaded ? .service : foreground ? .foreground : .stopped log.inCluster = inCluster log.providerHoldsInstanceLock = providerHoldsInstanceLock + log.scriptedStarts = scriptedStarts self.log = log let record = { (event: String) in log.lock.withLock { log.events.append(event) } } host = UpdateRollback.Host( @@ -476,6 +514,9 @@ private final class RecordingHost: @unchecked Sendable { provider: { log.lock.withLock { log.provider } }, serviceProcess: { serviceProcess }, holdProviderStartsOut: { + if let next = log.lock.withLock({ log.scriptedStarts.isEmpty ? nil : log.scriptedStarts.removeFirst() }) { + return next + } guard !log.lock.withLock({ log.providerHoldsInstanceLock }) else { return .busy(nil) } return try UpdateProcessLock.attempt(at: install.providerInstanceLock, operation: UpdateRollback.operation) }, From 8f875de39c0b842dc273516fd01749f78bb3a7b8 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:11:22 -0600 Subject: [PATCH 0215/1441] cluster: budget and headroom tests model their stated Mac, not the host LongContextLimitsTests, RequestScopedRefusalTests and PrefixCacheContractTests built an observation of a 128 GiB Mac but took the loading headroom or the prefix-cache ceiling from the Mac running the test. On a Mac with less than 96 GiB (the 48 GiB CI VM) the headroom scales down and the ceiling halves, so the asserted 128 GiB figures failed. The tests now take the margins of the Mac they describe, as decisions on an observation do. QwenStagePrefixCache.budget and refreshBudget take the ceiling as a parameter that defaults to this Mac's. Co-Authored-By: Claude Opus 5.5 --- .../Qwen/Prefix/QwenStagePrefixCache.swift | 17 +++++------ .../LongContextLimitsTests.swift | 2 +- .../PrefixCacheContractTests.swift | 28 ++++++++++++------- .../RequestScopedRefusalTests.swift | 7 +++-- 4 files changed, 32 insertions(+), 22 deletions(-) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Prefix/QwenStagePrefixCache.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Prefix/QwenStagePrefixCache.swift index d6f585a0a3..13c685f3df 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Prefix/QwenStagePrefixCache.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Prefix/QwenStagePrefixCache.swift @@ -170,12 +170,13 @@ public final class QwenStagePrefixCache: @unchecked Sendable { var captureCost: QwenStagePrefixCaptureCost? { lock.withLock { measured } } /// The budget for `roomBytes` of admissible memory left beside the - /// serving context's charge: half of it, at most `maximumBudgetBytes`, - /// rounded down to 256 MiB so the idle refresh does not move it with - /// every small drift. The serving context is never reduced for the - /// cache; the other half stays for the desktop's own drift. - public static func budget(roomBytes: Int) -> Int { - max(0, min(maximumBudgetBytes, roomBytes / 2) / budgetGranuleBytes * budgetGranuleBytes) + /// serving context's charge: half of it, at most `maximumBytes` (this + /// Mac's `maximumBudgetBytes`), rounded down to 256 MiB so the idle + /// refresh does not move it with every small drift. The serving context + /// is never reduced for the cache; the other half stays for the desktop's + /// own drift. + public static func budget(roomBytes: Int, maximumBytes: Int = QwenStagePrefixCache.maximumBudgetBytes) -> Int { + max(0, min(maximumBytes, roomBytes / 2) / budgetGranuleBytes * budgetGranuleBytes) } static let budgetGranuleBytes = 256 << 20 /// The room a memory-bound serving context leaves for the cache: one granule of budget (half the room). @@ -260,8 +261,8 @@ public final class QwenStagePrefixCache: @unchecked Sendable { /// directions, so a load during a memory dip does not keep it small for as /// long as the model stays loaded. Entries beyond a lower budget go now. /// True when the budget changed. - @discardableResult func refreshBudget(roomBytes: Int) -> Bool { - let target = Self.budget(roomBytes: roomBytes) + @discardableResult func refreshBudget(roomBytes: Int, maximumBytes: Int = QwenStagePrefixCache.maximumBudgetBytes) -> Bool { + let target = Self.budget(roomBytes: roomBytes, maximumBytes: maximumBytes) return lock.withLock { guard target != budget else { return false } budget = target; evictLocked(reserving: 0); return true diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/LongContextLimitsTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/LongContextLimitsTests.swift index 58cc1608a8..377e928158 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/LongContextLimitsTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/LongContextLimitsTests.swift @@ -195,7 +195,7 @@ struct LongContextLimitsTests { chunkSize: min(512, context - 1)).conservativeStateAndBoundaryBytes let transient = try QwenResidentPrefillTransient.bytes(geometry: geometry, stageHasAttention: true, chunkTokens: min(512, context - 1), contextTokens: context) - let required = state + transient + QwenDenseStageLoadPolicy.loadingHeadroomBytes + let required = state + transient + QwenDenseStageLoadPolicy.loadingHeadroomBytes(physicalMemoryBytes: os.physicalMemoryBytes) return try QwenDenseStageLoadPolicy.decide(os, requiredBytes: required, purpose: "test context \(context)", now: 1_100).admitted } diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/PrefixCacheContractTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/PrefixCacheContractTests.swift index 7875afbd5b..a70b706329 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/PrefixCacheContractTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/PrefixCacheContractTests.swift @@ -21,6 +21,10 @@ private func state(_ frontier: Int) -> QwenStagePrefixState { @Suite("Prompt prefix reuse contracts (two-rank, no execution)") struct PrefixCacheContractTests { + /// The budget ceiling of a 128 GiB Mac. The budget checks use it, not + /// the ceiling of the Mac running the tests, which a smaller Mac lowers. + static let ceiling128GiB = QwenStagePrefixDiskPolicy.residentCeilingBytes(physicalBytes: 128 << 30) + @Test func plannedFramesStartAtTheReusedPrefixAndSplitTheLastToken() throws { let request = try QwenLayerStageGenerationRequest(profile: prefixProfile(), requestID: UUID(), promptTokenIDs: Array(0..<50), chunkSize: 16, outputCount: 3, stopTokenIDs: []) @@ -223,9 +227,12 @@ struct PrefixCacheContractTests { @Test func theBudgetComesFromTheRoomAndTheCaptureLimitFromTheMeasuredCost() { let gib = 1 << 30 #expect(QwenStagePrefixCache.budget(roomBytes: 26 * gib) == QwenStagePrefixCache.maximumBudgetBytes) - #expect(QwenStagePrefixCache.budget(roomBytes: 6 * gib) == 3 * gib) - #expect(QwenStagePrefixCache.budget(roomBytes: -1) == 0) - #expect(QwenStagePrefixCache.budget(roomBytes: 6 * gib + 300 << 20) == 3 * gib) + // A 128 GiB Mac's ceiling (4 GiB), whatever the memory of the Mac running the test. + let ceiling = Self.ceiling128GiB + #expect(QwenStagePrefixCache.budget(roomBytes: 26 * gib, maximumBytes: ceiling) == 4 * gib) + #expect(QwenStagePrefixCache.budget(roomBytes: 6 * gib, maximumBytes: ceiling) == 3 * gib) + #expect(QwenStagePrefixCache.budget(roomBytes: -1, maximumBytes: ceiling) == 0) + #expect(QwenStagePrefixCache.budget(roomBytes: 6 * gib + 300 << 20, maximumBytes: ceiling) == 3 * gib) let cache = QwenStagePrefixCache(entryLimit: 32, budgetBytes: 8 * gib) // Unmeasured: the budget is charged. #expect(cache.captureLimit(promptCount: 20_480, chunkSize: 512) == 8 * gib) @@ -394,21 +401,22 @@ struct PrefixCacheContractTests { /// both directions: a load during a memory dip does not keep the cache /// small (and prefix reuse off on the pair) for as long as it stays loaded. @Test func theIdleRefreshFollowsTheRoomInBothDirections() { - let mib = 1 << 20 + let mib = 1 << 20, ceiling = Self.ceiling128GiB // Loaded during a dip: 256 MiB. let cache = QwenStagePrefixCache(entryLimit: 32, budgetBytes: 256 * mib) - #expect(cache.refreshBudget(roomBytes: 4_096 * mib) && cache.budgetBytes == 2_048 * mib) + #expect(cache.refreshBudget(roomBytes: 4_096 * mib, maximumBytes: ceiling) && cache.budgetBytes == 2_048 * mib) // Drift within one 256 MiB step changes nothing. - #expect(!cache.refreshBudget(roomBytes: 4_096 * mib + 100 * mib) && cache.budgetBytes == 2_048 * mib) - #expect(cache.refreshBudget(roomBytes: 64 * 1_024 * mib) - && cache.budgetBytes == QwenStagePrefixCache.maximumBudgetBytes) + #expect(!cache.refreshBudget(roomBytes: 4_096 * mib + 100 * mib, maximumBytes: ceiling) + && cache.budgetBytes == 2_048 * mib) + #expect(cache.refreshBudget(roomBytes: 64 * 1_024 * mib, maximumBytes: ceiling) && cache.budgetBytes == ceiling) // Lowered with the room: entries beyond the new budget go at once. cache.insert(scope: "s", tokens: Array(0..<100), states: [sized(50, own: 300 * mib), sized(99, own: 300 * mib)], sharedBytes: 100 * mib) #expect(cache.bytesInUse == 700 * mib) - #expect(cache.refreshBudget(roomBytes: 1_024 * mib) && cache.budgetBytes == 512 * mib) + #expect(cache.refreshBudget(roomBytes: 1_024 * mib, maximumBytes: ceiling) && cache.budgetBytes == 512 * mib) #expect(cache.bytesInUse <= 512 * mib && cache.heldFrontiers == [99]) - #expect(cache.refreshBudget(roomBytes: 0) && cache.budgetBytes == 0 && cache.count == 0 && cache.bytesInUse == 0) + #expect(cache.refreshBudget(roomBytes: 0, maximumBytes: ceiling) && cache.budgetBytes == 0 && cache.count == 0 + && cache.bytesInUse == 0) } /// Finding F4: four rotating 8K documents, each captured with its split diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/RequestScopedRefusalTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/RequestScopedRefusalTests.swift index eb604889a8..b95b1bc231 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/RequestScopedRefusalTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/RequestScopedRefusalTests.swift @@ -99,7 +99,8 @@ struct RequestScopedRefusalTests { fileBackedPages: fileBacked) let reserved = 7 * Self.gib + 921 * Self.mib let admission = try QwenDenseStageLoadPolicy.decide(observation, - requiredBytes: reserved + QwenDenseStageLoadPolicy.loadingHeadroomBytes, purpose: "Resident request", now: Mac.now) + requiredBytes: reserved + QwenDenseStageLoadPolicy.loadingHeadroomBytes(physicalMemoryBytes: observation.physicalMemoryBytes), + purpose: "Resident request", now: Mac.now) let running = try QwenDenseStageLoadPolicy.decide(observation, requiredBytes: reserved, purpose: "Resident request", now: Mac.now, floor: QwenDenseStageLoadPolicy.minimumTrulyFreeBytes) #expect(!admission.admitted && running.admitted) @@ -109,8 +110,8 @@ struct RequestScopedRefusalTests { let roundTwo = Mac.observation(freeBytes: 6 * Self.gib + 300 * Self.mib, anonymousGiB: 55, fileBackedPages: (46 * Self.gib + 819 * Self.mib) / ConstructedMac.page) #expect(try QwenDenseStageLoadPolicy.decide(roundTwo, - requiredBytes: reserved + QwenDenseStageLoadPolicy.loadingHeadroomBytes, purpose: "Resident request", - now: Mac.now).admitted) + requiredBytes: reserved + QwenDenseStageLoadPolicy.loadingHeadroomBytes(physicalMemoryBytes: roundTwo.physicalMemoryBytes), + purpose: "Resident request", now: Mac.now).admitted) // Almost all allocated: a load or reservation floor (6 GiB) would refuse; continuing does not. let full = Mac.observation(freeBytes: 512 * Self.mib, fileBackedGiB: 5, anonymousGiB: 85, inactiveFileBackedBytes: 0) #expect(!(try QwenDenseStageLoadPolicy.decide(full, requiredBytes: 100 * Self.mib, purpose: "Resident request", From 86fdc7bfc613cf81a6bd5c3c2311313ea5ef9311 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:14:22 -0600 Subject: [PATCH 0216/1441] docs: the cluster service lock and the rollback's hold of it Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 9d40490161..ad6963b272 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3572,6 +3572,14 @@ part the same key with a different file (`ClusterServiceAgent.partHealthPath`, service's heartbeat and still waits for its registration as a supervised member. An empty or absent key is passed on unchanged. +One cluster service runs per home: it holds an exclusive `flock` on +`~/.darkbloom/cluster-setup/service.lock` while it runs, and `ClusterService.running` +reports whether one holds it. `darkbloom update --rollback` takes the same lock +(`ClusterService.holdStopped`) while it swaps the installed release, so no cluster +service starts on a release that is being replaced; a service that starts then +exits as already running, and its login agent starts it again +([`darkbloom update`](../provider/cli-reference.md#darkbloom-update)). + ## Cluster service listeners follow the cable and the pairing Each Mac's cluster service answers the other Mac on two listeners: the setup From e7e017a0a16007b40171a15fcba792356df3b84b Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:16:14 -0600 Subject: [PATCH 0217/1441] ci: run the darkbloom-cluster test suites on every provider pull request DarkbloomClusterRuntimeTests runs in selections that scripts/cluster-test-plan.py defines, each in its own process through run-nested-suite.sh: base selections for every test without a switch, and opt-in selections for the tests one switch enables. Cluster Runtime Tests (three shards) runs the selections that pass on the Blacksmith macOS VM and joins the Provider Tests gate. Cluster GPU Tests (two shards) runs the rest, the long-running test and the benchmarks, and reports without failing the workflow. Cluster Focused Checks runs the runner scripts under libs/darkbloom-cluster/Tests that Cluster Metadata Checks does not, and Cluster Metadata Checks now also runs PrefillScheduleChecks in its retained native build. test-cluster-test-plan.py checks that the plan names each gated test and each runner once. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 180 ++++++------- docs/developer/test.md | 35 ++- scripts/ci-component-paths.py | 1 + scripts/cluster-test-plan.py | 380 +++++++++++++++++++++++++++ scripts/test-ci-component-paths.py | 1 + scripts/test-cluster-test-plan.py | 113 ++++++++ scripts/test-darkbloom-route.py | 5 +- scripts/test-provider-ci-workflow.py | 43 +-- 8 files changed, 638 insertions(+), 120 deletions(-) create mode 100755 scripts/cluster-test-plan.py create mode 100755 scripts/test-cluster-test-plan.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4acbb90c2b..e94669ff67 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,6 +48,12 @@ jobs: test-provider-summary macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} test-provider-sdk macos_arm64 blacksmith-12vcpu-macos-27 ${{ (github.event_name == 'push' || needs.changes.outputs.sdk == 'true') && 1 || 0 }} test-cluster-checks macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} + test-cluster-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} + test-cluster-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} + test-cluster-3 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} + test-cluster-gpu-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} + test-cluster-gpu-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} + test-cluster-focused macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} release-integrity: name: Release Integrity @@ -80,6 +86,7 @@ jobs: python3 scripts/test-provider-ci-cache.py python3 scripts/test-provider-ci-workflow.py python3 scripts/test-provider-test-shards.py + python3 scripts/test-cluster-test-plan.py python3 scripts/test-ci-component-paths.py python3 scripts/test-darkbloom-route.py python3 scripts/test-prepare-prompt-fixtures.py @@ -737,6 +744,14 @@ jobs: DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS: '12' DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT: ${{ runner.temp }}/cluster-native-metadata run: bash libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh + # Builds the bootstrap product beside the capability runner's, in the same + # retained build, before the steps below record and save it. + - name: Run prefill schedule checks + if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} + env: + DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS: '12' + DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT: ${{ runner.temp }}/cluster-native-metadata + run: bash libs/darkbloom-cluster/Tests/PrefillScheduleChecks/run.sh - name: Record source timestamps for the cluster build if: ${{ !cancelled() && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' }} run: | @@ -767,123 +782,92 @@ jobs: if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} run: bash provider-swift/Tests/ClusterOnboardingChecks/run.sh - cluster-discovery: - # TEMPORARY discovery job: learn what the Blacksmith macOS VM can run. - name: Cluster discovery (${{ matrix.part }}) - needs: [changes] - runs-on: blacksmith-12vcpu-macos-27 - timeout-minutes: 170 + test-cluster: + # DarkbloomClusterRuntimeTests in selections, each in its own process, on + # separate Macs (scripts/cluster-test-plan.py): every test without a + # switch, and the switched tests that pass on these runners. + name: Cluster Runtime Tests (shard ${{ matrix.shard }}) + needs: [changes, route] + if: ${{ needs.changes.outputs.provider == 'true' }} + runs-on: ${{ fromJSON(needs.route.outputs.routes)[format('test-cluster-{0}', matrix.shard)] }} + timeout-minutes: 60 strategy: fail-fast: false matrix: - part: ['1/4', '2/4', '3/4', '4/4', runners] + shard: [1, 2, 3] + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + submodules: recursive + - name: Build cluster test products + id: provider-ci-build + uses: ./.github/actions/provider-ci-build + with: + lane: cluster + - name: Run cluster runtime tests + if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} + timeout-minutes: 40 + env: + SHARD: ${{ matrix.shard }} + run: python3 scripts/cluster-test-plan.py run blocking "$SHARD" + + test-cluster-gpu: + # The switched cluster runtime tests these runners cannot pass, the long + # ones and the benchmarks (scripts/cluster-test-plan.py). They run and + # report on every pull request; a failure does not fail the workflow. + name: Cluster GPU Tests (non-blocking, shard ${{ matrix.shard }}) + needs: [changes, route] + if: ${{ needs.changes.outputs.provider == 'true' }} + runs-on: ${{ fromJSON(needs.route.outputs.routes)[format('test-cluster-gpu-{0}', matrix.shard)] }} + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + shard: [1, 2] steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: submodules: recursive - - name: Describe the VM - run: | - sysctl hw.memsize hw.ncpu machdep.cpu.brand_string || true - sw_vers || true - system_profiler SPDisplaysDataType || true - name: Build cluster test products id: provider-ci-build - if: ${{ matrix.part != 'runners' }} uses: ./.github/actions/provider-ci-build with: lane: cluster + - name: Run non-blocking cluster GPU tests + if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} + continue-on-error: true + timeout-minutes: 40 + env: + SHARD: ${{ matrix.shard }} + run: python3 scripts/cluster-test-plan.py run nonblocking "$SHARD" + + test-cluster-focused: + # The model-free runner scripts under libs/darkbloom-cluster/Tests that + # Cluster Metadata Checks does not run (scripts/cluster-test-plan.py). + name: Cluster Focused Checks + needs: [changes, route] + if: ${{ needs.changes.outputs.provider == 'true' }} + runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-cluster-focused'] }} + timeout-minutes: 60 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + submodules: recursive - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - if: ${{ matrix.part == 'runners' }} with: python-version: '3.12.10' - name: Select SDK 27 provider toolchain - if: ${{ matrix.part == 'runners' }} + id: toolchain run: ./scripts/prepare-provider-release-toolchain.sh - - name: Discover - if: ${{ !cancelled() }} - env: - PART: ${{ matrix.part }} - DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS: '12' - run: | - out="$RUNNER_TEMP/discovery" - mkdir -p "$out/logs" - python3 - "$out" <<'PY' - import json, os, re, subprocess, sys, time - from pathlib import Path - out = Path(sys.argv[1]); part = os.environ["PART"] - gates = {name: "1" for name in ( - "QWEN_TP_MTP_GPU", "QWEN_TP_BATCH_GPU", "QWEN_TP_AQV_GPU", "QWEN_TP_REAL_GEOMETRY_GPU", - "QWEN_TP_SHARE_PROBE_GPU", "QWEN_TP_MOE_GPU", "QWEN_TP_MOE_GPU_DIAG", "GLM53_DEPTH_INVARIANCE", - "GLM53_PAGED_KV", "GLM53_PREFIX_SSD", "GLM53_WINDOW_CENSUS", "GLM53_ROW_INVARIANCE", - "DARKBLOOM_PAGED_BENCH", "QWEN_TP_AQV_BENCH", "QWEN_TP_WIDE_BENCH", "PREFIX_RECORD_ENCODE_BENCH")} - def run(name, argv, cwd, env, timeout): - log = out / "logs" / (re.sub(r"[^A-Za-z0-9_.-]", "_", name) + ".log") - start = time.time(); status = None - with open(log, "w") as handle: - try: - status = subprocess.run(argv, cwd=cwd, env=env, stdout=handle, stderr=subprocess.STDOUT, - timeout=timeout).returncode - except subprocess.TimeoutExpired: - status = "timeout" - text = log.read_text(errors="replace") - record = {"name": name, "status": status, "seconds": round(time.time() - start, 1)} - record["passed"] = sum(int(n) for n in re.findall(r"Test run with (\d+) tests? (?:in \d+ suites? )?passed", text)) - record["failed_lines"] = [l.strip()[:300] for l in text.splitlines() - if re.search(r"(✘|error:|failed|Fatal error|signal)", l)][:40] - record["skipped"] = len(re.findall(r"(?m)^[^A-Za-z0-9]*(?:Test|Suite) .+ skipped", text)) - record["xctest"] = re.findall(r"Executed \d+ tests?, with .*", text)[-1:] - record["summary"] = re.findall(r"Test run with .*", text)[-1:] - print(json.dumps(record), flush=True) - return record - results = [] - base = dict(os.environ) - if part == "runners": - tests = Path("libs/darkbloom-cluster/Tests") - for directory in sorted(tests.iterdir()): - if (directory / "run.sh").is_file(): - argv = ["bash", str(directory / "run.sh")] - elif (directory / "run.py").is_file(): - argv = ["python3", str(directory / "run.py"), "--output", str(out / ("runner-" + directory.name))] - else: - continue - results.append(run("runner-" + directory.name, argv, None, base, 1500)) - else: - index, total = map(int, part.split("/")) - package = "libs/darkbloom-cluster" - listed = subprocess.run(["swift", "test", "list", "--skip-build"], cwd=package, - capture_output=True, text=True) - (out / "list.txt").write_text(listed.stdout + listed.stderr) - suites = sorted({f"{m.group(1)}.{m.group(2)}" for line in listed.stdout.splitlines() - if (m := re.match(r"^([^./]+)[./]([^./ ]+)", line.strip()))}) - print(f"{len(suites)} suites", flush=True) - mine = suites[index - 1::total] - for suite in mine: - module, name = suite.split(".", 1) - selector = f"^{module}[./]{name}([./]|$)" - record = run(suite, ["swift", "test", "--skip-build", "--filter", selector], package, base, 1200) - record["mode"] = "default"; results.append(record) - if record["skipped"]: - gated = run(suite + "-gated", ["swift", "test", "--skip-build", "--filter", selector], - package, {**base, **gates}, 1800) - gated["mode"] = "gated"; results.append(gated) - (out / "results.json").write_text(json.dumps(results, indent=1)) - with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: - summary.write("| name | status | seconds | passed | skipped | summary |\n|---|---|---|---|---|---|\n") - for r in results: - summary.write(f"| {r['name']} | {r['status']} | {r['seconds']} | {r['passed']} | {r['skipped']} | {(r['summary'] or r['xctest'] or [''])[0][:120]} |\n") - PY - - name: Upload discovery - if: ${{ !cancelled() }} - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: cluster-discovery-${{ strategy.job-index }} - path: ${{ runner.temp }}/discovery - retention-days: 7 + - name: Run cluster focused checks + if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} + timeout-minutes: 40 + run: python3 scripts/cluster-test-plan.py run focused 1 provider-test-gate: name: Provider Tests runs-on: ubuntu-24.04 - needs: [changes, test-provider, test-provider-summary] + needs: [changes, test-provider, test-provider-summary, test-cluster, test-cluster-focused] if: ${{ always() }} steps: - name: Require selected provider lanes or verified intentional skips @@ -892,6 +876,8 @@ jobs: PROVIDER_CHANGED: ${{ needs.changes.outputs.provider }} UNIT_RESULT: ${{ needs.test-provider.result }} SUMMARY_RESULT: ${{ needs.test-provider-summary.result }} + CLUSTER_RESULT: ${{ needs.test-cluster.result }} + CLUSTER_FOCUSED_RESULT: ${{ needs.test-cluster-focused.result }} run: | test "$CHANGES_RESULT" = success case "$PROVIDER_CHANGED" in @@ -901,6 +887,8 @@ jobs: esac test "$UNIT_RESULT" = "$expected" test "$SUMMARY_RESULT" = "$expected" + test "$CLUSTER_RESULT" = "$expected" + test "$CLUSTER_FOCUSED_RESULT" = "$expected" cache-swift: name: Swift Build + Cache diff --git a/docs/developer/test.md b/docs/developer/test.md index f34dd96624..ab4879e7c7 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-11-01 +> Last updated: 2026-11-03 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -1158,13 +1158,16 @@ with isolated fixture runners: each `provider-swift/Tests/Cluster*Checks/run.sh` `libs/darkbloom-cluster/Tests/*Checks/run.sh` and `libs/darkbloom-cluster-worker/Tests/*Checks/run.sh` prints its pass count and exits non-zero on a failure. The CI job `test-cluster-checks` (Cluster Metadata -Checks, `.github/workflows/ci.yml`) runs five of them on every pull request that +Checks, `.github/workflows/ci.yml`) runs these of them on every pull request that changes provider code: `libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh`, +`libs/darkbloom-cluster/Tests/PrefillScheduleChecks/run.sh`, `libs/darkbloom-cluster/Tests/StageMetadataChecks/run.py`, `libs/darkbloom-cluster/Tests/GPTOSSStageChecks/run.sh`, `libs/darkbloom-cluster/Tests/NemotronStageChecks/run.sh` and `provider-swift/Tests/ClusterModelProvisioningChecks/run.sh provisioning`. The -last one runs the provisioning checks only. Its download cache-policy check +job `test-cluster-focused` (Cluster Focused Checks) runs every other runner +under `libs/darkbloom-cluster/Tests`. The provisioning runner runs the +provisioning checks only. Its download cache-policy check reads how many written pages stay in the file cache, which the host's kernel and disk decide: on the hosted CI VM 0.75 of the pages written with `F_NOCACHE` stayed resident. Run `run.sh` with no argument on a Mac for that @@ -1172,10 +1175,28 @@ check. The capability runner compiles with `DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS` jobs (4 by default; CI uses 12). CI keeps its build in `DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT` between runs and restores source timestamps only for unchanged files, so SwiftPM rebuilds only -what changed. The library's XCTest targets -(`swift test --package-path libs/darkbloom-cluster`) and the worker package's -tests (built for macOS 26.2) need the GPU and exclusive device access. A -loopback or fixture pass never counts as a two-Mac hardware pass. +what changed. The worker package's tests (built for macOS 26.2) need the GPU +and exclusive device access. A loopback or fixture pass never counts as a +two-Mac hardware pass. + +CI runs the runtime test target (`DarkbloomClusterRuntimeTests`) on the +provider's Blacksmith macOS runners, in selections that +`scripts/cluster-test-plan.py` defines. Each selection runs in a process of its +own through `scripts/run-nested-suite.sh`, which fails when the selection runs +no test or skips a test. Every process starts with `MLX_QMV_BATCH_INVARIANT=1`, +as every cluster process does. + +| Selection | Job | Tests | +|---|---|---| +| Base | Cluster Runtime Tests (blocking) | Every test that needs no environment switch. The base selections pass `--skip` for the switched tests and the tests that need a model, so a test that skips there has a gate that the plan does not name | +| Opt-in | Cluster Runtime Tests (blocking) | The tests that one switch (for example `QWEN_TP_MTP_GPU=1`) enables and that pass on the CI runners | +| Opt-in | Cluster GPU Tests (non-blocking) | The switched tests that fail on the CI runners' GPU, the long-running tests and the benchmarks. The job reports their results and does not fail the workflow | +| Needs a model | None | The tests that need a model directory, an artifact or its metadata (`REQUIRES_MODEL`). CI has no model | + +`python3 scripts/test-cluster-test-plan.py` (Release Integrity) checks that the +plan names each gated test in the sources once, and each runner under +`libs/darkbloom-cluster/Tests` once. When you add an environment gate to a +runtime test, add the test to a selection or to `REQUIRES_MODEL`. Build the runtime tests once (`swift build --package-path libs/darkbloom-cluster -c release --build-tests --triple arm64-apple-macosx26.2 -Xcc -target -Xcc diff --git a/scripts/ci-component-paths.py b/scripts/ci-component-paths.py index 52b0da0610..f73b1cf9e2 100644 --- a/scripts/ci-component-paths.py +++ b/scripts/ci-component-paths.py @@ -28,6 +28,7 @@ "scripts/run-paged-kernel-tests.sh", "scripts/run-provider-test-watchdog.py", "scripts/run-exclusive-native-gpu-test.sh", "scripts/provider-test-shards.py", "scripts/provider-test-shard-weights.json", + "scripts/cluster-test-plan.py", "scripts/prepare-mimo-*-fixtures.py", "scripts/verify-*-prompt-parity.sh", "scripts/prepare-prompt-fixtures.py", "scripts/test-prepare-prompt-fixtures.py", "scripts/verify-prompt-parity.sh", "scripts/test-qwen4-packaged-resources.py", diff --git a/scripts/cluster-test-plan.py b/scripts/cluster-test-plan.py new file mode 100755 index 0000000000..59f9578b9b --- /dev/null +++ b/scripts/cluster-test-plan.py @@ -0,0 +1,380 @@ +#!/usr/bin/env python3 +"""Which CI process runs each darkbloom-cluster test, and the runner for one job shard. + +The runtime target (`DarkbloomClusterRuntimeTests`) runs in selections, each in +a process of its own (docs/developer/test.md): the base selections run every +test that needs no switch, and each opt-in selection runs only the tests one +environment switch enables. Every selection goes through +scripts/run-nested-suite.sh, which fails on zero executed tests and on any +skip. The base selections pass `--skip` for exactly the switched tests, so a +test that skips there has a gate this plan does not name. `audit` checks that +the plan names exactly the gated tests in the sources and every focused +runner under libs/darkbloom-cluster/Tests. + +Lanes: `blocking` (Cluster Runtime Tests), `nonblocking` (Cluster GPU Tests, +reported but not failing the workflow) and `focused` (Cluster Focused Checks, +the model-free runner scripts). + +Subcommands: + shards LANE print the lane's shard numbers as a JSON list + run LANE SHARD run the selections of one shard, each in its own process + audit check the plan against the sources and the workflow +""" + +import argparse +from dataclasses import dataclass, field +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import time + + +ROOT = Path(__file__).resolve().parent.parent +PACKAGE = ROOT / "libs/darkbloom-cluster" +RUNTIME_TESTS = PACKAGE / "Tests/DarkbloomClusterRuntimeTests" +WORKFLOW = ROOT / ".github/workflows/ci.yml" +NESTED_SUITE = ROOT / "scripts/run-nested-suite.sh" +MODULE = "DarkbloomClusterRuntimeTests" +LANES = ("blocking", "nonblocking", "focused") +# Every cluster process starts with this switch (ClusterQuantizedRowRouting); +# MLX reads it once per process. +PROCESS_ENVIRONMENT = {"MLX_QMV_BATCH_INVARIANT": "1"} + + +@dataclass(frozen=True) +class Selection: + name: str + lane: str + shard: int + environment: dict = field(default_factory=dict) + # Opt-in: the gated test functions the environment enables. + tests: tuple = () + # Base: these suites only, or every suite no other base selection takes. + suites: tuple | None = None + # Focused: a runner script under libs/darkbloom-cluster/Tests. + runner: str | None = None + + @property + def base(self): + return not self.tests and self.runner is None + + +QWEN_TP_MTP_GPU_TESTS = ( + "oneResidentAssistantSurvivesCreditJoinsRectanglesAndResumedSpeculation", + "nineBRatioAssistantSurvivesCreditJoinsRectanglesAndResumedSpeculation", + "finalNativeWindowStillPublishesEveryAcceptedTokenUnderSeparateCredits", + "concurrentRoundsKeepIndependentCreditsAndSurviveCohortRetirement", + "eligibleCohortCoexistsWithOrdinaryHistoryAndLogprobLanes", + "concurrentFinalWindowsDrainWithoutFurtherNativeWork", + "failedConcurrentDraftPublishesNothingAndRetainsAllRowsForCheckedRetirement", + "staggeredRowsVerifyAsOneCohortAndMatchTheirSoloRuns", + "aheadRowStopsCleanlyAndItsCohortContinues", + "batchedCohortDraftsMatchRowByRowDraftsWithOneHeadCallPerStep", + "exactDraftRowsEqualTheirSoloRunsAndThePlainTargetAtEveryWidth", + "unequalHistoriesAndKeepsDiscardRejectedSuffixesAndResumeBatchDecode", + "capturedGreedyChoicesAndContinuationMatchOrdinaryTargetColumns", + "oneProductOverManyRowsChangesQuantizedArithmetic", + "sharedWindowCallsKeepEveryRowsQuantizedArithmetic", + "everyRectangleRowEqualsItsOwnSingleRequestWindowBitwise", + "capturedCohortCannotBePartiallyFinalizedAndFaultRetiresAllRows", + "graphConstructionFailurePoisonsAllBoundRowsAndReturnsTheirStorage", + "laterDraftStepsForManyRowsEqualEachRowAlone", + "windowPositionsEqualPlainDecodeStepsBitwise", + "shortSettledWindowsEqualTheirPlainStepsBitwise", + "fusedResidualStepsKeepEveryOutputBitwise", + "decodeRowsEqualTheirSoloStepsBitwise", + "cohortHeadRowsKeepEachRowsOwnProduct", + "exactDraftProjectionsKeepEachRowsOwnProductAtQwen27Shapes", + "realAssistantAndTargetRoundsSettleBeforePublicationAndRetireAfterFault", + "boundedHistoryFlushKeepsTargetVerifiedOutputs", + "promptHistoryFlushesKeepDraftsAndBoundTheBacklog", + "capturedWindowsAllocateNoSecondHistory", + "actualHybridShardsCommitAndRetireCapturedWindows", + "pairedPrefixPreservesHybridSpeculationAndRejectsFailedDonors", + "pipelinedDraftsEmitTheSameTokensAndCollectives", + "oneRankFailingMidChainFailsBothAndRetires", + "deferredRangeCheckKeepsTheWindowAndItsHistory", + "wholeAndLayeredWindowsAreBitwise", +) + +SELECTIONS = ( + # Its CPU path is the longest suite, so it has a shard of its own. + Selection("base-batch-session", "blocking", 1, suites=("QwenTensorParallelBatchSessionTests",)), + Selection("base", "blocking", 2), + Selection("qwen-tp-batch-gpu", "blocking", 3, {"QWEN_TP_BATCH_GPU": "1"}, tests=( + "bothTilesGiveTheSameBytes", + "actualHybridShardsPreserveAttentionConvAndSSMRows", + "nineBRatioDenseShardsBatchExactly", + "routedExpertShardsBatchExactly", + "routedExpertNativeMixedSamplingKeepsRowsIndependent", + "warmHybridPrefixesPreserveConvSSMAndMixedPositions", + "ssdHybridPrefixesRestoreConvSSMAfterTheTiersReopen", + "deepRestoresEqualColdPrefillOnBothRanks", + )), + Selection("qwen-tp-batch-gpu-paged", "blocking", 3, {"QWEN_TP_BATCH_GPU": "1", "QWEN_TP_BATCH_KV": "paged"}, tests=( + "fullHistoryGatherIsOnePromptFramesTransient", + "cohortSurvivorKeepsOnlyItsOwnRows", + "routedExpertCapacityOneAndTwoKeepExactPagedLogitsAndHistory", + "capacityOneAndTwoKeepExactPagedLogitsAndHistory", + "pagesGrowMidDecodeWithoutChangingAByte", + "promptLayerSubmissionKeepsEveryBit", + )), + Selection("qwen-tp-mtp-gpu", "blocking", 3, {"QWEN_TP_MTP_GPU": "1"}, tests=QWEN_TP_MTP_GPU_TESTS), + Selection("qwen-tp-aqv-gpu", "blocking", 3, {"QWEN_TP_AQV_GPU": "1"}, tests=( + "declinesWhatItDoesNotCover", + "agreesWithTheDequantizedProduct", + "everyVectorEqualsItsOwnSingleVectorCall", + "everyLayoutGivesTheSameBits", + "swigluEqualsTwoProjectionsAndTheSwiGLU", + "swigluEqualsTheCompiledSwiGLUAtEveryGateValue", + "siluMultiplyEqualsTheUnfusedChain", + "sigmoidGateEqualsTheUnfusedChain", + "cachedGatedDeltaScalesEqualFreshOnes", + "transposedCPUSumWaitsBeforeTheCopyOnGPU", + )), + Selection("qwen-tp-moe-gpu", "blocking", 3, {"QWEN_TP_MOE_GPU": "1", "QWEN_TP_MOE_GPU_DIAG": "1"}, tests=( + "packedSharedExpertCollectiveIsBitIdenticalOnTwoGPURanks", + "packedRunsRepeatAndShortPromptsOnTwoGPURanks", + )), + Selection("qwen-tp-share-probe-gpu", "blocking", 3, {"QWEN_TP_SHARE_PROBE_GPU": "1"}, tests=( + "eachRankTimesItsShareAloneAndReleasesItsRequest", + "aRefusalOrAFailureGivesNoProbeAndKeepsNothing", + )), + Selection("glm53-prefix-ssd", "blocking", 3, {"GLM53_PREFIX_SSD": "1"}, tests=( + "aServingStageRestoresFromTheSSDExactly", + "aServingStageRestoresFromABalancedRecord", + )), + Selection("qwen-tp-real-geometry-gpu", "nonblocking", 1, {"QWEN_TP_REAL_GEOMETRY_GPU": "1"}, tests=( + "rowsEqualTheirSoloStepsAndWindowPositionsAtRealWidths", + )), + Selection("qwen-tp-mtp-gpu-wide-kernel", "nonblocking", 2, {"QWEN_TP_MTP_GPU": "1"}, tests=( + "wideKernelRowsEqualEachRowsOwnWindowCall", + )), + Selection("qwen-tp-aqv-gpu-fused-kernels", "nonblocking", 2, {"QWEN_TP_AQV_GPU": "1"}, tests=( + "residualRMSNormEqualsTheUnfusedOps", + "gatedDeltaConvolutionEqualsTheUnfusedOps", + "gatedDeltaQKNormEqualsTheUnfusedOps", + "cpuStreamSumIsBitwiseOnGPU", + "chainWithCPUHopsIsBitwiseOnGPU", + )), + Selection("glm53-paged-kv", "nonblocking", 2, {"GLM53_PAGED_KV": "1"}, tests=( + "pagedRequestsDecideAndHoldWhatContiguousOnesDo", + "pagedMediaRequestsDecideAndHoldWhatContiguousOnesDo", + )), + Selection("glm53-row-invariance", "nonblocking", 2, {"GLM53_ROW_INVARIANCE": "1"}, tests=( + "roundsAreEachRequestsOwnRound", + )), + Selection("glm53-depth-invariance", "nonblocking", 2, {"GLM53_DEPTH_INVARIANCE": "1"}, tests=( + "everyDepthAndKeptPatternIsTheDepthTwoDecode", + "loadPolicyLanesAreEachRequestAloneAtDepthTwo", + "prefillIsTheSameWithAndWithoutTheSwitch", + "unpaddedLastRoundsStayOneRowWindows", + )), + Selection("glm53-window-census", "nonblocking", 2, {"GLM53_WINDOW_CENSUS": "1"}, tests=( + "windowWidthCensus", + "sublayerCensus", + "projectionRowCensus", + )), + Selection("paged-verify-bench", "nonblocking", 2, {"DARKBLOOM_PAGED_BENCH": "1"}, tests=( + "verifyAndPrefillAttention", + )), + Selection("qwen-tp-aqv-bench", "nonblocking", 2, {"QWEN_TP_AQV_BENCH": "1"}, tests=( + "throughputAgainstMLXCalls", + )), + Selection("qwen-tp-wide-bench", "nonblocking", 2, {"QWEN_TP_WIDE_BENCH": "1"}, tests=( + "wideKernelVariantThroughput", + )), + Selection("prefix-record-encode-bench", "nonblocking", 2, {"PREFIX_RECORD_ENCODE_BENCH": "1"}, tests=( + "encodingThroughputAtTheBetaShape", + )), + *(Selection(f"focused-{name}", "focused", 1, runner=name) for name in ( + "BootstrapChecks", "CapabilityChecks", "CheckpointChecks", "DeadlineChecks", "ExitChecks", + "GLMImageAdmissionChecks", "LinkControlChecks", "LinkWorkerChecks", "NativePairChecks", + "ObservabilityChecks", "PlacementChecks", "PrefixPolicyChecks", "PreludeChecks", + "ProcessChecks", "ProtocolChecks", "QwenMediaChecks", "RemoteChecks", "SSHChecks", + "SecurityChecks", "StageTransferChecks", "StillImageChecks", "TensorParallelPlanChecks", + )), +) + +# Gated tests that need a model directory, an artifact or its metadata. CI has +# none, so no selection runs them; the base selections skip them by name. +REQUIRES_MODEL = ( + "theRegisteredArtifactReproducesItsPinnedInventory", + "thePinnedSourceEqualsTheFileBackedSource", + "theRealModelsPerTokenCharge", + "aReservationsChargeDoesNotHashTheInventory", + "eigenLabs8841HeadersMatchExactPinsAndAllStructuralCuts", + "setupStepsOnTheRealMetadata", + "packedSharedExpertCollectiveIsBitIdenticalOnTheRealArtifact", + "cohortRoundPhasesByWidthAndDraftBatching", + "completeLoadQuoteByWidth", + "perRankDecodeCompute", + "exactAndMLXDraftsOnRealPromptsAreLosslessWithTheirAcceptance", + "routedExpertDecodeStepProfile", + "oneRowRoundPhasesByOwnerCapacity", + "cohortRowsEqualTheirSoloRowsOnTheRealArtifact", + "verifyWindowRoundsByRowCount", +) +REQUIRES_MODEL_SUITES = ("GLM5NextServingMetadataTests", "GLM5NextTensorParallelMediaTowerTests") +# Gated on the GPU, not on a switch: enabled where float32 products are full +# (no TF32 on the CI VM's GPU). They run in a base selection. +HARDWARE_GATED = ("receiverCommitPrecedesProducerPublicationAndMatchesFullCachedForward",) +# Runners the Cluster Metadata Checks job runs with its retained native build. +METADATA_JOB_RUNNERS = ("GPTOSSStageChecks", "NemotronStageChecks", "PrefillScheduleChecks", "StageMetadataChecks") + + +def functions_regex(names): + return f"/(?:{'|'.join(sorted(names))})\\(" + + +def suites_regex(suites): + return f"^{MODULE}[./](?:{'|'.join(sorted(suites))})(?:[./]|$)" + + +def switched_regex(): + """Every test a base selection must not run: the switched and model-gated tests.""" + gated = [name for selection in SELECTIONS for name in selection.tests] + list(REQUIRES_MODEL) + return f"{functions_regex(gated)}|{suites_regex(REQUIRES_MODEL_SUITES)}" + + +def swift_arguments(selection): + """The run-nested-suite.sh arguments: the filter, then extra `swift test` arguments.""" + if selection.tests: + return [functions_regex(selection.tests), "--no-parallel"] + if selection.suites: + return [suites_regex(selection.suites), "--skip", switched_regex(), "--no-parallel"] + others = [suite for other in SELECTIONS if other.base and other.suites for suite in other.suites] + return [f"^{MODULE}[./]", "--skip", f"{switched_regex()}|{suites_regex(others)}", "--no-parallel"] + + +def command(selection, output): + if selection.runner is None: + return PACKAGE, [str(NESTED_SUITE), *swift_arguments(selection)] + directory = PACKAGE / "Tests" / selection.runner + if (directory / "run.py").is_file(): + return ROOT, ["python3", str(directory / "run.py"), "--output", str(output / selection.runner)] + return ROOT, ["bash", str(directory / "run.sh")] + + +def environment(selection): + switches = {name for other in SELECTIONS for name in other.environment} + values = {name: value for name, value in os.environ.items() if name not in switches} + return {**values, **PROCESS_ENVIRONMENT, **selection.environment} + + +def shards(lane): + return sorted({selection.shard for selection in SELECTIONS if selection.lane == lane}) + + +def run(lane, shard): + selected = [selection for selection in SELECTIONS if selection.lane == lane and selection.shard == shard] + if not selected: + raise ValueError(f"No selections in {lane} shard {shard}") + output = Path(tempfile.mkdtemp(prefix="cluster-runner-output-")) + rows = [] + for selection in selected: + cwd, argv = command(selection, output) + print(f"::group::{selection.name}", flush=True) + started = time.monotonic() + status = subprocess.run(argv, cwd=cwd, env=environment(selection)).returncode + seconds = time.monotonic() - started + print("::endgroup::", flush=True) + rows.append((selection.name, status, seconds)) + if status: + level = "warning" if lane == "nonblocking" else "error" + print(f"::{level}::{selection.name} failed with exit status {status}", flush=True) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a") as handle: + handle.write(f"### Cluster {lane} shard {shard}\n\n| Selection | Result | Seconds |\n|---|---|---|\n") + for name, status, seconds in rows: + handle.write(f"| {name} | {'passed' if status == 0 else 'failed'} | {seconds:.0f} |\n") + return 1 if any(status for _, status, _ in rows) else 0 + + +def gated_in_sources(directory=RUNTIME_TESTS): + """(gated test functions, gated suites, function names defined more than once).""" + functions, suites, defined = set(), set(), {} + attribute = re.compile(r"@(Test|Suite)\(") + for path in sorted(directory.glob("*.swift")): + text = path.read_text() + for match in re.finditer(r"\bfunc (\w+)\(", text): + defined[match.group(1)] = defined.get(match.group(1), 0) + 1 + for match in attribute.finditer(text): + depth, index = 0, match.end() - 1 + while True: + depth += {"(": 1, ")": -1}.get(text[index], 0) + if depth == 0: + break + index += 1 + if ".enabled(if:" not in text[match.start():index]: + continue + following = text[index + 1:] + if match.group(1) == "Test": + functions.add(re.search(r"\bfunc (\w+)\(", following).group(1)) + else: + suites.add(re.search(r"\b(?:struct|class|enum) (\w+)", following).group(1)) + repeated = {name for name, count in defined.items() if count > 1} + return functions, suites, repeated + + +def audit(): + errors = [] + planned = [name for selection in SELECTIONS for name in selection.tests] + for name in sorted({name for name in planned if planned.count(name) > 1}): + errors.append(f"{name} is in more than one selection") + named_once = planned + list(REQUIRES_MODEL) + list(HARDWARE_GATED) + functions, suites, repeated = gated_in_sources() + for name in sorted(functions - set(named_once)): + errors.append(f"Gated test {name} is in no selection, REQUIRES_MODEL or HARDWARE_GATED") + for name in sorted(set(named_once) - functions): + errors.append(f"{name} is planned but is not a gated test in {RUNTIME_TESTS.relative_to(ROOT)}") + for name in sorted(set(named_once) & repeated): + errors.append(f"{name} is defined more than once; its name does not select one test") + if suites != set(REQUIRES_MODEL_SUITES): + errors.append(f"Gated suites {sorted(suites)} differ from REQUIRES_MODEL_SUITES {sorted(REQUIRES_MODEL_SUITES)}") + names = [selection.name for selection in SELECTIONS] + if len(names) != len(set(names)) or any(selection.lane not in LANES for selection in SELECTIONS): + errors.append("Selection names must be unique and every lane known") + for lane in LANES: + if shards(lane) != list(range(1, len(shards(lane)) + 1)): + errors.append(f"{lane} shards are not numbered 1 to N: {shards(lane)}") + runners = {path.parent.name for pattern in ("*/run.sh", "*/run.py") for path in (PACKAGE / "Tests").glob(pattern)} + focused = {selection.runner for selection in SELECTIONS if selection.runner} + if runners != focused | set(METADATA_JOB_RUNNERS) or focused & set(METADATA_JOB_RUNNERS): + errors.append(f"Runners {sorted(runners)} must each be in exactly one of the focused lane " + f"{sorted(focused)} and METADATA_JOB_RUNNERS {sorted(METADATA_JOB_RUNNERS)}") + workflow = WORKFLOW.read_text() + for runner in METADATA_JOB_RUNNERS: + if f"libs/darkbloom-cluster/Tests/{runner}/run." not in workflow: + errors.append(f"{runner} is not run by the workflow") + return errors + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + commands = parser.add_subparsers(dest="command", required=True) + command_parser = commands.add_parser("shards") + command_parser.add_argument("lane", choices=LANES) + command_parser = commands.add_parser("run") + command_parser.add_argument("lane", choices=LANES) + command_parser.add_argument("shard", type=int) + commands.add_parser("audit") + args = parser.parse_args() + if args.command == "shards": + print(json.dumps(shards(args.lane))) + return 0 + if args.command == "run": + return run(args.lane, args.shard) + errors = audit() + for error in errors: + print(f"::error::{error}") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/test-ci-component-paths.py b/scripts/test-ci-component-paths.py index aa82c47eee..361863fb46 100644 --- a/scripts/test-ci-component-paths.py +++ b/scripts/test-ci-component-paths.py @@ -83,6 +83,7 @@ def test_selected_executable_dependencies_are_classified(self): "scripts/run-nested-suite.sh", "scripts/run-paged-kernel-tests.sh", "scripts/run-exclusive-native-gpu-test.sh", "scripts/provider-test-shards.py", "scripts/provider-test-shard-weights.json", + "scripts/cluster-test-plan.py", "scripts/run-provider-test-watchdog.py", "scripts/prepare-mimo-audio-fixtures.py", "scripts/prepare-mimo-provider-fixtures.py", "scripts/prepare-mimo-prompt-fixtures.py", "scripts/prepare-prompt-fixtures.py", "scripts/test-prepare-prompt-fixtures.py", diff --git a/scripts/test-cluster-test-plan.py b/scripts/test-cluster-test-plan.py new file mode 100755 index 0000000000..7a9473751d --- /dev/null +++ b/scripts/test-cluster-test-plan.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Offline checks of the cluster test plan and the jobs that run it.""" + +import importlib.util +import os +from pathlib import Path +import re +import unittest +from unittest import mock + + +ROOT = Path(__file__).resolve().parent.parent +_SPEC = importlib.util.spec_from_file_location("cluster_test_plan", ROOT / "scripts/cluster-test-plan.py") +plan = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(plan) +_SPEC = importlib.util.spec_from_file_location("provider_workflow", ROOT / "scripts/test-provider-ci-workflow.py") +workflow = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(workflow) + + +def selected(selection, test_id): + """Whether `swift test` with this selection's filter and skip runs `test_id`.""" + filter_regex, *extra = plan.swift_arguments(selection) + skip = extra[extra.index("--skip") + 1] if "--skip" in extra else None + return bool(re.search(filter_regex, test_id)) and not (skip and re.search(skip, test_id)) + + +class ClusterTestPlanTests(unittest.TestCase): + def setUp(self): + self.jobs = workflow.job_blocks(plan.WORKFLOW.read_text()) + + def test_plan_names_every_gated_test_and_runner(self): + self.assertEqual(plan.audit(), []) + + def test_every_test_runs_in_exactly_one_selection_unless_it_needs_a_model(self): + module = plan.MODULE + swift = [selection for selection in plan.SELECTIONS if selection.runner is None] + cases = {f"{module}.AnySuite/{name}(sharded:)": name for selection in swift for name in selection.tests} + cases.update({f"{module}.AnySuite/{name}()": name for name in plan.HARDWARE_GATED}) + cases.update({ + f"{module}.QwenTensorParallelBatchSessionTests/actualShardsBatchIndependentHistories()": "base-batch-session", + f"{module}.QwenTensorParallelBatchSessionTests/Nested/plainCase()": "base-batch-session", + f"{module}.PrefixCacheContractTests/plannedFramesStartAtTheReusedPrefix()": "base", + f"{module}.QwenBatchCancellationTests/testAcceptedStartStaysCharged": "base", + f"{module}.QwenTensorParallelBatchSessionTestsMore/plainCase()": "base", + }) + for test_id, owner in cases.items(): + with self.subTest(test_id=test_id): + runs = [selection for selection in swift if selected(selection, test_id)] + self.assertEqual(len(runs), 1, [selection.name for selection in runs]) + runner = runs[0] + self.assertTrue(runner.name == owner or owner in runner.tests or + (owner in plan.HARDWARE_GATED and runner.base), runner.name) + needs_model = [f"{module}.AnySuite/{name}()" for name in plan.REQUIRES_MODEL] + needs_model += [f"{module}.{suite}/anyCase()" for suite in plan.REQUIRES_MODEL_SUITES] + for test_id in needs_model: + with self.subTest(test_id=test_id): + self.assertEqual([selection.name for selection in swift if selected(selection, test_id)], []) + + def test_every_selection_runs_through_the_zero_skip_wrapper_serially(self): + for selection in plan.SELECTIONS: + with self.subTest(selection=selection.name): + cwd, argv = plan.command(selection, Path("/output")) + if selection.runner is None: + self.assertEqual(cwd, plan.PACKAGE) + self.assertEqual(argv[0], str(ROOT / "scripts/run-nested-suite.sh")) + self.assertEqual(argv[-1], "--no-parallel") + else: + self.assertEqual(cwd, ROOT) + self.assertTrue(Path(argv[1]).is_file(), argv) + + def test_each_process_has_only_its_own_switches(self): + switches = {name: "1" for selection in plan.SELECTIONS for name in selection.environment} + with mock.patch.dict(os.environ, switches): + for selection in plan.SELECTIONS: + with self.subTest(selection=selection.name): + environment = plan.environment(selection) + self.assertEqual(environment["MLX_QMV_BATCH_INVARIANT"], "1") + own = {name: value for name, value in environment.items() if name in switches} + self.assertEqual(own, selection.environment) + + def test_jobs_run_every_shard_of_their_lane(self): + jobs = {"test-cluster": "blocking", "test-cluster-gpu": "nonblocking"} + for job_id, lane in jobs.items(): + with self.subTest(job=job_id): + job = self.jobs[job_id] + matrix = re.search(r"(?m)^ shard: \[([0-9, ]+)\]$", job).group(1) + self.assertEqual([int(shard) for shard in matrix.split(",")], plan.shards(lane)) + for shard in plan.shards(lane): + self.assertIn(f" {job_id}-{shard} macos_arm64 ", self.jobs["route"]) + steps = workflow.step_blocks(job) + build = next(step for step in steps if workflow.field(step, "uses") == workflow.BUILD_ACTION) + self.assertEqual(workflow.field(build, "lane", indent=10), "cluster") + run = steps[-1] + self.assertEqual(workflow.run_command(run), f'python3 scripts/cluster-test-plan.py run {lane} "$SHARD"') + self.assertEqual(workflow.field(run, "SHARD", indent=10), "${{ matrix.shard }}") + self.assertEqual(workflow.field(run, "if"), workflow.READY) + self.assertEqual(plan.shards("focused"), [1]) + focused = workflow.step_blocks(self.jobs["test-cluster-focused"]) + self.assertEqual(workflow.run_command(focused[-1]), "python3 scripts/cluster-test-plan.py run focused 1") + self.assertIn(" test-cluster-focused macos_arm64 ", self.jobs["route"]) + + def test_only_the_gpu_job_continues_after_a_failure_and_the_gate_requires_the_others(self): + self.assertIn("continue-on-error: true", workflow.step_blocks(self.jobs["test-cluster-gpu"])[-1]) + for job_id in ("test-cluster", "test-cluster-focused"): + with self.subTest(job=job_id): + self.assertNotIn("continue-on-error:", self.jobs[job_id]) + self.assertIn(job_id, workflow.field(self.jobs["provider-test-gate"], "needs", indent=4)) + self.assertNotIn("test-cluster-gpu", self.jobs["provider-test-gate"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test-darkbloom-route.py b/scripts/test-darkbloom-route.py index f7b72158bf..e2136cc6c6 100755 --- a/scripts/test-darkbloom-route.py +++ b/scripts/test-darkbloom-route.py @@ -52,6 +52,9 @@ "test-provider-summary": ("macos_arm64", MACOS_FALLBACK, PROVIDER), "test-provider-sdk": ("macos_arm64", MACOS_FALLBACK, SDK), "test-cluster-checks": ("macos_arm64", MACOS_FALLBACK, PROVIDER), + "test-cluster": ("macos_arm64", MACOS_FALLBACK, PROVIDER), + "test-cluster-gpu": ("macos_arm64", MACOS_FALLBACK, PROVIDER), + "test-cluster-focused": ("macos_arm64", MACOS_FALLBACK, PROVIDER), }, "docs-impact.yml": { "commit-signatures": ("linux_arm64", LINUX_FALLBACK, None), @@ -68,7 +71,7 @@ "threat-model-review.yml", "bedrock-smoke.yml", "claude.yml", "codex.yml") # The plane grants a lane whole, so each shard of these jobs reads a lane of its # own, `-`, and gets a free sandbox even when the others fall back. -SHARDED = {"test-provider"} +SHARDED = {"test-provider", "test-cluster", "test-cluster-gpu"} # Master and dispatched warming feed release builds, so only PRs read the route. RUNS_ON = {"warm": "${{ github.event_name == 'pull_request' && " "fromJSON(needs.route.outputs.routes)['warm'] || 'blacksmith-12vcpu-macos-27' }}"} diff --git a/scripts/test-provider-ci-workflow.py b/scripts/test-provider-ci-workflow.py index 4ffd770041..bbd68e7628 100644 --- a/scripts/test-provider-ci-workflow.py +++ b/scripts/test-provider-ci-workflow.py @@ -235,7 +235,7 @@ def test_route_requests_exactly_one_lane_per_provider_shard(self): def test_existing_required_check_requires_every_lane_even_after_failures(self): job = self.jobs["provider-test-gate"] self.assertIn(" name: Provider Tests\n", job) - self.assertIn(" needs: [changes, test-provider, test-provider-summary]\n", job) + self.assertIn(" needs: [changes, test-provider, test-provider-summary, test-cluster, test-cluster-focused]\n", job) # Provider SDK Tests notifies after merge and never blocks this gate. self.assertNotIn("test-provider-sdk", job) self.assertIn(" if: ${{ always() }}\n", job) @@ -244,14 +244,15 @@ def test_existing_required_check_requires_every_lane_even_after_failures(self): command = run_command(step) # Prompt Parity is a step of a provider shard: its failure is UNIT_RESULT's. self.assertNotIn("test-provider-parity", job) - for unit, summary in (("success", "success"), ("failure", "success"), ("success", "failure"), - ("skipped", "success"), ("success", "skipped"), ("cancelled", "success"), - ("success", "cancelled")): - result = subprocess.run(["bash", "-e", "-c", command], - env={**os.environ, "CHANGES_RESULT": "success", "PROVIDER_CHANGED": "true", "UNIT_RESULT": unit, - "SUMMARY_RESULT": summary}, - capture_output=True, timeout=5) - self.assertEqual(result.returncode == 0, unit == summary == "success") + lanes = ("UNIT_RESULT", "SUMMARY_RESULT", "CLUSTER_RESULT", "CLUSTER_FOCUSED_RESULT") + for failed in (None, *lanes): + for outcome in ("failure", "skipped", "cancelled"): + results = {lane: outcome if lane == failed else "success" for lane in lanes} + result = subprocess.run(["bash", "-e", "-c", command], + env={**os.environ, "CHANGES_RESULT": "success", "PROVIDER_CHANGED": "true", + **results}, + capture_output=True, timeout=5) + self.assertEqual(result.returncode == 0, failed is None, results) def test_each_lane_checks_out_recursive_sources_before_its_build(self): for job_id, lane in LANES.items(): @@ -670,6 +671,7 @@ def test_cluster_metadata_runners_run_every_runner_and_fail_on_any(self): self.assertEqual(run_command(toolchain), "./scripts/prepare-provider-release-toolchain.sh") runners = { "Run worker capability checks": "bash libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh", + "Run prefill schedule checks": "bash libs/darkbloom-cluster/Tests/PrefillScheduleChecks/run.sh", "Run stage metadata checks": 'python3 libs/darkbloom-cluster/Tests/StageMetadataChecks/run.py ' '--output "$RUNNER_TEMP/stage-metadata-checks"', "Run GPT-OSS stage checks": "bash libs/darkbloom-cluster/Tests/GPTOSSStageChecks/run.sh", @@ -685,13 +687,18 @@ def test_cluster_metadata_runners_run_every_runner_and_fail_on_any(self): self.assertEqual(field(step, "if"), "${{ !cancelled() && steps.toolchain.outcome == 'success' }}") self.assertTrue((ROOT / command.split()[1]).is_file()) # The capability build may use the whole dedicated runner. - capability = named["Run worker capability checks"] - self.assertEqual(field(capability, "DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS", indent=10), "'12'") - # Its release build is restored with timestamps only for unchanged - # sources, keyed by toolchain, manifests, submodule pins and paths. - self.assertEqual(field(capability, "DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT", indent=10), - "${{ runner.temp }}/cluster-native-metadata") + # The prefill schedule runner builds its bootstrap product in the same + # retained build, before that build is recorded and saved. + for name in ("Run worker capability checks", "Run prefill schedule checks"): + native = named[name] + self.assertEqual(field(native, "DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS", indent=10), "'12'") + # Its release build is restored with timestamps only for unchanged + # sources, keyed by toolchain, manifests, submodule pins and paths. + self.assertEqual(field(native, "DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT", indent=10), + "${{ runner.temp }}/cluster-native-metadata") order = [field(step, "name", indent=6) for step in steps] + self.assertLess(order.index("Run prefill schedule checks"), + order.index("Record source timestamps for the cluster build")) restore, timestamps, record, upload = (order.index(name) for name in ( "Restore cluster metadata build", "Restore unchanged source timestamps", "Record source timestamps for the cluster build", "Upload cluster metadata build cache")) @@ -747,6 +754,7 @@ def test_composite_action_cannot_bypass_build_and_metallib_on_cache_hits(self): by_id = {field(step, "id", indent=6): step for step in steps if field(step, "id", indent=6)} provider = by_id["provider-build"] sdk = by_id["sdk-build"] + cluster = by_id["cluster-build"] metallib = by_id["metallib"] self.assertEqual(field(provider, "if", indent=6), "inputs.lane == 'provider'") self.assertEqual(field(provider, "working-directory", indent=6), "provider-swift") @@ -756,9 +764,12 @@ def test_composite_action_cannot_bypass_build_and_metallib_on_cache_hits(self): self.assertEqual(field(sdk, "working-directory", indent=6), "libs/mlx-swift-lm") self.assertIn("swift package edit --path ../mlx-swift mlx-swift", sdk) self.assertIn("swift build --build-tests", sdk) + self.assertEqual(field(cluster, "if", indent=6), "inputs.lane == 'cluster'") + self.assertEqual(field(cluster, "working-directory", indent=6), "libs/darkbloom-cluster") + self.assertIn("swift build --build-tests", cluster) self.assertIsNone(field(metallib, "if", indent=6)) self.assertIn('./scripts/stage-test-metallib.sh "$bin"', metallib) - for step in (provider, sdk, metallib): + for step in (provider, sdk, cluster, metallib): self.assertNotIn("--filter", step) self.assertNotIn("--skip", step) self.assertNotIn("cache-hit", step) From dca9a1bdd345d3bc04cc45db4f540e4274159267 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:18:52 -0600 Subject: [PATCH 0218/1441] ci: extend the Provider Tests truth table to the cluster lanes Co-Authored-By: Claude Opus 5.5 --- scripts/test-ci-component-paths.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/scripts/test-ci-component-paths.py b/scripts/test-ci-component-paths.py index 361863fb46..cbc7179bde 100644 --- a/scripts/test-ci-component-paths.py +++ b/scripts/test-ci-component-paths.py @@ -276,7 +276,7 @@ def test_detector_has_full_history_no_credentials_or_api_truncation(self): def test_provider_aggregate_exhaustive_truth_table(self): jobs = workflow.job_blocks((ROOT / ".github/workflows/ci.yml").read_text()) gate = jobs["provider-test-gate"] - self.assertIn("needs: [changes, test-provider, test-provider-summary]", gate) + self.assertIn("needs: [changes, test-provider, test-provider-summary, test-cluster, test-cluster-focused]", gate) self.assertNotIn("test-provider-sdk", gate) self.assertIn("if: ${{ always() }}", gate) self.assertNotIn("continue-on-error:", gate) @@ -284,18 +284,20 @@ def test_provider_aggregate_exhaustive_truth_table(self): for name, expression in { "CHANGES_RESULT": "needs.changes.result", "PROVIDER_CHANGED": "needs.changes.outputs.provider", "UNIT_RESULT": "needs.test-provider.result", "SUMMARY_RESULT": "needs.test-provider-summary.result", + "CLUSTER_RESULT": "needs.test-cluster.result", + "CLUSTER_FOCUSED_RESULT": "needs.test-cluster-focused.result", }.items(): self.assertIn(name + ": ${{ " + expression + " }}", step) command = workflow.run_command(step) results = ("success", "skipped", "failure", "cancelled") # Prompt Parity runs in a provider shard, so UNIT_RESULT carries it. self.assertNotIn("PARITY_RESULT", step) - for detector, changed, unit, summary in itertools.product( - results, ("true", "false", ""), results, results): + names = ("UNIT_RESULT", "SUMMARY_RESULT", "CLUSTER_RESULT", "CLUSTER_FOCUSED_RESULT") + for detector, changed, *lanes in itertools.product( + results, ("true", "false", ""), *[results] * len(names)): result = subprocess.run(["bash", "-e", "-c", command], capture_output=True, timeout=5, env={**os.environ, "CHANGES_RESULT": detector, "PROVIDER_CHANGED": changed, - "UNIT_RESULT": unit, "SUMMARY_RESULT": summary}) - lanes = (unit, summary) + **dict(zip(names, lanes))}) expected = detector == "success" and ((changed == "true" and set(lanes) == {"success"}) or (changed == "false" and set(lanes) == {"skipped"})) self.assertEqual(result.returncode == 0, expected, (detector, changed, *lanes)) From 25ae291ee8f5bc238588b9642ea29ab9efbb1c52 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:17:41 -0600 Subject: [PATCH 0219/1441] docs: Qwen TP saved-width byte figures include the prompt wavefront term #1724 measured the 8-lane LOAD figures before #1725 added the shared 367,001,600-byte merged-step term to every Qwen TP batch quote. With both merged, ClusterPlacementTensorWidthRegisteredTests prints 40,911,618,048 / 60,734,767,104 bytes reserved per rank and 54,441,306,624 / 77,998,565,888 bytes needed (composition CI run 41631482989). The width table is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index de77534ad5..db4d9e4f56 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -5573,11 +5573,13 @@ the served layout; `ClusterPlacementTensorWidthRegisteredTests`): | 64 GiB | 8 | 4 | | 96 GiB and larger | 8 | 8 | -At eight lanes, each rank of an equal split reserves 40,544,616,448 bytes at -LOAD without the assistant and 60,367,765,504 bytes with it, each lane's -prompt-prefix capture included ([prefix ownership](hardware-support.md#qwen27-tp-batch-prefix-ownership)); -with its weights and loading headroom it needs 54,074,305,024 and -77,631,564,288 bytes. Every +At eight lanes, each rank of an equal split reserves 40,911,618,048 bytes at +LOAD without the assistant and 60,734,767,104 bytes with it, each lane's +prompt-prefix capture ([prefix ownership](hardware-support.md#qwen27-tp-batch-prefix-ownership)) +and the shared 367,001,600-byte prompt wavefront term +([prompt wavefront](#qwen-tensor-parallel-prompt-wavefront)) included; with its +weights and loading headroom it needs 54,441,306,624 and 77,998,565,888 bytes. +Every registered Qwen TP row is sized the same way from its own quotes. GLM keeps its eight lanes and other families keep their defaults. From 18732bceb3a92c2d1d38150b59b03d965b8adfb5 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:26:55 -0600 Subject: [PATCH 0220/1441] test(provider): the cluster service lock is held at the swap, not through the drain The exclusion test still expected the lock held during the drain, which 9dd1501d5 (review finding M3) moved to the swap. It now checks the lease during the drain and at the swap, the lock free during the drain and held at the swap. Co-Authored-By: Claude Opus 5.5 --- .../UpdateRollbackCommandTests.swift | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift index bfd3d8159b..7959eb9343 100644 --- a/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift @@ -199,15 +199,20 @@ struct UpdateRollbackCommandTests { #expect(refused.events.isEmpty) cycle.release() - // The rollback holds the lease from the drain to the swap: a pair update cycle cannot claim it, and no - // cluster service can start. + // The rollback holds the lease from before the drain through the swap: a pair update cycle cannot claim it. + // The cluster service lock is held only at the swap, so `darkbloom cluster` and its status see no service + // for the drain's length. let probe = Probe() let host = RecordingHost(install: install, loaded: true, answer: "y", beforeDrain: { probe.cycleRefused = (try? install.updater.beginUpdateSession(operation: "cluster-auto-update")) == nil - probe.serviceHeldOut = try !install.isFree(install.clusterServiceLock) + probe.serviceFreeDuringDrain = try install.isFree(install.clusterServiceLock) + }, atTheSwap: { + probe.serviceHeldOut = (try? install.isFree(install.clusterServiceLock)) == false + probe.cycleRefusedAtSwap = (try? install.updater.beginUpdateSession(operation: "cluster-auto-update")) == nil }) try await install.rollback(host: host, yes: true) - #expect(probe.cycleRefused && probe.serviceHeldOut) + #expect(probe.cycleRefused && probe.cycleRefusedAtSwap) + #expect(probe.serviceFreeDuringDrain && probe.serviceHeldOut) #expect(try install.liveBinary() == "1.0.0-darkbloom") #expect(try install.isFree(install.clusterServiceLock)) try install.updater.beginUpdateSession(operation: "lease-check").release() @@ -497,7 +502,7 @@ private final class RecordingHost: @unchecked Sendable { inClusterOnceAnswered: Bool? = nil, providerHoldsInstanceLock: Bool = false, serviceProcess: ProcessIdentity? = nil, scriptedStarts: [UpdateProcessLock.Attempt] = [], onceAnswered: @escaping () throws -> Void = {}, - beforeDrain: @escaping () throws -> Void = {}) { + beforeDrain: @escaping () throws -> Void = {}, atTheSwap: @escaping () -> Void = {}) { let log = Log() log.provider = loaded ? .service : foreground ? .foreground : .stopped log.inCluster = inCluster @@ -514,6 +519,8 @@ private final class RecordingHost: @unchecked Sendable { provider: { log.lock.withLock { log.provider } }, serviceProcess: { serviceProcess }, holdProviderStartsOut: { + // Called at the swap, with the cluster service lock held. + atTheSwap() if let next = log.lock.withLock({ log.scriptedStarts.isEmpty ? nil : log.scriptedStarts.removeFirst() }) { return next } @@ -552,6 +559,8 @@ private final class RecordingHost: @unchecked Sendable { private final class Probe: @unchecked Sendable { var cycleRefused = false var serviceHeldOut = false + var serviceFreeDuringDrain = false + var cycleRefusedAtSwap = false var joinCluster: (() -> Void)? var lock: UpdateProcessLock? } From 34ead05025652413b1b6a4d34a06b679fe903bfb Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 05:45:28 -0600 Subject: [PATCH 0221/1441] feat(provider): the other Mac of a pair follows a rollback Owner ruling 2026-11-03 (open question 1 of #1702): when one Mac of a `darkbloom cluster` pair rolls a release back (three failed starts, a failed start check, or `darkbloom update --rollback` with its cluster service stopped), the other Mac rolls back to the same earlier release and the pair serves it together. - Each Mac's progress reports the release quarantined on it (ClusterPairUpdateProgress.quarantined), over the existing pair channel. - ClusterPairUpdateCycle.followRollback: decided under the update lease the pair's cycles hold; the other Mac must have quarantined the release this Mac runs and run the release this Mac keeps. It reuses the cycle's partner wait, pair drain, deferral and restart, and restores the predecessor with SelfUpdater.rollBackToPredecessor, quarantining the release here too. - The supervisor checks at its start and every 60 s while no cycle runs. - `update --rollback`'s cluster refusal now says the other Mac follows. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-pair-follows-rollback.md | 6 + docs/developer/test.md | 14 +- docs/provider/cli-reference.md | 5 +- docs/provider/cluster-always-on.md | 61 ++++++- docs/provider/installation.md | 10 +- .../Installed/ClusterPairUpdateProgress.swift | 7 +- .../ClusterPairUpdate.swift | 3 + .../Update/ClusterPairUpdateCycle.swift | 129 +++++++++++++- .../Update/SelfUpdater+Rollback.swift | 6 +- .../ProviderCore/Update/SelfUpdater.swift | 7 + .../darkbloom/ClusterMemberSupervisor.swift | 43 ++++- .../darkbloom/ClusterServiceCommand.swift | 8 +- .../Sources/darkbloom/UpdateRollback.swift | 8 +- .../ClusterServiceUpdateTests.swift | 42 ++++- .../Update/ClusterPairUpdateTests.swift | 167 ++++++++++++++++++ 15 files changed, 484 insertions(+), 32 deletions(-) create mode 100644 changelog.d/cluster-pair-follows-rollback.md diff --git a/changelog.d/cluster-pair-follows-rollback.md b/changelog.d/cluster-pair-follows-rollback.md new file mode 100644 index 0000000000..c4320fc4ff --- /dev/null +++ b/changelog.d/cluster-pair-follows-rollback.md @@ -0,0 +1,6 @@ +### Both Macs of a pair roll back together + +- When one Mac of a `darkbloom cluster` pair rolls a release back (three failed starts of its cluster service, a failed start check, or `darkbloom update --rollback` while its cluster service was stopped), the other Mac now rolls back to the same earlier release, and the pair serves it together. Before, the pair stayed split until a newer release updated both Macs. +- The other Mac checks at its start and every minute while no update runs, also with automatic updates off. It finishes the accepted requests of its part first, as for an update, restores the release it kept from before its last update, quarantines the rolled-back release and restarts. Both Macs then skip that release, and the next newer release updates both. +- A Mac that keeps another earlier release, or none, does not follow and says so once in `~/.darkbloom/cluster-setup/service.log`. A Mac whose partner stops answering during the follow waits at most 15 minutes, then changes nothing and tries again at the next check. +- To roll back a pair by hand, stop one Mac's cluster service with `darkbloom cluster stop`, run `darkbloom update --rollback` there, and start it again with `darkbloom cluster`; the other Mac follows. diff --git a/docs/developer/test.md b/docs/developer/test.md index f34dd96624..9827221563 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1075,8 +1075,13 @@ automatic updates off downloads nothing at the slot, while `darkbloom update` on both Macs updates them; that a part that cannot drain downloads nothing; that a Mac whose partner cannot be asked goes on alone only while no pair runs on it; the candidate's promotion (kept under another update's lease) and rollback; -the start check's verdicts on script binaries; and the rollback at once of a -candidate that failed its start check. +the start check's verdicts on script binaries; the rollback at once of a +candidate that failed its start check; and the other Mac following a rollback +(`followRollback`): after it promoted the release, while its own cycle still +holds the update lease (it waits, then follows), with the other Mac no longer +answering (bounded wait, then a deferral with nothing changed), and the +quarantine on both Macs, with no follow back and no follow to a release the Mac +does not keep. `ClusterServiceUpdateTests` (`provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift`) drives the real supervisor with a shell standing in for the cluster service: the @@ -1088,7 +1093,10 @@ rollback and promotion. The start check runs the temporary install's 1 s bound or reports another version is rolled back and quarantined without the re-exec, and the supervisor serves again from the restored binary; a release that answers is re-executed into as before; a restored predecessor that cannot -start is not re-executed into. The re-exec is observed, never performed. +start is not re-executed into. A supervisor with automatic updates off still +checks for a rollback of the other Mac to follow, reports its own quarantine in +its progress, and restarts into the restored release. The re-exec is observed, +never performed. `Tests/ClusterSupervisionChecks/run.sh` checks the progress rules (`ClusterPairUpdate.partnerState`) with plain `swiftc`. diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index b3e543f2ad..d499d590ce 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -779,7 +779,10 @@ release, the installed `Darkbloom.app` is not the recorded release, or the kept release fails its hash or signature check (`RollbackRefusal`). A refusal at the swap, after the drain, restarts the drained provider on the installed release; when another provider took the instance lock during the drain, it is -not signalled and the service stays drained. Steps are in +not signalled and the service stays drained. On a `darkbloom cluster` Mac, +stop its cluster service first; once it runs again, the other Mac follows the +rollback to the same release +([a rollback on one Mac](./cluster-always-on.md#a-rollback-on-one-mac)). Steps are in [installation → Roll back to the previous release](./installation.md#roll-back-to-the-previous-release). See [installation → Update](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/docs/provider/installation.md). diff --git a/docs/provider/cluster-always-on.md b/docs/provider/cluster-always-on.md index 8feb15d2fb..710374488c 100644 --- a/docs/provider/cluster-always-on.md +++ b/docs/provider/cluster-always-on.md @@ -172,14 +172,69 @@ loader and the frameworks it links, its code signature and the argument parser. A binary that fails is not restarted into. The supervisor counts one failed start, restores the verified predecessor and quarantines the release at once (`ClusterCandidateRecovery.recordFailedStartCheck`), and starts the cluster -service again from the restored binary. The other Mac is not rolled back with -it: if the release started there, the two Macs run different releases, and the -pair serves again once a newer release updates both. A rollback after three +service again from the restored binary. The other Mac follows that rollback +([a rollback on one Mac](#a-rollback-on-one-mac)). A rollback after three failed starts checks the restored predecessor the same way; if that check fails too, the supervisor starts the cluster service itself instead of restarting into it. A binary that passes the check but whose supervisor fails before it starts the cluster service is still not rolled back. +### A rollback on one Mac + +When one Mac of a pair rolls a release back, the other Mac rolls back to the +same earlier release, and the pair serves that release together. This answers +the question the coordinated update left open: before, the pair stayed split +(each Mac on another release, so the leader never planned it again) until a +newer release updated both Macs. + +A rollback is any of: three failed starts of the release's cluster service, a +failed start check, or `darkbloom update --rollback` run while the Mac's +cluster service was stopped. Each restores the verified predecessor and +quarantines the release on that Mac. The Mac's progress then reports the +quarantined release beside the version it runs +(`ClusterPairUpdateProgress.quarantined`), and the other Mac reads it over the +link with the rest of the progress. + +The other Mac's supervisor checks for a rollback to follow at its start and +then every `ClusterPairUpdate.followCheckSeconds` (60 s) while no update cycle +runs, also with automatic updates off: the release it restores is one the Mac +ran before. It follows (`ClusterPairUpdateCycle.followRollback`) when the other +Mac quarantined the release this Mac runs (installed or promoted) and runs the +release this Mac keeps for rollback. The follow is the update cycle's sequence +with a rollback in place of the install: + +1. It takes the update lease, the one every update cycle, candidate recovery + and `darkbloom update --rollback` take, and decides under it. Another + holder (this Mac's own cycle, still installing or restarting) makes it wait + for the next check, with nothing changed. +2. It waits until the other Mac reports the earlier release (it does already, + so this is at once), then drains this Mac's part as for an update. An other + Mac that stops answering is waited for at most + `ClusterPairUpdate.partnerStageWaitSeconds` (900 s) while a pair runs on + this Mac. The follow is then deferred with the reason `the other Mac did not + confirm it runs v within 900 s`, nothing is changed, and the next + check tries again. +3. It restores the verified predecessor and quarantines the release + (`SelfUpdater.rollBackToPredecessor`), with the reason `the other Mac of the + pair rolled v back to v; this Mac followed`. Both Macs + now keep the release quarantined: neither's update slot installs it again, + and the next newer release updates both. +4. The supervisor restarts the cluster service from the restored binary, after + the same start check as for an update. Once both Macs answer with the same + build, the leader plans the model again. + +A Mac that keeps another release for rollback, or none, cannot restore the same +release. It changes nothing and says once `cluster update: not following the +other Mac's rollback: `; the pair serves again once a newer release +updates both Macs. Other lines: `cluster update: the other Mac rolled +v back to v and quarantined it; this Mac follows to +v` and `cluster update: restored v and quarantined +v, as on the other Mac`. + +A cluster-member provider service (`darkbloom start --cluster-member +--always-on`) does not run this coordinated update and does not follow a +rollback: roll back both Macs. + After both Macs restarted, the leader's cluster service plans the same model again once both answer with the same worker build (`ClusterOnboardingUpdate.oneBuild`), and the pair registers again under the diff --git a/docs/provider/installation.md b/docs/provider/installation.md index 78d976e8b5..c357d0d2b8 100644 --- a/docs/provider/installation.md +++ b/docs/provider/installation.md @@ -223,10 +223,12 @@ in `~/.darkbloom/recovery/predecessor/` (`provider-swift/Sources/ProviderCore/Up `snapshotLiveAsPredecessor`). A release that runs but regresses can be rolled back to it on one Mac, with automatic updates left on: -1. On a Mac that serves in a `darkbloom cluster` pair, first stop the pair: - `darkbloom cluster stop` (or `darkbloom stop` for a cluster-member provider - service). Roll back both Macs, then start the pair again with - `darkbloom cluster`. The command refuses while the pair serves. +1. On a Mac that serves in a `darkbloom cluster` pair, first stop its cluster + service with `darkbloom cluster stop`, roll it back, then start it again + with `darkbloom cluster`. The other Mac follows the rollback to the same + release by itself ([the pair's coordinated update](./cluster-always-on.md#a-rollback-on-one-mac)). + For a cluster-member provider service, stop it with `darkbloom stop` and + roll back both Macs. The command refuses while the pair serves. 2. Run the rollback and answer `y`: ```bash diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPairUpdateProgress.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPairUpdateProgress.swift index f16d19d48e..1b724eb426 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPairUpdateProgress.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPairUpdateProgress.swift @@ -42,9 +42,13 @@ public struct ClusterPairUpdateProgress: Codable, Equatable, Sendable { public var request: String? public var writtenAt: Double public var detail: String? + /// The release quarantined on this Mac: one it rolled back (after failed starts, a failed start check, or + /// `darkbloom update --rollback`). The other Mac follows a rollback of the release it runs + /// (`ClusterPairUpdateCycle.followRollback`). Absent from earlier builds. + public var quarantined: String? public init(phase: Phase, target: String? = nil, running: String, cycleStartedAt: Double? = nil, - request: String? = nil, writtenAt: Double, detail: String? = nil) { + request: String? = nil, writtenAt: Double, detail: String? = nil, quarantined: String? = nil) { self.phase = phase self.target = target self.running = running @@ -52,6 +56,7 @@ public struct ClusterPairUpdateProgress: Codable, Equatable, Sendable { self.request = request self.writtenAt = writtenAt self.detail = detail + self.quarantined = quarantined } public var isEnd: Bool { phase == .deferred || phase == .failed } diff --git a/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift b/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift index e28a352959..a6f6754edf 100644 --- a/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift +++ b/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift @@ -24,6 +24,9 @@ public enum ClusterPairUpdate { public static let progressStaleSeconds: Double = 60 /// How often a supervisor in a cycle rewrites its progress and reads the other Mac's. public static let pollSeconds: Double = 5 + /// How often a supervisor with no cycle running asks whether the other Mac rolled back the release this Mac runs + /// (`ClusterPairUpdateCycle.followRollback`). + public static let followCheckSeconds: Double = 60 /// The other Mac as this Mac reads it. public enum Partner: Equatable, Sendable { diff --git a/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift b/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift index 88da167303..549768285e 100644 --- a/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift +++ b/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift @@ -10,6 +10,10 @@ import DarkbloomClusterRemote /// cancelling, when accepted work does not finish), commit, restart. Two steps differ. The drain is the pair's: it /// begins once the other Mac has the release too, and it is complete once both Macs drained. The restart is the /// supervisor's: it stops the cluster service and starts again from the installed binary. +/// +/// The same cycle follows the other Mac's rollback (`followRollback`): when the other Mac rolled back and quarantined +/// the release this Mac runs, this Mac restores the same earlier release through the same pair drain, under the same +/// update lease, and quarantines it too, so the pair serves the earlier release together. public final class ClusterPairUpdateCycle: @unchecked Sendable { public struct Timing: Sendable { public var partnerStageWait = ClusterPairUpdate.partnerStageWaitSeconds @@ -75,6 +79,8 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { private var partDrain: PartDrain? /// Why the pair cannot drain this cycle (said once, published with the deferral). private var gaveUp: String? + /// The cycle follows the other Mac's rollback to `target` instead of installing a release. + private var following = false public init(environment: Environment) { self.environment = environment @@ -85,12 +91,7 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { public func run(request: String? = nil, restart: @escaping @Sendable (String) async throws -> Void) async -> AutoUpdateController.Outcome { lock.withLock { startedAt = Self.now(); self.request = request } - let heartbeat = Task { [weak self, environment] in - while !Task.isCancelled { - await ClusterPairUpdateCycle.sleep(environment.timing.poll) - self?.rewriteProgress() - } - } + let heartbeat = startHeartbeat() let updater = environment.updater, log = environment.log let deps = AutoUpdateController.Dependencies( claimStart: { self.claim() }, @@ -115,6 +116,114 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { return outcome } + /// Keeps the working phase fresh for the other Mac until cancelled. + private func startHeartbeat() -> Task { + Task { [weak self, environment] in + while !Task.isCancelled { + await ClusterPairUpdateCycle.sleep(environment.timing.poll) + self?.rewriteProgress() + } + } + } + + // MARK: - Following the other Mac's rollback + + public enum FollowOutcome: Equatable, Sendable { + /// The other Mac quarantined no release this Mac runs (or cannot be asked): nothing was done or published. + case nothingToFollow + /// The other Mac rolled back the release this Mac runs, but this Mac cannot restore the same release (it keeps + /// another one, or none, for rollback). Nothing was changed; the pair serves again once a newer release + /// updates both Macs. + case cannotFollow(String) + /// Another update or recovery holds the update lease; the next check tries again. + case busy + /// The cycle that followed it ended as an update cycle ends: `.restarted` once the earlier release is restored + /// and the restart asked for. + case followed(AutoUpdateController.Outcome) + } + + /// The other Mac rolled back and quarantined the release this Mac runs (`ClusterPairUpdateProgress.quarantined`), + /// and runs the release this Mac keeps for rollback (`plan.to`). + public static func follows(_ partner: ClusterPairUpdate.Partner, plan: SelfUpdater.RollbackPlan) -> Bool { + guard case .reported(let progress) = partner else { return false } + return progress.quarantined == plan.from && progress.running == plan.to + } + + /// One check, and when the other Mac rolled back the release this Mac runs, the same rollback here (owner ruling + /// 2026-11-03: the peer follows the rollback). It is decided under the update lease, the one the pair's update + /// cycle holds, and runs as that cycle does: this Mac's part drains once the other Mac is confirmed on the earlier + /// release (it runs it already: `ClusterPairUpdate.partnerState` is ready at once), the verified predecessor is + /// restored and the release quarantined (`SelfUpdater.rollBackToPredecessor`), and `restart` restarts the cluster + /// service into the restored release. An other Mac that stops answering is waited for at most + /// `Timing.partnerStageWait`, then the follow is deferred with that reason and the next check tries again. + public func followRollback(restart: @escaping @Sendable (String) async throws -> Void) async -> FollowOutcome { + let updater = environment.updater + // Read before the lease: most checks find nothing, and the lease belongs to the pair's cycles. + let partner = environment.partner() + guard case .reported(let progress) = partner, let quarantined = progress.quarantined else { return .nothingToFollow } + let session: SelfUpdater.UpdateSession + do { + session = try updater.beginUpdateSession(operation: "cluster-follow-rollback", timeout: 0) + try session.recover() + } catch { + return .busy + } + let plan: SelfUpdater.RollbackPlan + do { + plan = try updater.rollbackPlan(session: session) + } catch { + let state = try? session.readState() + session.release() + guard (state?.candidate?.release ?? state?.current)?.version == quarantined else { return .nothingToFollow } + return .cannotFollow("the other Mac rolled v\(quarantined) back to v\(progress.running); this Mac cannot: \(error)") + } + guard plan.from == quarantined else { session.release(); return .nothingToFollow } + guard Self.follows(partner, plan: plan) else { + session.release() + return .cannotFollow("the other Mac rolled v\(quarantined) back to v\(progress.running), but this Mac keeps " + + "v\(plan.to) for rollback; it stays on v\(quarantined) until a newer release updates both Macs") + } + lock.withLock { + startedAt = Self.now(); request = nil; self.session = session + installed = plan.from; target = plan.to; following = true + } + let heartbeat = startHeartbeat() + defer { heartbeat.cancel() } + environment.log("cluster update: the other Mac rolled v\(plan.from) back to v\(plan.to) and quarantined it; " + + "this Mac follows to v\(plan.to)") + await beginPairDrain() + let drained = await waitForPairDrain(.milliseconds(Int64(environment.timing.drainTimeout * 1000))) + if Task.isCancelled || !drained { + resume() + let outcome: AutoUpdateController.Outcome = Task.isCancelled ? .cancelled : .drainTimedOut + finish(outcome) + return .followed(outcome) + } + let reason = "the other Mac of the pair rolled v\(plan.from) back to v\(plan.to); this Mac followed" + do { + try updater.rollBackToPredecessor(session: session, plan: plan, reason: reason) + } catch { + resume() + let outcome = AutoUpdateController.Outcome.commitFailed("restoring v\(plan.to) failed: \(error)") + finish(outcome) + return .followed(outcome) + } + environment.log("cluster update: restored v\(plan.to) and quarantined v\(plan.from), as on the other Mac") + session.release() + lock.withLock { self.session = nil } + publish(.restarting) + do { + try await restart(plan.to) + } catch { + let outcome = AutoUpdateController.Outcome.restartFailed("\(error)") + finish(outcome) + return .followed(outcome) + } + let outcome = AutoUpdateController.Outcome.restarted(from: plan.from, to: plan.to, drained: true) + finish(outcome) + return .followed(outcome) + } + // MARK: - Steps private func claim() -> Bool { @@ -173,6 +282,8 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { private func beginPairDrain() async { guard let target = lock.withLock({ target }) else { return giveUp("no release to install") } let (started, timing) = (lock.withLock { startedAt }, environment.timing) + // Following a rollback, the other Mac runs the target already: what is waited for is that it still says so. + let following = lock.withLock { self.following } publish(.staged) let deadline = started + timing.partnerStageWait var said = false @@ -189,12 +300,12 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { case .cannotCoordinate, .waiting: if !said { said = true - environment.log("cluster update: waiting for the other Mac to have v\(target) (at most \(Int(max(0, deadline - Self.now()))) s)") + environment.log("cluster update: waiting for the other Mac to \(following ? "confirm it runs" : "have") v\(target) (at most \(Int(max(0, deadline - Self.now()))) s)") } } if Task.isCancelled { return giveUp("the cycle was stopped") } guard Self.now() < deadline else { - return giveUp("the other Mac did not have v\(target) within \(Int(timing.partnerStageWait)) s") + return giveUp("the other Mac did not \(following ? "confirm it runs" : "have") v\(target) within \(Int(timing.partnerStageWait)) s") } await Self.sleep(timing.poll) } @@ -398,7 +509,7 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { lock.withLock { let value = ClusterPairUpdateProgress(phase: phase, target: phase == .idle ? nil : target, running: environment.updater.currentVersion, cycleStartedAt: phase == .idle ? nil : startedAt, - request: request, writtenAt: Self.now(), detail: detail) + request: request, writtenAt: Self.now(), detail: detail, quarantined: environment.updater.quarantinedVersion()) progress = value ClusterPairUpdate.writeProgress(value, to: environment.progressPath) } diff --git a/provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift b/provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift index dfd8d25c86..d9dc54fb06 100644 --- a/provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift +++ b/provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift @@ -117,10 +117,12 @@ extension SelfUpdater { /// Carries out a confirmed `plan` while the caller holds `session` (for a /// running provider, the lease its drain took). Returns the restored version. + /// `reason` is the quarantine's; the operator's by default. @discardableResult - public func rollBackToPredecessor(session: UpdateSession, plan: RollbackPlan) throws -> String { + public func rollBackToPredecessor(session: UpdateSession, plan: RollbackPlan, reason: String? = nil) throws -> String { try confirmRollbackPlan(plan, session: session) - let reason = "rolled back by the operator to v\(plan.to) (\(BuildEnvironment.current.cliName) update --rollback)" + let reason = reason + ?? "rolled back by the operator to v\(plan.to) (\(BuildEnvironment.current.cliName) update --rollback)" do { return try session.rollback(now: now(), reason: reason) } catch { diff --git a/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift b/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift index a73c27253e..bb0df1029e 100644 --- a/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift +++ b/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift @@ -660,6 +660,13 @@ public struct SelfUpdater: Sendable { return Self.installRoot(forExecutablePath: executablePath) } + /// The release quarantined on this Mac, read without the lease as + /// `checkForUpdate` reads it (the state file is replaced atomically); nil + /// when none is, or the state cannot be read. + public func quarantinedVersion() -> String? { + try? recoveryStore()?.loadState().quarantine?.version + } + private func recoveryStore() -> UpdateRecoveryStore? { guard let root = resolvedInstallRoot() else { return nil } return UpdateRecoveryStore( diff --git a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift index 50bc99a18a..68b86f5728 100644 --- a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift +++ b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift @@ -38,6 +38,13 @@ final class ClusterMemberSupervisor: @unchecked Sendable { var recovery: ClusterCandidateRecovery? /// Whether the service's published status says this Mac's part serves again (logged once after an update). var partServes: @Sendable () -> Bool = { false } + /// One check whether the other Mac rolled back the release this Mac runs, and if so the same rollback here + /// (`ClusterPairUpdateCycle.followRollback`), run every `ClusterPairUpdate.followCheckSeconds` while no cycle runs. + var follow: @Sendable (_ log: @escaping @Sendable (String) -> Void, + _ restart: @escaping @Sendable (String) async throws -> Void) async + -> ClusterPairUpdateCycle.FollowOutcome = { _, _ in .nothingToFollow } + /// The release quarantined on this Mac, which its progress reports to the other Mac. + var quarantined: @Sendable () -> String? = { nil } } struct Configuration { @@ -83,6 +90,10 @@ final class ClusterMemberSupervisor: @unchecked Sendable { private var pairCycle: Task? private var pairCycleRunning = false private var requestedRestart: String? + // When the next check for a rollback of the other Mac to follow is due (main loop only), and the last reason it + // could not be followed (under `lock`), said once. + private var nextFollowCheck: Double = 0 + private var cannotFollow: String? // The candidate this run's service is (main loop only), until it is promoted. private var candidate: String? private var updatedServiceServes = false @@ -473,9 +484,10 @@ final class ClusterMemberSupervisor: @unchecked Sendable { if let request { log("cluster update: `darkbloom update` asked for a restart into the installed release together with the other Mac (\(request.id.prefix(8)))") } else if !configuration.autoUpdate { - return restAsDisabled(pair, now: now) + restAsDisabled(pair, now: now) + return startFollowCheckIfDue(pair, pid: pid, now: now) } else if !slotDue { - return + return startFollowCheckIfDue(pair, pid: pid, now: now) } // A cycle at or after the slot is that slot's. if slotDue { pairSlot = pair.clusterID().map { ClusterMemberUpdateSlot.nextSlot(after: now, clusterID: $0) } } @@ -491,9 +503,34 @@ final class ClusterMemberSupervisor: @unchecked Sendable { } } + /// While no cycle runs, every `ClusterPairUpdate.followCheckSeconds` (and at once after a start): whether the other + /// Mac rolled back the release this Mac runs, which this Mac then follows, as a cycle of its own. Automatic updates + /// off do not stop it: it restores a release this Mac ran before, as a rollback after failed starts does. + private func startFollowCheckIfDue(_ pair: PairUpdate, pid: Int32, now: Double) { + guard now >= nextFollowCheck else { return } + nextFollowCheck = now + ClusterPairUpdate.followCheckSeconds + lock.withLock { pairCycleRunning = true } + let log: @Sendable (String) -> Void = { [weak self] in self?.log($0) } + let restart: @Sendable (String) async throws -> Void = { [weak self] version in + try self?.restartForUpdate(into: version, pid: pid) + } + pairCycle = Task.detached { [weak self] in + let outcome = await pair.follow(log, restart) + guard let self else { return } + let say: String? = self.lock.withLock { + defer { self.pairCycleRunning = false } + guard case .cannotFollow(let reason) = outcome else { self.cannotFollow = nil; return nil } + defer { self.cannotFollow = reason } + return self.cannotFollow == reason ? nil : reason + } + if let say { self.log("cluster update: not following the other Mac's rollback: \(say)") } + } + } + /// This Mac outside a cycle: idle, or disabled while its automatic updates are off. private func restingProgress(now: Double) -> ClusterPairUpdateProgress { - .init(phase: configuration.autoUpdate ? .idle : .disabled, running: ProviderCore.version, writtenAt: now) + .init(phase: configuration.autoUpdate ? .idle : .disabled, running: ProviderCore.version, writtenAt: now, + quarantined: configuration.pairUpdate?.quarantined()) } /// With automatic updates off, the end of a cycle `darkbloom update` asked for stays the other Mac's (and the diff --git a/provider-swift/Sources/darkbloom/ClusterServiceCommand.swift b/provider-swift/Sources/darkbloom/ClusterServiceCommand.swift index c99142bf94..65b14f2ef9 100644 --- a/provider-swift/Sources/darkbloom/ClusterServiceCommand.swift +++ b/provider-swift/Sources/darkbloom/ClusterServiceCommand.swift @@ -113,7 +113,13 @@ extension Cluster { recovery: ClusterCandidateRecovery(updater: SelfUpdater(coordinatorBaseURL: coordinatorURL)), partServes: { ClusterService.publishedLive().map { $0.serving && $0.child.running && $0.session?.ready != false } ?? false - })) + }, + follow: { log, restart in + let environment = ClusterPairUpdateCycle.Environment.live( + serviceDirectory: serviceDirectory, coordinatorURL: coordinatorURL, log: log) + return await ClusterPairUpdateCycle(environment: environment).followRollback(restart: restart) + }, + quarantined: { SelfUpdater(coordinatorBaseURL: coordinatorURL).quarantinedVersion() })) } } diff --git a/provider-swift/Sources/darkbloom/UpdateRollback.swift b/provider-swift/Sources/darkbloom/UpdateRollback.swift index 770a9533c1..d5cb88d30d 100644 --- a/provider-swift/Sources/darkbloom/UpdateRollback.swift +++ b/provider-swift/Sources/darkbloom/UpdateRollback.swift @@ -76,10 +76,10 @@ struct UpdateRollback { let say: (String) -> Void static let clusterRefusal = """ - This Mac serves in a two-Mac cluster. Both Macs of a pair run one release, so `\(cli) update --rollback` \ - does not roll back one Mac of a pair. Stop the pair first (`\(cli) cluster stop`, or `\(cli) stop` for a \ - cluster member service), run `\(cli) update --rollback` on each Mac, then start the pair again with \ - `\(cli) cluster`. Nothing was changed. + This Mac serves in a two-Mac cluster, and `\(cli) update --rollback` does not change one Mac of a running \ + pair. Stop this Mac's cluster service (`\(cli) cluster stop`), run `\(cli) update --rollback`, then start \ + it again with `\(cli) cluster`: the other Mac follows the rollback to the same release. For a cluster \ + member service, stop it with `\(cli) stop` and roll back both Macs. Nothing was changed. """ static let foregroundRefusal = """ diff --git a/provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift b/provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift index e90bd86ce9..9af784e47b 100644 --- a/provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift @@ -54,6 +54,10 @@ struct ClusterServiceUpdateTests { installed: String = "/installed/darkbloom", startCheckSeconds: Double = 5, autoUpdate: Bool, clusterID: String, recovery: ClusterCandidateRecovery? = nil, reexecs: Recorder, + follow: @escaping @Sendable (@escaping @Sendable (String) -> Void, + @escaping @Sendable (String) async throws -> Void) async + -> ClusterPairUpdateCycle.FollowOutcome = { _, _ in .nothingToFollow }, + quarantined: @escaping @Sendable () -> String? = { nil }, run: @escaping @Sendable (String?, @escaping @Sendable (String) -> Void, @escaping @Sendable (String) async throws -> Void) async -> AutoUpdateController.Outcome) -> ClusterMemberSupervisor.Configuration { @@ -71,7 +75,7 @@ struct ClusterServiceUpdateTests { pairUpdate: .init(clusterID: { clusterID }, run: run, requestPath: ClusterServiceAgent.updateRequestPath(serviceDirectory: directory), progressPath: ClusterServiceAgent.updateProgressPath(serviceDirectory: directory), - recovery: recovery), + recovery: recovery, follow: follow, quarantined: quarantined), reexec: { reexecs.add($0.joined(separator: " ")) }, startCheckTimeoutSeconds: startCheckSeconds, sweepsOrphans: false) } @@ -104,6 +108,42 @@ struct ClusterServiceUpdateTests { #expect(configured.childArguments == ["cluster", "service", "--config", path.path]) } + // MARK: - Following the other Mac's rollback + + /// While no cycle runs (here with automatic updates off, which do not stop it), the supervisor checks at once whether + /// the other Mac rolled back the release this Mac runs; following it ends in the same restart as an update, into + /// the restored release. Its progress reports this Mac's quarantine to the other Mac. + @Test func supervisorFollowsTheOtherMacsRollbackAndRestartsIntoTheRestoredRelease() async throws { + let directory = try temporaryDirectory("cluster-follow-rollback") + defer { try? FileManager.default.removeItem(at: directory) } + let calls = Recorder(), follows = Recorder(), reexecs = Recorder() + let supervisor = ClusterMemberSupervisor(configuration: configuration(directory: directory, script: "exec sleep 60", + autoUpdate: false, clusterID: imminentClusterID(), reexecs: reexecs, + follow: { log, restart in + follows.add("follow") + log("cluster update: test follow") + try? await restart("1.0.0") + return .followed(.restarted(from: "2.0.0", to: "1.0.0", drained: true)) + }, + quarantined: { "2.0.0" }) { request, _, _ in + calls.add(request ?? "slot") + return .upToDate + }) + let run = Task { await supervisor.run() } + #expect(await waitUntil(seconds: 2) { + ClusterPairUpdate.readProgress(from: ClusterServiceAgent.updateProgressPath(serviceDirectory: directory))?.quarantined == "2.0.0" + }, "the other Mac reads this Mac's quarantine") + #expect(await waitUntil(seconds: 15) { !reexecs.all.isEmpty }, "the follow restarted the service and the supervisor re-executed") + #expect(follows.all == ["follow"]) + #expect(reexecs.all == ["/installed/darkbloom cluster service --supervise"]) + #expect(state(directory)?.lastRun?.end == "stopped to restart into v1.0.0") + #expect(calls.all.isEmpty, "automatic updates are off: no slot cycle ran") + #expect(await waitUntil(seconds: 10) { state(directory)?.runs == 2 && state(directory)?.phase == .running }) + supervisor.requestStop() + #expect(await run.value == 0) + #expect(follows.all == ["follow"], "the next check is a minute later") + } + // MARK: - The slot /// At the pair's slot the cycle runs beside the serving service; its restart stops the service and the supervisor diff --git a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift index 4d97d8ee77..d03c0e6bf8 100644 --- a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift @@ -128,6 +128,39 @@ private struct PairMac { } } +/// A rollback on one Mac of the pair, which the other Mac follows (`ClusterPairUpdateCycle.followRollback`). +private enum FollowTestError: Error { case notInstalled } + +extension PairMac { + var store: UpdateRecoveryStore { UpdateRecoveryStore(installRoot: fixture.installRoot, verifyCodeSignatures: false) } + + /// v2 installed by the updater and restarted into, as the pair's cycle leaves it: a pending candidate over v1. + @discardableResult + func installCandidate() async throws -> SelfUpdater { + let updater = fixture.updater(baseURL: baseURL) + guard case .updated(_, "2.0.0") = await updater.update() else { throw FollowTestError.notInstalled } + try updater.prepareCandidateLaunch(operation: "cluster-restart", baseline: nil) + return updater + } + + /// The candidate passed its stabilization window. + func promote() throws { + var state = try store.loadState() + state.promoteCandidate() + try store.writeState(state) + } + + /// This Mac's supervisor rolled v2 back (it failed its start check), restored v1 and quarantined v2, and, started + /// again from v1, publishes its resting progress with the quarantine. + func rollBackAfterFailedStartCheck() async throws { + let updater = try await installCandidate() + #expect(ClusterCandidateRecovery(updater: updater).recordFailedStartCheck(version: "2.0.0", reason: "`--version` exited 1", + now: 200) == .rolledBack(from: "2.0.0", to: "1.0.0")) + ClusterPairUpdate.writeProgress(.init(phase: .idle, running: "1.0.0", writtenAt: Date().timeIntervalSince1970, + quarantined: updater.quarantinedVersion()), to: progressPath) + } +} + private final class Restarts: @unchecked Sendable { private let lock = NSLock() private var values: [String] = [] @@ -430,4 +463,138 @@ struct ClusterPairUpdateTests { guard case .quarantined(let version, _) = await updater.checkForUpdate() else { Issue.record("not quarantined"); return } #expect(version == "2.0.0", "the next slot does not install it again") } + + // MARK: - The peer follows a rollback (owner ruling 2026-11-03) + + /// The other Mac promoted v2 before this one rolled it back: it drains its part, restores v1 under the update lease, + /// quarantines v2 and restarts into v1, so the pair serves v1 together. + @Test func peerThatPromotedTheReleaseFollowsTheRollback() async throws { + let rolledBack = try await PairMac.make(part: false), peer = try await PairMac.make() + defer { Task { await rolledBack.cleanUp(); await peer.cleanUp() } } + try await peer.installCandidate() + try peer.promote() + try await rolledBack.rollBackAfterFailedStartCheck() + + let log = Lines(), restarts = Restarts() + let outcome = await peer.cycle(partner: rolledBack, log: log).followRollback { restarts.record("peer", $0) } + + #expect(outcome == .followed(.restarted(from: "2.0.0", to: "1.0.0", drained: true)), "\(log.all)") + #expect(restarts.all == ["peer:1.0.0"]) + #expect(peer.mailbox.readClusterUpdateDrainStatus()?.outcome == .notServing, "its part was asked to drain first") + #expect(try peer.fixture.liveBinaryContents() == "1.0.0-darkbloom") + let state = try peer.store.loadState() + #expect(state.current?.version == "1.0.0" && state.candidate == nil) + #expect(state.quarantine?.version == "2.0.0") + #expect(state.quarantine?.reason.contains("the other Mac of the pair rolled v2.0.0 back to v1.0.0") == true) + let progress = ClusterPairUpdate.readProgress(from: peer.progressPath) + #expect(progress?.phase == .restarting && progress?.target == "1.0.0" && progress?.quarantined == "2.0.0") + #expect(log.all.contains { $0.contains("this Mac follows to v1.0.0") }) + try peer.fixture.updater(baseURL: peer.baseURL).beginUpdateSession(operation: "lease-check").release() + } + + /// The other Mac is still mid-update: its cycle holds the update lease, so the follow waits for the next check and + /// changes nothing; then its unpromoted candidate is rolled back the same way. + @Test func peerStillMidUpdateFollowsOnceItsCycleLetsTheLeaseGo() async throws { + let rolledBack = try await PairMac.make(part: false), peer = try await PairMac.make(part: false) + defer { Task { await rolledBack.cleanUp(); await peer.cleanUp() } } + let updater = try await peer.installCandidate() + try await rolledBack.rollBackAfterFailedStartCheck() + + let log = Lines(), restarts = Restarts() + let cycle = try updater.beginUpdateSession(operation: "cluster-auto-update") + let refused = await peer.cycle(partner: rolledBack, log: log).followRollback { restarts.record("peer", $0) } + #expect(refused == .busy) + #expect(try peer.fixture.liveBinaryContents() == "2.0.0-darkbloom") + #expect(try peer.store.loadState().candidate?.release.version == "2.0.0") + #expect(ClusterPairUpdate.readProgress(from: peer.progressPath) == nil, "nothing was published") + cycle.release() + + let outcome = await peer.cycle(partner: rolledBack, log: log).followRollback { restarts.record("peer", $0) } + #expect(outcome == .followed(.restarted(from: "2.0.0", to: "1.0.0", drained: true)), "\(log.all)") + #expect(restarts.all == ["peer:1.0.0"]) + #expect(try peer.fixture.liveBinaryContents() == "1.0.0-darkbloom") + let state = try peer.store.loadState() + #expect(state.candidate == nil && state.current?.version == "1.0.0" && state.quarantine?.version == "2.0.0") + } + + /// The other Mac stops answering once the follow began: it waits at most the bound, then defers with a clear reason, + /// changes nothing and frees the lease. One that cannot be asked at all is not followed. + @Test func unreachablePeerIsWaitedForThenTheFollowDefers() async throws { + let rolledBack = try await PairMac.make(part: false), peer = try await PairMac.make(part: false) + defer { Task { await rolledBack.cleanUp(); await peer.cleanUp() } } + try await peer.installCandidate() + try peer.promote() + try await rolledBack.rollBackAfterFailedStartCheck() + var timing = pairTiming + timing.partnerStageWait = 1 + func cycle(partner: @escaping @Sendable () -> ClusterPairUpdate.Partner, log: Lines) -> ClusterPairUpdateCycle { + var environment = ClusterPairUpdateCycle.Environment(updater: peer.fixture.updater(baseURL: peer.baseURL), + progressPath: peer.progressPath, partner: partner, part: { .notRunning }, partStarting: { _ in false }, + mailboxDirectory: peer.mailboxDirectory, pairRunsHere: { true }, log: { log.append($0) }) + environment.timing = timing + return ClusterPairUpdateCycle(environment: environment) + } + let log = Lines(), restarts = Restarts() + let unasked = await cycle(partner: { .unreachable }, log: log).followRollback { restarts.record("peer", $0) } + #expect(unasked == .nothingToFollow) + #expect(ClusterPairUpdate.readProgress(from: peer.progressPath) == nil) + + let asked = Lines() + let reported = try #require(ClusterPairUpdate.readProgress(from: rolledBack.progressPath)) + let started = Date() + let outcome = await cycle(partner: { + asked.append("asked") + return asked.all.count == 1 ? .reported(reported) : .unreachable + }, log: log).followRollback { restarts.record("peer", $0) } + + #expect(outcome == .followed(.drainTimedOut), "\(log.all)") + #expect(Date().timeIntervalSince(started) < 15, "the wait is bounded") + #expect(restarts.all.isEmpty) + #expect(try peer.fixture.liveBinaryContents() == "2.0.0-darkbloom") + #expect(try peer.store.loadState().quarantine == nil) + let progress = ClusterPairUpdate.readProgress(from: peer.progressPath) + #expect(progress?.phase == .deferred) + #expect(progress?.detail == "the other Mac did not confirm it runs v1.0.0 within 1 s") + try peer.fixture.updater(baseURL: peer.baseURL).beginUpdateSession(operation: "lease-check").release() + } + + /// Both Macs keep v2 quarantined: neither's next check installs it again, each one's progress says so, and the Mac + /// that rolled back first finds nothing to follow in its peer's rollback (no loop). A peer that keeps another + /// release for rollback cannot follow and changes nothing. + @Test func quarantineAppliesOnBothMacs() async throws { + let rolledBack = try await PairMac.make(part: false), peer = try await PairMac.make(part: false) + defer { Task { await rolledBack.cleanUp(); await peer.cleanUp() } } + try await peer.installCandidate() + try peer.promote() + try await rolledBack.rollBackAfterFailedStartCheck() + let log = Lines(), restarts = Restarts() + let followed = await peer.cycle(partner: rolledBack, log: log).followRollback { restarts.record("peer", $0) } + #expect(followed == .followed(.restarted(from: "2.0.0", to: "1.0.0", drained: true)), "\(log.all)") + + for mac in [rolledBack, peer] { + let updater = mac.fixture.updater(baseURL: mac.baseURL) + #expect(updater.quarantinedVersion() == "2.0.0") + guard case .quarantined(let version, _) = await updater.checkForUpdate() else { + Issue.record("v2.0.0 is not quarantined on \(mac.directory.lastPathComponent)"); continue + } + #expect(version == "2.0.0") + } + let first = await rolledBack.cycle(partner: peer, log: log).followRollback { restarts.record("rolledBack", $0) } + #expect(first == .nothingToFollow, "the Mac that rolled back first does not follow its peer back") + #expect(restarts.all == ["peer:1.0.0"]) + + // A rollback to a release this Mac does not keep is not followed. + let other = try await PairMac.make(part: false) + defer { Task { await other.cleanUp() } } + try await other.installCandidate() + try other.promote() + ClusterPairUpdate.writeProgress(.init(phase: .idle, running: "0.9.0", writtenAt: Date().timeIntervalSince1970, + quarantined: "2.0.0"), to: rolledBack.progressPath) + guard case .cannotFollow(let reason) = await other.cycle(partner: rolledBack, log: log).followRollback({ _ in }) else { + Issue.record("followed a rollback to a release it does not keep"); return + } + #expect(reason.contains("keeps v1.0.0 for rollback")) + #expect(try other.fixture.liveBinaryContents() == "2.0.0-darkbloom") + #expect(try other.store.loadState().quarantine == nil) + } } From 700a4b73a61a45ac56271d3f8239ae0ae75b5b1d Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 05:51:18 -0600 Subject: [PATCH 0222/1441] fix(provider): no follow of a Mac that reinstalled its quarantined release; publish a quarantine between cycles Co-Authored-By: Claude Opus 5.5 --- .../ProviderCore/Update/ClusterPairUpdateCycle.swift | 4 +++- .../Sources/darkbloom/ClusterMemberSupervisor.swift | 11 +++++++++++ .../Update/ClusterPairUpdateTests.swift | 11 +++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift b/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift index 549768285e..7e17b311f5 100644 --- a/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift +++ b/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift @@ -160,7 +160,9 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { let updater = environment.updater // Read before the lease: most checks find nothing, and the lease belongs to the pair's cycles. let partner = environment.partner() - guard case .reported(let progress) = partner, let quarantined = progress.quarantined else { return .nothingToFollow } + // A Mac that runs the release it quarantined (installed again with `--override-quarantine`) rolled nothing back. + guard case .reported(let progress) = partner, let quarantined = progress.quarantined, + progress.running != quarantined else { return .nothingToFollow } let session: SelfUpdater.UpdateSession do { session = try updater.beginUpdateSession(operation: "cluster-follow-rollback", timeout: 0) diff --git a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift index 68b86f5728..09b6eec1b6 100644 --- a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift +++ b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift @@ -509,6 +509,7 @@ final class ClusterMemberSupervisor: @unchecked Sendable { private func startFollowCheckIfDue(_ pair: PairUpdate, pid: Int32, now: Double) { guard now >= nextFollowCheck else { return } nextFollowCheck = now + ClusterPairUpdate.followCheckSeconds + publishQuarantine(pair) lock.withLock { pairCycleRunning = true } let log: @Sendable (String) -> Void = { [weak self] in self?.log($0) } let restart: @Sendable (String) async throws -> Void = { [weak self] version in @@ -527,6 +528,16 @@ final class ClusterMemberSupervisor: @unchecked Sendable { } } + /// A rollback since the progress was written (a candidate's third failed start, while no cycle ran) reaches the + /// other Mac with the next follow check: only the quarantine changes, the rest stays as the last cycle left it. + private func publishQuarantine(_ pair: PairUpdate) { + guard var progress = ClusterPairUpdate.readProgress(from: pair.progressPath) else { return } + let quarantined = pair.quarantined() + guard progress.quarantined != quarantined else { return } + progress.quarantined = quarantined + ClusterPairUpdate.writeProgress(progress, to: pair.progressPath) + } + /// This Mac outside a cycle: idle, or disabled while its automatic updates are off. private func restingProgress(now: Double) -> ClusterPairUpdateProgress { .init(phase: configuration.autoUpdate ? .idle : .disabled, running: ProviderCore.version, writtenAt: now, diff --git a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift index d03c0e6bf8..6132b89e2e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift @@ -583,6 +583,17 @@ struct ClusterPairUpdateTests { #expect(first == .nothingToFollow, "the Mac that rolled back first does not follow its peer back") #expect(restarts.all == ["peer:1.0.0"]) + // A Mac that installed the quarantined release again (`--override-quarantine`) rolled nothing back. + ClusterPairUpdate.writeProgress(.init(phase: .idle, running: "2.0.0", writtenAt: Date().timeIntervalSince1970, + quarantined: "2.0.0"), to: rolledBack.progressPath) + let reinstalled = try await PairMac.make(part: false) + defer { Task { await reinstalled.cleanUp() } } + try await reinstalled.installCandidate() + try reinstalled.promote() + let overridden = await reinstalled.cycle(partner: rolledBack, log: log).followRollback { restarts.record("reinstalled", $0) } + #expect(overridden == .nothingToFollow) + #expect(try reinstalled.fixture.liveBinaryContents() == "2.0.0-darkbloom") + // A rollback to a release this Mac does not keep is not followed. let other = try await PairMac.make(part: false) defer { Task { await other.cleanUp() } } From 8353e64f616d289abc0340a1f6169218cb97fc3c Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:09:13 -0600 Subject: [PATCH 0223/1441] fix(provider): pair follow decided before the lease, waits for a drainable part, backs off to the next slot (Refactor Pass) Refactor Pass findings, fixed: - High 1: documented that the restored release reports the rollback, so a rollback to a release without the follow is not followed. - High 2: the follow is decided from the recovery state without the lease; only a Mac that runs the quarantined release takes the lease and verifies its kept release. - High 3: a Mac whose part does not drain (local API, alone) does not follow yet and says so once, instead of deferring every minute. - Medium 1: a deferred follow is tried again at the pair's next update slot. - Medium 2: the follow waits at most progressStaleSeconds for the other Mac; the Mac that rolled back says once that the other Mac still runs the release; the alone path is documented. - Medium 3: ClusterPairUpdate.partnerState gives up a release the other Mac quarantined. - Low: the follow environment is built once; a failed recovery is reported, not taken for busy; troubleshooting row and test docs; checks for an older build's progress and the partner's quarantine. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-pair-follows-rollback.md | 3 +- docs/developer/test.md | 7 ++- docs/provider/cluster-always-on.md | 48 +++++++++++++------ .../ClusterPairUpdate.swift | 2 + .../Update/ClusterPairUpdateCycle.swift | 47 +++++++++++++----- .../ProviderCore/Update/SelfUpdater.swift | 7 ++- .../darkbloom/ClusterMemberSupervisor.swift | 26 +++++++--- .../darkbloom/ClusterServiceCommand.swift | 9 ++-- .../Tests/ClusterSupervisionChecks/main.swift | 9 ++++ .../Update/ClusterPairUpdateTests.swift | 31 ++++++++++++ 10 files changed, 149 insertions(+), 40 deletions(-) diff --git a/changelog.d/cluster-pair-follows-rollback.md b/changelog.d/cluster-pair-follows-rollback.md index c4320fc4ff..6e9b06eb36 100644 --- a/changelog.d/cluster-pair-follows-rollback.md +++ b/changelog.d/cluster-pair-follows-rollback.md @@ -2,5 +2,6 @@ - When one Mac of a `darkbloom cluster` pair rolls a release back (three failed starts of its cluster service, a failed start check, or `darkbloom update --rollback` while its cluster service was stopped), the other Mac now rolls back to the same earlier release, and the pair serves it together. Before, the pair stayed split until a newer release updated both Macs. - The other Mac checks at its start and every minute while no update runs, also with automatic updates off. It finishes the accepted requests of its part first, as for an update, restores the release it kept from before its last update, quarantines the rolled-back release and restarts. Both Macs then skip that release, and the next newer release updates both. -- A Mac that keeps another earlier release, or none, does not follow and says so once in `~/.darkbloom/cluster-setup/service.log`. A Mac whose partner stops answering during the follow waits at most 15 minutes, then changes nothing and tries again at the next check. +- A Mac that keeps another earlier release, or none, or whose part serves on the leader's local API or alone, does not follow (yet) and says so once in `~/.darkbloom/cluster-setup/service.log`. While a pair runs on it, a Mac whose partner stops answering during the follow waits at most a minute, then changes nothing and tries again at the pair's next update slot. A Mac whose partner quarantined a release does not install that release either. +- Both Macs need this release or a later one, and the release a Mac rolls back to must have it too: the Mac that rolled back reports the rollback from the restored release. A rollback of this release itself is therefore not followed; rollbacks of later releases are. - To roll back a pair by hand, stop one Mac's cluster service with `darkbloom cluster stop`, run `darkbloom update --rollback` there, and start it again with `darkbloom cluster`; the other Mac follows. diff --git a/docs/developer/test.md b/docs/developer/test.md index 9827221563..ff0e018ee3 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1081,7 +1081,12 @@ candidate that failed its start check; and the other Mac following a rollback holds the update lease (it waits, then follows), with the other Mac no longer answering (bounded wait, then a deferral with nothing changed), and the quarantine on both Macs, with no follow back and no follow to a release the Mac -does not keep. +does not keep; and what is decided before the lease (the Mac that rolled back +names the release the other Mac still runs, a part that cannot drain does not +follow yet, a Mac on another release does not ask for the lease). +`Tests/ClusterSupervisionChecks/run.sh` also checks that a release the other Mac +quarantined is given up, and that an older build's progress decodes without a +quarantine. `ClusterServiceUpdateTests` (`provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift`) drives the real supervisor with a shell standing in for the cluster service: the diff --git a/docs/provider/cluster-always-on.md b/docs/provider/cluster-always-on.md index 710374488c..4cb5482c02 100644 --- a/docs/provider/cluster-always-on.md +++ b/docs/provider/cluster-always-on.md @@ -200,36 +200,54 @@ then every `ClusterPairUpdate.followCheckSeconds` (60 s) while no update cycle runs, also with automatic updates off: the release it restores is one the Mac ran before. It follows (`ClusterPairUpdateCycle.followRollback`) when the other Mac quarantined the release this Mac runs (installed or promoted) and runs the -release this Mac keeps for rollback. The follow is the update cycle's sequence +release this Mac keeps for rollback. The check reads both Macs' recovery state +without the update lease; only a Mac that runs the quarantined release takes the +lease and verifies its kept release. The follow is the update cycle's sequence with a rollback in place of the install: 1. It takes the update lease, the one every update cycle, candidate recovery - and `darkbloom update --rollback` take, and decides under it. Another + and `darkbloom update --rollback` take, and decides again under it. Another holder (this Mac's own cycle, still installing or restarting) makes it wait for the next check, with nothing changed. 2. It waits until the other Mac reports the earlier release (it does already, so this is at once), then drains this Mac's part as for an update. An other Mac that stops answering is waited for at most - `ClusterPairUpdate.partnerStageWaitSeconds` (900 s) while a pair runs on - this Mac. The follow is then deferred with the reason `the other Mac did not - confirm it runs v within 900 s`, nothing is changed, and the next - check tries again. + `ClusterPairUpdate.progressStaleSeconds` (60 s) while a pair runs on this + Mac. The follow is then deferred with the reason `the other Mac did not + confirm it runs v within 60 s`, nothing is changed, and it is tried + again at the pair's next update slot, as a deferred update is. With no pair + running on this Mac, it follows alone, as an update goes on alone. 3. It restores the verified predecessor and quarantines the release (`SelfUpdater.rollBackToPredecessor`), with the reason `the other Mac of the pair rolled v back to v; this Mac followed`. Both Macs now keep the release quarantined: neither's update slot installs it again, - and the next newer release updates both. + and a Mac whose partner reports the release quarantined gives it up too + (`ClusterPairUpdate.partnerState`). The next newer release updates both. 4. The supervisor restarts the cluster service from the restored binary, after the same start check as for an update. Once both Macs answer with the same build, the leader plans the model again. -A Mac that keeps another release for rollback, or none, cannot restore the same -release. It changes nothing and says once `cluster update: not following the -other Mac's rollback: `; the pair serves again once a newer release -updates both Macs. Other lines: `cluster update: the other Mac rolled -v back to v and quarantined it; this Mac follows to -v` and `cluster update: restored v and quarantined -v, as on the other Mac`. +It does not follow, changes nothing, and says why once in its log +(`cluster update: not following the other Mac's rollback: `) when: + +- it keeps another release for rollback, or none: the pair serves again once a + newer release updates both Macs; +- its part does not drain for an update (it serves on the leader's local API, + or alone): it follows once its part can drain. + +The Mac that rolled back says once `cluster update: the other Mac still runs +v, which this Mac rolled back and quarantined` while the other Mac has +not followed. Other lines: `cluster update: the other Mac rolled v +back to v and quarantined it; this Mac follows to v` and +`cluster update: restored v and quarantined v, as on the +other Mac`. + +Both Macs need a build that follows rollbacks. The quarantine is reported by +the Mac that rolled back after the rollback, so by the restored release's +binary: a rollback *to* a release without this behaviour is not reported, and +the other Mac does not follow it. The first release with this behaviour is +therefore not followed when it is itself rolled back; rollbacks from the +release after it on are. The other Mac must run a build with the follow too. A cluster-member provider service (`darkbloom start --cluster-member --always-on`) does not run this coordinated update and does not follow a @@ -318,7 +336,7 @@ system setting: | Follower never connects; log shows `Local network prohibited` | **Privacy & Security → Local Network** | Turn on Darkbloom; an ad-hoc build needs this per build | | A firewall alert after an update | `codesign -dv` on the listening binary | The binary is not Developer-ID signed; install the release build | | Install or provider log says `permissions: not asked once` | The listed reasons | Install the signed release (a locally built binary is ad-hoc signed and outside `Darkbloom.app`) | -| The pair does not update | `cluster update:` lines in `~/.darkbloom/cluster-setup/service.log` on both Macs | `automatic updates are off`: run `darkbloom update` on both Macs, or set `auto_update` on both (`darkbloom autoupdate enable`), which takes effect when the cluster service next starts (at login, or after its next update). `deferred`: a request ran past 120 s, or one Mac could not take the release; the next slot tries again. `does not drain for an update`: the pair serves on the local API or a Mac serves alone. `failed its start check`: the release did not start on this Mac, which keeps its previous release and does not install that release again; a newer release updates it | +| The pair does not update | `cluster update:` lines in `~/.darkbloom/cluster-setup/service.log` on both Macs | `automatic updates are off`: run `darkbloom update` on both Macs, or set `auto_update` on both (`darkbloom autoupdate enable`), which takes effect when the cluster service next starts (at login, or after its next update). `deferred`: a request ran past 120 s, or one Mac could not take the release; the next slot tries again. `does not drain for an update`: the pair serves on the local API or a Mac serves alone. `failed its start check`: the release did not start on this Mac, which keeps its previous release and does not install that release again; the other Mac follows it back ([a rollback on one Mac](#a-rollback-on-one-mac)), and a newer release updates both. `not following the other Mac's rollback` or `the other Mac still runs`: see [a rollback on one Mac](#a-rollback-on-one-mac) | ## Developer: a coordinator-paired member as a service diff --git a/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift b/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift index a6f6754edf..8313b13fac 100644 --- a/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift +++ b/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift @@ -59,6 +59,8 @@ public enum ClusterPairUpdate { now: Double, requested: Bool = false) -> PartnerState { guard case .reported(let progress) = partner else { return .cannotCoordinate } if progress.running == target { return .ready } + // The other Mac rolled this release back: it will not install it, so neither does this Mac. + if progress.quarantined == target { return .gaveUp("the other Mac quarantined v\(target)") } switch progress.phase { case .disabled: // Its slot never comes, but its own `darkbloom update` may: a requested cycle waits for it while serving. diff --git a/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift b/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift index 7e17b311f5..1e0105cd74 100644 --- a/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift +++ b/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift @@ -131,10 +131,11 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { public enum FollowOutcome: Equatable, Sendable { /// The other Mac quarantined no release this Mac runs (or cannot be asked): nothing was done or published. case nothingToFollow - /// The other Mac rolled back the release this Mac runs, but this Mac cannot restore the same release (it keeps - /// another one, or none, for rollback). Nothing was changed; the pair serves again once a newer release - /// updates both Macs. + /// The other Mac rolled back the release this Mac runs, but this Mac cannot follow, or not yet (it keeps + /// another release, or none, for rollback; its part does not drain). Nothing was changed. case cannotFollow(String) + /// This Mac rolled back a release the other Mac still runs; the other Mac follows once it can. + case otherMacStillRuns(String) /// Another update or recovery holds the update lease; the next check tries again. case busy /// The cycle that followed it ended as an update cycle ends: `.restarted` once the earlier release is restored @@ -149,34 +150,54 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { return progress.quarantined == plan.from && progress.running == plan.to } + /// The release this Mac's recovery state says it runs: the pending candidate, else the promoted one. + private static func installed(_ state: UpdateRecoveryState?) -> String? { + (state?.candidate?.release ?? state?.current)?.version + } + /// One check, and when the other Mac rolled back the release this Mac runs, the same rollback here (owner ruling /// 2026-11-03: the peer follows the rollback). It is decided under the update lease, the one the pair's update /// cycle holds, and runs as that cycle does: this Mac's part drains once the other Mac is confirmed on the earlier /// release (it runs it already: `ClusterPairUpdate.partnerState` is ready at once), the verified predecessor is /// restored and the release quarantined (`SelfUpdater.rollBackToPredecessor`), and `restart` restarts the cluster /// service into the restored release. An other Mac that stops answering is waited for at most - /// `Timing.partnerStageWait`, then the follow is deferred with that reason and the next check tries again. + /// `ClusterPairUpdate.progressStaleSeconds` while a pair runs here, then the follow is deferred with that reason. public func followRollback(restart: @escaping @Sendable (String) async throws -> Void) async -> FollowOutcome { let updater = environment.updater - // Read before the lease: most checks find nothing, and the lease belongs to the pair's cycles. + // Decided without the lease first: most checks find nothing, and the lease belongs to the pair's cycles. let partner = environment.partner() + guard case .reported(let progress) = partner else { return .nothingToFollow } + let recorded = updater.recordedRecoveryState() + if let mine = recorded?.quarantine?.version, progress.running == mine, progress.quarantined != mine, + Self.installed(recorded) != mine { + return .otherMacStillRuns("the other Mac still runs v\(mine), which this Mac rolled back and quarantined; " + + "it follows once it runs a build that follows rollbacks and its part can drain") + } // A Mac that runs the release it quarantined (installed again with `--override-quarantine`) rolled nothing back. - guard case .reported(let progress) = partner, let quarantined = progress.quarantined, - progress.running != quarantined else { return .nothingToFollow } + guard let quarantined = progress.quarantined, progress.running != quarantined, + Self.installed(recorded) == quarantined else { return .nothingToFollow } + if environment.part() == .undrainable { + return .cannotFollow("the other Mac rolled v\(quarantined) back to v\(progress.running), but " + + Self.undrainable + "; it follows once its part can drain") + } let session: SelfUpdater.UpdateSession do { session = try updater.beginUpdateSession(operation: "cluster-follow-rollback", timeout: 0) - try session.recover() } catch { return .busy } + do { + try session.recover() + } catch { + session.release() + return .cannotFollow("this Mac's update recovery state could not be recovered (\(error))") + } + guard Self.installed(try? session.readState()) == quarantined else { session.release(); return .nothingToFollow } let plan: SelfUpdater.RollbackPlan do { plan = try updater.rollbackPlan(session: session) } catch { - let state = try? session.readState() session.release() - guard (state?.candidate?.release ?? state?.current)?.version == quarantined else { return .nothingToFollow } return .cannotFollow("the other Mac rolled v\(quarantined) back to v\(progress.running); this Mac cannot: \(error)") } guard plan.from == quarantined else { session.release(); return .nothingToFollow } @@ -287,7 +308,9 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { // Following a rollback, the other Mac runs the target already: what is waited for is that it still says so. let following = lock.withLock { self.following } publish(.staged) - let deadline = started + timing.partnerStageWait + // A follow read the other Mac on the earlier release a moment ago: it waits only as long as a progress stays fresh. + let stageWait = following ? min(timing.partnerStageWait, ClusterPairUpdate.progressStaleSeconds) : timing.partnerStageWait + let deadline = started + stageWait var said = false wait: while true { switch partnerState(.staged, target: target) { @@ -307,7 +330,7 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { } if Task.isCancelled { return giveUp("the cycle was stopped") } guard Self.now() < deadline else { - return giveUp("the other Mac did not \(following ? "confirm it runs" : "have") v\(target) within \(Int(timing.partnerStageWait)) s") + return giveUp("the other Mac did not \(following ? "confirm it runs" : "have") v\(target) within \(Int(stageWait)) s") } await Self.sleep(timing.poll) } diff --git a/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift b/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift index bb0df1029e..d147463418 100644 --- a/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift +++ b/provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift @@ -664,7 +664,12 @@ public struct SelfUpdater: Sendable { /// `checkForUpdate` reads it (the state file is replaced atomically); nil /// when none is, or the state cannot be read. public func quarantinedVersion() -> String? { - try? recoveryStore()?.loadState().quarantine?.version + recordedRecoveryState()?.quarantine?.version + } + + /// The recovery state, read without the lease as `quarantinedVersion` reads it; nil when it cannot be read. + public func recordedRecoveryState() -> UpdateRecoveryState? { + try? recoveryStore()?.loadState() } private func recoveryStore() -> UpdateRecoveryStore? { diff --git a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift index 09b6eec1b6..9a7a0718c3 100644 --- a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift +++ b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift @@ -93,7 +93,9 @@ final class ClusterMemberSupervisor: @unchecked Sendable { // When the next check for a rollback of the other Mac to follow is due (main loop only), and the last reason it // could not be followed (under `lock`), said once. private var nextFollowCheck: Double = 0 - private var cannotFollow: String? + private var followNotice: String? + /// A deferred follow is tried again only at the pair's next update slot, as a deferred update is (under `lock`). + private var followDeferredUntil: Double = 0 // The candidate this run's service is (main loop only), until it is promoted. private var candidate: String? private var updatedServiceServes = false @@ -507,8 +509,10 @@ final class ClusterMemberSupervisor: @unchecked Sendable { /// Mac rolled back the release this Mac runs, which this Mac then follows, as a cycle of its own. Automatic updates /// off do not stop it: it restores a release this Mac ran before, as a rollback after failed starts does. private func startFollowCheckIfDue(_ pair: PairUpdate, pid: Int32, now: Double) { - guard now >= nextFollowCheck else { return } + guard now >= nextFollowCheck, now >= lock.withLock({ followDeferredUntil }) else { return } nextFollowCheck = now + ClusterPairUpdate.followCheckSeconds + let nextSlot = pair.clusterID().map { ClusterMemberUpdateSlot.nextSlot(after: now, clusterID: $0) } + ?? now + ClusterMemberUpdateSlot.periodSeconds publishQuarantine(pair) lock.withLock { pairCycleRunning = true } let log: @Sendable (String) -> Void = { [weak self] in self?.log($0) } @@ -518,13 +522,21 @@ final class ClusterMemberSupervisor: @unchecked Sendable { pairCycle = Task.detached { [weak self] in let outcome = await pair.follow(log, restart) guard let self else { return } + // Each reason is said once, until the outcome changes. + let notice: String? + switch outcome { + case .cannotFollow(let reason): notice = "not following the other Mac's rollback: " + reason + case .otherMacStillRuns(let reason): notice = reason + default: notice = nil + } let say: String? = self.lock.withLock { - defer { self.pairCycleRunning = false } - guard case .cannotFollow(let reason) = outcome else { self.cannotFollow = nil; return nil } - defer { self.cannotFollow = reason } - return self.cannotFollow == reason ? nil : reason + defer { self.pairCycleRunning = false; self.followNotice = notice } + if case .followed(let ended) = outcome { + if case .restarted = ended {} else { self.followDeferredUntil = nextSlot } + } + return notice == self.followNotice ? nil : notice } - if let say { self.log("cluster update: not following the other Mac's rollback: \(say)") } + if let say { self.log("cluster update: \(say)") } } } diff --git a/provider-swift/Sources/darkbloom/ClusterServiceCommand.swift b/provider-swift/Sources/darkbloom/ClusterServiceCommand.swift index 65b14f2ef9..93884a7a3d 100644 --- a/provider-swift/Sources/darkbloom/ClusterServiceCommand.swift +++ b/provider-swift/Sources/darkbloom/ClusterServiceCommand.swift @@ -88,6 +88,8 @@ extension Cluster { ) -> ClusterMemberSupervisor.Configuration { let settings = Watchdog.settings(configPath: configPath, environment: environment) let coordinatorURL = settings.coordinatorURL + let followEnvironment = ClusterPairUpdateCycle.Environment.live( + serviceDirectory: serviceDirectory, coordinatorURL: coordinatorURL, log: { _ in }) return .init( executable: executable, childArguments: ClusterServiceAgentPlan.childArguments(serviceOptions: serviceOptions), @@ -114,9 +116,10 @@ extension Cluster { partServes: { ClusterService.publishedLive().map { $0.serving && $0.child.running && $0.session?.ready != false } ?? false }, - follow: { log, restart in - let environment = ClusterPairUpdateCycle.Environment.live( - serviceDirectory: serviceDirectory, coordinatorURL: coordinatorURL, log: log) + // Built once: its peer address and network session are kept between the minute's checks. + follow: { [followEnvironment] log, restart in + var environment = followEnvironment + environment.log = log return await ClusterPairUpdateCycle(environment: environment).followRollback(restart: restart) }, quarantined: { SelfUpdater(coordinatorBaseURL: coordinatorURL).quarantinedVersion() })) diff --git a/provider-swift/Tests/ClusterSupervisionChecks/main.swift b/provider-swift/Tests/ClusterSupervisionChecks/main.swift index a90c4e507b..e3648b999f 100644 --- a/provider-swift/Tests/ClusterSupervisionChecks/main.swift +++ b/provider-swift/Tests/ClusterSupervisionChecks/main.swift @@ -293,6 +293,15 @@ do { if case .gaveUp(let reason) = state(disabled, .staged) { check(reason.contains("off on the other Mac"), "auto_update off on the other Mac: \(reason)") } else { check(false, "the other Mac's automatic updates are off") } + // A release the other Mac rolled back and quarantined is installed on neither Mac. + let quarantinedThere = U.Partner.reported(.init(phase: .idle, running: "1.0.0", writtenAt: start, quarantined: "2.0.0")) + if case .gaveUp(let reason) = state(quarantinedThere, .staged) { + check(reason.contains("quarantined v2.0.0"), "the other Mac's quarantine is named: \(reason)") + } else { check(false, "a release the other Mac quarantined is not installed here") } + // A progress from a build without the quarantine field still decodes, with none. + let older = try? JSONDecoder().decode(ClusterPairUpdateProgress.self, + from: Data(#"{"phase":"idle","running":"1.0.0","writtenAt":1}"#.utf8)) + check(older != nil && older?.quarantined == nil, "an older build's progress has no quarantine") // `darkbloom update` waits, while serving, for the one run on the other Mac; a drained Mac does not wait for it. check(state(disabled, .staged, requested: true) == .waiting, "a requested update waits for the other Mac's") if case .gaveUp = state(disabled, .drained, requested: true) {} else { check(false, "a drained Mac does not wait for a Mac with updates off") } diff --git a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift index 6132b89e2e..689d05f118 100644 --- a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift @@ -608,4 +608,35 @@ struct ClusterPairUpdateTests { #expect(try other.fixture.liveBinaryContents() == "2.0.0-darkbloom") #expect(try other.store.loadState().quarantine == nil) } + + /// What decides the follow before the lease: the Mac that rolled back says the other Mac still runs the release; a + /// Mac whose part cannot drain does not follow yet; a Mac on another release finds nothing to follow without the + /// lease, even while another update holds it. + @Test func followIsDecidedBeforeTheLease() async throws { + let rolledBack = try await PairMac.make(part: false), peer = try await PairMac.make(part: false) + defer { Task { await rolledBack.cleanUp(); await peer.cleanUp() } } + try await peer.installCandidate() + try peer.promote() + try await rolledBack.rollBackAfterFailedStartCheck() + let log = Lines(), now = Date().timeIntervalSince1970 + + ClusterPairUpdate.writeProgress(.init(phase: .idle, running: "2.0.0", writtenAt: now), to: peer.progressPath) + guard case .otherMacStillRuns(let line) = await rolledBack.cycle(partner: peer, log: log).followRollback({ _ in }) else { + Issue.record("the Mac that rolled back did not say the other Mac still runs v2.0.0"); return + } + #expect(line.contains("the other Mac still runs v2.0.0")) + + guard case .cannotFollow(let reason) = await peer.cycle(partner: rolledBack, log: log, part: .undrainable) + .followRollback({ _ in }) else { Issue.record("a part that cannot drain followed"); return } + #expect(reason.contains("it follows once its part can drain")) + #expect(try peer.fixture.liveBinaryContents() == "2.0.0-darkbloom" && peer.store.loadState().quarantine == nil) + #expect(ClusterPairUpdate.readProgress(from: peer.progressPath)?.phase == .idle, "nothing was published") + + let held = try rolledBack.fixture.updater(baseURL: rolledBack.baseURL).beginUpdateSession(operation: "cluster-auto-update") + defer { held.release() } + ClusterPairUpdate.writeProgress(.init(phase: .idle, running: "1.0.0", writtenAt: now, quarantined: "2.0.0"), + to: peer.progressPath) + let other = await rolledBack.cycle(partner: peer, log: log).followRollback { _ in } + #expect(other == .nothingToFollow, "not .busy: the lease is not asked for") + } } From a9595034bd4a0c8954f5bfe1c303ff5b1bc159e7 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:13:50 -0600 Subject: [PATCH 0224/1441] fix(provider): pair follow: requested updates wait on a partner's quarantine; kept release decided before the lease (Refactor Pass round 2) - ClusterPairUpdate.partnerState: a cycle `darkbloom update` asked for waits at the staged step for a partner that keeps the release quarantined, so `--override-quarantine` on both Macs works as #1702 documents; slot cycles and the drained step still give it up. - A Mac that keeps another release for rollback cannot follow, decided from the recovery state without the lease. - The follow's wait for the other Mac's drain is bounded like its stage wait. - The deferral's next slot is computed when the follow ends. - Neutral wording for the split notice; docs for an override on a pair. Co-Authored-By: Claude Opus 5.5 --- docs/provider/cluster-always-on.md | 15 +++++++++++---- .../ClusterSupervision/ClusterPairUpdate.swift | 7 +++++-- .../Update/ClusterPairUpdateCycle.swift | 15 +++++++++++---- .../darkbloom/ClusterMemberSupervisor.swift | 9 ++++++--- .../Tests/ClusterSupervisionChecks/main.swift | 5 +++++ .../Update/ClusterPairUpdateTests.swift | 10 ++++++++++ 6 files changed, 48 insertions(+), 13 deletions(-) diff --git a/docs/provider/cluster-always-on.md b/docs/provider/cluster-always-on.md index 4cb5482c02..10ed913841 100644 --- a/docs/provider/cluster-always-on.md +++ b/docs/provider/cluster-always-on.md @@ -201,8 +201,8 @@ runs, also with automatic updates off: the release it restores is one the Mac ran before. It follows (`ClusterPairUpdateCycle.followRollback`) when the other Mac quarantined the release this Mac runs (installed or promoted) and runs the release this Mac keeps for rollback. The check reads both Macs' recovery state -without the update lease; only a Mac that runs the quarantined release takes the -lease and verifies its kept release. The follow is the update cycle's sequence +without the update lease; only a Mac that runs the quarantined release and keeps +the other Mac's release for rollback takes the lease and verifies it. The follow is the update cycle's sequence with a rollback in place of the install: 1. It takes the update lease, the one every update cycle, candidate recovery @@ -236,8 +236,15 @@ It does not follow, changes nothing, and says why once in its log or alone): it follows once its part can drain. The Mac that rolled back says once `cluster update: the other Mac still runs -v, which this Mac rolled back and quarantined` while the other Mac has -not followed. Other lines: `cluster update: the other Mac rolled v +v, which is quarantined on this Mac` while the other Mac has not +followed, or has installed the release again on purpose. + +To install a release both Macs quarantined anyway, run `darkbloom update +--override-quarantine` on both Macs: the cycle the first command starts waits, +while serving, for the other Mac's, as for `darkbloom update` with automatic +updates off. An update slot, by contrast, gives up a release the other Mac +reports quarantined. Right after an override, the other Mac may still read the +old quarantine for up to a minute and follow it. Other lines: `cluster update: the other Mac rolled v back to v and quarantined it; this Mac follows to v` and `cluster update: restored v and quarantined v, as on the other Mac`. diff --git a/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift b/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift index 8313b13fac..0a2b6aed31 100644 --- a/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift +++ b/provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift @@ -59,8 +59,11 @@ public enum ClusterPairUpdate { now: Double, requested: Bool = false) -> PartnerState { guard case .reported(let progress) = partner else { return .cannotCoordinate } if progress.running == target { return .ready } - // The other Mac rolled this release back: it will not install it, so neither does this Mac. - if progress.quarantined == target { return .gaveUp("the other Mac quarantined v\(target)") } + // The other Mac rolled this release back: it will not install it, so neither does this Mac. A cycle + // `darkbloom update` asked for waits instead, while serving, for the other Mac's (`--override-quarantine`). + if progress.quarantined == target { + return requested && step == .staged ? .waiting : .gaveUp("the other Mac quarantined v\(target)") + } switch progress.phase { case .disabled: // Its slot never comes, but its own `darkbloom update` may: a requested cycle waits for it while serving. diff --git a/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift b/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift index 1e0105cd74..60eb364a91 100644 --- a/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift +++ b/provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift @@ -170,12 +170,17 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { let recorded = updater.recordedRecoveryState() if let mine = recorded?.quarantine?.version, progress.running == mine, progress.quarantined != mine, Self.installed(recorded) != mine { - return .otherMacStillRuns("the other Mac still runs v\(mine), which this Mac rolled back and quarantined; " - + "it follows once it runs a build that follows rollbacks and its part can drain") + return .otherMacStillRuns("the other Mac still runs v\(mine), which is quarantined on this Mac") } // A Mac that runs the release it quarantined (installed again with `--override-quarantine`) rolled nothing back. guard let quarantined = progress.quarantined, progress.running != quarantined, Self.installed(recorded) == quarantined else { return .nothingToFollow } + // Only the release this Mac keeps for rollback can be restored; that is read without the lease too. + guard recorded?.predecessor?.release.version == progress.running else { + let kept = recorded?.predecessor.map { "keeps v\($0.release.version) for rollback" } ?? "keeps no earlier release" + return .cannotFollow("the other Mac rolled v\(quarantined) back to v\(progress.running), but this Mac \(kept); " + + "it stays on v\(quarantined) until a newer release updates both Macs") + } if environment.part() == .undrainable { return .cannotFollow("the other Mac rolled v\(quarantined) back to v\(progress.running), but " + Self.undrainable + "; it follows once its part can drain") @@ -403,7 +408,9 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { } } publish(.drained) - let deadline = started + timing.partnerDrainWait + let following = lock.withLock { self.following } + let drainWait = following ? min(timing.partnerDrainWait, ClusterPairUpdate.progressStaleSeconds) : timing.partnerDrainWait + let deadline = started + drainWait while true { switch partnerState(.drained, target: target) { case .ready: @@ -419,7 +426,7 @@ public final class ClusterPairUpdateCycle: @unchecked Sendable { } if Task.isCancelled { giveUp("the cycle was stopped"); return false } guard Self.now() < deadline else { - giveUp("the other Mac did not drain for v\(target) within \(Int(timing.partnerDrainWait)) s"); return false + giveUp("the other Mac did not drain for v\(target) within \(Int(drainWait)) s"); return false } await Self.sleep(timing.poll) } diff --git a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift index 9a7a0718c3..d9e406002c 100644 --- a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift +++ b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift @@ -511,8 +511,6 @@ final class ClusterMemberSupervisor: @unchecked Sendable { private func startFollowCheckIfDue(_ pair: PairUpdate, pid: Int32, now: Double) { guard now >= nextFollowCheck, now >= lock.withLock({ followDeferredUntil }) else { return } nextFollowCheck = now + ClusterPairUpdate.followCheckSeconds - let nextSlot = pair.clusterID().map { ClusterMemberUpdateSlot.nextSlot(after: now, clusterID: $0) } - ?? now + ClusterMemberUpdateSlot.periodSeconds publishQuarantine(pair) lock.withLock { pairCycleRunning = true } let log: @Sendable (String) -> Void = { [weak self] in self?.log($0) } @@ -532,7 +530,12 @@ final class ClusterMemberSupervisor: @unchecked Sendable { let say: String? = self.lock.withLock { defer { self.pairCycleRunning = false; self.followNotice = notice } if case .followed(let ended) = outcome { - if case .restarted = ended {} else { self.followDeferredUntil = nextSlot } + if case .restarted = ended {} else { + // From the deferral, not the check's start: a follow that ran past a slot waits for the next. + let ended = Date().timeIntervalSince1970 + self.followDeferredUntil = pair.clusterID().map { ClusterMemberUpdateSlot.nextSlot(after: ended, clusterID: $0) } + ?? ended + ClusterMemberUpdateSlot.periodSeconds + } } return notice == self.followNotice ? nil : notice } diff --git a/provider-swift/Tests/ClusterSupervisionChecks/main.swift b/provider-swift/Tests/ClusterSupervisionChecks/main.swift index e3648b999f..878d7f05d8 100644 --- a/provider-swift/Tests/ClusterSupervisionChecks/main.swift +++ b/provider-swift/Tests/ClusterSupervisionChecks/main.swift @@ -298,6 +298,11 @@ do { if case .gaveUp(let reason) = state(quarantinedThere, .staged) { check(reason.contains("quarantined v2.0.0"), "the other Mac's quarantine is named: \(reason)") } else { check(false, "a release the other Mac quarantined is not installed here") } + // `darkbloom update --override-quarantine` is run on both Macs: a requested cycle waits for the other Mac's. + check(state(quarantinedThere, .staged, requested: true) == .waiting, "a requested update waits for the other Mac's override") + if case .gaveUp = state(quarantinedThere, .drained, requested: true) {} else { + check(false, "a drained Mac does not wait for a Mac that keeps the release quarantined") + } // A progress from a build without the quarantine field still decodes, with none. let older = try? JSONDecoder().decode(ClusterPairUpdateProgress.self, from: Data(#"{"phase":"idle","running":"1.0.0","writtenAt":1}"#.utf8)) diff --git a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift index 689d05f118..af740dd454 100644 --- a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift @@ -638,5 +638,15 @@ struct ClusterPairUpdateTests { to: peer.progressPath) let other = await rolledBack.cycle(partner: peer, log: log).followRollback { _ in } #expect(other == .nothingToFollow, "not .busy: the lease is not asked for") + + // A Mac that runs the quarantined release but keeps another one cannot follow, decided without the lease. + let peerLease = try peer.fixture.updater(baseURL: peer.baseURL).beginUpdateSession(operation: "cluster-auto-update") + defer { peerLease.release() } + ClusterPairUpdate.writeProgress(.init(phase: .idle, running: "0.9.0", writtenAt: now, quarantined: "2.0.0"), + to: rolledBack.progressPath) + guard case .cannotFollow(let keeps) = await peer.cycle(partner: rolledBack, log: log).followRollback({ _ in }) else { + Issue.record("a Mac keeping another release asked for the lease"); return + } + #expect(keeps.contains("keeps v1.0.0 for rollback")) } } From 5c379d81c9423d42171170dbb6da4235d998227a Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:14:42 -0600 Subject: [PATCH 0225/1441] fix(provider): read the cluster ID outside the supervisor lock; doc paragraph order Co-Authored-By: Claude Opus 5.5 --- docs/provider/cluster-always-on.md | 10 +++++----- .../darkbloom/ClusterMemberSupervisor.swift | 18 ++++++++++-------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/docs/provider/cluster-always-on.md b/docs/provider/cluster-always-on.md index 10ed913841..63101b499c 100644 --- a/docs/provider/cluster-always-on.md +++ b/docs/provider/cluster-always-on.md @@ -237,17 +237,17 @@ It does not follow, changes nothing, and says why once in its log The Mac that rolled back says once `cluster update: the other Mac still runs v, which is quarantined on this Mac` while the other Mac has not -followed, or has installed the release again on purpose. +followed, or has installed the release again on purpose. Other lines: +`cluster update: the other Mac rolled v back to v and +quarantined it; this Mac follows to v` and `cluster update: restored +v and quarantined v, as on the other Mac`. To install a release both Macs quarantined anyway, run `darkbloom update --override-quarantine` on both Macs: the cycle the first command starts waits, while serving, for the other Mac's, as for `darkbloom update` with automatic updates off. An update slot, by contrast, gives up a release the other Mac reports quarantined. Right after an override, the other Mac may still read the -old quarantine for up to a minute and follow it. Other lines: `cluster update: the other Mac rolled v -back to v and quarantined it; this Mac follows to v` and -`cluster update: restored v and quarantined v, as on the -other Mac`. +old quarantine for up to a minute and follow it. Both Macs need a build that follows rollbacks. The quarantine is reported by the Mac that rolled back after the rollback, so by the restored release's diff --git a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift index d9e406002c..e80a0118d9 100644 --- a/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift +++ b/provider-swift/Sources/darkbloom/ClusterMemberSupervisor.swift @@ -527,16 +527,18 @@ final class ClusterMemberSupervisor: @unchecked Sendable { case .otherMacStillRuns(let reason): notice = reason default: notice = nil } + // From the deferral, not the check's start: a follow that ran past a slot waits for the next. + var deferredUntil: Double? + if case .followed(let ended) = outcome { + if case .restarted = ended {} else { + let now = Date().timeIntervalSince1970 + deferredUntil = pair.clusterID().map { ClusterMemberUpdateSlot.nextSlot(after: now, clusterID: $0) } + ?? now + ClusterMemberUpdateSlot.periodSeconds + } + } let say: String? = self.lock.withLock { defer { self.pairCycleRunning = false; self.followNotice = notice } - if case .followed(let ended) = outcome { - if case .restarted = ended {} else { - // From the deferral, not the check's start: a follow that ran past a slot waits for the next. - let ended = Date().timeIntervalSince1970 - self.followDeferredUntil = pair.clusterID().map { ClusterMemberUpdateSlot.nextSlot(after: ended, clusterID: $0) } - ?? ended + ClusterMemberUpdateSlot.periodSeconds - } - } + if let deferredUntil { self.followDeferredUntil = deferredUntil } return notice == self.followNotice ? nil : notice } if let say { self.log("cluster update: \(say)") } From 5fdde48f837261832c8e174fffe34eeddbc9877e Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:41:30 -0600 Subject: [PATCH 0226/1441] ci: run the GLM switched tests that pass on the CI VM in the blocking job The first run with MLX_QMV_BATCH_INVARIANT=1 passed the GLM paged-KV and row-invariance tests and two each of the depth-invariance and census tests; they move to Cluster Runtime Tests shard 2. The fused residual-norm sum test and the paged prompt-frame transient test move to the non-blocking job. Co-Authored-By: Claude Opus 5.5 --- scripts/cluster-test-plan.py | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/scripts/cluster-test-plan.py b/scripts/cluster-test-plan.py index 59f9578b9b..62b1433535 100755 --- a/scripts/cluster-test-plan.py +++ b/scripts/cluster-test-plan.py @@ -116,7 +116,6 @@ def base(self): "deepRestoresEqualColdPrefillOnBothRanks", )), Selection("qwen-tp-batch-gpu-paged", "blocking", 3, {"QWEN_TP_BATCH_GPU": "1", "QWEN_TP_BATCH_KV": "paged"}, tests=( - "fullHistoryGatherIsOnePromptFramesTransient", "cohortSurvivorKeepsOnlyItsOwnRows", "routedExpertCapacityOneAndTwoKeepExactPagedLogitsAndHistory", "capacityOneAndTwoKeepExactPagedLogitsAndHistory", @@ -134,7 +133,6 @@ def base(self): "siluMultiplyEqualsTheUnfusedChain", "sigmoidGateEqualsTheUnfusedChain", "cachedGatedDeltaScalesEqualFreshOnes", - "transposedCPUSumWaitsBeforeTheCopyOnGPU", )), Selection("qwen-tp-moe-gpu", "blocking", 3, {"QWEN_TP_MOE_GPU": "1", "QWEN_TP_MOE_GPU_DIAG": "1"}, tests=( "packedSharedExpertCollectiveIsBitIdenticalOnTwoGPURanks", @@ -148,6 +146,21 @@ def base(self): "aServingStageRestoresFromTheSSDExactly", "aServingStageRestoresFromABalancedRecord", )), + Selection("glm53-paged-kv", "blocking", 2, {"GLM53_PAGED_KV": "1"}, tests=( + "pagedRequestsDecideAndHoldWhatContiguousOnesDo", + "pagedMediaRequestsDecideAndHoldWhatContiguousOnesDo", + )), + Selection("glm53-row-invariance", "blocking", 2, {"GLM53_ROW_INVARIANCE": "1"}, tests=( + "roundsAreEachRequestsOwnRound", + )), + Selection("glm53-depth-invariance", "blocking", 2, {"GLM53_DEPTH_INVARIANCE": "1"}, tests=( + "prefillIsTheSameWithAndWithoutTheSwitch", + "unpaddedLastRoundsStayOneRowWindows", + )), + Selection("glm53-window-census", "blocking", 2, {"GLM53_WINDOW_CENSUS": "1"}, tests=( + "sublayerCensus", + "projectionRowCensus", + )), Selection("qwen-tp-real-geometry-gpu", "nonblocking", 1, {"QWEN_TP_REAL_GEOMETRY_GPU": "1"}, tests=( "rowsEqualTheirSoloStepsAndWindowPositionsAtRealWidths", )), @@ -160,24 +173,18 @@ def base(self): "gatedDeltaQKNormEqualsTheUnfusedOps", "cpuStreamSumIsBitwiseOnGPU", "chainWithCPUHopsIsBitwiseOnGPU", + "transposedCPUSumWaitsBeforeTheCopyOnGPU", )), - Selection("glm53-paged-kv", "nonblocking", 2, {"GLM53_PAGED_KV": "1"}, tests=( - "pagedRequestsDecideAndHoldWhatContiguousOnesDo", - "pagedMediaRequestsDecideAndHoldWhatContiguousOnesDo", - )), - Selection("glm53-row-invariance", "nonblocking", 2, {"GLM53_ROW_INVARIANCE": "1"}, tests=( - "roundsAreEachRequestsOwnRound", + Selection("qwen-tp-batch-gpu-paged-transient", "nonblocking", 2, + {"QWEN_TP_BATCH_GPU": "1", "QWEN_TP_BATCH_KV": "paged"}, tests=( + "fullHistoryGatherIsOnePromptFramesTransient", )), - Selection("glm53-depth-invariance", "nonblocking", 2, {"GLM53_DEPTH_INVARIANCE": "1"}, tests=( + Selection("glm53-depth-invariance-widths", "nonblocking", 2, {"GLM53_DEPTH_INVARIANCE": "1"}, tests=( "everyDepthAndKeptPatternIsTheDepthTwoDecode", "loadPolicyLanesAreEachRequestAloneAtDepthTwo", - "prefillIsTheSameWithAndWithoutTheSwitch", - "unpaddedLastRoundsStayOneRowWindows", )), - Selection("glm53-window-census", "nonblocking", 2, {"GLM53_WINDOW_CENSUS": "1"}, tests=( + Selection("glm53-window-width-census", "nonblocking", 2, {"GLM53_WINDOW_CENSUS": "1"}, tests=( "windowWidthCensus", - "sublayerCensus", - "projectionRowCensus", )), Selection("paged-verify-bench", "nonblocking", 2, {"DARKBLOOM_PAGED_BENCH": "1"}, tests=( "verifyAndPrefillAttention", From f6fb0137372b16b4460a80bd2c81f3681686adb6 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:42:05 -0600 Subject: [PATCH 0227/1441] docs: the cluster prefix tier's budget ceiling and its parameter Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 9d40490161..2a30b03843 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-11-01 +> Last updated: 2026-11-03 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -125,6 +125,12 @@ admission and LOAD safeguards remain authoritative. GLM, private-image and coordinator-installed native-member sessions do not use this automatic policy. Explicit diagnostic mode or lane settings retain their choice. +A stage's resident prefix tier takes half the room that LOAD measures beside +its quote, in 256 MiB steps, up to a ceiling of a thirty-second of the Mac's +memory (`QwenStagePrefixCache.budget(roomBytes:maximumBytes:)`, and the idle +refresh `refreshBudget`). The ceiling is the Mac's own unless the caller gives +the ceiling of the Mac that it models, as the budget tests do for a 128 GiB Mac. + Automatic replacement reads the installed plan helper's device profile and the current pair's recorded keyed-link costs and served-request history. It uses the same measurement readers as initial placement, so a supported TP batch From 38df73ad17f131247dc1b70da294245f8883d6f7 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 06:53:00 -0600 Subject: [PATCH 0228/1441] ci: refactor pass on the cluster test plan Run the TF32 forward comparison in its own MLX_ENABLE_TF32=0 selection, so it runs on any Mac the route grants instead of skipping on an M5. Strip every test switch prefix from inherited environments, scan test subdirectories, drop the unused shards subcommand, match the gate's needs list by name, and correct run-nested-suite.sh's description of what it runs. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 4 ++-- docs/developer/test.md | 2 +- scripts/cluster-test-plan.py | 27 +++++++++++++-------------- scripts/run-nested-suite.sh | 10 +++++----- scripts/test-cluster-test-plan.py | 10 ++++++---- 5 files changed, 27 insertions(+), 26 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 2a30b03843..e402024328 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -128,8 +128,8 @@ automatic policy. Explicit diagnostic mode or lane settings retain their choice. A stage's resident prefix tier takes half the room that LOAD measures beside its quote, in 256 MiB steps, up to a ceiling of a thirty-second of the Mac's memory (`QwenStagePrefixCache.budget(roomBytes:maximumBytes:)`, and the idle -refresh `refreshBudget`). The ceiling is the Mac's own unless the caller gives -the ceiling of the Mac that it models, as the budget tests do for a 128 GiB Mac. +refresh `refreshBudget`). The ceiling is the Mac's own: `maximumBytes` +defaults to it. Automatic replacement reads the installed plan helper's device profile and the current pair's recorded keyed-link costs and served-request history. It uses diff --git a/docs/developer/test.md b/docs/developer/test.md index ab4879e7c7..76d8b6fe12 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1158,7 +1158,7 @@ with isolated fixture runners: each `provider-swift/Tests/Cluster*Checks/run.sh` `libs/darkbloom-cluster/Tests/*Checks/run.sh` and `libs/darkbloom-cluster-worker/Tests/*Checks/run.sh` prints its pass count and exits non-zero on a failure. The CI job `test-cluster-checks` (Cluster Metadata -Checks, `.github/workflows/ci.yml`) runs these of them on every pull request that +Checks, `.github/workflows/ci.yml`) runs these runners on every pull request that changes provider code: `libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh`, `libs/darkbloom-cluster/Tests/PrefillScheduleChecks/run.sh`, `libs/darkbloom-cluster/Tests/StageMetadataChecks/run.py`, diff --git a/scripts/cluster-test-plan.py b/scripts/cluster-test-plan.py index 62b1433535..306cf02b13 100755 --- a/scripts/cluster-test-plan.py +++ b/scripts/cluster-test-plan.py @@ -16,14 +16,12 @@ the model-free runner scripts). Subcommands: - shards LANE print the lane's shard numbers as a JSON list run LANE SHARD run the selections of one shard, each in its own process audit check the plan against the sources and the workflow """ import argparse from dataclasses import dataclass, field -import json import os from pathlib import Path import re @@ -161,6 +159,9 @@ def base(self): "sublayerCensus", "projectionRowCensus", )), + Selection("tf32-off", "blocking", 2, {"MLX_ENABLE_TF32": "0"}, tests=( + "receiverCommitPrecedesProducerPublicationAndMatchesFullCachedForward", + )), Selection("qwen-tp-real-geometry-gpu", "nonblocking", 1, {"QWEN_TP_REAL_GEOMETRY_GPU": "1"}, tests=( "rowsEqualTheirSoloStepsAndWindowPositionsAtRealWidths", )), @@ -227,9 +228,6 @@ def base(self): "verifyWindowRoundsByRowCount", ) REQUIRES_MODEL_SUITES = ("GLM5NextServingMetadataTests", "GLM5NextTensorParallelMediaTowerTests") -# Gated on the GPU, not on a switch: enabled where float32 products are full -# (no TF32 on the CI VM's GPU). They run in a base selection. -HARDWARE_GATED = ("receiverCommitPrecedesProducerPublicationAndMatchesFullCachedForward",) # Runners the Cluster Metadata Checks job runs with its retained native build. METADATA_JOB_RUNNERS = ("GPTOSSStageChecks", "NemotronStageChecks", "PrefillScheduleChecks", "StageMetadataChecks") @@ -267,9 +265,15 @@ def command(selection, output): return ROOT, ["bash", str(directory / "run.sh")] +# Variables the runtime tests read to change what they run; no selection +# inherits one from the runner. +TEST_SWITCH_PREFIXES = ("QWEN_TP_", "GLM53_", "DARKBLOOM_PAGED_BENCH", "PREFIX_RECORD_") + + def environment(selection): switches = {name for other in SELECTIONS for name in other.environment} - values = {name: value for name, value in os.environ.items() if name not in switches} + values = {name: value for name, value in os.environ.items() + if name not in switches and not name.startswith(TEST_SWITCH_PREFIXES)} return {**values, **PROCESS_ENVIRONMENT, **selection.environment} @@ -307,7 +311,7 @@ def gated_in_sources(directory=RUNTIME_TESTS): """(gated test functions, gated suites, function names defined more than once).""" functions, suites, defined = set(), set(), {} attribute = re.compile(r"@(Test|Suite)\(") - for path in sorted(directory.glob("*.swift")): + for path in sorted(directory.rglob("*.swift")): text = path.read_text() for match in re.finditer(r"\bfunc (\w+)\(", text): defined[match.group(1)] = defined.get(match.group(1), 0) + 1 @@ -334,10 +338,10 @@ def audit(): planned = [name for selection in SELECTIONS for name in selection.tests] for name in sorted({name for name in planned if planned.count(name) > 1}): errors.append(f"{name} is in more than one selection") - named_once = planned + list(REQUIRES_MODEL) + list(HARDWARE_GATED) + named_once = planned + list(REQUIRES_MODEL) functions, suites, repeated = gated_in_sources() for name in sorted(functions - set(named_once)): - errors.append(f"Gated test {name} is in no selection, REQUIRES_MODEL or HARDWARE_GATED") + errors.append(f"Gated test {name} is in no selection or REQUIRES_MODEL") for name in sorted(set(named_once) - functions): errors.append(f"{name} is planned but is not a gated test in {RUNTIME_TESTS.relative_to(ROOT)}") for name in sorted(set(named_once) & repeated): @@ -365,16 +369,11 @@ def audit(): def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) commands = parser.add_subparsers(dest="command", required=True) - command_parser = commands.add_parser("shards") - command_parser.add_argument("lane", choices=LANES) command_parser = commands.add_parser("run") command_parser.add_argument("lane", choices=LANES) command_parser.add_argument("shard", type=int) commands.add_parser("audit") args = parser.parse_args() - if args.command == "shards": - print(json.dumps(shards(args.lane))) - return 0 if args.command == "run": return run(args.lane, args.shard) errors = audit() diff --git a/scripts/run-nested-suite.sh b/scripts/run-nested-suite.sh index 33688fda0f..9a79142f28 100755 --- a/scripts/run-nested-suite.sh +++ b/scripts/run-nested-suite.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # -# Run ONE swift-testing suite inside libs/mlx-swift-lm and fail if it executed -# zero tests. +# Run one `swift test` selection (a filter plus extra arguments) and fail if +# it executed zero tests or skipped one. # # THE TRIPWIRE IS THE POINT. `swift test` exits 0 even when the swift-testing # pass executes NOTHING — that is how the four paged suites sat dark for a @@ -64,9 +64,9 @@ fi # # A suite whose every case self-skips (XCTSkip on a missing fixture, a # .disabled/.enabled(if:) trait nobody meant to trip) asserts nothing — the -# same dark-gate failure mode, one layer up. Fail on ANY skip: these nested -# suites are hermetic by design (tiny models, no weights, no env gates), so a -# skip here means a precondition broke, not that skipping was intended. +# same dark-gate failure mode, one layer up. Fail on ANY skip: these +# selections are hermetic by design (every test they select is meant to run), +# so a skip here means a precondition broke, not that skipping was intended. if grep -qE '^[^A-Za-z0-9]*(Test|Suite) .+ skipped[.:]|with [1-9][0-9]* tests? skipped|skipped [1-9][0-9]* test' "$log"; then echo "::error::${filter} skipped one or more tests — a skipped gate gates" \ "nothing. If the skip is a broken precondition (missing metallib," \ diff --git a/scripts/test-cluster-test-plan.py b/scripts/test-cluster-test-plan.py index 7a9473751d..06167456a2 100755 --- a/scripts/test-cluster-test-plan.py +++ b/scripts/test-cluster-test-plan.py @@ -36,7 +36,6 @@ def test_every_test_runs_in_exactly_one_selection_unless_it_needs_a_model(self): module = plan.MODULE swift = [selection for selection in plan.SELECTIONS if selection.runner is None] cases = {f"{module}.AnySuite/{name}(sharded:)": name for selection in swift for name in selection.tests} - cases.update({f"{module}.AnySuite/{name}()": name for name in plan.HARDWARE_GATED}) cases.update({ f"{module}.QwenTensorParallelBatchSessionTests/actualShardsBatchIndependentHistories()": "base-batch-session", f"{module}.QwenTensorParallelBatchSessionTests/Nested/plainCase()": "base-batch-session", @@ -49,8 +48,7 @@ def test_every_test_runs_in_exactly_one_selection_unless_it_needs_a_model(self): runs = [selection for selection in swift if selected(selection, test_id)] self.assertEqual(len(runs), 1, [selection.name for selection in runs]) runner = runs[0] - self.assertTrue(runner.name == owner or owner in runner.tests or - (owner in plan.HARDWARE_GATED and runner.base), runner.name) + self.assertTrue(runner.name == owner or owner in runner.tests, runner.name) needs_model = [f"{module}.AnySuite/{name}()" for name in plan.REQUIRES_MODEL] needs_model += [f"{module}.{suite}/anyCase()" for suite in plan.REQUIRES_MODEL_SUITES] for test_id in needs_model: @@ -71,12 +69,14 @@ def test_every_selection_runs_through_the_zero_skip_wrapper_serially(self): def test_each_process_has_only_its_own_switches(self): switches = {name: "1" for selection in plan.SELECTIONS for name in selection.environment} + switches.update({"GLM53_WINDOW_CENSUS_LONG": "1", "DARKBLOOM_PAGED_BENCH_CTX": "4096"}) with mock.patch.dict(os.environ, switches): for selection in plan.SELECTIONS: with self.subTest(selection=selection.name): environment = plan.environment(selection) self.assertEqual(environment["MLX_QMV_BATCH_INVARIANT"], "1") own = {name: value for name, value in environment.items() if name in switches} + # Only its own switches: also none of the other variables the tests read. self.assertEqual(own, selection.environment) def test_jobs_run_every_shard_of_their_lane(self): @@ -102,10 +102,12 @@ def test_jobs_run_every_shard_of_their_lane(self): def test_only_the_gpu_job_continues_after_a_failure_and_the_gate_requires_the_others(self): self.assertIn("continue-on-error: true", workflow.step_blocks(self.jobs["test-cluster-gpu"])[-1]) + gate = workflow.field(self.jobs["provider-test-gate"], "needs", indent=4) + needs = [name.strip() for name in gate.strip("[]").split(",")] for job_id in ("test-cluster", "test-cluster-focused"): with self.subTest(job=job_id): self.assertNotIn("continue-on-error:", self.jobs[job_id]) - self.assertIn(job_id, workflow.field(self.jobs["provider-test-gate"], "needs", indent=4)) + self.assertIn(job_id, needs) self.assertNotIn("test-cluster-gpu", self.jobs["provider-test-gate"]) From 54687f11a2667f20e7d5273abde3519ef020ddb1 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 07:03:47 -0600 Subject: [PATCH 0229/1441] ci: run the Qwen TP prompt wavefront GPU tests from dev in the blocking job Co-Authored-By: Claude Opus 5.5 --- scripts/cluster-test-plan.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/cluster-test-plan.py b/scripts/cluster-test-plan.py index 306cf02b13..58c513f40a 100755 --- a/scripts/cluster-test-plan.py +++ b/scripts/cluster-test-plan.py @@ -112,6 +112,9 @@ def base(self): "warmHybridPrefixesPreserveConvSSMAndMixedPositions", "ssdHybridPrefixesRestoreConvSSMAfterTheTiersReopen", "deepRestoresEqualColdPrefillOnBothRanks", + "mergedStepTemporariesStayWithinTheirCharge", + "mergedFramesKeepEveryBit", + "executorRunsThePlannedMergedStep", )), Selection("qwen-tp-batch-gpu-paged", "blocking", 3, {"QWEN_TP_BATCH_GPU": "1", "QWEN_TP_BATCH_KV": "paged"}, tests=( "cohortSurvivorKeepsOnlyItsOwnRows", From 4d4d99504e9e1a85d3b150de0a9c6951aa1d18e4 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 07:32:58 -0600 Subject: [PATCH 0230/1441] docs: the other Mac follows a rollback, in the pages #1702 updated Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 4 +++- docs/provider/two-mac-cluster.md | 8 ++++++-- docs/reference/configuration.md | 2 +- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 6237619913..013942abb3 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3026,7 +3026,9 @@ cluster service re-plans and re-adopts the same model by itself answer with the same worker build (`ClusterOnboardingUpdate.oneBuild`): the [pair's coordinated update](../provider/cluster-always-on.md#the-pairs-coordinated-update) restarts the two Macs seconds apart, and a plan made while one still runs the -other build would fail and wait 600 s. A model change of +other build would fail and wait 600 s. A Mac that rolls a release back is followed by the other +Mac to the same release ([a rollback on one Mac](../provider/cluster-always-on.md#a-rollback-on-one-mac)), +which the leader then plans the same way. A model change of a serving cluster (`m`, or `darkbloom cluster local `) plans the same way: its list was priced while the running parts held their memory, where tensor parallel may not fit now, so once both parts stopped and both Macs gave the diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index b2c887bb08..fff29cfaab 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -563,8 +563,12 @@ release's cluster service has stayed healthy for 10 minutes, three of its starts that end by themselves bring back the previous release and quarantine the new one, as the watchdog does for a single Mac. A Mac never restarts into a new release that does not start at all (it checks before the restart): it brings -back the previous release at once and quarantines the new one. How the cluster -service does this is in +back the previous release at once and quarantines the new one. When one Mac +brings back the previous release this way, or with `darkbloom update +--rollback`, the other Mac brings back the same release and quarantines the new +one too, so the pair serves the previous release together +([a rollback on one Mac](cluster-always-on.md#a-rollback-on-one-mac)). How the +cluster service does this is in [the pair's coordinated update](cluster-always-on.md#the-pairs-coordinated-update). To update at once, run on each Mac: diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index fa2ca6bfeb..fe454477e9 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -407,7 +407,7 @@ provider or model command is running. Code: | Variable | Values / type | Default | Read in | Effect | |---|---|---|---|---| -| `DARKBLOOM_NO_UPDATE_CHECK` | any value | unset | `provider-swift/Sources/darkbloom/Darkbloom.swift`; `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift`; `provider-swift/Sources/darkbloom/WatchdogCommand.swift`; `provider-swift/Sources/ProviderCore/ProviderLoop+AutoUpdate.swift`; `provider-swift/Sources/darkbloom/ClusterServiceCommand.swift` (`supervisorConfiguration`); forwarded by `provider-swift/Sources/ProviderCore/Service/WatchdogAgent.swift` | Skips the startup version banner, the in-daemon auto-update loop, the start-mode check, the watchdog's update check and the `darkbloom cluster` pair's update at its slot; `scripts/install.sh` sets it for the runtime smoke test. | +| `DARKBLOOM_NO_UPDATE_CHECK` | any value | unset | `provider-swift/Sources/darkbloom/Darkbloom.swift`; `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift`; `provider-swift/Sources/darkbloom/WatchdogCommand.swift`; `provider-swift/Sources/ProviderCore/ProviderLoop+AutoUpdate.swift`; `provider-swift/Sources/darkbloom/ClusterServiceCommand.swift` (`supervisorConfiguration`); forwarded by `provider-swift/Sources/ProviderCore/Service/WatchdogAgent.swift` | Skips the startup version banner, the in-daemon auto-update loop, the start-mode check, the watchdog's update check and the `darkbloom cluster` pair's update at its slot; `scripts/install.sh` sets it for the runtime smoke test. It does not stop a pair Mac from following the other Mac's rollback to the release it ran before ([a rollback on one Mac](../provider/cluster-always-on.md#a-rollback-on-one-mac)). | | `DARKBLOOM_AUTH_TOKEN_PATH` | file path | `~/.darkbloom/auth_token` | `provider-swift/Sources/ProviderCore/Auth/DeviceAuth.swift` | A nonempty explicit path replaces the token path. Without it, the token is read only from `~/.darkbloom/auth_token` (for `sudo darkbloom report`, the invoking user's, read-only through `AuthTokenStore.loadReadOnly`); there is no legacy-path fallback. | | `DARKBLOOM_LOCAL_DIR` | directory | `~/.darkbloom` | `provider-swift/Sources/ProviderCore/Server/LocalEndpoint.swift` | Directory for `local_token` and `local.json` (direct mode). | | `DARKBLOOM_STATE_FILE` | file path | `~/.darkbloom/daemon-state.json` | `provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift` | Daemon state snapshot read by `status`, `doctor` and the watchdog. | From 984f1dc1b7bf011196376fffa427853d4e49f7bb Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 08:14:17 -0600 Subject: [PATCH 0231/1441] test(provider): label the restart argument in the follow tests Four calls passed the closure in parentheses without its label, which does not compile. No expectation changed. Co-Authored-By: Claude Opus 5.5 --- .../ProviderCoreTests/Update/ClusterPairUpdateTests.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift index af740dd454..c7325b4d05 100644 --- a/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift @@ -601,7 +601,7 @@ struct ClusterPairUpdateTests { try other.promote() ClusterPairUpdate.writeProgress(.init(phase: .idle, running: "0.9.0", writtenAt: Date().timeIntervalSince1970, quarantined: "2.0.0"), to: rolledBack.progressPath) - guard case .cannotFollow(let reason) = await other.cycle(partner: rolledBack, log: log).followRollback({ _ in }) else { + guard case .cannotFollow(let reason) = await other.cycle(partner: rolledBack, log: log).followRollback(restart: { _ in }) else { Issue.record("followed a rollback to a release it does not keep"); return } #expect(reason.contains("keeps v1.0.0 for rollback")) @@ -621,13 +621,13 @@ struct ClusterPairUpdateTests { let log = Lines(), now = Date().timeIntervalSince1970 ClusterPairUpdate.writeProgress(.init(phase: .idle, running: "2.0.0", writtenAt: now), to: peer.progressPath) - guard case .otherMacStillRuns(let line) = await rolledBack.cycle(partner: peer, log: log).followRollback({ _ in }) else { + guard case .otherMacStillRuns(let line) = await rolledBack.cycle(partner: peer, log: log).followRollback(restart: { _ in }) else { Issue.record("the Mac that rolled back did not say the other Mac still runs v2.0.0"); return } #expect(line.contains("the other Mac still runs v2.0.0")) guard case .cannotFollow(let reason) = await peer.cycle(partner: rolledBack, log: log, part: .undrainable) - .followRollback({ _ in }) else { Issue.record("a part that cannot drain followed"); return } + .followRollback(restart: { _ in }) else { Issue.record("a part that cannot drain followed"); return } #expect(reason.contains("it follows once its part can drain")) #expect(try peer.fixture.liveBinaryContents() == "2.0.0-darkbloom" && peer.store.loadState().quarantine == nil) #expect(ClusterPairUpdate.readProgress(from: peer.progressPath)?.phase == .idle, "nothing was published") @@ -644,7 +644,7 @@ struct ClusterPairUpdateTests { defer { peerLease.release() } ClusterPairUpdate.writeProgress(.init(phase: .idle, running: "0.9.0", writtenAt: now, quarantined: "2.0.0"), to: rolledBack.progressPath) - guard case .cannotFollow(let keeps) = await peer.cycle(partner: rolledBack, log: log).followRollback({ _ in }) else { + guard case .cannotFollow(let keeps) = await peer.cycle(partner: rolledBack, log: log).followRollback(restart: { _ in }) else { Issue.record("a Mac keeping another release asked for the lease"); return } #expect(keeps.contains("keeps v1.0.0 for rollback")) From 325248ec0d632f4f0eab0480923b258a9c92a634 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 08:40:43 -0600 Subject: [PATCH 0232/1441] ci: refuse a dev plain-build default on master, and a prod one on dev provider-swift/Package.swift falls back to an environment when DARKBLOOM_RELEASE_ENVIRONMENT is unset. master must fall back to prod and dev to dev. scripts/provider-build-default.py reads that fallback and checks it for a target branch; it fails when it cannot find the fallback, so a change to Package.swift cannot turn the check off. - ci.yml, Release Integrity: checks the pull request's base branch, or the pushed branch (master -> prod, dev -> dev, others unchecked). - release-provider.yml, resolve-env: a staging or prod lane (master) stops before the build and signing unless the default is prod. - release-swift.yml and release-dev-branch.yml: the new script joins the push path lists, which test-provider-release-pipeline.py and test-release-dev-branch.py require to cover every release script and to stay equal. The dev lane does not run the check. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 8 ++ .github/workflows/release-dev-branch.yml | 1 + .github/workflows/release-provider.yml | 7 ++ .github/workflows/release-swift.yml | 1 + docs/developer/build.md | 8 +- docs/operations/provider-release.md | 6 +- scripts/provider-build-default.py | 59 +++++++++++++ scripts/test-provider-build-default.py | 102 +++++++++++++++++++++++ 8 files changed, 190 insertions(+), 2 deletions(-) create mode 100644 scripts/provider-build-default.py create mode 100644 scripts/test-provider-build-default.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e94669ff67..1a5b7baa16 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,6 +62,14 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + # A plain build of master must be prod and a plain build of dev must be + # dev. The target is the pull request's base branch, or the pushed branch. + - name: Check the provider's plain-build default for the target branch + env: + TARGET_BRANCH: ${{ github.base_ref || github.ref_name }} + run: | + python3 scripts/test-provider-build-default.py + python3 scripts/provider-build-default.py --branch "$TARGET_BRANCH" - name: Validate changelog fragments run: | python3 scripts/test-changelog.py diff --git a/.github/workflows/release-dev-branch.yml b/.github/workflows/release-dev-branch.yml index fdfebf8928..24669f7a94 100644 --- a/.github/workflows/release-dev-branch.yml +++ b/.github/workflows/release-dev-branch.yml @@ -68,6 +68,7 @@ on: - 'scripts/provider_release_github.py' - 'scripts/provider_release_identity.py' - 'scripts/provider-signing-validation.py' + - 'scripts/provider-build-default.py' - 'scripts/provider-cluster-runtime-models.py' - 'scripts/provider-cluster-runtime-facts.sh' - 'scripts/build-cluster-helpers.sh' diff --git a/.github/workflows/release-provider.yml b/.github/workflows/release-provider.yml index 00d73c0df3..011b9f4855 100644 --- a/.github/workflows/release-provider.yml +++ b/.github/workflows/release-provider.yml @@ -158,6 +158,13 @@ jobs: with: ref: ${{ steps.trust.outputs.source_sha }} persist-credentials: false + # staging and prod release master, whose plain build must be prod even + # though the build sets DARKBLOOM_RELEASE_ENVIRONMENT. A wrong default + # stops the release here, before any build or signing. The dev lane + # releases the dev branch, whose default is dev; CI checks that one. + - name: Check that master's plain build defaults to prod + if: inputs.environment != 'dev' + run: python3 scripts/provider-build-default.py --branch master - id: pick env: GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/release-swift.yml b/.github/workflows/release-swift.yml index 0432033734..1a5aa3ee0f 100644 --- a/.github/workflows/release-swift.yml +++ b/.github/workflows/release-swift.yml @@ -63,6 +63,7 @@ on: - 'scripts/provider_release_github.py' - 'scripts/provider_release_identity.py' - 'scripts/provider-signing-validation.py' + - 'scripts/provider-build-default.py' - 'scripts/provider-cluster-runtime-models.py' - 'scripts/provider-cluster-runtime-facts.sh' - 'scripts/build-cluster-helpers.sh' diff --git a/docs/developer/build.md b/docs/developer/build.md index cd63dd49be..037ec3b224 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build The Provider And Landing -> Last updated: 2026-10-31 +> Last updated: 2026-11-03 Build the provider, its source-matched native resources, and the independent landing site from this repository. Backend, sidecar, console and admin builds @@ -189,6 +189,12 @@ On the `dev` branch a plain `swift build` is a DevNet build: `prod`. Set `DARKBLOOM_RELEASE_ENVIRONMENT=prod` to build a production binary from the `dev` branch. +CI enforces both defaults. The Release Integrity job runs +`scripts/provider-build-default.py`: a pull request into master or a push to +master fails unless the default is `prod`, and the same for `dev` with `dev`. A +staging or prod release runs the same check and stops if master's default is +not `prod`. + Use the `dev` branch to run a provider from source against the DevNet coordinator. A push to `dev` that changes the provider publishes the DevNet release through `.github/workflows/release-dev-branch.yml` diff --git a/docs/operations/provider-release.md b/docs/operations/provider-release.md index c1b3e897c2..907bb66a73 100644 --- a/docs/operations/provider-release.md +++ b/docs/operations/provider-release.md @@ -1,6 +1,6 @@ # Release A Provider Version -> Last updated: 2026-11-02 +> Last updated: 2026-11-03 Build, sign, notarize and publish an explicitly authorized provider artifact. The pipeline registers its exact official identity through the external platform @@ -403,6 +403,10 @@ identity (`provider-swift/Package.swift`). Config, CLI flags and `DARKBLOOM_R2_CDN_URL` still override defaults. Dev/prod products have different cache keys, and packaged smoke must report the selected build environment. +A staging or prod lane builds master. Before the build, job `resolve-env` runs +`scripts/provider-build-default.py --branch master`. The lane stops if the +plain-build default in master's `provider-swift/Package.swift` is not `prod`. + A dev release from a dev push has the version `X.Y.Z-dev.branch.N`, and a master validation build has `X.Y.Z-dev.N`. `X.Y.Z` is the source `ProviderCore.version` and `N` is the workflow run number. The release lane diff --git a/scripts/provider-build-default.py b/scripts/provider-build-default.py new file mode 100644 index 0000000000..fa4af38b04 --- /dev/null +++ b/scripts/provider-build-default.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Check the provider's plain-build environment for a target branch. + +provider-swift/Package.swift reads DARKBLOOM_RELEASE_ENVIRONMENT and falls back +to a default when it is unset or empty. That default must be prod on master and +dev on dev (docs/developer/build.md). Other branches are not checked. When the +default line cannot be found, the check fails: a change to Package.swift must +not turn the check off. +""" +import argparse +import re +import sys +from pathlib import Path + +PACKAGE = Path(__file__).resolve().parents[1] / "provider-swift" / "Package.swift" +EXPECTED = {"master": "prod", "dev": "dev"} +# environment["DARKBLOOM_RELEASE_ENVIRONMENT"] +# .flatMap { $0.isEmpty ? nil : $0 } ?? "dev" +DEFAULT = re.compile( + r'environment\["DARKBLOOM_RELEASE_ENVIRONMENT"\]\s*' + r'\.flatMap\s*\{[^{}]*\}\s*\?\?\s*"([^"]*)"') + + +def plain_build_default(package_text): + found = DEFAULT.findall(package_text) + if len(found) != 1: + raise ValueError( + "expected one plain-build default for DARKBLOOM_RELEASE_ENVIRONMENT in " + f"Package.swift, found {len(found)}; update scripts/provider-build-default.py " + "with the new form") + return found[0] + + +def check(branch, package_text): + """Return a report line, or raise ValueError when the default is wrong.""" + expected = EXPECTED.get(branch) + if expected is None: + return f"target {branch!r}: no plain-build default is required" + actual = plain_build_default(package_text) + if actual != expected: + raise ValueError( + f"target {branch!r} requires the plain-build default {expected!r}, but " + f"Package.swift defaults to {actual!r}") + return f"target {branch!r}: plain-build default is {actual!r}" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--branch", required=True, help="Target branch name, for example master or dev") + parser.add_argument("--package", type=Path, default=PACKAGE) + args = parser.parse_args() + try: + print(check(args.branch, args.package.read_text(encoding="utf-8"))) + except (OSError, ValueError) as error: + sys.exit(f"provider-build-default: {error}") + + +if __name__ == "__main__": + main() diff --git a/scripts/test-provider-build-default.py b/scripts/test-provider-build-default.py new file mode 100644 index 0000000000..b0ea9b5c7f --- /dev/null +++ b/scripts/test-provider-build-default.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +import importlib.util +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts" / "provider-build-default.py" +SPEC = importlib.util.spec_from_file_location("provider_build_default", SCRIPT) +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + + +def package(default): + return ( + "// swift-tools-version: 6.1\n" + "// DARKBLOOM_RELEASE_ENVIRONMENT selects the build environment.\n" + 'let releaseEnvironment = ProcessInfo.processInfo.environment["DARKBLOOM_RELEASE_ENVIRONMENT"]\n' + ' .flatMap { $0.isEmpty ? nil : $0 } ?? "' + default + '"\n' + 'precondition(["prod", "dev", "staging"].contains(releaseEnvironment),\n' + ' "DARKBLOOM_RELEASE_ENVIRONMENT must be prod, dev or staging")\n') + + +class ProviderBuildDefaultTests(unittest.TestCase): + def test_master_requires_prod(self): + self.assertIn("'prod'", MODULE.check("master", package("prod"))) + for default in ["dev", "staging", ""]: + with self.subTest(default=default), self.assertRaisesRegex(ValueError, "requires the plain-build default 'prod'"): + MODULE.check("master", package(default)) + + def test_dev_requires_dev(self): + self.assertIn("'dev'", MODULE.check("dev", package("dev"))) + for default in ["prod", "staging"]: + with self.subTest(default=default), self.assertRaisesRegex(ValueError, "requires the plain-build default 'dev'"): + MODULE.check("dev", package(default)) + + def test_other_targets_are_not_checked(self): + for branch in ["main", "feature/x", "masterx", ""]: + with self.subTest(branch=branch): + self.assertIn("no plain-build default is required", MODULE.check(branch, "no default here")) + + def test_a_missing_or_changed_default_line_fails(self): + refactors = [ + "", + 'let releaseEnvironment = ProcessInfo.processInfo.environment["DARKBLOOM_RELEASE_ENVIRONMENT"] ?? "prod"\n', + 'let releaseEnvironment = ProcessInfo.processInfo.environment["DARKBLOOM_RELEASE_ENVIRONMENT"]\n' + " .flatMap { $0.isEmpty ? nil : $0 } ?? fallbackEnvironment\n", + package("prod") + package("dev"), + ] + for text in refactors: + for branch in ["master", "dev"]: + with self.subTest(text=text, branch=branch), self.assertRaisesRegex(ValueError, "expected one plain-build default"): + MODULE.check(branch, text) + + def test_reads_this_checkout_package(self): + self.assertIn(MODULE.plain_build_default(MODULE.PACKAGE.read_text(encoding="utf-8")), + ["prod", "dev", "staging"]) + + def test_command_exit_status_and_message(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "Package.swift" + path.write_text(package("dev"), encoding="utf-8") + run = lambda branch: subprocess.run( + [sys.executable, str(SCRIPT), "--branch", branch, "--package", str(path)], + capture_output=True, text=True) + passed = run("dev") + self.assertEqual(passed.returncode, 0, passed.stderr) + self.assertIn("plain-build default is 'dev'", passed.stdout) + failed = run("master") + self.assertEqual(failed.returncode, 1) + self.assertIn("requires the plain-build default 'prod'", failed.stderr) + missing = subprocess.run( + [sys.executable, str(SCRIPT), "--branch", "master", "--package", str(Path(directory) / "absent")], + capture_output=True, text=True) + self.assertEqual(missing.returncode, 1) + self.assertIn("provider-build-default:", missing.stderr) + + def test_ci_checks_the_target_branch_in_release_integrity(self): + ci = (ROOT / ".github/workflows/ci.yml").read_text(encoding="utf-8") + job = re.search(r"(?ms)^ release-integrity:\n(.*?)(?=^ [a-z][a-z0-9_-]*:\n)", ci).group(1) + self.assertNotIn("\n if:", job) + self.assertIn("TARGET_BRANCH: ${{ github.base_ref || github.ref_name }}", job) + self.assertIn("python3 scripts/test-provider-build-default.py", job) + self.assertIn('python3 scripts/provider-build-default.py --branch "$TARGET_BRANCH"', job) + + def test_master_release_lanes_check_before_build_and_signing(self): + release = (ROOT / ".github/workflows/release-provider.yml").read_text(encoding="utf-8") + resolve = release.split("\n resolve-env:\n", 1)[1].split("\n build-provider:\n", 1)[0] + guard = resolve.split("- name: Check that master's plain build defaults to prod\n", 1)[1].split("\n - ", 1)[0] + self.assertIn("if: inputs.environment != 'dev'", guard) + self.assertIn("run: python3 scripts/provider-build-default.py --branch master", guard) + self.assertLess(resolve.index("ref: ${{ steps.trust.outputs.source_sha }}"), + resolve.index("provider-build-default.py")) + self.assertLess(resolve.index("provider-build-default.py"), + resolve.index("./scripts/resolve-provider-release.sh")) + + +if __name__ == "__main__": + unittest.main() From 9c89ce960c61dbf8b012b263247ebf9fd144fb6b Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 08:43:54 -0600 Subject: [PATCH 0233/1441] ci: check master's default on every run of master's source, not by lane The dispatched dev validation build also builds master's source. Skip the check only for a dev push. Tighten the build.md wording. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release-provider.yml | 11 ++++++----- docs/developer/build.md | 8 ++++---- docs/operations/provider-release.md | 6 +++--- scripts/test-provider-build-default.py | 2 +- 4 files changed, 14 insertions(+), 13 deletions(-) diff --git a/.github/workflows/release-provider.yml b/.github/workflows/release-provider.yml index 011b9f4855..ed256821db 100644 --- a/.github/workflows/release-provider.yml +++ b/.github/workflows/release-provider.yml @@ -158,12 +158,13 @@ jobs: with: ref: ${{ steps.trust.outputs.source_sha }} persist-credentials: false - # staging and prod release master, whose plain build must be prod even - # though the build sets DARKBLOOM_RELEASE_ENVIRONMENT. A wrong default - # stops the release here, before any build or signing. The dev lane - # releases the dev branch, whose default is dev; CI checks that one. + # Every run except a dev push builds master's source (a tag, a master + # push or a dispatch), whose plain build must be prod even though the + # build sets DARKBLOOM_RELEASE_ENVIRONMENT. A wrong default stops the run + # here, before any build or signing. The dev branch defaults to dev; CI + # checks that one. - name: Check that master's plain build defaults to prod - if: inputs.environment != 'dev' + if: github.ref != 'refs/heads/dev' run: python3 scripts/provider-build-default.py --branch master - id: pick env: diff --git a/docs/developer/build.md b/docs/developer/build.md index 037ec3b224..af3bd19bac 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -190,10 +190,10 @@ On the `dev` branch a plain `swift build` is a DevNet build: from the `dev` branch. CI enforces both defaults. The Release Integrity job runs -`scripts/provider-build-default.py`: a pull request into master or a push to -master fails unless the default is `prod`, and the same for `dev` with `dev`. A -staging or prod release runs the same check and stops if master's default is -not `prod`. +`scripts/provider-build-default.py`: a pull request into master, or a push to +master, fails unless the default is `prod`; one into or to `dev` fails unless +it is `dev`. Every release of master runs the same check and stops before the +build if the default is not `prod`. Use the `dev` branch to run a provider from source against the DevNet coordinator. A push to `dev` that changes the provider publishes the DevNet diff --git a/docs/operations/provider-release.md b/docs/operations/provider-release.md index 907bb66a73..db167641ae 100644 --- a/docs/operations/provider-release.md +++ b/docs/operations/provider-release.md @@ -403,9 +403,9 @@ identity (`provider-swift/Package.swift`). Config, CLI flags and `DARKBLOOM_R2_CDN_URL` still override defaults. Dev/prod products have different cache keys, and packaged smoke must report the selected build environment. -A staging or prod lane builds master. Before the build, job `resolve-env` runs -`scripts/provider-build-default.py --branch master`. The lane stops if the -plain-build default in master's `provider-swift/Package.swift` is not `prod`. +Every run except a dev push builds master's source. Before the build, job +`resolve-env` runs `scripts/provider-build-default.py --branch master`. The run +stops if the plain-build default in `provider-swift/Package.swift` is not `prod`. A dev release from a dev push has the version `X.Y.Z-dev.branch.N`, and a master validation build has `X.Y.Z-dev.N`. `X.Y.Z` is the source diff --git a/scripts/test-provider-build-default.py b/scripts/test-provider-build-default.py index b0ea9b5c7f..8309c3e628 100644 --- a/scripts/test-provider-build-default.py +++ b/scripts/test-provider-build-default.py @@ -90,7 +90,7 @@ def test_master_release_lanes_check_before_build_and_signing(self): release = (ROOT / ".github/workflows/release-provider.yml").read_text(encoding="utf-8") resolve = release.split("\n resolve-env:\n", 1)[1].split("\n build-provider:\n", 1)[0] guard = resolve.split("- name: Check that master's plain build defaults to prod\n", 1)[1].split("\n - ", 1)[0] - self.assertIn("if: inputs.environment != 'dev'", guard) + self.assertIn("if: github.ref != 'refs/heads/dev'", guard) self.assertIn("run: python3 scripts/provider-build-default.py --branch master", guard) self.assertLess(resolve.index("ref: ${{ steps.trust.outputs.source_sha }}"), resolve.index("provider-build-default.py")) From 1864aa57f660507fb24d9c02ab273da2e56c6b9f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 07:20:22 -0800 Subject: [PATCH 0234/1441] feat(cluster): mark each model's split, tensor parallel or pipeline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The word cut had removed one marker the owner wants back (2026-11-03): whether the planner splits a model by tensor parallel or as a pipeline. - Each planned model's line in the list now ends with it: "Qwen3.8-27B-4bit-mtp · 16.3 GB · pipeline". - The serving lines name it right after the model: "✓ Serving Z.ai: GLM-5.3-Flash (tensor parallel) at http://localhost:8000 (local only)". - Both the leader and the Mac that follows show it, read from the setup each Mac saved. - Speculative rounds and compact decode framing still show "pipeline". An opt-in hand-off mode keeps its own words. An unknown mode gets no marker. - A marker sent by another build is shown only if it is a few plain words. An older build's choice or answer carries no marker. Tested: onboarding checks 706 passed, 14 of them new. They cover the marker for each mode, the list and serving lines, and unsafe or missing markers. The from-scratch leader screen is 100 words, exactly its budget. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 10 ++-- docs/provider/two-mac-cluster.md | 14 ++--- .../Onboarding/ClusterOnboardingFlow.swift | 53 ++++++++++++++----- .../Onboarding/ClusterOnboardingLive.swift | 14 +++-- .../OnboardingChecks.swift | 52 +++++++++++++----- 5 files changed, 103 insertions(+), 40 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index f8dd09817a..5bcb612809 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -278,9 +278,13 @@ such field and are listed as they come. A member's `darkbloom cluster` shows the status and where to manage the cluster, with a list only to set up a cable port that is not set up yet (`ClusterOnboardingDriver.member`, `fixPortItem`); the leader's is a list of the control operations (`ClusterOnboardingDriver.menu`). -A model's list line is its name and size, then "copy" or "download" when it -must reach a Mac first (`ClusterOnboardingModelChoice.listLine`); its split, -speed and tensor-parallel note are planned and carried but not said. Every copy +A model's list line is its name, its size and the split's marker ("tensor +parallel" or "pipeline", `ClusterOnboardingDeployment.splitMarker`), then +"copy" or "download" when it must reach a Mac first +(`ClusterOnboardingModelChoice.listLine`); its shares, speed and +tensor-parallel note are planned and carried but not said. The serving lines +mark the running plan's split the same way after the model ("Serving … (pipeline) +at …", `ClusterOnboardingReady.summary`, from the setup each Mac saved). Every copy of a missing model is a list as well, a short one with its predicted time (`ClusterOnboardingDriver.provision`). The public-traffic line (`ClusterOnboardingModelChoice.publicTraffic`) is said only for a private image diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index b55763396d..a825759ef9 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -46,7 +46,7 @@ onto the Macs and, later, what to do with a running cluster. Where the screen has no color (`NO_COLOR`, `TERM=dumb`, a pipe), the same list is numbered and one key answers it: a number, enter for the first line, or a letter only one line starts with (`y` for "Yes"). q or Esc cancels any list, so q never -picks a line such as "Qwen3.8-27B-4bit-mtp · 16.3 GB". While the setup waits (for the other Mac, +picks a line such as "Qwen3.8-27B-4bit-mtp · 16.3 GB · pipeline". While the setup waits (for the other Mac, for Allow), q or Esc stops it and an arrow key does nothing; no prompt asks for a key to do something. The model list shows only models approved for clusters (`ClusterPublicModels.declared`: GLM-5.3-Flash and @@ -89,8 +89,8 @@ Mac chooses the model. You can close this window."; started with other Mac."). A signed Darkbloom.app's login agent keeps serving; without one, as for a development build, the line ends "Keep this window open." and the Mac serves only while the window stays open. The leader ends with what serves and -how ("✓ Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through -Darkbloom)", or "(local only)"), the test ("✓ Test response in 0.61 s"), +how ("✓ Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning +through Darkbloom)", or "(local only)"), the test ("✓ Test response in 0.61 s"), whether the windows can close ("Done. You can close both windows.") and, last, "Run `darkbloom cluster` again to manage it." @@ -175,13 +175,13 @@ format instruction only, as on one Mac | 1 | the first Mac | Run `darkbloom cluster`. Its first line is "Allow macOS's password and Local Network prompts." It checks the Thunderbolt cable ("✓ Cable ready") and Local Network access. Nobody waits on the cable yet, so this Mac leads; its last line is **"Run `darkbloom cluster` on the other Mac."**, and it waits (q cancels). With two cables it asks "Which cable goes to the other Mac?" | the cable's port, once (your password; sudo in this terminal where macOS shows no window); Local Network access for the terminal app only where macOS blocks it | | 2 | the other Mac | Run `darkbloom cluster`. The same checks; then it finds the waiting Mac on the cable by itself (no address, no host name). Both screens show the same six-digit code ("Code 123 456. Same on the other Mac?"); a Mac that answered first says "Now confirm on the other Mac." | the same as the first Mac; **Yes** on each Mac when the codes match | | 3 | both Macs | Each says it is paired ("✓ Paired. This Mac leads." on the leader, "✓ Paired. The other Mac leads." on the other Mac). Both cluster services now run, and macOS asks on both Macs at the same moment to let Darkbloom find devices on your local network: click Allow on each; each screen waits for its own ("✓ Allowed"). Nothing else is ever asked on the other Mac; its last line is "Done here: the other Mac chooses the model. You can close this window." | Local Network access for Darkbloom, once on each Mac | -| 4 | the leader | It lists every model approved for clusters that the pair can serve (held by both Macs, by one of them, or in Darkbloom's catalog), one line each with its size ("Qwen3.8-27B-4bit-mtp · 16.3 GB"), ending "copy" or "download" when the model must reach a Mac first. A model a Mac holds twice (a catalog download beside the cluster's own copy) is listed once. The planner records why a model that has tensor parallel is split otherwise (for example "tensor parallel: slower here", "tensor parallel: not measured yet" or "tensor parallel: link unmeasured"); `darkbloom cluster plan` gives the full reason under "Tensor parallel or pipeline". Models that fit in the Macs' free memory now come first; one that does not ends with "does not fit now". Choose the model with ↑↓ and enter (enter takes the first). If the other Mac does not answer over the cable (its Darkbloom prompt may still wait for Allow), it offers **Try again** or **Cancel**. | the copy first in a list; a short one says its time ("Copy to the other Mac (about 7 s)") | -| 5 | — | Choosing is starting: the leader saves the setup, sends it to the other Mac over the cable and starts both Macs; once both are loaded it says where the pair serves ("✓ Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom)", or "(local only)") and answers one test request ("✓ Test response in 0.61 s"). | nothing | +| 4 | the leader | It lists every model approved for clusters that the pair can serve (held by both Macs, by one of them, or in Darkbloom's catalog), one line each with its size and how the planner splits it, "tensor parallel" or "pipeline" ("Qwen3.8-27B-4bit-mtp · 16.3 GB · pipeline"), ending "copy" or "download" when the model must reach a Mac first (a model no Mac holds yet is split once it arrives, so its line has no split). A model a Mac holds twice (a catalog download beside the cluster's own copy) is listed once. The planner records why a model that has tensor parallel is split otherwise (for example "tensor parallel: slower here", "tensor parallel: not measured yet" or "tensor parallel: link unmeasured"); `darkbloom cluster plan` gives the full reason under "Tensor parallel or pipeline". Models that fit in the Macs' free memory now come first; one that does not ends with "does not fit now". Choose the model with ↑↓ and enter (enter takes the first). If the other Mac does not answer over the cable (its Darkbloom prompt may still wait for Allow), it offers **Try again** or **Cancel**. | the copy first in a list; a short one says its time ("Copy to the other Mac (about 7 s)") | +| 5 | — | Choosing is starting: the leader saves the setup, sends it to the other Mac over the cable and starts both Macs; once both are loaded it says where and how the pair serves ("✓ Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom)", or "(local only)") and answers one test request ("✓ Test response in 0.61 s"). | nothing | When it serves, the screen says where in one line, for example: ``` -✓ Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom) +✓ Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom) ``` Every screen names the Macs from where it is shown: "this Mac" is the Mac the @@ -325,7 +325,7 @@ decodes with its speculative assistant under the default `mtp_mode` 2. Read the API's place from the ready screen: ``` - ✓ Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 and on the network (local only) + ✓ Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 and on the network (local only) ``` 3. Get the key: `darkbloom local` on the Mac the screen names prints the base diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift index a442446de3..be3c516b16 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift @@ -236,25 +236,30 @@ public struct ClusterOnboardingModelChoice: Codable, Sendable, Equatable { /// (2026-11-02 onboarding review: "only allow ones that are allowed to cluster serve and validated"). Nil from /// an older leader, which does not say: its list is shown as it came. public var validated: Bool? + /// How the planner splits it, as the list marks it (`ClusterOnboardingDeployment.splitMarker`: "tensor parallel" + /// or "pipeline"). Nil before it is planned (it has to reach a Mac first) and from an older build. + public var split: String? public init(title: String, lines: [String], blocker: String?, provision: ClusterOnboardingProvisionOffer? = nil, fitRemedy: String? = nil, - modelID: String? = nil, publicTraffic: String? = nil, tensorParallelNote: String? = nil, validated: Bool? = nil) { + modelID: String? = nil, publicTraffic: String? = nil, tensorParallelNote: String? = nil, validated: Bool? = nil, + split: String? = nil) { self.title = title; self.lines = lines; self.blocker = blocker; self.provision = provision; self.fitRemedy = fitRemedy self.modelID = modelID; self.publicTraffic = publicTraffic; self.tensorParallelNote = tensorParallelNote - self.validated = validated + self.validated = validated; self.split = split } /// Offered on the setup's list: it can be served on these Macs and is not known to be unapproved. public var listed: Bool { blocker == nil && validated != false } /// The list's one line: the title (with the model's id when another choice shows the same title) and its size, - /// the first fact of its first line, then "copy" or "download" when it has to reach a Mac first (2026-11-03: the - /// list keeps only what the choice needs; how it is split is the planner's business). + /// the first fact of its first line, the split's marker, then "copy" or "download" when it has to reach a Mac + /// first (2026-11-03: the list keeps only what the choice needs; the owner kept whether it is tensor parallel or + /// a pipeline, the rest of the plan is the planner's business). public func listLine(sameTitleElsewhere: Bool) -> String { let name = sameTitleElsewhere ? "\(title) (\(modelID ?? title))" : title let size = lines.first?.components(separatedBy: " · ").first.flatMap { $0.isEmpty ? nil : $0 } let move = provision.map { $0.leaderDownloads && !$0.fromOtherMac ? "download" : "copy" } - return ([name] + [size, move].compactMap { $0 }).joined(separator: " · ") + return ([name] + [size, ClusterOnboardingDeployment.shownMarker(split), move].compactMap { $0 }).joined(separator: " · ") } } @@ -291,7 +296,24 @@ public enum ClusterOnboardingDeployment { if lower.hasPrefix("pipeline_mtp") { return "pipeline with speculative decoding" } if lower.hasPrefix("pipeline") { return "pipeline" } if lower.hasPrefix("phase_split") { return "prompt split, then one Mac decodes" } - return "split across the Macs" + return unknownModeWords + } + + static let unknownModeWords = "split across the Macs" + + /// The split as the model list and the serving lines mark it (owner, 2026-11-03: "keep a marker or small wording + /// showing if the split is tensor parallelism or pipeline"): "tensor parallel" or "pipeline", speculative rounds + /// or not; an opt-in hand-off mode in its own words; nil for a mode these words do not know. + public static func splitMarker(_ raw: String) -> String? { + let words = modeWords(raw) + if words.hasPrefix("pipeline with") { return "pipeline" } + return words == unknownModeWords ? nil : words + } + + /// A split's marker as a screen shows it, whichever Mac's build sent it: a few plain words, else nothing. + static func shownMarker(_ split: String?) -> String? { + guard let split, !split.isEmpty, split.count <= 48, shownPlainly(split) else { return nil } + return split } /// "M3 Ultra 40 layers / M5 Ultra 24 layers" (pipeline) or "M3 Ultra 60% / M5 Ultra 40%" (tensor parallel); on a @@ -514,18 +536,23 @@ public struct ClusterOnboardingReady: Codable, Sendable, Equatable { /// Both Macs' members are registered and the pair is offered to the coordinator for pairing: the one line that /// says so (approval and its end). Such a pair has no local API; nil for every other way of serving. public var offered: String? = nil + /// How the plan that runs splits the model, as the serving line marks it (`ClusterOnboardingDeployment.splitMarker`); + /// nil when it is not known here, one Mac serves alone, or from an older build. + public var split: String? = nil public init(servedBy: String, port: Int, deployment: String? = nil, notice: String? = nil, network: Bool? = nil, - offered: String? = nil) { + offered: String? = nil, split: String? = nil) { self.servedBy = servedBy; self.port = port; self.deployment = deployment; self.notice = notice; self.network = network - self.offered = offered + self.offered = offered; self.split = split } - /// The screens' one line (2026-11-03: less is better), "Serving Qwen3.8 27B at http://localhost:8000": when rank 0, - /// which serves the API, is the other Mac the line says so (this Mac's own loopback serves nothing), and listening - /// on the network too, it says that. Offered for pairing, the offered line instead: there is no local API. + /// The screens' one line (2026-11-03: less is better), "Serving Qwen3.8 27B (pipeline) at http://localhost:8000", + /// with the split's marker the owner kept: when rank 0, which serves the API, is the other Mac the line says so + /// (this Mac's own loopback serves nothing), and listening on the network too, it says that. Offered for pairing, + /// the offered line instead: there is no local API. public func summary(model: String) -> String { - if let offered { return "Serving \(model): \(offered)" } - return "Serving \(model) at http://localhost:\(port)" + (servesHere ? "" : " on the other Mac") + let name = ClusterOnboardingDeployment.shownMarker(split).map { "\(model) (\($0))" } ?? model + if let offered { return "Serving \(name): \(offered)" } + return "Serving \(name) at http://localhost:\(port)" + (servesHere ? "" : " on the other Mac") + (network == true ? " and on the network" : "") } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift index bc618a1cb4..85f48bda79 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift @@ -680,7 +680,8 @@ final class OnboardingLive: @unchecked Sendable { blocker: option.blocker, provision: offer, fitRemedy: remedy, modelID: modelID, publicTraffic: context.settings.privateImageQualification ? "Private unqualified image candidate; public traffic is prohibited." : plan.publicTraffic, - tensorParallelNote: plan.tensorParallelNote, validated: approved(option.model.artifactSHA256)) + tensorParallelNote: plan.tensorParallelNote, validated: approved(option.model.artifactSHA256), + split: ClusterOnboardingDeployment.splitMarker(plan.mode)) } // Open choices first (the models this Mac has), then catalog models no Mac has yet, then the blocked ones. typealias Listed = (choice: ClusterOnboardingModelChoice, key: ChoiceKey, artifact: ListedArtifact?) @@ -1421,7 +1422,14 @@ final class OnboardingLive: @unchecked Sendable { let notice = now.local ? ClusterService.servingNotice() : now.child?.notice let byChoice = notice == ClusterLocalServing.localOnlyNotice return .init(servedBy: now.local ? here : there, port: port, deployment: savedDeployment(perspective: true) ?? leadership?.deployment, - notice: notice, network: byChoice ? (leadership?.scope.reachableFromNetwork ?? false) : nil) + notice: notice, network: byChoice ? (leadership?.scope.reachableFromNetwork ?? false) : nil, split: savedSplit()) + } + + /// How the setup this Mac saved (what runs) splits its model, as the serving line marks it (both Macs save it). + func savedSplit() -> String? { + guard case .success(let reference?) = context.savedConfiguration().reference, + let saved = try? ClusterConfigurationStore(paths: context.paths).load(reference: reference) else { return nil } + return ClusterOnboardingDeployment.splitMarker(saved.configuration.selectedGenerationMode.rawValue) } /// One look at the cluster from the control leader: ready (where the serving API listens) or a progress line. @@ -1482,7 +1490,7 @@ final class OnboardingLive: @unchecked Sendable { } if registered(own), registered(peer) { return (.init(servedBy: here, port: 0, deployment: savedDeployment(perspective: true) ?? leadership?.deployment, - offered: offered), "ready") + offered: offered, split: savedSplit()), "ready") } var line = "registering both Macs with the coordinator for pairing" for (mac, child) in [(hereShort, own), (thereShort, peer)] where child?.running == false { diff --git a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift index d3df676ed0..593642885a 100644 --- a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift +++ b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift @@ -173,10 +173,10 @@ import Darwin expect(screen.contains { $0.contains(stage) && $0.contains(meter) }, "colour: \(stage) carries its meter") } // A taken choice folds to its one line: the ▸ and the option, the list and its hint erased. - expect(screen.contains(" \u{25B8} Yes") && screen.contains(" \u{25B8} Qwen3.8-27B-4bit-mtp · 16.3 GB"), + expect(screen.contains(" \u{25B8} Yes") && screen.contains(" \u{25B8} Qwen3.8-27B-4bit-mtp · 16.3 GB · pipeline"), "colour: each choice folds to the chosen line") expect(run.text.contains("\u{1B}[3A\r\u{1B}[J"), "colour: the list is erased in place once chosen") - expect(screen.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom)"), + expect(screen.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom)"), "colour: the serving line reads plainly") for live in ["Checking the cable", "Reading both Macs over the cable", "Planning each model for both Macs", "Loading Qwen3.8-27B-4bit-mtp on both Macs", "Sending a test request"] { @@ -399,9 +399,9 @@ import Darwin /// a model these chips may not serve is not listed. static let choices = [ ClusterOnboardingModelChoice(title: "Qwen3.8-27B-4bit-mtp", lines: ["16.3 GB · pipeline · this Mac 32 layers / the other Mac 32 layers"], blocker: nil, - validated: true), + validated: true, split: "pipeline"), ClusterOnboardingModelChoice(title: "Z.ai: GLM-5.3-Flash", lines: ["181.8 GB · tensor parallel · this Mac 50% / the other Mac 50%"], blocker: nil, - validated: true), + validated: true, split: "tensor parallel"), ClusterOnboardingModelChoice(title: "gpt-oss-20b", lines: [], blocker: "not granted for this pair of chips")] /// A copy's live report, logged for a transcript, then the line for the record. @@ -441,7 +441,8 @@ import Darwin thisMacName: String? = nil, reachFailures: Int = 0, readyResult: Result = .success(.init(servedBy: "this Mac", port: 8000, - deployment: "Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers"))) -> ClusterOnboardingOperations { + deployment: "Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers", + split: "pipeline"))) -> ClusterOnboardingOperations { let answered = DispatchSemaphore(value: 0) let chosenPort = Recorder() return ClusterOnboardingOperations( @@ -510,8 +511,8 @@ import Darwin testRequest: { recorder.note("testRequest"); return testResult }, // Rank 0, which serves the API, is the Mac that leads: this Mac on the leader, the other Mac on a member. status: { recorder.note("status"); return resume.role == .member - ? ["Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 on the other Mac (earning through Darkbloom)."] - : ["Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom)."] }, + ? ["Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 on the other Mac (earning through Darkbloom)."] + : ["Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom)."] }, stop: { recorder.note("stop"); return .success(["Stopping both Macs. Run `darkbloom cluster` to serve again."]) }, provision: { index, download, progress in recorder.note("provision \(index) \(download ? "download" : "copy")") @@ -698,7 +699,8 @@ import Darwin expect(run.waitFor(" " + prompt(2), count: 2), "leader: the model list") let listed = run.text expect(!listed.contains("This Mac: Apple"), "leader: no line of both Macs' hardware") - expect(listed.contains(" 1) Qwen3.8-27B-4bit-mtp · 16.3 GB\n 2) Z.ai: GLM-5.3-Flash · 181.8 GB\n"), "leader: one short line per model: \(listed)") + expect(listed.contains(" 1) Qwen3.8-27B-4bit-mtp · 16.3 GB · pipeline\n 2) Z.ai: GLM-5.3-Flash · 181.8 GB · tensor parallel\n"), + "leader: one short line per model, with how it is split: \(listed)") expect(!listed.contains("rank 1 (decodes)"), "leader: the rest of a model's lines is not said") expect(!listed.contains("gpt-oss-20b"), "leader: a model these Macs cannot serve is not listed") run.type("\r") @@ -710,7 +712,7 @@ import Darwin " " + ClusterOnboardingPairing.otherMacAnswerLine, " \u{2713} Paired. This Mac leads.", " \(prompt(2))Qwen3.8-27B-4bit-mtp", - " \u{2713} Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom)", + " \u{2713} Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom)", " \u{2713} Test response in 0.61 s", ] { expect(text.contains(line + "\n"), "leader: \(line)") @@ -911,8 +913,8 @@ import Darwin let text = run.text expect(text.contains("This Mac follows the other Mac\n"), "member again: who leads, in the opening") expect(!text.contains("derived") && !text.contains("term ") && !text.contains("rank 0"), "member again: no leadership jargon") - expect(text.contains(" Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 on the other Mac (earning through Darkbloom).\n"), - "member again: the status") + expect(text.contains(" Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 on the other Mac (earning through Darkbloom).\n"), + "member again: the status, with how it is split") expect(text.hasSuffix(ClusterOnboardingDriver.memberNothingLine + "\n"), "member again: where to manage the cluster, last: \(text)") expect(!text.contains("Change model") && !text.contains("Choose 1-"), "member again: no menu") expect(recorder.all == ["ensureService", "status"], "member again: its service and the status only: \(recorder.all)") @@ -1203,6 +1205,13 @@ import Darwin expect(D.modeWords("something_new_v2") == "split across the Macs", "an unknown mode is never shown raw") expect(D.modeWords("phase_split_mtp_v1") == "prompt split, then one Mac decodes", "phase split in words, never claimed as an opt-in") expect(D.modeWords("pipeline_mtp_v1") == "pipeline with speculative decoding", "the pipeline's speculative rounds in words") + // The marker the owner kept (2026-11-03): tensor parallel or pipeline, whatever the pipeline's framing. + for (mode, marker) in [("tensor_parallel_v1", "tensor parallel"), ("pipeline_v1", "pipeline"), ("pipeline_compact_decode_v1", "pipeline"), + ("pipeline_mtp_v1", "pipeline"), ("phase_split_v1", "prompt split, then one Mac decodes"), + ("pipeline_prefill_tensor_decode_v1", "pipeline prefill, tensor parallel decode")] { + expect(D.splitMarker(mode) == marker, "split marker: \(mode) -> \(String(describing: D.splitMarker(mode)))") + } + expect(D.splitMarker("something_new_v2") == nil, "split marker: an unknown mode is not marked") expect(D.choiceLine(size: "6.1 GB", mode: "pipeline_v1", shares: pipeline, speed: "about 90 tokens/s") == "6.1 GB · pipeline · M3 Ultra 40 layers / M5 Ultra 24 layers · about 90 tokens/s", "choice line: one line, no ranks") } @@ -1734,8 +1743,17 @@ import Darwin .listLine(sameTitleElsewhere: false) == "m · 6.1 GB · download" && C(title: "m", lines: ["6.1 GB"], blocker: nil, provision: fromPeer).listLine(sameTitleElsewhere: false) == "m · 6.1 GB · copy", "model line: what has to move first") + expect(C(title: "m", lines: ["6.1 GB · tensor parallel · this Mac 50% / the other Mac 50%"], blocker: nil, split: "tensor parallel") + .listLine(sameTitleElsewhere: false) == "m · 6.1 GB · tensor parallel" + && C(title: "m", lines: ["6.1 GB"], blocker: nil, provision: copy, split: "pipeline").listLine(sameTitleElsewhere: false) + == "m · 6.1 GB · pipeline · copy", "model line: the split's marker after the size, before what has to move") + for unsafe in ["pipeline\u{1B}[2J", "", String(repeating: "x", count: 49)] { + expect(C(title: "m", lines: ["6.1 GB"], blocker: nil, split: unsafe).listLine(sameTitleElsewhere: false) == "m · 6.1 GB", + "model line: a marker that is not a few plain words is left out") + } let older = try? JSONDecoder().decode(C.self, from: Data(#"{"title":"m","lines":["a"]}"#.utf8)) - expect(older != nil && older?.tensorParallelNote == nil && older?.validated == nil, "model line: an older Mac's choice decodes") + expect(older != nil && older?.tensorParallelNote == nil && older?.validated == nil && older?.split == nil, + "model line: an older Mac's choice decodes") let listed = [ C(title: "Qwen3.5-9B", lines: ["6.1 GB · pipeline · M3 Ultra 16 layers / M5 Max 16 layers · about 92 tokens/s", "Pipeline: tensor parallel is predicted slower for requests of 1024 prompt and 256 answer tokens."], blocker: nil, @@ -1788,8 +1806,14 @@ import Darwin let there = ClusterOnboardingReady(servedBy: "the other Mac (Apple M4 Max, 128 GB)", port: 8000, network: true) expect(there.summary(model: "m") == "Serving m at http://localhost:8000 on the other Mac and on the network", "ready: network, that Mac") expect(ClusterOnboardingReady(servedBy: "this Mac", port: 8000).summary(model: "m") == "Serving m at http://localhost:8000", "ready: loopback unchanged") + expect(ClusterOnboardingReady(servedBy: "this Mac", port: 8000, split: "tensor parallel").summary(model: "m") + == "Serving m (tensor parallel) at http://localhost:8000", "ready: the split's marker after the model") + expect(ClusterOnboardingReady(servedBy: "this Mac", port: 0, offered: "offered for pairing", split: "pipeline").summary(model: "m") + == "Serving m (pipeline): offered for pairing", "ready: offered, the marker too") + expect(ClusterOnboardingReady(servedBy: "this Mac", port: 8000, split: "x\u{7}").summary(model: "m") == "Serving m at http://localhost:8000", + "ready: a marker with control characters is left out") let older = try? JSONDecoder().decode(ClusterOnboardingReady.self, from: Data(#"{"servedBy":"this Mac","port":8000}"#.utf8)) - expect(older?.network == nil, "ready: an older Mac's answer decodes without the network field") + expect(older?.network == nil && older?.split == nil, "ready: an older Mac's answer decodes without the network and split fields") } /// The four steps, in order. @@ -1896,7 +1920,7 @@ import Darwin expect(run.finish() == 0, "serves: exit 0") let text = run.text expect(!text.contains("public traffic in pipeline mode"), "serves: no public-traffic line at the choice: \(text)") - expect(text.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom)\n"), + expect(text.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom)\n"), "serves: through Darkbloom, on the serving line: \(text)") let local = TerminalRun(operations(Recorder(), resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: qualified, readyResult: .success(localReady)), request: localRequest) From 44b8daeda59af498a1ffd8dea4ec66e8a29e047d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 07:27:41 -0800 Subject: [PATCH 0235/1441] fix(cluster): name the list item instead of a key in the help and service lines Three lines still told people to press a key the setup no longer reads. Each now names the list item, matching the setup screens: - `darkbloom cluster --help` said "press y on each". It now says "choose Yes on each", and it quotes the new first steps: allow macOS's password and Local Network prompts, then "Run `darkbloom cluster` on the other Mac.". - `darkbloom cluster local --help` said "press p there". It now says "choose Serve through Darkbloom there". - The cluster service's cable-port line said "press f". It now says "choose Set up the cable port", taken from the menu's own item. Tested: swift build --build-tests (0 errors); the built CLI's `darkbloom cluster --help` reads as above. Co-Authored-By: Claude Opus 5.5 --- .../Inference/Distributed/Onboarding/ClusterService.swift | 2 +- provider-swift/Sources/darkbloom/ClusterLocalCommand.swift | 2 +- provider-swift/Sources/darkbloom/ClusterSetupCommand.swift | 5 +++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index 492bd73813..74e81298f1 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -415,7 +415,7 @@ public final class ClusterService: @unchecked Sendable { say("the cable is on \(moved.interface) now: answering the paired Mac there") // A port that was never set up has no fixed address: the other Mac cannot find this one there. if let port = OnboardingLive.unsetCablePort(ClusterLinkReadinessProbe.inspectLocalLink()) { - say("\(port) is not set up for the cluster: run `darkbloom cluster` on this Mac and press f (macOS asks for your password once)") + say("\(port) is not set up for the cluster: run `darkbloom cluster` on this Mac and choose \(ClusterOnboardingDriver.fixPortItem) (macOS asks for your password once)") } case .pairingChanged(let current): say("this Mac's pairing changed (\(current.clusterID)): answering the paired Mac with the new one") diff --git a/provider-swift/Sources/darkbloom/ClusterLocalCommand.swift b/provider-swift/Sources/darkbloom/ClusterLocalCommand.swift index 59e0a529d0..b64615a484 100644 --- a/provider-swift/Sources/darkbloom/ClusterLocalCommand.swift +++ b/provider-swift/Sources/darkbloom/ClusterLocalCommand.swift @@ -16,7 +16,7 @@ extension Cluster { key: `darkbloom local` on that Mac shows the address and the key. The choice is kept: both Macs serve this way after restarts, until `darkbloom cluster` is used to \ - serve through Darkbloom again (press p there). Run it on a cluster that already serves to switch it. + serve through Darkbloom again (choose Serve through Darkbloom there). Run it on a cluster that already serves to switch it. """) @OptionGroup var configOptions: ConfigOptions @Argument(help: "The model to serve, by its id or name as `darkbloom cluster` lists it; without one, the list is shown.") diff --git a/provider-swift/Sources/darkbloom/ClusterSetupCommand.swift b/provider-swift/Sources/darkbloom/ClusterSetupCommand.swift index a611438675..f212bebaf8 100644 --- a/provider-swift/Sources/darkbloom/ClusterSetupCommand.swift +++ b/provider-swift/Sources/darkbloom/ClusterSetupCommand.swift @@ -10,8 +10,9 @@ extension Cluster { abstract: "Set up two or more Macs to serve one model together. Run it on each Mac and follow the screen.", discussion: """ Run `darkbloom cluster` in Terminal on each Mac (`darkbloom cluster setup` is the same). The first Mac \ - checks its Thunderbolt cable and asks macOS for one approval, then says "On your other Mac, run \ - `darkbloom cluster`". The other Mac finds it by itself; both show the same code; press y on each. \ + checks its Thunderbolt cable, has you allow macOS's password and Local Network prompts, then says \ + "Run `darkbloom cluster` on the other Mac." The other Mac finds it by itself; both show the same code; \ + choose Yes on each. \ Then choose a model on the first Mac: Darkbloom works out how to split it across both Macs, copies \ it to a Mac that lacks it, starts both Macs and shows one line saying how the model is served. \ Nothing else is needed: no SSH, no address and no network setting is typed. From 7312cbbfb5998aeeeeba65586b5737db6341471d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 07:52:30 -0800 Subject: [PATCH 0236/1441] feat(cluster): declare MiMo-V2.6-Flash and Gemma 4 26B QAT public The owner approved more cluster models for public traffic on 2026-11-03: "Mark them all approved for public traffic", then "If you did just add Mimo and Gemma to start". - `ClusterPublicModels.declared` adds MiMo-V2.6-Flash (`mimo-v2.6-flash-mopd`) and Gemma 4 26B QAT (`gemma-4-26b-qat-4bit`), matched by runtime model, catalog ID and the artifact their bundled records ran. Both are declared in pipeline and tensor parallel on schedules 1 and 2, the same as GLM-5.3-Flash and Qwen3.8-27B. A release's cluster runtime facts then carry their pair-serving grants and parity qualifications, and `darkbloom cluster` lists them. - MiMo-V2.6-Flash also keeps its speculative pipeline (`pipeline_mtp_v1`), which is the split it plans by default. A declared grant replaces the families the records grant, and a coordinator never forms a pair planned in a family its grant omits. Without this, MiMo pairs would have stopped forming through Darkbloom. `ClusterPublicModels.placement` now places a speculative pipeline the same way as a pipeline, cut at half the layers. - The pipelines rest on the bundled records: 19 passing records for MiMo, and for Gemma 2 passes that no divergence contradicts. Their tensor parallel rests on the owner's decision, and serves once its code (#1706, #1707) is in the build. - The evidence report records the decision and the records. Its new digest is in `ClusterPublicModels.evidenceSHA256` and in the pinned dev-branch17 facts fixture, whose grant and qualifications follow the declaration. The declaration's `qualified_at` is 2026-11-03. - No coordinator change is needed. It derives approvals for any model a release declares, and applies each family's qualification on any Apple silicon pair and at any cut (`parityQualification`'s family fallback). The two M5 Ultras in the declaration name where the evidence ran; they are not a limit. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-onboarding-simple.md | 5 +- changelog.d/cluster-public-mimo-gemma.md | 4 ++ docs/developer/test.md | 5 +- docs/operations/provider-release.md | 5 +- docs/provider/two-mac-cluster.md | 4 +- docs/reference/configuration.md | 26 +++++---- .../2026-10-31-public-cluster-models.md | 57 +++++++++++++++---- docs/reports/README.md | 2 +- .../Config/ClusterRuntimeApprovalFacts.swift | 6 +- .../Installed/ClusterPublicModels.swift | 35 ++++++++---- .../ClusterRuntimeApprovalFactsTests.swift | 25 +++++--- .../glm-5.3-flash-dev-branch17.json | 2 +- 12 files changed, 126 insertions(+), 50 deletions(-) create mode 100644 changelog.d/cluster-public-mimo-gemma.md diff --git a/changelog.d/cluster-onboarding-simple.md b/changelog.d/cluster-onboarding-simple.md index bc60a89691..73e3b45e2f 100644 --- a/changelog.d/cluster-onboarding-simple.md +++ b/changelog.d/cluster-onboarding-simple.md @@ -3,8 +3,9 @@ - `darkbloom cluster` setup says far less: four steps (Connect, Pair, Model, Start), a line per thing that happened, and the next thing to do last. Every choice is a list (↑↓ and enter, as `darkbloom start` picks models; numbered in plain transcripts); q or Esc cancels. -- The model list shows only the models approved for clusters (GLM-5.3-Flash and Qwen3.8 27B) that the two Macs can - serve, each with its size. +- The model list shows only the models approved for clusters (GLM-5.3-Flash, Qwen3.8 27B, MiMo-V2.6-Flash and + Gemma 4 26B QAT) that the two Macs can serve, each with its size and its split: tensor parallel or pipeline. The + serving lines name the split too. - The Mac you set up on leads and keeps leading: every plan puts rank 0 on it, the cluster service's own re-plans included, so a pair set up with 0.10.6 whose other Mac took over leading moves back at its next plan. - macOS's password and Local Network prompts come at stated moments (sudo in the terminal over SSH); both Macs ask diff --git a/changelog.d/cluster-public-mimo-gemma.md b/changelog.d/cluster-public-mimo-gemma.md new file mode 100644 index 0000000000..af6f88c4e5 --- /dev/null +++ b/changelog.d/cluster-public-mimo-gemma.md @@ -0,0 +1,4 @@ +### MiMo-V2.6-Flash and Gemma 4 26B QAT serve public cluster traffic + +- Two more models are approved for public traffic on two-Mac clusters, in pipeline and tensor parallel, as GLM-5.3-Flash and Qwen3.8 27B are: MiMo-V2.6-Flash (`mimo-v2.6-flash-mopd`) and Gemma 4 26B QAT (`gemma-4-26b-qat-4bit`). A release's cluster runtime facts carry their pair-serving grants and parity qualifications, so a pair of either model earns through Darkbloom on any Apple silicon pair, and `darkbloom cluster` lists them. +- Their tensor parallel serves once its code is in the build (Gemma 4 and MiMo tensor parallel PRs); until then they pair as a pipeline. MiMo-V2.6-Flash's speculative pipeline, its default split, is declared too. diff --git a/docs/developer/test.md b/docs/developer/test.md index 34f8451e18..e3d1064097 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1433,7 +1433,10 @@ parity qualifications included) and a block whose derived approval, grant or parity qualification IDs exceed 128 bytes, refuse a registration body over the coordinator's 64 KiB limit before staging (65,536 bytes accepted, 65,537 refused), accept the GLM-5.3-Flash block pinned from the 0.10.5-dev.branch.17 -app, and check that registration sends the block in its canonical form. +app (its digests are that app's; its grant and parity qualifications are this +build's declaration, so its evidence digest and `qualified_at` follow +`ClusterPublicModels`), and check that registration sends the block in its +canonical form. `scripts/test-provider-cluster-runtime-models.py` runs the release's model-metadata fetch against a local HTTP registry: the environment's catalog and CDN, candidate selection, the manifest and `config.json` checks, each candidate's diff --git a/docs/operations/provider-release.md b/docs/operations/provider-release.md index db167641ae..da70f43c75 100644 --- a/docs/operations/provider-release.md +++ b/docs/operations/provider-release.md @@ -761,8 +761,9 @@ accepts the block derives from it that build's cluster approvals, their pair-serving grants (without one no pair of GLM-5.3-Flash or Qwen3.8-27B forms: [why](../architecture/inference.md#cluster-runtime-facts-of-an-installed-app)), and the parity qualifications (public traffic) of the models the build declares -public (`ClusterPublicModels`: GLM-5.3-Flash and Qwen3.8-27B in pipeline and -tensor parallel, the owner's decisions of 2026-10-31, +public (`ClusterPublicModels`: GLM-5.3-Flash, Qwen3.8-27B, MiMo-V2.6-Flash and +Gemma 4 26B QAT in pipeline and tensor parallel, MiMo-V2.6-Flash also in its +speculative pipeline, the owner's decisions of 2026-10-31 and 2026-11-03, [evidence](../reports/2026-10-31-public-cluster-models.md)). No operator posts approvals, grants or public qualifications per build. A coordinator applies the qualifications to each declared family on any Apple silicon pair: the declared diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 4e2becf458..1214495e36 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -49,8 +49,8 @@ line starts with (`y` for "Yes"). q or Esc cancels any list, so q never picks a line such as "Qwen3.8-27B-4bit-mtp · 16.3 GB · pipeline". While the setup waits (for the other Mac, for Allow), q or Esc stops it and an arrow key does nothing; no prompt asks for a key to do something. The model list shows only models -approved for clusters (`ClusterPublicModels.declared`: GLM-5.3-Flash and -Qwen3.8 27B) that these two Macs can serve; any other model is left out, and a +approved for clusters (`ClusterPublicModels.declared`: GLM-5.3-Flash, +Qwen3.8 27B, MiMo-V2.6-Flash and Gemma 4 26B QAT) that these two Macs can serve; any other model is left out, and a model named on the command line that is not approved is refused. Each Mac asks for up to two macOS approvals, at stated moments while you are at diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index fa2ca6bfeb..eafac58611 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -964,20 +964,23 @@ runtime digest, and the provider computes no facts for it | `models[].profile_sha256` | the capability's `profileFingerprint` | | `models[].resource_policy_sha256` | `DistributedInstalledNativeStart.resourcePolicySHA256` of the capability, the value a native start carries | | `models[].pair_serving_grant` | `null`, or exactly `evidence_sha256` and `mode_families` (1 to 4 of `hand_off`, `pipeline`, `pipeline_speculative`, `tensor_parallel`, in byte order). A model the build's public declaration (`ClusterPublicModels`) names by runtime model, catalog ID and artifact: its declared families, with the evidence document's SHA-256. Any other model: the families the build's bundled records grant its artifact (`ClusterPairServingGrants.grant`), with the SHA-256 of the records that grant is computed from (the artifact's passing records, without a pass that a divergence of the same shape contradicts) as canonical JSON Lines (`ClusterPairServingGrant.evidenceSHA256`: each record's `encodedLine` in bundle order, joined by `\n`, no trailing newline); `null` when they grant none | -| `models[].parity_qualifications` | `[]` unless the model is declared; then one object per declared mode family (in byte order: `pipeline`, then `tensor_parallel`) and schedule (ascending), with the fields below. At most 8 | +| `models[].parity_qualifications` | `[]` unless the model is declared; then one object per declared mode family (in byte order: `pipeline`, `pipeline_speculative`, then `tensor_parallel`) and schedule (ascending), with the fields below. At most 8 | | `…schedule` | `1` or `2`: the derived approval it qualifies | | `…numerics_classes` | each rank's `ClusterMemberDeviceProfile.numericsClass` of the evidence placement with this block's `metallib_sha256`, for example `g17d-nax1-mlx-98bab9d7-macos27.0` (Apple M5 Ultra, NAX on, macOS 27.0); two, the members of a derived approval | -| `…mode`, `…cuts` | `pipeline`: `pipeline_v1` cut at `[num_hidden_layers / 2]` (integer division) of the model's `config.json`, read at the top level or else in `text_config` (`[22]` for GLM-5.3-Flash, `[32]` for Qwen3.8-27B); without a layer count the pipeline's qualifications are left out and the command names the family on standard error. `tensor_parallel`: `tensor_parallel_v1`, `[]` (`ClusterPublicModels.placement`) | +| `…mode`, `…cuts` | `pipeline`: `pipeline_v1` cut at `[num_hidden_layers / 2]` (integer division) of the model's `config.json`, read at the top level or else in `text_config` (`[22]` for GLM-5.3-Flash, `[32]` for Qwen3.8-27B, `[24]` for MiMo-V2.6-Flash, `[15]` for Gemma 4 26B QAT); without a layer count the pipeline's qualifications are left out and the command names the family on standard error. `pipeline_speculative` (MiMo-V2.6-Flash): `pipeline_mtp_v1`, cut as the pipeline is. `tensor_parallel`: `tensor_parallel_v1`, `[]` (`ClusterPublicModels.placement`) | | `…tensor_parallel_shares` | `null`: equal shares | | `…promotable`, `…diverged` | `true`, `false` | | `…evidence_sha256` | SHA-256 of the evidence document, [`docs/reports/2026-10-31-public-cluster-models.md`](../reports/2026-10-31-public-cluster-models.md) | -| `…qualified_at` | `2026-10-31T00:00:00Z` | -| `…request_envelope` | `sampling` and `tools` `true`; `max_prompt_tokens` and `max_output_tokens` 1,048,576 (the coordinator's maximum: only the model's own limits apply); where the placement serves media (`ClusterModelFeaturePolicy.mediaContract`: both declared models in tensor parallel; a pipeline is text only), `vision` when the model's catalog entry in the release's environment lists `image` in `input_modalities`, `video` when it also lists `video` (`ClusterPublicModels.requestEnvelope`). A model given by hand has no catalog entry, so its envelope admits text only | +| `…qualified_at` | `2026-11-03T00:00:00Z`, the date of the latest declaration | +| `…request_envelope` | `sampling` and `tools` `true`; `max_prompt_tokens` and `max_output_tokens` 1,048,576 (the coordinator's maximum: only the model's own limits apply); where the placement serves media (`ClusterModelFeaturePolicy.mediaContract`: GLM-5.3-Flash and Qwen3.8-27B in tensor parallel; a pipeline is text only), `vision` when the model's catalog entry in the release's environment lists `image` in `input_modalities`, `video` when it also lists `video` (`ClusterPublicModels.requestEnvelope`). A model given by hand has no catalog entry, so its envelope admits text only | The public declaration names GLM-5.3-Flash (`registered_glm53_flash`, `glm-5.3-flash`) and Qwen3.8-27B (`registered_qwen38_27b`, -`EigenLabs/Qwen3.8-27B-4bit-mtp`), each in `pipeline` and `tensor_parallel` on -schedules 1 and 2, on the owner's decisions of 2026-10-31 +`EigenLabs/Qwen3.8-27B-4bit-mtp`) on the owner's decisions of 2026-10-31, and +MiMo-V2.6-Flash (`registered_mimo_v26_flash_mopd`, `mimo-v2.6-flash-mopd`) and +Gemma 4 26B QAT (`registered_gemma4_26b_qat_4bit`, `gemma-4-26b-qat-4bit`) on +those of 2026-11-03, each in `pipeline` and `tensor_parallel` on schedules 1 +and 2, and MiMo-V2.6-Flash also in `pipeline_speculative`, its default split ([evidence](../reports/2026-10-31-public-cluster-models.md)). Every other model's clusters serve their owner only. @@ -988,11 +991,14 @@ family's promotable records, merged under the request envelope they all allow, on any numerics classes, cuts and shares, unless a diverged record of the same numerics-class combination withholds it ([`parityQualification`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/registry/cluster_parity_qualification.go)). -Under a derived approval, public traffic for GLM-5.3-Flash and Qwen3.8-27B is +Under a derived approval, public traffic for every declared model is therefore admitted in pipeline and tensor parallel on any Apple silicon pair, -within the envelope. No pipeline of either model ran on two Apple M5 Ultras, -and GLM-5.3-Flash has no tensor-parallel cross-cable record: both rest on the -owner's decision of 2026-10-31 and the DevNet serving results. GLM-5.3-Flash's +within the envelope. No pipeline of GLM-5.3-Flash or Qwen3.8-27B ran on two +Apple M5 Ultras, and GLM-5.3-Flash has no tensor-parallel cross-cable record: +both rest on the owner's decision of 2026-10-31 and the DevNet serving results. +MiMo-V2.6-Flash's and Gemma 4 26B QAT's pipelines rest on their bundled records +and the owner's decision of 2026-11-03; their tensor parallel rests on that +decision alone, and serves once its code (#1706, #1707) is in the build. GLM-5.3-Flash's runtime serves only the serial prefill schedule (`supportedPrefillSchedules` of its registered specification), so its schedule 2 approval, grant and qualifications are inert. The setup's public-traffic line says a diff --git a/docs/reports/2026-10-31-public-cluster-models.md b/docs/reports/2026-10-31-public-cluster-models.md index 5c2781fbf0..fe17b3063f 100644 --- a/docs/reports/2026-10-31-public-cluster-models.md +++ b/docs/reports/2026-10-31-public-cluster-models.md @@ -1,6 +1,6 @@ -# Public cluster models: GLM-5.3-Flash and Qwen3.8-27B +# Public cluster models: GLM-5.3-Flash, Qwen3.8-27B, MiMo-V2.6-Flash and Gemma 4 26B QAT -> Last updated: 2026-10-31 +> Last updated: 2026-11-03 This record is the evidence document of the provider's public cluster model declaration (`ClusterPublicModels`): the declaration's `evidenceSHA256` is the @@ -20,7 +20,17 @@ The owner (jonathan308) decided on 2026-10-31: shouldn't matter for the coordinator" The owner approved both modes, pipeline and tensor parallel, for both models, -and the public qualification of both models is done. No other model serves +and the public qualification of both models is done. + +On 2026-11-03 the owner added two models. Of the cluster-validated models +that served their owner only, the owner said "Mark them all approved for public +traffic", then "If you did just add Mimo and Gemma to start". MiMo-V2.6-Flash +and Gemma 4 26B QAT are declared in the same two families, pipeline and tensor +parallel, as the 2026-10-31 ruling on families reads. MiMo-V2.6-Flash also +keeps its speculative pipeline, the split it plans by default. A declared +model's grant replaces the families its records grant, and a coordinator never +forms a pair planned in a family its grant omits, so without it a MiMo pair +planned that way would not form through Darkbloom at all. No other model serves public cluster traffic: a cluster of any other model serves its owner only. ## Declared models @@ -29,18 +39,22 @@ public cluster traffic: a cluster of any other model serves its owner only. |---|---|---|---|---| | `registered_glm53_flash` | `glm-5.3-flash` | `3aae613ff188bb0f72e880774a84e4d8e9943ab20c929d8a302af9c57b97d5ac` | `pipeline`, `tensor_parallel` | 1 (serial), 2 (one-chunk lookahead) | | `registered_qwen38_27b` | `EigenLabs/Qwen3.8-27B-4bit-mtp` | `bbd0e0adcfe74e095073fefd0b9e116e4311d606ad9989cf81f8175e8ac18463` | `pipeline`, `tensor_parallel` | 1 (serial), 2 (one-chunk lookahead) | +| `registered_mimo_v26_flash_mopd` | `mimo-v2.6-flash-mopd` | `2334547d8acc9898ad4a74570ce44d2b12390bbac8d4bc52c092eb5ad5cfe034` | `pipeline`, `pipeline_speculative`, `tensor_parallel` | 1 (serial), 2 (one-chunk lookahead) | +| `registered_gemma4_26b_qat_4bit` | `gemma-4-26b-qat-4bit` | `2468a0cb3049a871f42052f4d9f9380bf12a0792f64c7a29f768559fc7d28785` | `pipeline`, `tensor_parallel` | 1 (serial), 2 (one-chunk lookahead) | -The artifacts are the ones the cluster runtime registers for the two models. +The artifacts are the ones the cluster runtime registers for the four models. Each family is qualified on 2 ranks, each an Apple M5 Ultra (GPU architecture -`applegpu_g17d`, NAX on) on macOS 27.0, at 2026-10-31T00:00:00Z: +`applegpu_g17d`, NAX on) on macOS 27.0, at 2026-11-03T00:00:00Z, the date of the latest declaration: | Family | Mode | Cuts | Shares | |---|---|---|---| -| `pipeline` | `pipeline_v1` | `[num_hidden_layers / 2]` (integer division): `[22]` for GLM-5.3-Flash (45 layers), `[32]` for Qwen3.8-27B (64 layers) | not applicable | +| `pipeline` | `pipeline_v1` | `[num_hidden_layers / 2]` (integer division): `[22]` for GLM-5.3-Flash (45 layers), `[32]` for Qwen3.8-27B (64 layers), `[24]` for MiMo-V2.6-Flash (48 layers), `[15]` for Gemma 4 26B QAT (30 layers) | not applicable | +| `pipeline_speculative` (MiMo-V2.6-Flash only) | `pipeline_mtp_v1` | `[num_hidden_layers / 2]`: `[24]` | not applicable | | `tensor_parallel` | `tensor_parallel_v1` | `[]` | equal | -Both models' `config.json` give the layer count as `text_config.num_hidden_layers`; -neither has a top-level `num_hidden_layers`. +GLM-5.3-Flash's, Qwen3.8-27B's and Gemma 4 26B QAT's `config.json` give the +layer count as `text_config.num_hidden_layers`; MiMo-V2.6-Flash's gives it at the +top level. ## What was run @@ -67,6 +81,14 @@ does not re-run them. This record holds no pipeline run on two Apple M5 Ultras. +For MiMo-V2.6-Flash and Gemma 4 26B QAT this record holds no run on two Apple +M5 Ultras. Their pipeline rests on the bundled records below and the owner's +decision of 2026-11-03. Their tensor parallel rests on the owner's decision +alone: its code is in open PRs (#1706 and #1707, with #1715 and #1716), and no +cross-cable record of it exists yet. MiMo-V2.6-Flash's speculative pipeline +(`pipeline_mtp_v1`, family `pipeline_speculative`) rests on its 2 passing +records below. + ## Bundled cross-cable records The qualification records the build bundles @@ -85,6 +107,19 @@ The qualification records the build bundles Apple M5 Max, cut 39, `serial_v1`) and no `tensor_parallel_v1` record. Its pipeline rests on that run and the owner's ruling; its tensor parallel rests on the owner's decision and the DevNet serving results above. +- MiMo-V2.6-Flash: 19 passing records over `jaccl`, all on an Apple M5 Ultra + with an Apple M3 Ultra, from 2026-10-14, with prompts up to 16,384 tokens. The + `pipeline` family has 8 `pipeline_v1` records (cuts 14 and 47; 7 `serial_v1` + and 1 `one_chunk_lookahead_v1`) and 3 `pipeline_compact_decode_v1` records + (cut 47, `serial_v1`). The others are 2 `pipeline_mtp_v1` and 6 `phase_split_v1` + records. None diverged. +- Gemma 4 26B QAT: 7 `pipeline_v1` records over `jaccl`, from 2026-10-09 and + 2026-10-12, on an Apple M3 Ultra with an Apple M5 Max or an Apple M5 Ultra. + 4 passed and 3 diverged. A pass that a divergence of the same placement + contradicts counts for nothing, so its records grant rests on 2 passes, both + on an Apple M3 Ultra with an Apple M5 Ultra: cut 5 with `one_chunk_lookahead_v1` + and cut 15 with `serial_v1`. The planner refuses the diverged placements (cut 2 + on that pair, and cuts 12 and 18 on the Apple M5 Max pair). ## Pair-serving grants @@ -106,7 +141,7 @@ records as its evidence; a model the records grant nothing has none. ## Request envelope -Both models, both families: sampling and tool calls are allowed, and +Every declared model, both families: sampling and tool calls are allowed, and `max_prompt_tokens` and `max_output_tokens` are 1,048,576 (the coordinator's maximum, so only the model's own limits apply). Media follows what the placement serves (`ClusterModelFeaturePolicy.mediaContract`). In tensor @@ -116,11 +151,13 @@ catalog entry in the release's environment lists `image` in `input_modalities`, and `video` when it also lists `video`. A pipeline serves text only, so its envelope admits neither. GLM-5.3-Flash's DevNet catalog entry lists `text`, `image` and `video`; Qwen3.8-27B's lists `text` and `image`. +MiMo-V2.6-Flash's and Gemma 4 26B QAT's media in tensor parallel follow the same +contract, once their tensor-parallel code serves. ## Where it is used `provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift` -declares the two models with this file's SHA-256. A release's cluster runtime +declares the four models with this file's SHA-256. A release's cluster runtime facts (`cluster_runtime`) carry, for a declared model, the grant of its declared families and one parity qualification for each declared family and schedule: `pipeline` first, then `tensor_parallel`. A coordinator that derives approvals diff --git a/docs/reports/README.md b/docs/reports/README.md index 5200bb7ed9..ea59d1aab7 100644 --- a/docs/reports/README.md +++ b/docs/reports/README.md @@ -5,7 +5,7 @@ Dated records and raw native evidence retain their original content, revisions and limitations. A record is not a fresh test result or proof of private platform compatibility. - [Gemma pipeline prompt experts](2026-11-01-gemma-pipeline-prompt-experts.md) - the registered Gemma stages' prompt expert blocks in one shared dispatch with the same bytes: CPU and M5 Ultra GPU equality evidence and synthetic one-layer timings; no pair or qualification result. -- [Public cluster models](2026-10-31-public-cluster-models.md) - the owner's declaration of GLM-5.3-Flash and Qwen3.8-27B for public cluster traffic in pipeline and tensor parallel, the checks it rests on and why releases carry pair-serving grants; the evidence document of `ClusterPublicModels`. +- [Public cluster models](2026-10-31-public-cluster-models.md) - the owner's declaration of GLM-5.3-Flash, Qwen3.8-27B, MiMo-V2.6-Flash and Gemma 4 26B QAT for public cluster traffic in pipeline and tensor parallel, the checks it rests on and why releases carry pair-serving grants; the evidence document of `ClusterPublicModels`. - [Mixed-step prefill geometry](2026-10-21-mixed-step-prefill-geometry.md) - load, engine, inter-token latency and KV-subtracted activation measurements behind Gemma 4's 2,048 / 4,096 prompt geometry, its media ceiling and the GPT-OSS and dense Qwen opt-in. - [GLM-5.3-Flash single-Mac qualification record](2026-10-21-glm53-flash-single-mac-qualification.md) - [Startup shape warmup: first-request TTFT](2026-10-21-startup-shape-warmup-first-request.md) diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift index dc8dcd80d5..62cf23b671 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift @@ -312,9 +312,9 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { } /// The parity qualifications of a declared model: one per declared family - /// (byte order: `pipeline`, then `tensor_parallel`) and schedule - /// (ascending), so each approval's first is the pipeline and its second - /// tensor parallel. Each is placed as `ClusterPublicModels.placement` says + /// (byte order: `pipeline`, `pipeline_speculative`, then `tensor_parallel`) + /// and schedule (ascending), so each approval's first is the pipeline and + /// its last tensor parallel. Each is placed as `ClusterPublicModels.placement` says /// (a pipeline needs the model's `layers`: without them its records are /// left out), its ranks in this build's numerics class, its envelope /// admitting media only when its mode `servesMedia` for this model diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift index bbc2914c27..61160fde7a 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift @@ -33,7 +33,9 @@ public struct ClusterPublicModel: Sendable, Equatable { /// The models whose clusters serve public traffic: the owner's declaration /// (jonathan308, 2026-10-31: "public traffic should not be manual"; "only glm /// 5.3 flash should be serving public & qwen 3.8 27b they are both good to go -/// they should be approved for serving"), reviewed in PRs like any code. A +/// they should be approved for serving"; 2026-11-03: "Mark them all approved +/// for public traffic", then "just add Mimo and Gemma to start": MiMo-V2.6-Flash +/// and Gemma 4 26B QAT), reviewed in PRs like any code. A /// release's cluster runtime facts carry, for each of these models, a /// pair-serving grant of the declared families and a parity qualification for /// each declared family and schedule (`ClusterRuntimeApprovalFacts`), from @@ -44,16 +46,22 @@ public struct ClusterPublicModel: Sendable, Equatable { /// equal), so a released CLI names it without carrying the file. public enum ClusterPublicModels { public static let evidenceDocument = "docs/reports/2026-10-31-public-cluster-models.md" - public static let evidenceSHA256 = "dccbc68bd337f634be9295eed8f909702252eab707a4ac3fdb5290ce8b98a86d" - public static let qualifiedAt = "2026-10-31T00:00:00Z" + public static let evidenceSHA256 = "cb16451549b2ba1f3a1908e280c17f572260c227aa27e86b73d39b8c3e6530a9" + public static let qualifiedAt = "2026-11-03T00:00:00Z" /// A public request's prompt and output allowance: the coordinator's /// maximum, so only the model's own limits apply. public static let maximumTokens = 1_048_576 - /// Two Apple M5 Ultras (Metal `applegpu_g17d`, NAX on) on macOS 27.0. + /// Two Apple M5 Ultras (Metal `applegpu_g17d`, NAX on) on macOS 27.0: where the declared evidence ran. It names the + /// evidence, not a limit: a coordinator applies each declared family's qualification on any Apple silicon pair and + /// cut (owner, 2026-11-03: "universal for hardware not hardwired to 2x m5 ultras"). static let twoM5Ultras = ClusterPublicModel.Ranks(count: 2, gpuArchitecture: "applegpu_g17d", macOSMajor: 27, macOSMinor: 0) /// Owner ruling, 2026-10-31: "It should be tensor or pipeline obviously but that shouldn't matter for the coordinator". + /// MiMo-V2.6-Flash and Gemma 4 26B QAT (2026-11-03) take the same two families: their pipeline rests on the bundled + /// records, their tensor parallel on the owner's decision (its code lands with #1706 and #1707). MiMo also keeps + /// the speculative pipeline its records grant, its default split: a declared grant replaces the records' families, + /// and a coordinator never forms a pair planned in a family its grant omits. public static let declared: [ClusterPublicModel] = [ .init(runtimeModelID: "registered_glm53_flash", catalogModelID: "glm-5.3-flash", artifactSHA256: "3aae613ff188bb0f72e880774a84e4d8e9943ab20c929d8a302af9c57b97d5ac", @@ -61,22 +69,29 @@ public enum ClusterPublicModels { .init(runtimeModelID: "registered_qwen38_27b", catalogModelID: "EigenLabs/Qwen3.8-27B-4bit-mtp", artifactSHA256: "bbd0e0adcfe74e095073fefd0b9e116e4311d606ad9989cf81f8175e8ac18463", families: [.pipeline, .tensorParallel], schedules: [1, 2], ranks: twoM5Ultras), + .init(runtimeModelID: "registered_mimo_v26_flash_mopd", catalogModelID: "mimo-v2.6-flash-mopd", + artifactSHA256: "2334547d8acc9898ad4a74570ce44d2b12390bbac8d4bc52c092eb5ad5cfe034", + families: [.pipeline, .pipelineSpeculative, .tensorParallel], schedules: [1, 2], ranks: twoM5Ultras), + .init(runtimeModelID: "registered_gemma4_26b_qat_4bit", catalogModelID: "gemma-4-26b-qat-4bit", + artifactSHA256: "2468a0cb3049a871f42052f4d9f9380bf12a0792f64c7a29f768559fc7d28785", + families: [.pipeline, .tensorParallel], schedules: [1, 2], ranks: twoM5Ultras), ] /// The placement a declared family is qualified at, for a model of /// `layers` layers on `ranks` ranks: tensor parallel splits every layer /// (`tensor_parallel_v1`, no cut); a pipeline (`pipeline_v1`) cuts the - /// layers evenly (two ranks: `[layers / 2]`), so it needs the layer count. - /// Nil for a family without such a placement here, or a pipeline without - /// enough layers. + /// layers evenly (two ranks: `[layers / 2]`), so it needs the layer count, + /// and a speculative pipeline (`pipeline_mtp_v1`, its last rank drafting) + /// is cut the same way. Nil for a hand-off (an opt-in, never declared), or + /// a pipeline without enough layers. static func placement(of family: ClusterPairServingModeFamily, layers: Int?, ranks: Int) -> (mode: ClusterGenerationMode, cuts: [Int])? { switch family { case .tensorParallel: return (.tensorParallel, []) - case .pipeline: + case .pipeline, .pipelineSpeculative: guard let layers, ranks >= 2, layers >= ranks else { return nil } - return (.pipeline, (1.. Date: Tue, 3 Nov 2026 10:42:09 -0600 Subject: [PATCH 0237/1441] feat(provider): log App Attest entitlement evidence for is_supported_false To find why isSupported is false after a self-update, the provider now writes one local log line at startup and at each is_supported_false answer. The line shows the start reason, the App Attest entitlements that the kernel gave the running process (SecTaskCopyValueForEntitlement) next to the ones in the code on disk, and the executable's modification time minus the process start time. The line goes to stderr, which launchd sends to the local provider log. Nothing goes on the wire and no schema changes. Co-Authored-By: Claude Opus 5.5 --- changelog.d/app-attest-unsupported-restart.md | 1 + docs/provider/attestation.md | 11 ++- .../AppAttestPreflightProbe.swift | 67 +++++++++++++++++++ .../ProviderLoop+AppAttestStall.swift | 3 + .../Sources/ProviderCore/ProviderLoop.swift | 4 ++ .../Service/ProviderProcessRun.swift | 12 ++++ .../darkbloom/Start/StartCommand+Modes.swift | 1 + .../KeyHistoryAndPreflightTests.swift | 32 +++++++++ .../Service/ProviderLifecycleTests.swift | 25 +++++++ 9 files changed, 155 insertions(+), 1 deletion(-) diff --git a/changelog.d/app-attest-unsupported-restart.md b/changelog.d/app-attest-unsupported-restart.md index 20767a0a6d..97ed5acd15 100644 --- a/changelog.d/app-attest-unsupported-restart.md +++ b/changelog.d/app-attest-unsupported-restart.md @@ -3,3 +3,4 @@ - A provider that launchd runs as its provider job now relaunches through launchd after a startup self-update, as it already did after a background update. Only a provider that launchd does not run, such as `darkbloom start --foreground` in a terminal, replaces itself in place. A background update or App Attest restart in such a provider no longer starts the LaunchAgent instead. - When App Attest reports `is_supported_false` on a Mac that the coordinator verified for App Attest in the last 7 days, the provider restarts once through launchd. It waits until the state lasts 5 minutes and the provider is idle, and it checks Apple's answer again after the drain. If the new process still reports unsupported, it does not restart again until the coordinator verifies the Mac again. This restart and the stall restart share one limit: one automatic App Attest restart per 6 hours. Cluster members never restart for it. - The provider keeps the time of its last App Attest authorization in `app-attest-verified.json` beside the daemon state file. +- The local provider log gets an `App Attest entitlement evidence` line at startup and at each `is_supported_false` answer: the start reason, the App Attest entitlements of the running process and of the code on disk, and the executable's modification time relative to the process start. It is not sent to the coordinator. diff --git a/docs/provider/attestation.md b/docs/provider/attestation.md index 1c005c719d..75b3b6ea14 100644 --- a/docs/provider/attestation.md +++ b/docs/provider/attestation.md @@ -105,7 +105,16 @@ this Mac App Attest in the last 7 days and launchd runs the provider, the provider restarts once through launchd when the state lasts 5 minutes and the provider is idle. It restarts once per verified episode: if the new process still reports unsupported, it waits until the coordinator verifies the Mac -again. This restart shares the stall restart's limit of one per 6 hours. The log line starts with `App Attest: isSupported is false`. See the +again. This restart shares the stall restart's limit of one per 6 hours. + +For root-cause analysis, the provider log (`~/.darkbloom/provider.log`) gets a +line that starts with `App Attest entitlement evidence` once at startup and at +each `is_supported_false` answer. It shows the start reason, the App Attest +entitlements the kernel gave the running process next to the ones in the code +on disk, and the executable's modification time minus the process start time. +The line stays on the Mac; it is not sent to the coordinator +(`provider-swift/Sources/ProviderAppAttest/AppAttestPreflightProbe.swift`, +`AppAttestEntitlementEvidence`). The log line starts with `App Attest: isSupported is false`. See the [thresholds and limits](../reference/app-attest-shadow.md#bounds-and-credential-lifecycle). The separate [supervised worker candidate](../architecture/security/identity-binding.md#supervised-app-attest-worker-candidate) diff --git a/provider-swift/Sources/ProviderAppAttest/AppAttestPreflightProbe.swift b/provider-swift/Sources/ProviderAppAttest/AppAttestPreflightProbe.swift index 6d3a089428..0a2f064c6c 100644 --- a/provider-swift/Sources/ProviderAppAttest/AppAttestPreflightProbe.swift +++ b/provider-swift/Sources/ProviderAppAttest/AppAttestPreflightProbe.swift @@ -93,3 +93,70 @@ enum ProvisioningProfileDecoder { return content as Data } } + +/// Local root-cause evidence for `is_supported_false`. It compares the App +/// Attest entitlements the kernel gave this process at launch with the ones in +/// the code on disk, which is all the `preflight` diagnostic can see, and +/// records how the executable's modification time relates to the process start. +/// It goes to the local provider log only; it is never sent and never changes +/// a decision. +public struct AppAttestEntitlementEvidence: Sendable, Equatable { + /// Nil when the running task's entitlements could not be read. + public var runtimeOptIn: Bool? + public var runtimeEnvironment: AppAttestPreflight.EnvironmentEntitlement? + /// Nil when signing information for the code on disk was unavailable. + public var diskOptIn: Bool? + public var diskEnvironment: AppAttestPreflight.EnvironmentEntitlement? + /// Executable modification time minus process start, whole seconds. A + /// positive value means the file changed after this process started (an + /// in-place exec of a replaced binary keeps the earlier start time). + public var executableModifiedMinusStartSeconds: Int? + + /// `runtime` reads one entitlement of the running task; nil from the + /// reader means it is absent. `runtime` itself nil means the task was unavailable. + static func build(runtime: ((String) -> Any?)?, diskEntitlements: [String: Any]?, + executableModifiedAt: Date?, processStartedAt: Date?) -> AppAttestEntitlementEvidence { + func optIn(_ value: Any?) -> Bool { + (value as? String) == "CDhash" || (value as? [String])?.contains("CDhash") == true + } + var evidence = AppAttestEntitlementEvidence() + if let runtime { + evidence.runtimeOptIn = optIn(runtime(AppAttestEntitlementPolicy.optIn)) + evidence.runtimeEnvironment = AppAttestPreflight.environmentClass(runtime(AppAttestEntitlementPolicy.environment)) + } + if let diskEntitlements { + evidence.diskOptIn = optIn(diskEntitlements[AppAttestEntitlementPolicy.optIn]) + evidence.diskEnvironment = AppAttestPreflight.environmentClass(diskEntitlements[AppAttestEntitlementPolicy.environment]) + } + if let executableModifiedAt, let processStartedAt { + let delta = executableModifiedAt.timeIntervalSince(processStartedAt) + if delta.isFinite { evidence.executableModifiedMinusStartSeconds = Int(delta.rounded()) } + } + return evidence + } + + /// Live probe of this process. `processStartedAt` is the kernel start time. + public static func current(processStartedAt: Date?) -> AppAttestEntitlementEvidence { + let task = SecTaskCreateFromSelf(nil) + let runtime: ((String) -> Any?)? = task.map { task in + { key in SecTaskCopyValueForEntitlement(task, key as CFString, nil) } + } + let disk = AppAttestSigningInfo.current() + .map { $0[kSecCodeInfoEntitlementsDict as String] as? [String: Any] ?? [:] } + let modified = Bundle.main.executableURL.flatMap { + (try? FileManager.default.attributesOfItem(atPath: $0.resolvingSymlinksInPath().path))?[.modificationDate] as? Date + } + return build(runtime: runtime, diskEntitlements: disk, executableModifiedAt: modified, + processStartedAt: processStartedAt) + } + + /// One log line of closed values: `context` and `startReason` name the + /// moment; `unavailable` marks a value that could not be read. + public func line(context: String, startReason: AppAttestStartReason?) -> String { + func show(_ value: Bool?) -> String { value.map { $0 ? "true" : "false" } ?? "unavailable" } + return "App Attest entitlement evidence (\(context)): start_reason=\(startReason?.rawValue ?? "unknown")" + + " runtime_opt_in=\(show(runtimeOptIn)) runtime_environment=\(runtimeEnvironment?.rawValue ?? "unavailable")" + + " disk_opt_in=\(show(diskOptIn)) disk_environment=\(diskEnvironment?.rawValue ?? "unavailable")" + + " executable_modified_minus_start_s=\(executableModifiedMinusStartSeconds.map(String.init) ?? "unavailable")" + } +} diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift index 246424a72b..debb7dcce9 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift @@ -38,6 +38,9 @@ extension ProviderLoop { /// Called with each `ready` this process answers. Starts the monitor when /// `isSupported` is false on a Mac that may restart for it. internal func noteAppAttestAvailability(_ status: AppAttestLocalStatus?, now: Date = Date()) { + // Root-cause evidence for every unsupported answer, whether or not a + // restart may follow. + if status?.availabilityReason == .isSupportedFalse { appAttestEvidenceLog("is_supported_false") } guard serveUsesHostServices, !isClusterMember, !usesAppAttestWorker, status?.availabilityReason == .isSupportedFalse, appAttestUnsupportedRestartEligible(status, now: now) else { appAttestUnsupportedSince = nil diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index e30767c4f4..740592330b 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -231,6 +231,10 @@ public actor ProviderLoop { internal var appAttestRestart: AppAttestRestart = { try ProcessLifecycle.restartAfterUpdate(cause: $0, route: $1) } /// Seam for the install the App Attest restart leases; nil is the running install. internal var appAttestRestartUpdater: SelfUpdater? + /// Seam for the local entitlement evidence line written at `is_supported_false`. + internal var appAttestEvidenceLog: @Sendable (_ context: String) -> Void = { + ProviderProcessRun.logAppAttestEntitlementEvidence(context: $0) + } internal let loopConfig: ProviderLoopConfig internal var ordinaryServingModelIDs: Set /// The operator's explicit selection: `enabled_models` with the start diff --git a/provider-swift/Sources/ProviderCore/Service/ProviderProcessRun.swift b/provider-swift/Sources/ProviderCore/Service/ProviderProcessRun.swift index d014feec94..082c688511 100644 --- a/provider-swift/Sources/ProviderCore/Service/ProviderProcessRun.swift +++ b/provider-swift/Sources/ProviderCore/Service/ProviderProcessRun.swift @@ -86,3 +86,15 @@ public enum ProviderProcessRun { } } } + +extension ProviderProcessRun { + /// Writes `AppAttestEntitlementEvidence` for this serve process to stderr, + /// which launchd sends to the local provider log. Never sent anywhere. + public static func logAppAttestEntitlementEvidence(context label: String) { + let run = current + let started = run?.processStartMicros.map { Date(timeIntervalSince1970: Double($0) / 1_000_000) } + let line = AppAttestEntitlementEvidence.current(processStartedAt: started) + .line(context: label, startReason: run?.startReason) + FileHandle.standardError.write(Data((line + "\n").utf8)) + } +} diff --git a/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift b/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift index 583bffc3c5..b6c3861b0e 100644 --- a/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift +++ b/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift @@ -205,6 +205,7 @@ extension Start { // Only the lock holder is the serving process: record its start // (previous_exit / start_reason) before any in-place update exec. ProviderProcessRun.begin() + ProviderProcessRun.logAppAttestEntitlementEvidence(context: "startup") let selectedIDs = Set(selectedModels.map(\.id)) let autopilot = config.backend.modelAutopilot diff --git a/provider-swift/Tests/ProviderAppAttestTests/KeyHistoryAndPreflightTests.swift b/provider-swift/Tests/ProviderAppAttestTests/KeyHistoryAndPreflightTests.swift index fbf678e6e0..9ee3961f5d 100644 --- a/provider-swift/Tests/ProviderAppAttestTests/KeyHistoryAndPreflightTests.swift +++ b/provider-swift/Tests/ProviderAppAttestTests/KeyHistoryAndPreflightTests.swift @@ -214,6 +214,38 @@ final class KeyHistoryAndPreflightTests: XCTestCase { XCTAssertEqual(AppAttestPreflight.pathClass(home + "/Applications/Darkbloom.app", home: home), .applications) } + func testEntitlementEvidenceComparesTheRunningTaskWithTheCodeOnDisk() { + let started = Date(timeIntervalSince1970: 1_790_000_000) + let disk: [String: Any] = [AppAttestEntitlementPolicy.optIn: ["CDhash"], + AppAttestEntitlementPolicy.environment: "production"] + // The disk check passes while the kernel gave the task no App Attest entitlement. + let missing = AppAttestEntitlementEvidence.build(runtime: { _ in nil }, diskEntitlements: disk, + executableModifiedAt: started.addingTimeInterval(40), processStartedAt: started) + XCTAssertEqual(missing.runtimeOptIn, false) + XCTAssertEqual(missing.runtimeEnvironment, .absent) + XCTAssertEqual(missing.diskOptIn, true) + XCTAssertEqual(missing.diskEnvironment, .production) + XCTAssertEqual(missing.executableModifiedMinusStartSeconds, 40, "the binary changed after this process started") + XCTAssertEqual(missing.line(context: "is_supported_false", startReason: .update), + "App Attest entitlement evidence (is_supported_false): start_reason=update runtime_opt_in=false" + + " runtime_environment=absent disk_opt_in=true disk_environment=production executable_modified_minus_start_s=40") + + let granted = AppAttestEntitlementEvidence.build(runtime: { disk[$0] }, diskEntitlements: disk, + executableModifiedAt: started.addingTimeInterval(-3600), processStartedAt: started) + XCTAssertEqual(granted.runtimeOptIn, true) + XCTAssertEqual(granted.runtimeEnvironment, .production) + XCTAssertEqual(granted.executableModifiedMinusStartSeconds, -3600) + + // Unreadable values are reported as unavailable, never guessed. + let unknown = AppAttestEntitlementEvidence.build(runtime: nil, diskEntitlements: nil, + executableModifiedAt: nil, processStartedAt: started) + XCTAssertEqual(unknown, AppAttestEntitlementEvidence()) + XCTAssertEqual(unknown.line(context: "startup", startReason: nil), + "App Attest entitlement evidence (startup): start_reason=unknown runtime_opt_in=unavailable" + + " runtime_environment=unavailable disk_opt_in=unavailable disk_environment=unavailable" + + " executable_modified_minus_start_s=unavailable") + } + func testRealEmbeddedProfileExpiryDecodesWhenInstalled() throws { let url = FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent(".darkbloom/Darkbloom.app/Contents/embedded.provisionprofile") diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift index ef8a182de6..c7fc11d6ee 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift @@ -36,6 +36,10 @@ private extension ProviderLoop { appAttestSupportProbe = supported appAttestRestart = { restarts.append($0, $1) } appAttestRestartUpdater = updater + appAttestEvidenceLog = { _ in } + } + func captureAppAttestEvidence(_ contexts: AppAttestEvidenceContexts) { + appAttestEvidenceLog = { contexts.append($0) } } func setAppAttestRestartSeams(route: ProcessLifecycle.RelaunchRoute, supported: Bool) { setAppAttestRestartSeams(route: route, supported: { supported }) @@ -314,6 +318,13 @@ private final class AppAttestRestartLog: @unchecked Sendable { var causes: [ProviderRunMarker.ExitCause] { lock.withLock { entries.map(\.0) } } } +private final class AppAttestEvidenceContexts: @unchecked Sendable { + private let lock = NSLock() + private var entries: [String] = [] + func append(_ context: String) { lock.withLock { entries.append(context) } } + var values: [String] { lock.withLock { entries } } +} + /// Apple boundary with no outstanding call; availability comes from the probe seam. private actor IdleAppAttestService: AppAttestService { func checkAvailability(environment: String) {} @@ -503,6 +514,20 @@ struct AppAttestUnsupportedRestartTests { await loop.cancelAppAttestStallMonitor() } + @Test func everyUnsupportedReadyWritesEntitlementEvidenceEvenWithoutARestart() async throws { + let (loop, root) = try await lifecycleLoop() + defer { try? FileManager.default.removeItem(at: root) } + await loop.setAppAttestRestartSeams(route: .exec, supported: false) + let contexts = AppAttestEvidenceContexts() + await loop.captureAppAttestEvidence(contexts) + // Never verified and not under launchd: no restart, but the evidence is written. + await loop.noteAppAttestAvailability(unsupportedReady(), now: Date()) + await loop.noteAppAttestAvailability(AppAttestLocalStatus(observedAt: 0, launchSession: .gui), now: Date()) + await loop.noteAppAttestAvailability(unsupportedReady(), now: Date()) + #expect(contexts.values == ["is_supported_false", "is_supported_false"]) + #expect(await loop.appAttestUnsupportedSince == nil) + } + @Test func clusterMemberNeverArmsTheUnsupportedRestart() async throws { let (loop, root) = try await lifecycleLoop(role: .clusterMember) defer { try? FileManager.default.removeItem(at: root) } From 3b875a28e1fb3af3ab8f0b165353c98b46867f5e Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 10:42:43 -0600 Subject: [PATCH 0238/1441] ci: fix the summary's needs pin; refactor pass wording in test.md and a test comment Co-Authored-By: Claude Opus 5.5 --- docs/developer/test.md | 6 +++--- scripts/test-ci-component-paths.py | 2 +- scripts/test-provider-ci-workflow.py | 3 ++- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/developer/test.md b/docs/developer/test.md index bdd2ef065e..11d9fb103c 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -134,9 +134,9 @@ When the shards drift apart, replace the weights file with that artifact. A suite moves from the parallel class to the serial class when it fails or flakes in parallel; when in doubt, a suite stays serial. -The provider lanes and Cluster Metadata Checks restore their build cache by the -exact key first, then by the key prefix. A push to `dev`, `main` or `master` -saves its build. A pull request saves its build only when it restored nothing. +The jobs that use the `provider-ci-build` action and Cluster Metadata Checks +restore their build cache by the exact key first, then by the key prefix. A +push to `dev`, `main` or `master` saves its build. A pull request saves its build only when it restored nothing. Its later pushes then restore that entry or the base branch's entry and add no new entry, so they do not evict the base branch's entries. CI has no separate push-only Swift cache job. diff --git a/scripts/test-ci-component-paths.py b/scripts/test-ci-component-paths.py index 37207e8a3c..dffb99c951 100644 --- a/scripts/test-ci-component-paths.py +++ b/scripts/test-ci-component-paths.py @@ -237,7 +237,7 @@ def test_expensive_jobs_depend_on_successful_classifier(self): jobs = workflow.job_blocks((ROOT / ".github/workflows" / name).read_text()) self.assertIn("uses: ./.github/workflows/component-changes.yml", jobs["changes"]) self.assertIn("contents: read", jobs["changes"]) - # Runner routing follows the classifier, so only selected lanes are requested. + # The route job waits for the classifier (ci.yml, route). self.assertIn(" needs: changes\n", jobs["route"]) for lane, component in lanes.items(): self.assertIn(" needs: changes\n", jobs[lane]) diff --git a/scripts/test-provider-ci-workflow.py b/scripts/test-provider-ci-workflow.py index 42088c825c..ed6a3aeb78 100644 --- a/scripts/test-provider-ci-workflow.py +++ b/scripts/test-provider-ci-workflow.py @@ -226,7 +226,8 @@ def test_route_requests_no_macos_lane(self): "test-cluster", "test-cluster-gpu", "test-cluster-focused"): with self.subTest(job=job_id): self.assertIn(" runs-on: blacksmith-12vcpu-macos-27\n", self.jobs[job_id]) - self.assertIn(" needs: changes\n", self.jobs[job_id]) + needs = re.search(r"(?m)^ needs: (.+)$", self.jobs[job_id]).group(1) + self.assertNotIn("route", needs) def test_existing_required_check_requires_every_lane_even_after_failures(self): job = self.jobs["provider-test-gate"] From 21c05aabfcc73edca29649cd49de63be0f11d175 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 11:14:54 -0600 Subject: [PATCH 0239/1441] Fix two cluster test flakes: prelude cancel race, record lock race PreludeChecks: the transcript-mismatch group cancelled rank 1's owner socket right after it refused rank 0. Rank 1 writes its completion only after it reads the peer confirmation, so a cancel that came first shut the socket under that write and the child exited 1. The owner now reads rank 1's completion before it cancels. Children inherit stderr, so a failing child names its own failure. ClusterSetupStore.updateRecord: the record lock was a single non-blocking flock. The service clears a stop drain in the same supervision tick that publishes child.running=false, so a stop request at that moment failed with "could not save the stop request". An operator who runs `darkbloom cluster stop` again after a timeout hits the same window. Record writes now poll the lock for up to 2 s. Other callers of withLock and update keep the single attempt. Co-Authored-By: Claude Opus 5.5 --- .../Tests/PreludeChecks/main.swift | 6 +++- .../Config/ClusterConfigurationFiles.swift | 13 +++++--- .../Console/ClusterSetupWizardStore.swift | 8 ++++- .../ClusterServiceRecoveryTests.swift | 32 +++++++++++++++++++ 4 files changed, 53 insertions(+), 6 deletions(-) diff --git a/libs/darkbloom-cluster/Tests/PreludeChecks/main.swift b/libs/darkbloom-cluster/Tests/PreludeChecks/main.swift index 79d3edd8cd..d1022fe103 100644 --- a/libs/darkbloom-cluster/Tests/PreludeChecks/main.swift +++ b/libs/darkbloom-cluster/Tests/PreludeChecks/main.swift @@ -66,7 +66,7 @@ func unhex(_ string: String) -> Data { process.arguments = [mode, listener.socketPath, String(getpid()), String(rank), String(until), startHex, extra] process.standardInput = FileHandle.nullDevice process.standardOutput = FileHandle.nullDevice - process.standardError = FileHandle.nullDevice + // Inherited, so a child that fails prints its own "FAIL:" line in the log. try process.run(); return process } @@ -312,6 +312,10 @@ func unhex(_ string: String) -> Data { try reject("owner accepted a fabricated transcript") { try prelude0.requireComplete(transcriptSHA256: Data(SHA256.hash(data: Data("forged".utf8)))) } + // Rank 1 writes its completion after it reads the peer confirmation. + // Read that completion before the cancel: a cancel that came first + // would shut the socket under rank 1's write and fail its path. + try prelude1.requireComplete(transcriptSHA256: binding.transcriptSHA256) prelude0.cancel(); prelude1.cancel() try reap(child0); try reap(child1) } diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterConfigurationFiles.swift b/provider-swift/Sources/ProviderCore/Config/ClusterConfigurationFiles.swift index 7ab04fed2a..06094a813e 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterConfigurationFiles.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterConfigurationFiles.swift @@ -140,8 +140,9 @@ enum ClusterConfigurationFiles { try parent.check() } + /// `waitSeconds` is how long a held lock is polled before `.busy`; 0 tries once. static func withLock(_ parent: Directory, name: String, requireEmpty: Bool = false, - privateMode: Bool = false, _ body: () throws -> T) throws -> T { + privateMode: Bool = false, waitSeconds: Double = 0, _ body: () throws -> T) throws -> T { try parent.check() try requireName(name) let fd = openat(parent.descriptor, name, O_RDWR | O_CREAT | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC, 0o600) @@ -153,7 +154,11 @@ enum ClusterConfigurationFiles { value.st_dev == named.st_dev, value.st_ino == named.st_ino else { throw ClusterConfigurationError.invalid("Configuration lock is unsafe") } - guard flock(fd, LOCK_EX | LOCK_NB) == 0 else { throw ClusterConfigurationError.busy } + let limit = DispatchTime.now().uptimeNanoseconds + UInt64(max(0, waitSeconds) * 1_000_000_000) + while flock(fd, LOCK_EX | LOCK_NB) != 0 { + guard DispatchTime.now().uptimeNanoseconds < limit else { throw ClusterConfigurationError.busy } + usleep(5_000) + } defer { _ = flock(fd, LOCK_UN) } guard fstat(fd, &value) == 0, !requireEmpty || value.st_size == 0 else { throw ClusterConfigurationError.invalid("Unresolved native ownership journal; run `darkbloom cluster recover`") @@ -202,11 +207,11 @@ enum ClusterConfigurationFiles { /// stable sidecar lock used by existing CLI writers. A transform failure leaves /// the old bytes intact. Published cluster records may remain unreferenced if /// this later pointer update fails; they are never treated as enabled setup. - static func update(_ url: URL, maximum: Int, transform: (Data?) throws -> Data) throws { + static func update(_ url: URL, maximum: Int, lockWaitSeconds: Double = 0, transform: (Data?) throws -> Data) throws { try requireAbsolute(url.path) let parent = try directory(url.deletingLastPathComponent(), create: true) defer { Darwin.close(parent.descriptor) } - try withLock(parent, name: url.lastPathComponent + ".lock") { + try withLock(parent, name: url.lastPathComponent + ".lock", waitSeconds: lockWaitSeconds) { let original = try readAt(parent, name: url.lastPathComponent, maximum: maximum) let next = try transform(original) guard !next.isEmpty, next.count <= maximum else { throw ClusterConfigurationError.invalid("Provider configuration serialization failed or exceeded its bound") } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift index 6314ae9957..3527794ff6 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift @@ -198,12 +198,18 @@ public struct ClusterSetupStore: Sendable { return value } + /// How long a write waits while another writer holds the record's lock. Each holder only reads, changes and + /// writes the record, so a held lock is a write in progress (the service's supervision tick, a stop or the + /// wizard), not a refusal. + static let recordLockWaitSeconds: Double = 2 + /// Applies `change` to the record as it is on disk now and writes the result. @discardableResult public func updateRecord(_ change: (inout ClusterSetupRecord) throws -> Void) throws -> ClusterSetupRecord { try ClusterConfigurationFiles.ensureDirectory(paths.directory, create: true, privateMode: true) var result = ClusterSetupRecord() - try ClusterConfigurationFiles.update(paths.record, maximum: ClusterSetupRecord.maximumBytes) { current in + try ClusterConfigurationFiles.update(paths.record, maximum: ClusterSetupRecord.maximumBytes, + lockWaitSeconds: Self.recordLockWaitSeconds) { current in var record = try current.map { try JSONDecoder().decode(ClusterSetupRecord.self, from: $0) } ?? .init() guard record.schema == ClusterSetupRecord.schemaName else { throw ClusterConfigurationError.invalid("The setup wizard's record has another schema") diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRecoveryTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRecoveryTests.swift index 89ee9edf28..7bb3ab7b4e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRecoveryTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRecoveryTests.swift @@ -348,6 +348,38 @@ struct ClusterServiceRecoveryTests { #expect(!notLeader.running) } + /// The service clears a stop drain in the same supervision tick that publishes child.running=false. A stop + /// request that meets that write waits for the record lock; it does not fail with "could not save the stop request". + @Test func stopRequestWaitsForAnotherRecordWriterAndALockHeldPastTheBoundStaysBusy() throws { + let home = try NativePairMemberFixture.privateRoot() + defer { try? FileManager.default.removeItem(at: home) } + let store = ClusterSetupStore(paths: .init(paths: try ClusterUserPaths(homeDirectory: home))) + _ = try store.updateRecord { _ in } + let lockPath = store.paths.record.path + ".lock" + // Another open file description: flock excludes it in this process too. + let holder = open(lockPath, O_RDWR | O_CLOEXEC) + try #require(holder >= 0 && flock(holder, LOCK_EX | LOCK_NB) == 0) + defer { close(holder) } + let released = DispatchSemaphore(value: 0), start = DispatchTime.now() + DispatchQueue.global().asyncAfter(deadline: start + 0.2) { _ = flock(holder, LOCK_UN); released.signal() } + let stopID = UUID() + let saved = try store.updateRecord { $0.stopDrain = .init(id: stopID, keepPeerRunning: false) } + let waited = Double(DispatchTime.now().uptimeNanoseconds - start.uptimeNanoseconds) / 1e9 + #expect(waited >= 0.2, "the write ran only after the other writer let go (\(waited) s)") + try #require(released.wait(timeout: .now() + 5) == .success) + let reread = try store.readRecord() + #expect(saved.stopDrain?.id == stopID && reread.stopDrain?.id == stopID) + + try #require(flock(holder, LOCK_EX | LOCK_NB) == 0) + let parent = try ClusterConfigurationFiles.directory(store.paths.directory, privateMode: true) + defer { close(parent.descriptor) } + let name = store.paths.record.lastPathComponent + ".lock" + #expect(throws: ClusterConfigurationError.busy) { + try ClusterConfigurationFiles.withLock(parent, name: name, waitSeconds: 0.05) {} + } + #expect(throws: ClusterConfigurationError.busy) { try ClusterConfigurationFiles.withLock(parent, name: name) {} } + } + @Test func plannedStopRejectsUnknownLiveServiceAndDoesNotSignalRecycledIdentity() throws { let home = try NativePairMemberFixture.privateRoot() defer { try? FileManager.default.removeItem(at: home) } From ef46a13af235e1e91b16cda20a6863b45cbfeeab Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 11:19:08 -0600 Subject: [PATCH 0240/1441] Review pass: service tick keeps one lock try; tighter lock poll - ClusterService.publish(afterSupervision:) clears the stop drain while it holds the service lock. It now tries the record lock once and waits for the next tick when the record is busy, so the service lock is never held for the 2 s wait. - withLock polls only while flock reports EWOULDBLOCK or EINTR. - The new test closes its descriptor only after the scheduled unlock. - PreludeChecks: a failing child prints its mode and rank; the summary counts 11 children. Co-Authored-By: Claude Opus 5.5 --- libs/darkbloom-cluster/Tests/PreludeChecks/main.swift | 7 +++++-- .../Config/ClusterConfigurationFiles.swift | 3 ++- .../Distributed/Console/ClusterSetupWizardStore.swift | 10 ++++++---- .../Distributed/Onboarding/ClusterService.swift | 3 ++- .../Distributed/ClusterServiceRecoveryTests.swift | 6 ++++-- 5 files changed, 19 insertions(+), 10 deletions(-) diff --git a/libs/darkbloom-cluster/Tests/PreludeChecks/main.swift b/libs/darkbloom-cluster/Tests/PreludeChecks/main.swift index d1022fe103..54314e5d17 100644 --- a/libs/darkbloom-cluster/Tests/PreludeChecks/main.swift +++ b/libs/darkbloom-cluster/Tests/PreludeChecks/main.swift @@ -31,12 +31,15 @@ func unhex(_ string: String) -> Data { static func main() { do { - if CommandLine.arguments.count > 1 { try child(); return } + if CommandLine.arguments.count > 1 { + do { try child() } catch { fputs("FAIL child \(CommandLine.arguments[1]) rank \(CommandLine.arguments[4]): \(error)\n", stderr); exit(1) } + return + } try codecVectors() try fullTwoRankExchange() try refusalGroups() try preludeThenMesh() - print(#"{"passed":true,"groups":4,"actualChildren":10,"modelExecution":false,"networkUsed":false,"rdma":false}"#) + print(#"{"passed":true,"groups":4,"actualChildren":11,"modelExecution":false,"networkUsed":false,"rdma":false}"#) } catch { fputs("FAIL: \(error)\n", stderr); exit(1) } } diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterConfigurationFiles.swift b/provider-swift/Sources/ProviderCore/Config/ClusterConfigurationFiles.swift index 06094a813e..1badee5499 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterConfigurationFiles.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterConfigurationFiles.swift @@ -156,7 +156,8 @@ enum ClusterConfigurationFiles { } let limit = DispatchTime.now().uptimeNanoseconds + UInt64(max(0, waitSeconds) * 1_000_000_000) while flock(fd, LOCK_EX | LOCK_NB) != 0 { - guard DispatchTime.now().uptimeNanoseconds < limit else { throw ClusterConfigurationError.busy } + guard errno == EWOULDBLOCK || errno == EINTR, + DispatchTime.now().uptimeNanoseconds < limit else { throw ClusterConfigurationError.busy } usleep(5_000) } defer { _ = flock(fd, LOCK_UN) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift index 3527794ff6..f4c1c7e1b6 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift @@ -201,15 +201,17 @@ public struct ClusterSetupStore: Sendable { /// How long a write waits while another writer holds the record's lock. Each holder only reads, changes and /// writes the record, so a held lock is a write in progress (the service's supervision tick, a stop or the /// wizard), not a refusal. - static let recordLockWaitSeconds: Double = 2 + public static let recordLockWaitSeconds: Double = 2 - /// Applies `change` to the record as it is on disk now and writes the result. + /// Applies `change` to the record as it is on disk now and writes the result. A caller that holds another lock + /// passes `lockWaitSeconds: 0` and tries again later instead of waiting. @discardableResult - public func updateRecord(_ change: (inout ClusterSetupRecord) throws -> Void) throws -> ClusterSetupRecord { + public func updateRecord(lockWaitSeconds: Double = Self.recordLockWaitSeconds, + _ change: (inout ClusterSetupRecord) throws -> Void) throws -> ClusterSetupRecord { try ClusterConfigurationFiles.ensureDirectory(paths.directory, create: true, privateMode: true) var result = ClusterSetupRecord() try ClusterConfigurationFiles.update(paths.record, maximum: ClusterSetupRecord.maximumBytes, - lockWaitSeconds: Self.recordLockWaitSeconds) { current in + lockWaitSeconds: lockWaitSeconds) { current in var record = try current.map { try JSONDecoder().decode(ClusterSetupRecord.self, from: $0) } ?? .init() guard record.schema == ClusterSetupRecord.schemaName else { throw ClusterConfigurationError.invalid("The setup wizard's record has another schema") diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index 6abb81a8e8..7ba988e987 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -1267,7 +1267,8 @@ public final class ClusterService: @unchecked Sendable { do { var record = try store.readRecord() if let drain = record.stopDrain, drain.id == supervisedStopDrainID { - record = try store.updateRecord { + // Under the service lock: one try; a busy record waits for the next tick. + record = try store.updateRecord(lockWaitSeconds: 0) { if $0.stopDrain?.id == drain.id, $0.leadership?.serving != true { $0.stopDrain = nil } } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRecoveryTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRecoveryTests.swift index 7bb3ab7b4e..92f9669193 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRecoveryTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRecoveryTests.swift @@ -359,17 +359,19 @@ struct ClusterServiceRecoveryTests { // Another open file description: flock excludes it in this process too. let holder = open(lockPath, O_RDWR | O_CLOEXEC) try #require(holder >= 0 && flock(holder, LOCK_EX | LOCK_NB) == 0) - defer { close(holder) } let released = DispatchSemaphore(value: 0), start = DispatchTime.now() + // The scheduled unlock uses this descriptor; it is closed only after that unlock ran. + defer { _ = released.wait(timeout: .now() + 5); close(holder) } DispatchQueue.global().asyncAfter(deadline: start + 0.2) { _ = flock(holder, LOCK_UN); released.signal() } let stopID = UUID() let saved = try store.updateRecord { $0.stopDrain = .init(id: stopID, keepPeerRunning: false) } let waited = Double(DispatchTime.now().uptimeNanoseconds - start.uptimeNanoseconds) / 1e9 #expect(waited >= 0.2, "the write ran only after the other writer let go (\(waited) s)") - try #require(released.wait(timeout: .now() + 5) == .success) let reread = try store.readRecord() #expect(saved.stopDrain?.id == stopID && reread.stopDrain?.id == stopID) + try #require(released.wait(timeout: .now() + 5) == .success) + released.signal() // For the defer. try #require(flock(holder, LOCK_EX | LOCK_NB) == 0) let parent = try ClusterConfigurationFiles.directory(store.paths.directory, privateMode: true) defer { close(parent.descriptor) } From a2db6ab256e2fe3d3540eddb18816ae88532c240 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 11:23:36 -0600 Subject: [PATCH 0241/1441] fix(provider): arm the App Attest restart on the first episode after an update The is_supported_false restart needs app-attest-verified.json, which versions before 1731 never wrote. So the first episode after an update from such a version could not restart. At start, before this run's first daemon-state write, the provider now seeds the marker once, while it is missing, from the previous daemon-state.json: the time of an App Attest grant, or the last successful Apple call of a stored key that Apple attested. Both fields exist from v0.10.5. All other guards stay: launchd-run, idle, profile not expired, not a cluster member, 5 min, 7 days, one restart per episode, and the shared 6 h limit. Co-Authored-By: Claude Opus 5.5 --- changelog.d/app-attest-first-episode.md | 3 + docs/provider/cli-reference.md | 4 +- docs/reference/app-attest-shadow.md | 4 +- .../ProviderLoop+AppAttestStall.swift | 37 ++++++++ .../ProviderCore/ProviderLoop+Serve.swift | 2 + .../Service/ProviderLifecycleTests.swift | 89 +++++++++++++++++++ 6 files changed, 135 insertions(+), 4 deletions(-) create mode 100644 changelog.d/app-attest-first-episode.md diff --git a/changelog.d/app-attest-first-episode.md b/changelog.d/app-attest-first-episode.md new file mode 100644 index 0000000000..4bfb4881ac --- /dev/null +++ b/changelog.d/app-attest-first-episode.md @@ -0,0 +1,3 @@ +### App Attest restart covers the first episode after an update + +- The `is_supported_false` restart now also works in the first process after an update from a version that did not record its App Attest authorizations. At start, when `app-attest-verified.json` is missing, the provider fills it once from the previous `daemon-state.json`: the time of an App Attest grant, or the last successful Apple call of a stored key that Apple attested. All other conditions stay the same. diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 961a9c877b..502bf14b12 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1,6 +1,6 @@ # Provider CLI reference -> Last updated: 2026-11-02 +> Last updated: 2026-11-03 Reference for the `darkbloom` command-line tool: every subcommand and flag, the files and identifiers it creates, the `provider.toml` keys it reads with their @@ -2203,7 +2203,7 @@ qualification or performance. Sources: | Watchdog state | `~/.darkbloom/watchdog-state.json` (`DARKBLOOM_WATCHDOG_STATE`) | `provider-swift/Sources/ProviderCore/Service/WatchdogState.swift` | | KV-backend crash-loop guard | `~/.darkbloom/kv-backend-guard.json` (`DARKBLOOM_KV_BACKEND_GUARD`) | `provider-swift/Sources/ProviderCore/Service/KVBackendGuard.swift` | | App Attest stall restart marker | `app-attest-stall-restart.json` beside the daemon state file, `0600`; time of the last automatic App Attest restart, for a stalled DeviceCheck call or for `is_supported_false` ([limits](../reference/app-attest-shadow.md#bounds-and-credential-lifecycle)) | `provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift` (`AppAttestStallRestartMarker`) | -| App Attest verified marker | `app-attest-verified.json` beside the daemon state file, `0600`; time of the last coordinator App Attest authorization, rewritten at most once per hour. It only allows the `is_supported_false` restart; it never authorizes serving | `provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift` (`AppAttestVerifiedMarker`) | +| App Attest verified marker | `app-attest-verified.json` beside the daemon state file, `0600`; time of the last coordinator App Attest authorization, rewritten at most once per hour. When it is missing at start, it is seeded once from the previous daemon state (an App Attest grant, or the last Apple success of an attested key). It only allows the `is_supported_false` restart; it never authorizes serving | `provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift` (`AppAttestVerifiedMarker`) | | Provider run marker | `provider-run.json` beside the daemon state file, `0600`. Set to `running` when a serve process starts and to `clean` (with cause) after its drain or before an update/stall relaunch. Explicit update/stall relaunch causes survive later generic termination callbacks; a failed hand-off restores running state and clears the cause. The next process derives `previous_exit` and `start_reason` from it | `provider-swift/Sources/ProviderCore/Service/ProviderRunMarker.swift`, `ProviderProcessRun.swift` | | APNs push history | `apns-push-history.json` beside the daemon state file, `0600`. The last 50 code-identity push receipt times and reply times, plus whether a device token was present. No token, nonce or payload | `provider-swift/Sources/ProviderCore/Apns/APNsPushHistory.swift` | | Provider LaunchAgent | label `io.darkbloom.provider`; `~/Library/LaunchAgents/io.darkbloom.provider.plist`; `RunAtLoad = true`, `KeepAlive = false`; stdout/stderr → `~/.darkbloom/provider.log` | `provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift` (`label`, `plistPath`, `logPath`) | diff --git a/docs/reference/app-attest-shadow.md b/docs/reference/app-attest-shadow.md index 22239e451b..9565b74ab2 100644 --- a/docs/reference/app-attest-shadow.md +++ b/docs/reference/app-attest-shadow.md @@ -1,6 +1,6 @@ # App Attest shadow protocol, machine inventory, and evidence -> Last updated: 2026-11-02 +> Last updated: 2026-11-03 App Attest shadow collection records stable machine identities, fleet adoption, submitted proofs and receipts alongside legacy verification. Shadow alone changes no routing, rewards or trust. The separately enabled [provider authorization path](provider-authorization.md) uses qualified evidence for MDM-optional serving and rewards. DeviceCheck's separate two-bit API remains deferred. @@ -127,7 +127,7 @@ provider-local Apple callback, retry, key-budget and socket fences remain separa | Session recovery | Generic or server-unavailable Apple API failures retry after one minute, then five minutes, then at most the normal ten-minute assertion interval. Other transient coordinator/storage failures retain the one-minute, five-minute, then hourly backoff. Every attempt gets a new session/nonce and reloads durable acceptance/counters. Successful assertions reset backoff. An Apple API error is an unknown prospective verdict and grants no permission; verified crypto/policy rejections remain terminal, and cancellation stops retries. Persistent generic errors still need native domain/code diagnostics from a signed upgraded client. [Dead-key rotation](#dead-key-rotation) and the [invalid-key enrollment backoff](#invalid-key-enrollment-backoff) replace this delay in their specific cases. Code: [coordinator/internal/appattest/recovery/recovery_policy.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/internal/appattest/recovery/recovery_policy.go) (`ExchangeRetryDelay`), [coordinator/internal/appattest/recovery/driver.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/internal/appattest/recovery/driver.go) (`Driver.Run`); session wiring in [coordinator/appattest/service/retry.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/appattest/service/retry.go) (`run`). | | First-risk-receipt wait | A valid first assertion with no verified risk receipt yet, including an initial `renewal_required` receipt, stays unknown. Without an existing authorization record, a fresh assertion retries after one minute, five minutes, then at the normal ten-minute cadence while Apple's receipt renewal runs independently. Only complete fresh evidence can authorize serving. Code: [coordinator/appattest/service/authorization_identity.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/appattest/service/authorization_identity.go) and `retry.go`. | | Apple callbacks | 25-second waiter deadline. The actual uncancellable Apple operation retains admission until its callback arrives; retries receive `busy` in the meantime. A token fences duplicate late callbacks from unlocking a newer operation. A pre-cancelled call does not acquire admission. The gate records when it was acquired: once held longer than `AppleOperationStall.threshold` (15 min), `ready` replies return `busy` with `operation_stalled_seconds`, and the provider restarts itself through the background-update path (update lease, drain, `waitForSafeDisconnect`, `ProcessLifecycle.restartAfterUpdate`) only when no inference is in flight or loading and no update or lifecycle drain is running, at most once per `AppAttestStallRestartPolicy.minimumInterval` (6 h, persisted in `app-attest-stall-restart.json` beside the daemon state file before the restart is issued). An attempt that drains but cannot restart reopens serving and waits before draining again in the same process: `AppAttestStallRestartPolicy.drainRetryDelay` (15 min) when accepted work or the coordinator's drain acknowledgement did not finish in time, and a full `minimumInterval` when the marker cannot be written, since no restart may be issued without it. After the drain, and after its last suspension point, it checks again (`AppAttestStallRestartPolicy.afterDrain`): if Apple's callback released the gate, or a CLI stop, OS termination or scheduled shutdown took over the drain, it releases the update lease without restarting, and a lifecycle-owned drain stays closed. Code: `AppleOperationGate.swift`, `AppleAppAttestService.swift`, `AppleOperationStall.swift` and `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | -| `isSupported` false after verification | When a `ready` answers `is_supported_false` (macOS 27 or later), the provider restarts once through launchd if all of these hold: the coordinator granted this Mac an App Attest authorization within `AppAttestStallRestartPolicy.verifiedWithin` (7 days) and after the last automatic App Attest restart (the time is kept in `app-attest-verified.json` beside the daemon state file, rewritten at most once per hour), so one unsupported episode gets one restart; the embedded provisioning profile has not expired; this is not a cluster member; and launchd runs this provider (`ProcessLifecycle.RelaunchRoute`: launchd's record of the loaded provider job names this exact process, which an in-place exec keeps). The live `DCAppAttestService.isSupported` must stay false for `AppAttestStallRestartPolicy.unsupportedThreshold` (5 min) and again after the drain. The restart uses the stall restart's monitor, idle checks, drain, `app-attest-stall-restart.json` limit (one automatic App Attest restart per 6 h, for both causes) and `start_reason` `stall_restart`. It never uses an in-place exec. Code: `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | +| `isSupported` false after verification | When a `ready` answers `is_supported_false` (macOS 27 or later), the provider restarts once through launchd if all of these hold: the coordinator granted this Mac an App Attest authorization within `AppAttestStallRestartPolicy.verifiedWithin` (7 days) and after the last automatic App Attest restart (the time is kept in `app-attest-verified.json` beside the daemon state file, rewritten at most once per hour), so one unsupported episode gets one restart. A version that never wrote that file leaves it missing after an update; the provider then seeds it once, before its first daemon-state write, from the previous `daemon-state.json`: the time of an App Attest grant, or the last successful Apple call of a stored key that Apple attested (`ProviderLoop.appAttestVerifiedEvidence`); the embedded provisioning profile has not expired; this is not a cluster member; and launchd runs this provider (`ProcessLifecycle.RelaunchRoute`: launchd's record of the loaded provider job names this exact process, which an in-place exec keeps). The live `DCAppAttestService.isSupported` must stay false for `AppAttestStallRestartPolicy.unsupportedThreshold` (5 min) and again after the drain. The restart uses the stall restart's monitor, idle checks, drain, `app-attest-stall-restart.json` limit (one automatic App Attest restart per 6 h, for both causes) and `start_reason` `stall_restart`. It never uses an in-place exec. Code: `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | | Coordinator-driven rotation (client side) | An `attest` for a key this client already attested, with no cached proof, clears the key ID and replies `key_unregistered` without calling Apple. The next `prepare` generates a replacement within the per-key one-hour cooldown and the shared five-per-hour generation budget. Released 0.9.8 and 0.9.9 clients behave the same way. Code: `provider-swift/Sources/ProviderAppAttest/AppAttestShadowClient.swift`; pinned by `provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift`. | | Attestation retries | At most three attempts, 2/8-second waits, only for service unavailable. `ShadowEnrollmentAttempt` persists the original key/hash, status, session and timestamp across later coordinator retries and reconnects (the provider serves protocol 3 only; an attempt recorded under an earlier protocol is retired), as [Apple requires](https://developer.apple.com/documentation/devicecheck/dcerror-swift.struct/code/serverunavailable). Successful recovery uses the original stored server transaction; a subsequent serving assertion always signs fresh status/challenge/endpoint. Expired or malformed retry state retires under existing generation limits. | | Failed one-time enrollment | Non-service-unavailable Apple failures retire the enrollment key identifier under the existing generation limits. The app persists `attestationStartedAt` before calling Apple; an interrupted attempt without a saved proof is retired on the next prepare. Cached successful proofs remain recoverable. Generic assertion failures do not make the client rotate an accepted key on its own; an explicit invalid-key response can retire it, and the coordinator can request [dead-key rotation](#dead-key-rotation). Code: `provider-swift/Sources/ProviderAppAttest/EnrollmentKeyLifecycle.swift` and `AppAttestShadowClient.swift`. | diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift index debb7dcce9..460a2d2d83 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift @@ -267,4 +267,41 @@ extension ProviderLoop { logger.warning("App Attest: cannot persist the verified marker: \(error)") } } + + /// A version before `AppAttestVerifiedMarker` never wrote it, so the first + /// `is_supported_false` after an update from it would not restart. Seed the + /// marker once, while it is missing, from what that version left in + /// `daemon-state.json`. Runs before this process writes its own state. + internal func seedAppAttestVerifiedFromPreviousRun() { + let marker = appAttestVerifiedMarker() + // The usual eligibility rules (7 days, after the last restart) apply + // to the seeded time as to any other. + guard !FileManager.default.fileExists(atPath: marker.url.path), + let previous = DaemonStateFile.read(from: daemonStateFileOverride ?? DaemonStateFile.path()), + let verifiedAt = Self.appAttestVerifiedEvidence(in: previous) else { return } + do { + try marker.record(verifiedAt) + logger.info("App Attest: seeded the verified marker from the previous provider's state") + } catch { + logger.warning("App Attest: cannot seed the verified marker: \(error)") + } + } + + /// The latest time an earlier provider's state shows App Attest working on + /// this Mac: a coordinator App Attest grant (cleared at a disconnect, so + /// often absent after a clean restart), or a stored key that Apple attested, + /// at its last successful Apple attestation or assertion. Nil without a time. + static func appAttestVerifiedEvidence(in state: DaemonState) -> Date? { + var times: [Double] = [] + if let trust = state.trust, let grant = trust.authorization, + grant.hasCurrentAppAttestAuthorization(now: trust.receivedAt) { + times.append(trust.receivedAt) + } + if let status = state.appAttest, status.key?.attested == true, + let age = status.keyHistory?.lastSuccessAgeSeconds, age >= 0 { + let anchor = status.keyHistoryObservedAt ?? status.observedAt + times.append(anchor - Double(age)) + } + return times.filter(\.isFinite).max().map(Date.init(timeIntervalSince1970:)) + } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift index 4a576e1b6c..6f7b6c3f0b 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift @@ -19,6 +19,8 @@ extension ProviderLoop { // MARK: - Main Run Loop public func run() async throws { + // Before this run's first daemon-state write replaces the previous one. + seedAppAttestVerifiedFromPreviousRun() nativePairConfigurationClosed = true if isClusterMember { try prepareClusterMemberControl() } defer { diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift index c7fc11d6ee..dd3728250e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift @@ -537,4 +537,93 @@ struct AppAttestUnsupportedRestartTests { #expect(await loop.appAttestUnsupportedSince == nil) #expect(await loop.appAttestStallMonitorTask == nil) } + + /// The daemon-state shape that v0.10.5 to v0.10.6 and dev builds before the + /// verified marker leave behind: an attested key with its last Apple success. + private func previousRunState(at now: Date, attested: Bool = true, lastSuccessAge: Int? = 600, + grant: ProviderAuthorizationStatus? = nil, grantAt: Date? = nil) -> DaemonState { + let status = AppAttestLocalStatus( + observedAt: now.timeIntervalSince1970 - 30, launchSession: .gui, + key: AppAttestKeyState(recordPresent: true, attested: attested, generationBlockedUntil: nil), + keyHistory: AppAttestKeyHistory(lastSuccessAgeSeconds: lastSuccessAge), + keyHistoryObservedAt: now.timeIntervalSince1970 - 30) + let trust = grant.map { DaemonState.Trust(trustLevel: "self_signed", status: "online", reason: "", + receivedAt: (grantAt ?? now).timeIntervalSince1970, authorization: $0) } + return DaemonState(pid: 1, version: "0.10.6", writtenAt: now.timeIntervalSince1970 - 30, + startedAt: 0, trust: trust, appAttest: status) + } + + @Test func previousRunEvidenceIsAnAttestedKeysLastSuccessOrAGrant() { + let now = wholeSecondsNow() + #expect(ProviderLoop.appAttestVerifiedEvidence(in: previousRunState(at: now)) + == now.addingTimeInterval(-630)) + #expect(ProviderLoop.appAttestVerifiedEvidence(in: previousRunState(at: now, attested: false)) == nil, + "a key Apple never attested is no evidence") + #expect(ProviderLoop.appAttestVerifiedEvidence(in: previousRunState(at: now, lastSuccessAge: nil)) == nil, + "evidence without a time is not used") + // A grant newer than the key's last success wins. + let granted = previousRunState(at: now, lastSuccessAge: 7200, + grant: appAttestGrant(expiresAt: now.timeIntervalSince1970 + 900), grantAt: now.addingTimeInterval(-60)) + #expect(ProviderLoop.appAttestVerifiedEvidence(in: granted) == now.addingTimeInterval(-60)) + // A legacy path or an expired lease is not a grant. + let legacy = previousRunState(at: now, attested: false, + grant: appAttestGrant(expiresAt: now.timeIntervalSince1970 + 900, path: "legacy")) + #expect(ProviderLoop.appAttestVerifiedEvidence(in: legacy) == nil) + let expired = previousRunState(at: now, attested: false, + grant: appAttestGrant(expiresAt: now.timeIntervalSince1970 - 1)) + #expect(ProviderLoop.appAttestVerifiedEvidence(in: expired) == nil) + } + + /// The first episode after an update from a version that never wrote the + /// verified marker: the seed arms the restart; every other guard still holds. + @Test func firstUnsupportedEpisodeAfterAnUpdateFromAnOlderVersionArmsOnce() async throws { + let (loop, root) = try await lifecycleLoop() + defer { try? FileManager.default.removeItem(at: root) } + let install = try UpdateRecoveryFixture() + defer { install.cleanup() } + let restarts = AppAttestRestartLog() + await loop.setAppAttestRestartSeams(route: .launchd, supported: { false }, restarts: restarts, + updater: install.updater(baseURL: URL(string: "http://127.0.0.1:9")!)) + await loop.installIdleAppAttestClient() + let now = wholeSecondsNow() + DaemonStateFile.write(previousRunState(at: now), to: root.appendingPathComponent("state.json")) + let verified = AppAttestVerifiedMarker(directory: root) + #expect(verified.lastVerified() == nil) + + await loop.seedAppAttestVerifiedFromPreviousRun() + #expect(verified.lastVerified() == now.addingTimeInterval(-630)) + + await loop.noteAppAttestAvailability( + unsupportedReady(), now: now.addingTimeInterval(-AppAttestStallRestartPolicy.unsupportedThreshold - 60)) + #expect(await waitFor { restarts.routes.count == 1 }) + #expect(restarts.routes == [.launchd]) + + // Seeded once: the next process does not seed again from older state, + // so the restart does not repeat for the same episode. + DaemonStateFile.write(previousRunState(at: now.addingTimeInterval(60), lastSuccessAge: 0), + to: root.appendingPathComponent("state.json")) + await loop.seedAppAttestVerifiedFromPreviousRun() + #expect(verified.lastVerified() == now.addingTimeInterval(-630), "an existing marker is never overwritten") + await loop.noteAppAttestAvailability(unsupportedReady(), now: now.addingTimeInterval(120)) + #expect(await loop.appAttestUnsupportedSince == nil, "one restart per episode") + await loop.cancelAppAttestStallMonitor() + } + + @Test func seedNeedsEvidenceFromTheLast7Days() async throws { + let (loop, root) = try await lifecycleLoop() + defer { try? FileManager.default.removeItem(at: root) } + await loop.setAppAttestRestartSeams(route: .launchd, supported: false) + let now = wholeSecondsNow() + let old = Int(AppAttestStallRestartPolicy.verifiedWithin) + 3600 + DaemonStateFile.write(previousRunState(at: now, lastSuccessAge: old), to: root.appendingPathComponent("state.json")) + await loop.seedAppAttestVerifiedFromPreviousRun() + await loop.noteAppAttestAvailability(unsupportedReady(), now: now) + #expect(await loop.appAttestUnsupportedSince == nil, "evidence older than 7 days does not arm the restart") + + // No previous state at all: nothing is seeded. + let (fresh, freshRoot) = try await lifecycleLoop() + defer { try? FileManager.default.removeItem(at: freshRoot) } + await fresh.seedAppAttestVerifiedFromPreviousRun() + #expect(!FileManager.default.fileExists(atPath: AppAttestVerifiedMarker(directory: freshRoot).url.path)) + } } From 9a13252544549c6687b5abc49e12b930aedeb470 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 11:29:54 -0600 Subject: [PATCH 0242/1441] refactor(provider): apply the refactor pass to the verified-marker seed Findings from the independent refactor pass on PR 1744: - Seed at serve start, before the schedule wait. A scheduled provider outside its window rewrites daemon-state.json every 250 ms, so a seed inside ProviderLoop.run() found nothing. The seed is now a static AppAttestVerifiedMarker.seedFromPreviousRun, called once in the start command after the run marker. - Do not write evidence older than 7 days, so a later fresher one can still seed. - Move the evidence rule to DaemonState.appAttestVerifiedAt. - Tests: a file in the v0.10.6 shape decodes and seeds; a damaged marker is not replaced; a previous provider that was itself unsupported gives no evidence; an older version's stall restart after the evidence blocks the restart. - Docs: restore the conditions list, state that the seeded time can be an Apple success, and state the case that is not covered. Co-Authored-By: Claude Opus 5.5 --- changelog.d/app-attest-first-episode.md | 3 +- docs/provider/cli-reference.md | 2 +- docs/reference/app-attest-shadow.md | 2 +- .../ProviderLoop+AppAttestStall.swift | 37 ----- .../ProviderCore/ProviderLoop+Serve.swift | 2 - .../Service/AppAttestVerifiedSeed.swift | 44 ++++++ .../darkbloom/Start/StartCommand+Modes.swift | 6 + .../Service/ProviderLifecycleTests.swift | 137 ++++++++++++------ 8 files changed, 147 insertions(+), 86 deletions(-) create mode 100644 provider-swift/Sources/ProviderCore/Service/AppAttestVerifiedSeed.swift diff --git a/changelog.d/app-attest-first-episode.md b/changelog.d/app-attest-first-episode.md index 4bfb4881ac..e1802854a5 100644 --- a/changelog.d/app-attest-first-episode.md +++ b/changelog.d/app-attest-first-episode.md @@ -1,3 +1,4 @@ ### App Attest restart covers the first episode after an update -- The `is_supported_false` restart now also works in the first process after an update from a version that did not record its App Attest authorizations. At start, when `app-attest-verified.json` is missing, the provider fills it once from the previous `daemon-state.json`: the time of an App Attest grant, or the last successful Apple call of a stored key that Apple attested. All other conditions stay the same. +- The `is_supported_false` restart now also works in the first process after an update from a version that did not record its App Attest authorizations. At serve start, when `app-attest-verified.json` is missing, the provider fills it once from the previous `daemon-state.json`, with evidence from the last 7 days: the last successful Apple call of a stored key that Apple attested, or an App Attest grant left by an unclean exit. All other conditions stay the same. +- A Mac whose previous provider was itself reporting `is_supported_false` has no such evidence, so it still waits for the coordinator to grant App Attest again. diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 502bf14b12..c2f9967e5b 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -2203,7 +2203,7 @@ qualification or performance. Sources: | Watchdog state | `~/.darkbloom/watchdog-state.json` (`DARKBLOOM_WATCHDOG_STATE`) | `provider-swift/Sources/ProviderCore/Service/WatchdogState.swift` | | KV-backend crash-loop guard | `~/.darkbloom/kv-backend-guard.json` (`DARKBLOOM_KV_BACKEND_GUARD`) | `provider-swift/Sources/ProviderCore/Service/KVBackendGuard.swift` | | App Attest stall restart marker | `app-attest-stall-restart.json` beside the daemon state file, `0600`; time of the last automatic App Attest restart, for a stalled DeviceCheck call or for `is_supported_false` ([limits](../reference/app-attest-shadow.md#bounds-and-credential-lifecycle)) | `provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift` (`AppAttestStallRestartMarker`) | -| App Attest verified marker | `app-attest-verified.json` beside the daemon state file, `0600`; time of the last coordinator App Attest authorization, rewritten at most once per hour. When it is missing at start, it is seeded once from the previous daemon state (an App Attest grant, or the last Apple success of an attested key). It only allows the `is_supported_false` restart; it never authorizes serving | `provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift` (`AppAttestVerifiedMarker`) | +| App Attest verified marker | `app-attest-verified.json` beside the daemon state file, `0600`; time of the last coordinator App Attest authorization, rewritten at most once per hour. When it is missing at serve start, it is seeded once from the previous daemon state (the last Apple success of an attested key, or an App Attest grant left by an unclean exit), with evidence from the last 7 days. It only allows the `is_supported_false` restart; it never authorizes serving | `provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift` (`AppAttestVerifiedMarker`) | | Provider run marker | `provider-run.json` beside the daemon state file, `0600`. Set to `running` when a serve process starts and to `clean` (with cause) after its drain or before an update/stall relaunch. Explicit update/stall relaunch causes survive later generic termination callbacks; a failed hand-off restores running state and clears the cause. The next process derives `previous_exit` and `start_reason` from it | `provider-swift/Sources/ProviderCore/Service/ProviderRunMarker.swift`, `ProviderProcessRun.swift` | | APNs push history | `apns-push-history.json` beside the daemon state file, `0600`. The last 50 code-identity push receipt times and reply times, plus whether a device token was present. No token, nonce or payload | `provider-swift/Sources/ProviderCore/Apns/APNsPushHistory.swift` | | Provider LaunchAgent | label `io.darkbloom.provider`; `~/Library/LaunchAgents/io.darkbloom.provider.plist`; `RunAtLoad = true`, `KeepAlive = false`; stdout/stderr → `~/.darkbloom/provider.log` | `provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift` (`label`, `plistPath`, `logPath`) | diff --git a/docs/reference/app-attest-shadow.md b/docs/reference/app-attest-shadow.md index 9565b74ab2..5f969d15c1 100644 --- a/docs/reference/app-attest-shadow.md +++ b/docs/reference/app-attest-shadow.md @@ -127,7 +127,7 @@ provider-local Apple callback, retry, key-budget and socket fences remain separa | Session recovery | Generic or server-unavailable Apple API failures retry after one minute, then five minutes, then at most the normal ten-minute assertion interval. Other transient coordinator/storage failures retain the one-minute, five-minute, then hourly backoff. Every attempt gets a new session/nonce and reloads durable acceptance/counters. Successful assertions reset backoff. An Apple API error is an unknown prospective verdict and grants no permission; verified crypto/policy rejections remain terminal, and cancellation stops retries. Persistent generic errors still need native domain/code diagnostics from a signed upgraded client. [Dead-key rotation](#dead-key-rotation) and the [invalid-key enrollment backoff](#invalid-key-enrollment-backoff) replace this delay in their specific cases. Code: [coordinator/internal/appattest/recovery/recovery_policy.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/internal/appattest/recovery/recovery_policy.go) (`ExchangeRetryDelay`), [coordinator/internal/appattest/recovery/driver.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/internal/appattest/recovery/driver.go) (`Driver.Run`); session wiring in [coordinator/appattest/service/retry.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/appattest/service/retry.go) (`run`). | | First-risk-receipt wait | A valid first assertion with no verified risk receipt yet, including an initial `renewal_required` receipt, stays unknown. Without an existing authorization record, a fresh assertion retries after one minute, five minutes, then at the normal ten-minute cadence while Apple's receipt renewal runs independently. Only complete fresh evidence can authorize serving. Code: [coordinator/appattest/service/authorization_identity.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/appattest/service/authorization_identity.go) and `retry.go`. | | Apple callbacks | 25-second waiter deadline. The actual uncancellable Apple operation retains admission until its callback arrives; retries receive `busy` in the meantime. A token fences duplicate late callbacks from unlocking a newer operation. A pre-cancelled call does not acquire admission. The gate records when it was acquired: once held longer than `AppleOperationStall.threshold` (15 min), `ready` replies return `busy` with `operation_stalled_seconds`, and the provider restarts itself through the background-update path (update lease, drain, `waitForSafeDisconnect`, `ProcessLifecycle.restartAfterUpdate`) only when no inference is in flight or loading and no update or lifecycle drain is running, at most once per `AppAttestStallRestartPolicy.minimumInterval` (6 h, persisted in `app-attest-stall-restart.json` beside the daemon state file before the restart is issued). An attempt that drains but cannot restart reopens serving and waits before draining again in the same process: `AppAttestStallRestartPolicy.drainRetryDelay` (15 min) when accepted work or the coordinator's drain acknowledgement did not finish in time, and a full `minimumInterval` when the marker cannot be written, since no restart may be issued without it. After the drain, and after its last suspension point, it checks again (`AppAttestStallRestartPolicy.afterDrain`): if Apple's callback released the gate, or a CLI stop, OS termination or scheduled shutdown took over the drain, it releases the update lease without restarting, and a lifecycle-owned drain stays closed. Code: `AppleOperationGate.swift`, `AppleAppAttestService.swift`, `AppleOperationStall.swift` and `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | -| `isSupported` false after verification | When a `ready` answers `is_supported_false` (macOS 27 or later), the provider restarts once through launchd if all of these hold: the coordinator granted this Mac an App Attest authorization within `AppAttestStallRestartPolicy.verifiedWithin` (7 days) and after the last automatic App Attest restart (the time is kept in `app-attest-verified.json` beside the daemon state file, rewritten at most once per hour), so one unsupported episode gets one restart. A version that never wrote that file leaves it missing after an update; the provider then seeds it once, before its first daemon-state write, from the previous `daemon-state.json`: the time of an App Attest grant, or the last successful Apple call of a stored key that Apple attested (`ProviderLoop.appAttestVerifiedEvidence`); the embedded provisioning profile has not expired; this is not a cluster member; and launchd runs this provider (`ProcessLifecycle.RelaunchRoute`: launchd's record of the loaded provider job names this exact process, which an in-place exec keeps). The live `DCAppAttestService.isSupported` must stay false for `AppAttestStallRestartPolicy.unsupportedThreshold` (5 min) and again after the drain. The restart uses the stall restart's monitor, idle checks, drain, `app-attest-stall-restart.json` limit (one automatic App Attest restart per 6 h, for both causes) and `start_reason` `stall_restart`. It never uses an in-place exec. Code: `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | +| `isSupported` false after verification | When a `ready` answers `is_supported_false` (macOS 27 or later), the provider restarts once through launchd if all of these hold: the coordinator granted this Mac an App Attest authorization within `AppAttestStallRestartPolicy.verifiedWithin` (7 days) and after the last automatic App Attest restart (the time is kept in `app-attest-verified.json` beside the daemon state file, rewritten at most once per hour), so one unsupported episode gets one restart; the embedded provisioning profile has not expired; this is not a cluster member; and launchd runs this provider (`ProcessLifecycle.RelaunchRoute`: launchd's record of the loaded provider job names this exact process, which an in-place exec keeps). The live `DCAppAttestService.isSupported` must stay false for `AppAttestStallRestartPolicy.unsupportedThreshold` (5 min) and again after the drain. The restart uses the stall restart's monitor, idle checks, drain, `app-attest-stall-restart.json` limit (one automatic App Attest restart per 6 h, for both causes) and `start_reason` `stall_restart`. It never uses an in-place exec. A version that never wrote `app-attest-verified.json` leaves it missing after an update. At serve start, before the provider writes its own daemon state, it then seeds the file once from the previous `daemon-state.json`, with evidence from the last 7 days: the last successful Apple attestation or assertion of a stored key that Apple attested, or (only after an unclean exit) the time of an App Attest grant. So the seeded time can be an Apple success, not a coordinator grant. A previous provider that was itself answering `is_supported_false` published no key, so nothing is seeded and that Mac does not restart until the coordinator grants App Attest again (`DaemonState.appAttestVerifiedAt`, `AppAttestVerifiedMarker.seedFromPreviousRun` in `provider-swift/Sources/ProviderCore/Service/AppAttestVerifiedSeed.swift`). Code: `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | | Coordinator-driven rotation (client side) | An `attest` for a key this client already attested, with no cached proof, clears the key ID and replies `key_unregistered` without calling Apple. The next `prepare` generates a replacement within the per-key one-hour cooldown and the shared five-per-hour generation budget. Released 0.9.8 and 0.9.9 clients behave the same way. Code: `provider-swift/Sources/ProviderAppAttest/AppAttestShadowClient.swift`; pinned by `provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift`. | | Attestation retries | At most three attempts, 2/8-second waits, only for service unavailable. `ShadowEnrollmentAttempt` persists the original key/hash, status, session and timestamp across later coordinator retries and reconnects (the provider serves protocol 3 only; an attempt recorded under an earlier protocol is retired), as [Apple requires](https://developer.apple.com/documentation/devicecheck/dcerror-swift.struct/code/serverunavailable). Successful recovery uses the original stored server transaction; a subsequent serving assertion always signs fresh status/challenge/endpoint. Expired or malformed retry state retires under existing generation limits. | | Failed one-time enrollment | Non-service-unavailable Apple failures retire the enrollment key identifier under the existing generation limits. The app persists `attestationStartedAt` before calling Apple; an interrupted attempt without a saved proof is retired on the next prepare. Cached successful proofs remain recoverable. Generic assertion failures do not make the client rotate an accepted key on its own; an explicit invalid-key response can retire it, and the coordinator can request [dead-key rotation](#dead-key-rotation). Code: `provider-swift/Sources/ProviderAppAttest/EnrollmentKeyLifecycle.swift` and `AppAttestShadowClient.swift`. | diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift index 460a2d2d83..debb7dcce9 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift @@ -267,41 +267,4 @@ extension ProviderLoop { logger.warning("App Attest: cannot persist the verified marker: \(error)") } } - - /// A version before `AppAttestVerifiedMarker` never wrote it, so the first - /// `is_supported_false` after an update from it would not restart. Seed the - /// marker once, while it is missing, from what that version left in - /// `daemon-state.json`. Runs before this process writes its own state. - internal func seedAppAttestVerifiedFromPreviousRun() { - let marker = appAttestVerifiedMarker() - // The usual eligibility rules (7 days, after the last restart) apply - // to the seeded time as to any other. - guard !FileManager.default.fileExists(atPath: marker.url.path), - let previous = DaemonStateFile.read(from: daemonStateFileOverride ?? DaemonStateFile.path()), - let verifiedAt = Self.appAttestVerifiedEvidence(in: previous) else { return } - do { - try marker.record(verifiedAt) - logger.info("App Attest: seeded the verified marker from the previous provider's state") - } catch { - logger.warning("App Attest: cannot seed the verified marker: \(error)") - } - } - - /// The latest time an earlier provider's state shows App Attest working on - /// this Mac: a coordinator App Attest grant (cleared at a disconnect, so - /// often absent after a clean restart), or a stored key that Apple attested, - /// at its last successful Apple attestation or assertion. Nil without a time. - static func appAttestVerifiedEvidence(in state: DaemonState) -> Date? { - var times: [Double] = [] - if let trust = state.trust, let grant = trust.authorization, - grant.hasCurrentAppAttestAuthorization(now: trust.receivedAt) { - times.append(trust.receivedAt) - } - if let status = state.appAttest, status.key?.attested == true, - let age = status.keyHistory?.lastSuccessAgeSeconds, age >= 0 { - let anchor = status.keyHistoryObservedAt ?? status.observedAt - times.append(anchor - Double(age)) - } - return times.filter(\.isFinite).max().map(Date.init(timeIntervalSince1970:)) - } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift index 6f7b6c3f0b..4a576e1b6c 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift @@ -19,8 +19,6 @@ extension ProviderLoop { // MARK: - Main Run Loop public func run() async throws { - // Before this run's first daemon-state write replaces the previous one. - seedAppAttestVerifiedFromPreviousRun() nativePairConfigurationClosed = true if isClusterMember { try prepareClusterMemberControl() } defer { diff --git a/provider-swift/Sources/ProviderCore/Service/AppAttestVerifiedSeed.swift b/provider-swift/Sources/ProviderCore/Service/AppAttestVerifiedSeed.swift new file mode 100644 index 0000000000..db8e827391 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Service/AppAttestVerifiedSeed.swift @@ -0,0 +1,44 @@ +import Foundation +import ProviderAppAttest + +extension DaemonState { + /// The latest time this state shows App Attest working on this Mac, or nil + /// without a time: + /// - a stored key that Apple attested, at its last successful Apple + /// attestation or assertion (proof that `isSupported` was true then); + /// - a coordinator App Attest grant. The provider clears it at every + /// disconnect, so it is present only after an unclean exit. + /// A provider that was itself answering `is_supported_false` publishes no + /// key, so its state gives nil. + var appAttestVerifiedAt: Date? { + var times: [Double] = [] + if let trust, let grant = trust.authorization, grant.hasCurrentAppAttestAuthorization(now: trust.receivedAt) { + times.append(trust.receivedAt) + } + if let status = appAttest, status.key?.attested == true, + let age = status.keyHistory?.lastSuccessAgeSeconds, age >= 0 { + times.append((status.keyHistoryObservedAt ?? status.observedAt) - Double(age)) + } + return times.filter(\.isFinite).max().map(Date.init(timeIntervalSince1970:)) + } +} + +extension AppAttestVerifiedMarker { + /// A version before this marker never wrote it, so the first + /// `is_supported_false` after an update from it could not restart. While + /// the marker is missing, seed it from the previous `daemon-state.json`. + /// Call before this process writes its own daemon state (the serve start + /// does, before the schedule wait). An existing marker, even a damaged + /// one, is never replaced; evidence older than + /// `AppAttestStallRestartPolicy.verifiedWithin` is not written. Returns the + /// seeded time. + @discardableResult + public static func seedFromPreviousRun(stateFile: URL = DaemonStateFile.path(), now: Date = Date()) -> Date? { + let marker = AppAttestVerifiedMarker(directory: stateFile.deletingLastPathComponent()) + guard !FileManager.default.fileExists(atPath: marker.url.path), + let verifiedAt = DaemonStateFile.read(from: stateFile)?.appAttestVerifiedAt, + abs(now.timeIntervalSince(verifiedAt)) < AppAttestStallRestartPolicy.verifiedWithin, + (try? marker.record(verifiedAt)) != nil else { return nil } + return verifiedAt + } +} diff --git a/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift b/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift index 999345d36d..4ce2b729b4 100644 --- a/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift +++ b/provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift @@ -2,6 +2,7 @@ // optional unified local endpoint), startup auto-update, and scheduled windows. import Foundation import ArgumentParser +import ProviderAppAttest import ProviderCore #if canImport(Darwin) import Darwin @@ -206,6 +207,11 @@ extension Start { // (previous_exit / start_reason) before any in-place update exec. ProviderProcessRun.begin() ProviderProcessRun.logAppAttestEntitlementEvidence(context: "startup") + // Before this process writes its own daemon state, including the + // writes of a schedule wait. + if AppAttestVerifiedMarker.seedFromPreviousRun() != nil { + print("App Attest: seeded the verified marker from the previous provider's state") + } let selectedIDs = Set(selectedModels.map(\.id)) let autopilot = config.backend.modelAutopilot diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift index dd3728250e..d3f2675676 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift @@ -537,46 +537,107 @@ struct AppAttestUnsupportedRestartTests { #expect(await loop.appAttestUnsupportedSince == nil) #expect(await loop.appAttestStallMonitorTask == nil) } +} - /// The daemon-state shape that v0.10.5 to v0.10.6 and dev builds before the - /// verified marker leave behind: an attested key with its last Apple success. +/// The first `is_supported_false` episode after an update from a version that +/// never wrote `app-attest-verified.json`. +@Suite("App Attest verified marker seed") +struct AppAttestVerifiedSeedTests { + /// The shape the serving provider writes, through today's encoder. private func previousRunState(at now: Date, attested: Bool = true, lastSuccessAge: Int? = 600, + unsupported: Bool = false, grant: ProviderAuthorizationStatus? = nil, grantAt: Date? = nil) -> DaemonState { - let status = AppAttestLocalStatus( - observedAt: now.timeIntervalSince1970 - 30, launchSession: .gui, - key: AppAttestKeyState(recordPresent: true, attested: attested, generationBlockedUntil: nil), - keyHistory: AppAttestKeyHistory(lastSuccessAgeSeconds: lastSuccessAge), - keyHistoryObservedAt: now.timeIntervalSince1970 - 30) + let status = unsupported + ? AppAttestLocalStatus(observedAt: now.timeIntervalSince1970 - 30, launchSession: .gui, + availabilityReason: .isSupportedFalse) + : AppAttestLocalStatus( + observedAt: now.timeIntervalSince1970 - 30, launchSession: .gui, + key: AppAttestKeyState(recordPresent: true, attested: attested, generationBlockedUntil: nil), + keyHistory: AppAttestKeyHistory(lastSuccessAgeSeconds: lastSuccessAge), + keyHistoryObservedAt: now.timeIntervalSince1970 - 30) let trust = grant.map { DaemonState.Trust(trustLevel: "self_signed", status: "online", reason: "", receivedAt: (grantAt ?? now).timeIntervalSince1970, authorization: $0) } return DaemonState(pid: 1, version: "0.10.6", writtenAt: now.timeIntervalSince1970 - 30, startedAt: 0, trust: trust, appAttest: status) } - @Test func previousRunEvidenceIsAnAttestedKeysLastSuccessOrAGrant() { + private func stateDirectory() throws -> URL { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + return root + } + + @Test func evidenceIsAnAttestedKeysLastSuccessOrAGrant() { let now = wholeSecondsNow() - #expect(ProviderLoop.appAttestVerifiedEvidence(in: previousRunState(at: now)) - == now.addingTimeInterval(-630)) - #expect(ProviderLoop.appAttestVerifiedEvidence(in: previousRunState(at: now, attested: false)) == nil, + #expect(previousRunState(at: now).appAttestVerifiedAt == now.addingTimeInterval(-630)) + #expect(previousRunState(at: now, attested: false).appAttestVerifiedAt == nil, "a key Apple never attested is no evidence") - #expect(ProviderLoop.appAttestVerifiedEvidence(in: previousRunState(at: now, lastSuccessAge: nil)) == nil, + #expect(previousRunState(at: now, lastSuccessAge: nil).appAttestVerifiedAt == nil, "evidence without a time is not used") - // A grant newer than the key's last success wins. + // The previous process was itself unsupported: it published no key. + #expect(previousRunState(at: now, unsupported: true).appAttestVerifiedAt == nil) + // A grant (left only by an unclean exit) newer than the key's last success wins. let granted = previousRunState(at: now, lastSuccessAge: 7200, grant: appAttestGrant(expiresAt: now.timeIntervalSince1970 + 900), grantAt: now.addingTimeInterval(-60)) - #expect(ProviderLoop.appAttestVerifiedEvidence(in: granted) == now.addingTimeInterval(-60)) - // A legacy path or an expired lease is not a grant. + #expect(granted.appAttestVerifiedAt == now.addingTimeInterval(-60)) let legacy = previousRunState(at: now, attested: false, grant: appAttestGrant(expiresAt: now.timeIntervalSince1970 + 900, path: "legacy")) - #expect(ProviderLoop.appAttestVerifiedEvidence(in: legacy) == nil) + #expect(legacy.appAttestVerifiedAt == nil) let expired = previousRunState(at: now, attested: false, grant: appAttestGrant(expiresAt: now.timeIntervalSince1970 - 1)) - #expect(ProviderLoop.appAttestVerifiedEvidence(in: expired) == nil) + #expect(expired.appAttestVerifiedAt == nil) } - /// The first episode after an update from a version that never wrote the - /// verified marker: the seed arms the restart; every other guard still holds. - @Test func firstUnsupportedEpisodeAfterAnUpdateFromAnOlderVersionArmsOnce() async throws { + /// A file as v0.10.6 writes it (snake_case keys, its field set), not one + /// from today's encoder: a future required field would break the seed. + @Test func aDaemonStateWrittenByV0106Seeds() throws { + let root = try stateDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let now = 1_793_700_000.0 + let json = """ + {"schema":1,"pid":4242,"version":"0.10.6","written_at":\(now),"started_at":\(now - 3600), + "warm_models":[],"inference_active":false, + "stats":{"requests_served":3,"tokens_generated":40,"usage_gaps":0}, + "app_attest":{"observed_at":\(now - 20),"launch_session":"gui","boot_time":1789441846, + "key":{"record_present":true,"attested":true}, + "key_history":{"generations_last_24h":0,"last_success_age_seconds":120,"key_age_seconds":86400}, + "key_history_observed_at":\(now - 20)}} + """ + let stateFile = root.appendingPathComponent("daemon-state.json") + try Data(json.utf8).write(to: stateFile) + let seeded = AppAttestVerifiedMarker.seedFromPreviousRun(stateFile: stateFile, now: Date(timeIntervalSince1970: now)) + #expect(seeded == Date(timeIntervalSince1970: now - 140)) + #expect(AppAttestVerifiedMarker(directory: root).lastVerified() == Date(timeIntervalSince1970: now - 140)) + } + + @Test func seedWritesOnlyAMissingMarkerWithRecentEvidence() throws { + let root = try stateDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let stateFile = root.appendingPathComponent("state.json") + let marker = AppAttestVerifiedMarker(directory: root) + let now = wholeSecondsNow() + + // No previous state, or evidence older than 7 days: nothing is written, + // so fresher evidence can still seed later. + #expect(AppAttestVerifiedMarker.seedFromPreviousRun(stateFile: stateFile, now: now) == nil) + let old = Int(AppAttestStallRestartPolicy.verifiedWithin) + 3600 + DaemonStateFile.write(previousRunState(at: now, lastSuccessAge: old), to: stateFile) + #expect(AppAttestVerifiedMarker.seedFromPreviousRun(stateFile: stateFile, now: now) == nil) + #expect(!FileManager.default.fileExists(atPath: marker.url.path)) + + DaemonStateFile.write(previousRunState(at: now), to: stateFile) + #expect(AppAttestVerifiedMarker.seedFromPreviousRun(stateFile: stateFile, now: now) == now.addingTimeInterval(-630)) + // Seeded once: newer evidence never replaces an existing marker, even a damaged one. + DaemonStateFile.write(previousRunState(at: now.addingTimeInterval(60), lastSuccessAge: 0), to: stateFile) + #expect(AppAttestVerifiedMarker.seedFromPreviousRun(stateFile: stateFile, now: now) == nil) + #expect(marker.lastVerified() == now.addingTimeInterval(-630)) + try Data("not json".utf8).write(to: marker.url) + #expect(AppAttestVerifiedMarker.seedFromPreviousRun(stateFile: stateFile, now: now) == nil) + #expect(marker.lastVerified() == nil, "a damaged marker is no evidence and is not replaced") + } + + /// The seed arms the restart on the first episode; every other guard holds. + @Test func firstUnsupportedEpisodeAfterAnUpdateFromAnOlderVersionRestartsOnce() async throws { let (loop, root) = try await lifecycleLoop() defer { try? FileManager.default.removeItem(at: root) } let install = try UpdateRecoveryFixture() @@ -586,44 +647,32 @@ struct AppAttestUnsupportedRestartTests { updater: install.updater(baseURL: URL(string: "http://127.0.0.1:9")!)) await loop.installIdleAppAttestClient() let now = wholeSecondsNow() - DaemonStateFile.write(previousRunState(at: now), to: root.appendingPathComponent("state.json")) - let verified = AppAttestVerifiedMarker(directory: root) - #expect(verified.lastVerified() == nil) - - await loop.seedAppAttestVerifiedFromPreviousRun() - #expect(verified.lastVerified() == now.addingTimeInterval(-630)) + let stateFile = root.appendingPathComponent("state.json") + DaemonStateFile.write(previousRunState(at: now), to: stateFile) + #expect(AppAttestVerifiedMarker.seedFromPreviousRun(stateFile: stateFile, now: now) != nil) await loop.noteAppAttestAvailability( unsupportedReady(), now: now.addingTimeInterval(-AppAttestStallRestartPolicy.unsupportedThreshold - 60)) #expect(await waitFor { restarts.routes.count == 1 }) #expect(restarts.routes == [.launchd]) - - // Seeded once: the next process does not seed again from older state, - // so the restart does not repeat for the same episode. - DaemonStateFile.write(previousRunState(at: now.addingTimeInterval(60), lastSuccessAge: 0), - to: root.appendingPathComponent("state.json")) - await loop.seedAppAttestVerifiedFromPreviousRun() - #expect(verified.lastVerified() == now.addingTimeInterval(-630), "an existing marker is never overwritten") + // The same episode in the next process: the seeded time is older than + // the restart, so it does not restart again. await loop.noteAppAttestAvailability(unsupportedReady(), now: now.addingTimeInterval(120)) #expect(await loop.appAttestUnsupportedSince == nil, "one restart per episode") await loop.cancelAppAttestStallMonitor() } - @Test func seedNeedsEvidenceFromTheLast7Days() async throws { + /// An older version's stall restart after the seeded evidence also counts. + @Test func aStallRestartByTheOlderVersionAfterTheEvidenceBlocksTheRestart() async throws { let (loop, root) = try await lifecycleLoop() defer { try? FileManager.default.removeItem(at: root) } await loop.setAppAttestRestartSeams(route: .launchd, supported: false) let now = wholeSecondsNow() - let old = Int(AppAttestStallRestartPolicy.verifiedWithin) + 3600 - DaemonStateFile.write(previousRunState(at: now, lastSuccessAge: old), to: root.appendingPathComponent("state.json")) - await loop.seedAppAttestVerifiedFromPreviousRun() + let stateFile = root.appendingPathComponent("state.json") + DaemonStateFile.write(previousRunState(at: now), to: stateFile) + try AppAttestStallRestartMarker(directory: root).record(now.addingTimeInterval(-60)) + #expect(AppAttestVerifiedMarker.seedFromPreviousRun(stateFile: stateFile, now: now) != nil) await loop.noteAppAttestAvailability(unsupportedReady(), now: now) - #expect(await loop.appAttestUnsupportedSince == nil, "evidence older than 7 days does not arm the restart") - - // No previous state at all: nothing is seeded. - let (fresh, freshRoot) = try await lifecycleLoop() - defer { try? FileManager.default.removeItem(at: freshRoot) } - await fresh.seedAppAttestVerifiedFromPreviousRun() - #expect(!FileManager.default.fileExists(atPath: AppAttestVerifiedMarker(directory: freshRoot).url.path)) + #expect(await loop.appAttestUnsupportedSince == nil) } } From 3aa8535f6b9565e2453f6ee5f0e5f87329d254e6 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 11:52:52 -0600 Subject: [PATCH 0243/1441] Document the record lock wait for cluster stop Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 2 ++ docs/reference/configuration.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index e88b79d945..e711344eae 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -6096,6 +6096,8 @@ A live service acknowledges planned local stop only through a fresh private supe A local-only optional `ClusterSetupRecord.stopDrain` token is written atomically with serving=false. During that token’s lifetime, controlTick and final sendLease derive both remote running and serving from the same record, preserving the prior peer intent while the local supervisor drains. A matching stop-token supervision cycle may clear it only after no local child/leftover and no outbound lease remains in flight. New leases then reread stopped intent. Handover and background serve/stop synchronization wait; background mutation also holds command custody and rereads current intent. Normal wire fields and lease deadlines are unchanged. +The supervision cycle that clears the token also publishes `service-status.json` with `child.running = false`, and it writes that file first. A `darkbloom cluster stop` that starts at that moment (for example, a retry after a local timeout) can meet the service's record write. The stop's record write waits up to 2 seconds for the record lock, so it does not fail with "could not save the stop request". The service makes its write while it holds the service lock, so it tries the record lock once and tries again on its next cycle. + ### Qwen27 capacity changes preserve request arithmetic The authenticated Qwen3.8 27B tensor-parallel owner uses CBv2 request-owned attention and recurrent history at capacity one and at wider capacities. A singleton adapter keeps the existing one-token worker credit while executing the same native batch driver; its completion is constructed only after both ranks confirm retirement. Native metadata quotations charge the full singleton CBv2 state, workspace, collectives and prefix allowance, including the selected assistant policy. Within that charge a paged lane's pages are reserved as the request grows ([native context](#qwen27-tensor-parallel-native-context)). Other model families and unkeyed singleton probes retain their existing execution paths. See `QwenTensorParallelBatchSettings`, `QwenTensorParallelResidentRuntime+Singleton.swift`, `QwenTensorParallelBatchBudget` and `ClusterPlacementTensorBatchBudget` under `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/`. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index fa2ca6bfeb..decc97075d 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1658,3 +1658,5 @@ Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/C `provider-swift/Sources/darkbloom/ClusterServiceCommand.swift` (`Cluster.Stop`). The wizard’s optional local stopDrain token is saved with stopped intent and retained after a local timeout. Leases preserve the peer’s prior intent until the local supervisor retires its owned part and outstanding lease. The token is not a wire or user-facing configuration field; older records decode without it. A new serve is refused while it remains, and a model change retries the shared stop first. + +Every write of the wizard's record (`~/.darkbloom/cluster-setup/wizard.json`) takes the `wizard.json.lock` flock. When another writer holds that lock, the write waits up to 2 seconds for it (`ClusterSetupStore.recordLockWaitSeconds`). After 2 seconds the write fails with "Configuration or native device lease is currently held". The cluster service writes the record while it holds its own service lock, so it tries once and writes again on its next supervision cycle. Source: `provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift` (`ClusterSetupStore.updateRecord`). From 01df994b9c659204cce5ce4f99ff6cfefc2da19a Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 12:10:58 -0600 Subject: [PATCH 0244/1441] Repin libs/mlx-swift-lm to SDK main 36047ddb SDK main 36047ddbf245923bc3fe63f1fd5e7067a312b085 (merge of SDK #380 on top of #379). Co-Authored-By: Claude Opus 5.5 --- libs/mlx-swift-lm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index e97b657508..36047ddbf2 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit e97b6575080c6fefed27fdd34d196b1e5b3f98a3 +Subproject commit 36047ddbf245923bc3fe63f1fd5e7067a312b085 From 66d70935d36bfcd4df1b9ee6c481b676580babee Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 12:11:23 -0600 Subject: [PATCH 0245/1441] Repin libs/mlx-swift-lm to SDK main 36047ddb SDK main 36047ddbf245923bc3fe63f1fd5e7067a312b085 (merge of SDK #380 on top of #379). Tree equal to the old pin 22b3a8a7 (SDK #380's head). Co-Authored-By: Claude Opus 5.5 --- libs/mlx-swift-lm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 22b3a8a7a3..36047ddbf2 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 22b3a8a7a30e53ba2fdaa8274eb7967f570936d5 +Subproject commit 36047ddbf245923bc3fe63f1fd5e7067a312b085 From 0d7fbf55a9613acef72ff4ff2b0aba464aba216a Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 10:54:14 -0800 Subject: [PATCH 0246/1441] fix(cluster): plan tensor parallel with the serial prefill schedule its runtimes admit A two-Mac Gemma 4 or MiMo pair that the planner placed in tensor parallel did not start: - The planner gave every candidate the one-chunk lookahead whenever the model lists it, tensor parallel included, and setup saved that schedule. - Every tensor-parallel runtime (GLM, Gemma 4, MiMo, Qwen) admits only `serial_v1`, so the Gemma and MiMo runtimes refused the saved plan at load. A pipeline plan of the same pair would have served. - Qwen escaped only because the provider forces a serial policy on its tensor-parallel paths. The fastest-plan evidence rule (#1715) made the case rarer, but did not remove it. The fix: - `ClusterPrefillSchedule.planned(for:supported:)` is the one rule. Tensor parallel prefills serially; a layer split takes the lookahead where the model has it, as before. - The planner's candidates use it, and so does the served-speed history, so a tensor-parallel pair's own measurements match the plans they inform. - A policy that allows no serial schedule no longer gets a tensor-parallel candidate. Tested: - `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh` passes, including two new checks: - a Gemma plan in tensor parallel is serial while its pipeline keeps the lookahead; - the rule holds for every mode. With the old schedule line, the new Gemma check and the two-M4-Pro tensor-parallel plans fail. - `provider-swift/Tests/ClusterPlacementChecks/run.sh` passes 237. `TensorParallelPlanChecks` passes. `make docs-check` and `make docs-impact-check BASE=origin/dev` pass. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 6 ++++++ .../ClusterPlacementPlanner.swift | 16 +++++++++------- .../ClusterServedSpeed.swift | 3 ++- .../ClusterPrefillSchedule.swift | 9 +++++++++ .../Tests/PlacementChecks/AutoChoiceChecks.swift | 2 +- .../GemmaTensorParallelChecks.swift | 9 ++++++++- .../Tests/PlacementChecks/PlannerChecks.swift | 6 ++++++ 7 files changed, 41 insertions(+), 10 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index a5e20c9798..34b6dae8ed 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4323,6 +4323,12 @@ vocabulary rows, so each end counts as divided. The family also states its routing, 8 of 128 experts (`expertRouting`, `isRoutedExpert`), so the hardware prior reads 2,424,219,708 weight bytes per QAT 4-bit token. +**Prefill schedule.** A tensor-parallel candidate prefills serially +(`ClusterPrefillSchedule.planned`): every tensor-parallel runtime, Gemma's and +MiMo's included, admits only `serial_v1`, while a pipeline of the same model +takes the one-chunk lookahead. Planned with the lookahead, a Gemma or MiMo pair +in tensor parallel saved a setup its runtime refused at load (2026-11-03). + **The fastest-plan rule.** `ClusterTensorParallelChoice.fastest` exempts a family from `ClusterPlacementPolicy.tensorParallelFirst`: its tensor-parallel candidate is ranked by the planner's own comparison, which chooses it only when diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift index 91a9780c9c..a0407fcea5 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift @@ -748,10 +748,12 @@ public enum ClusterPlacementPlanner { var result: [ClusterPlacementCandidate] = [] let most = min(policy.maximumRanges, devices.count) guard most >= 2 else { return [] } - // A lookahead prefill is never slower than a serial one of the same placement. - let schedule = schedules.contains(.oneChunkLookahead) ? ClusterPrefillSchedule.oneChunkLookahead : schedules[0] + // A layer split prefills with the lookahead where the model has it; tensor parallel prefills serially. + let schedule = ClusterPrefillSchedule.planned(for: .pipeline, supported: schedules) + let tensorSchedule = ClusterPrefillSchedule.planned(for: .tensorParallel, supported: schedules) for ranges in 2...most { - let tensor = scope == .admitted && modes.contains(.tensorParallel) && placeable(.tensorParallel, ranges: ranges) + let tensor = scope == .admitted && modes.contains(.tensorParallel) && schedules.contains(tensorSchedule) + && placeable(.tensorParallel, ranges: ranges) let layerModes = modes.filter { !($0.usesTensorParallelPrefill) && placeable($0, ranges: ranges) } let pipeline = !layerModes.isEmpty && available.count >= ranges - 1 guard tensor || pipeline else { continue } @@ -770,10 +772,10 @@ public enum ClusterPlacementPlanner { if tensor { var splits: [ClusterPlacementCandidate] = [] if let weights = policy.requiredTensorShares { - splits.append(evaluate(order: order, cuts: [], mode: .tensorParallel, schedule: schedule, weights: weights)) - } else { splits.append(bestTensorShares(order: order, schedule: schedule)) } + splits.append(evaluate(order: order, cuts: [], mode: .tensorParallel, schedule: tensorSchedule, weights: weights)) + } else { splits.append(bestTensorShares(order: order, schedule: tensorSchedule)) } for weights in shares { - splits.append(evaluate(order: order, cuts: [], mode: .tensorParallel, schedule: schedule, weights: weights)) + splits.append(evaluate(order: order, cuts: [], mode: .tensorParallel, schedule: tensorSchedule, weights: weights)) } result += keepingWidenable(splits) } @@ -1235,7 +1237,7 @@ public enum ClusterPlacementPlanner { /// (`first`) or from its end, whatever is freed on it; 0 for none. A /// range's need only grows with its length, so the first failure ends it. func extent(_ device: ClusterPlacementDevice, first: Bool) -> Int { - let schedule = schedules.contains(.oneChunkLookahead) ? ClusterPrefillSchedule.oneChunkLookahead : schedules[0] + let schedule = ClusterPrefillSchedule.planned(for: .pipeline, supported: schedules) var most = 0 for count in 1.. ClusterPrefillSchedule { + if mode.usesTensorParallelPrefill { return .serial } + return supported.contains(.oneChunkLookahead) ? .oneChunkLookahead : supported.first ?? .serial + } } diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/AutoChoiceChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/AutoChoiceChecks.swift index 5117444a67..9641e68a22 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/AutoChoiceChecks.swift +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/AutoChoiceChecks.swift @@ -175,7 +175,7 @@ private func checkServedReplacesPrior(_ layout: ClusterModelLayout, _ checks: Pl NewMac(gib: 128, chip: "Apple M4 Max", decodeIndex: 21_100, prefillIndex: 520_000), layout: layout), layout: layout, link: link) var p = policy(prompt: 128, outputs: 128) let predicted = try ClusterPlacementPlanner.evaluate(devices: devices, cuts: [], mode: .tensorParallel, - prefillSchedule: layout.prefillSchedules.contains(.oneChunkLookahead) ? .oneChunkLookahead : .serial, + prefillSchedule: ClusterPrefillSchedule.planned(for: .tensorParallel, supported: layout.prefillSchedules), layout: layout, policy: p, link: link) let slower = predicted.rested.decodeTokensPerSecond * 0.6 let samples = (0..<3).map { _ in ClusterServedSample(route: .pair, member: nil, promptTokens: 128, outputTokens: 128, diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift index f56091bdc2..f5283a8c92 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift @@ -205,13 +205,20 @@ private func checkGemmaFastestPlan(_ layout: ClusterModelLayout, _ checks: Place policy: first(8_192, 128), link: .unmeasured) checks.require("Gemma fastest plan: without its choice the same layout, Macs and policy put tensor parallel first", ruled.chosen?.mode == .tensorParallel) + // Tensor parallel prefills serially, the only schedule a tensor-parallel runtime admits; the pipeline keeps the + // lookahead (2026-11-03: a Gemma or MiMo pair planned in tensor parallel was saved with the lookahead and refused at load). + let piped = try plan(ultras, first(8_192, 128), .unmeasured) + checks.require("Gemma: a plan in tensor parallel prefills serially, a pipeline with the lookahead", + ruled.chosen?.prefillSchedule == .serial && piped.chosen?.mode == .pipeline && piped.chosen?.prefillSchedule == .oneChunkLookahead + && layout.prefillSchedules.contains(.oneChunkLookahead)) // 2. Two small Macs (24 and 32 GB M4 Pro), default link costs: tensor parallel where the plan predicts it faster. for gib in [24.0, 32.0] { let small = try pros(gib) let decodeHeavy = try plan(small, first(128, 128), .unmeasured), times = predicted(decodeHeavy) checks.require("Gemma fastest plan: 2x M4 Pro \(Int(gib)) GB, default link costs, 128 + 128: tensor parallel, predicted faster by the margin (\(times.tensor) s vs \(times.other) s)", - tensor(decodeHeavy) && times.tensor < times.other * 0.95 && decodeHeavy.chosen?.ranks.allSatisfy({ $0.fit == .now }) == true) + tensor(decodeHeavy) && times.tensor < times.other * 0.95 && decodeHeavy.chosen?.ranks.allSatisfy({ $0.fit == .now }) == true + && decodeHeavy.chosen?.prefillSchedule == .serial) checks.require("Gemma fastest plan: 2x M4 Pro \(Int(gib)) GB, default link costs, 8,192 + 128: a pipeline (the prompt's sums dominate)", pipeline(try plan(small, first(8_192, 128), .unmeasured))) } diff --git a/libs/darkbloom-cluster/Tests/PlacementChecks/PlannerChecks.swift b/libs/darkbloom-cluster/Tests/PlacementChecks/PlannerChecks.swift index 245197c372..b4e9f23238 100644 --- a/libs/darkbloom-cluster/Tests/PlacementChecks/PlannerChecks.swift +++ b/libs/darkbloom-cluster/Tests/PlacementChecks/PlannerChecks.swift @@ -183,6 +183,12 @@ func checkRegisteredLayouts(_ inputs: RetainedQwenInputs, _ checks: PlacementChe checks.require("both list every generation mode the runtime executes (tensor parallel, not the hybrid) and both prefill schedules", nine.generationModes == executed && big.generationModes == executed && nine.prefillSchedules == [.serial, .oneChunkLookahead]) + let both: [ClusterPrefillSchedule] = [.serial, .oneChunkLookahead] + checks.require("prefill schedule: tensor parallel prefills serially; every layer split takes the lookahead the model has", + ClusterPrefillSchedule.planned(for: .tensorParallel, supported: both) == .serial + && ClusterGenerationMode.allCases.filter { !$0.usesTensorParallelPrefill } + .allSatisfy { ClusterPrefillSchedule.planned(for: $0, supported: both) == .oneChunkLookahead } + && ClusterPrefillSchedule.planned(for: .pipeline, supported: [.serial]) == .serial) // Stage sizes recorded by verified loads of the 27B (active bytes loaded). func loadedGiB(_ layout: ClusterModelLayout, _ range: Range) -> Double { Double(layout.range(range).loadedBytes) / Double(gib) } for (cut, first, last) in [(12, 3.059, 11.035), (16, 3.857, 10.238), (20, 4.654, 9.440)] { From 80f1ce9406fefc80aec6335b0d2ecc7ade51f3f8 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 13:35:22 -0600 Subject: [PATCH 0247/1441] ci: retry every transfer error in the MiMo audio fixture download `curl --retry 3` does not retry a reset connection (error 56) or a cut transfer, and the 1.87 GB codec download failed CI twice on 2026-11-03 after the Swift tests passed (runs 41683109822 and 41698550049). The download now retries all errors 5 times, 5 s apart, and ends a stalled attempt (under 100 KB/s for 60 s) so the next one starts. The size and SHA-256 check is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/developer/test.md | 4 +++- scripts/prepare-mimo-audio-fixtures.py | 7 ++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/developer/test.md b/docs/developer/test.md index eebdaa0b84..63c46f8068 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -540,7 +540,9 @@ platform parity. Ordinary fixtures use symmetric 128-context geometry; the separate complete-prefix process uses `--asymmetric` for K64/V128 and 1,024-context geometry. `scripts/prepare-mimo-audio-fixtures.py` prepares hash-pinned public inputs -including the genuine audio codec. Keep these output directories isolated from +including the genuine audio codec. It downloads only what its cache directory +lacks, retries every transfer error, ends a stalled attempt after 60 s below +100 KB/s, and keeps a file only when its size and SHA-256 match. Keep these output directories isolated from the ordinary regression inputs. Audio gates exercise PCM8 and AAC-video with a small target, not full-model quality or peak memory. Release-only builds do not provision test fixtures or opt into native qualification. diff --git a/scripts/prepare-mimo-audio-fixtures.py b/scripts/prepare-mimo-audio-fixtures.py index b84605b72b..7afaf183d6 100644 --- a/scripts/prepare-mimo-audio-fixtures.py +++ b/scripts/prepare-mimo-audio-fixtures.py @@ -54,8 +54,13 @@ def fetch(item): temporary = path.with_name(path.name + ".download") if temporary.is_symlink(): raise ValueError("unexpected download symlink") + # Retry every transfer error too (a reset connection, error 56, or a + # cut transfer is not a transient error to plain `--retry`), and + # end a stalled attempt so the next one starts. The digest check + # below still decides. subprocess.run(["curl", "--fail", "--silent", "--show-error", "--location", - "--retry", "3", "--max-time", "900", + "--retry", "5", "--retry-all-errors", "--retry-delay", "5", + "--speed-limit", "102400", "--speed-time", "60", "--max-time", "900", (VIDEO_URL if relative == "openrouter-aac.mp4" else BASE_URL + "/" + relative), "--output", str(temporary)], check=True) if not verify(temporary, size, digest): raise ValueError("MiMo audio fixture digest mismatch: " + relative) From 07daca6cde6f67fb93ee83013b8464b3318dde81 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 13:36:31 -0600 Subject: [PATCH 0248/1441] ci: refactor pass: bound the retries at 30 min; plain doc wording Co-Authored-By: Claude Opus 5.5 --- docs/developer/test.md | 7 ++++--- scripts/prepare-mimo-audio-fixtures.py | 8 ++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/developer/test.md b/docs/developer/test.md index 63c46f8068..dcc952d5aa 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -540,9 +540,10 @@ platform parity. Ordinary fixtures use symmetric 128-context geometry; the separate complete-prefix process uses `--asymmetric` for K64/V128 and 1,024-context geometry. `scripts/prepare-mimo-audio-fixtures.py` prepares hash-pinned public inputs -including the genuine audio codec. It downloads only what its cache directory -lacks, retries every transfer error, ends a stalled attempt after 60 s below -100 KB/s, and keeps a file only when its size and SHA-256 match. Keep these output directories isolated from +including the genuine audio codec. The script downloads only the files that its +cache directory lacks. It retries a failed download up to 5 times and ends an +attempt that stays below 100 KB/s for 60 s. It keeps a file only when the size +and SHA-256 match. Keep these output directories isolated from the ordinary regression inputs. Audio gates exercise PCM8 and AAC-video with a small target, not full-model quality or peak memory. Release-only builds do not provision test fixtures or opt into native qualification. diff --git a/scripts/prepare-mimo-audio-fixtures.py b/scripts/prepare-mimo-audio-fixtures.py index 7afaf183d6..caa3a96fd1 100644 --- a/scripts/prepare-mimo-audio-fixtures.py +++ b/scripts/prepare-mimo-audio-fixtures.py @@ -55,11 +55,11 @@ def fetch(item): if temporary.is_symlink(): raise ValueError("unexpected download symlink") # Retry every transfer error too (a reset connection, error 56, or a - # cut transfer is not a transient error to plain `--retry`), and - # end a stalled attempt so the next one starts. The digest check - # below still decides. + # cut transfer is not a transient error to plain `--retry`), end a + # stalled attempt so the next one starts, and start no retry after + # 30 min. The digest check below still decides. subprocess.run(["curl", "--fail", "--silent", "--show-error", "--location", - "--retry", "5", "--retry-all-errors", "--retry-delay", "5", + "--retry", "5", "--retry-all-errors", "--retry-delay", "5", "--retry-max-time", "1800", "--speed-limit", "102400", "--speed-time", "60", "--max-time", "900", (VIDEO_URL if relative == "openrouter-aac.mp4" else BASE_URL + "/" + relative), "--output", str(temporary)], check=True) if not verify(temporary, size, digest): From d3789880d07fb89ef5c3b5cc09405bfd062ea27c Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 13:55:21 -0600 Subject: [PATCH 0249/1441] Repin libs/mlx-swift-lm to SDK main 32f5c744 SDK main 32f5c744e2d94f06437040c94d4b14a1cd1bb4dc (merge of SDK #381). Adds only the forwardVerifyWindow guard over the old pin 0d8a4e48; its callers here run on tensor-parallel ranks. Co-Authored-By: Claude Opus 5.5 --- libs/mlx-swift-lm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 0d8a4e4898..32f5c744e2 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 0d8a4e489832ad39e2c75edd9b4844272f4b127e +Subproject commit 32f5c744e2d94f06437040c94d4b14a1cd1bb4dc From 6db1b8ed2ff744dc68c9ea328510500caf25f4a2 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 13:57:57 -0600 Subject: [PATCH 0250/1441] ci: run the cluster jobs only when cluster inputs change; 3 provider shards - New `cluster` component in scripts/ci-component-paths.py: the cluster packages, the MLX pins, the provider's Cluster, Distributed and NativePair sources and tests, the other provider files the cluster runners compile, the cluster plan and the shared build recipe. Every cluster input is also a provider input. A push that runs the provider lanes also runs the cluster jobs. - Cluster Metadata Checks, Cluster Runtime Tests, Cluster GPU Tests and Cluster Focused Checks run when `cluster` is true. The Provider Tests gate accepts a skipped cluster job only when `cluster` is false; a failed or cancelled one still fails it. - Provider Unit Tests: 3 shards instead of 8, balanced with the suite times of dev push run 41692426093 (1070 suites). Planned: 440 s each. The catch-all, the summary audit and coverage are unchanged. - The cluster plan is dev's: the share probe already runs after qwen-tp-batch-gpu in shard 3, and every base suite but the batch-session suite runs in one process. A test now pins both. Mac jobs per run: provider-only pull request 4 (+1 when SDK inputs change), cluster pull request 11 (+1), push 12. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 22 +- .github/workflows/component-changes.yml | 3 + docs/developer/test.md | 14 +- scripts/ci-component-paths.py | 34 +- scripts/provider-test-shard-weights.json | 1297 +++++++++++----------- scripts/test-ci-component-paths.py | 67 +- scripts/test-cluster-test-plan.py | 16 + scripts/test-provider-ci-workflow.py | 6 +- 8 files changed, 794 insertions(+), 665 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5990a173bb..1687c5116a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -144,7 +144,7 @@ jobs: # A failed shard does not cancel the other shards. fail-fast: false matrix: - shard: [1, 2, 3, 4, 5, 6, 7, 8] + shard: [1, 2, 3] steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: @@ -682,7 +682,7 @@ jobs: # no model load, no weights. Every runner runs even after another fails. name: Cluster Metadata Checks needs: changes - if: ${{ needs.changes.outputs.provider == 'true' }} + if: ${{ needs.changes.outputs.cluster == 'true' }} runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 steps: @@ -782,7 +782,7 @@ jobs: # switch, and the switched tests that pass on these runners. name: Cluster Runtime Tests (shard ${{ matrix.shard }}) needs: changes - if: ${{ needs.changes.outputs.provider == 'true' }} + if: ${{ needs.changes.outputs.cluster == 'true' }} runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 strategy: @@ -811,7 +811,7 @@ jobs: # report on every pull request; a failure does not fail the workflow. name: Cluster GPU Tests (non-blocking, shard ${{ matrix.shard }}) needs: changes - if: ${{ needs.changes.outputs.provider == 'true' }} + if: ${{ needs.changes.outputs.cluster == 'true' }} runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 strategy: @@ -840,7 +840,7 @@ jobs: # Cluster Metadata Checks does not run (scripts/cluster-test-plan.py). name: Cluster Focused Checks needs: changes - if: ${{ needs.changes.outputs.provider == 'true' }} + if: ${{ needs.changes.outputs.cluster == 'true' }} runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 steps: @@ -868,6 +868,7 @@ jobs: env: CHANGES_RESULT: ${{ needs.changes.result }} PROVIDER_CHANGED: ${{ needs.changes.outputs.provider }} + CLUSTER_CHANGED: ${{ needs.changes.outputs.cluster }} UNIT_RESULT: ${{ needs.test-provider.result }} SUMMARY_RESULT: ${{ needs.test-provider-summary.result }} CLUSTER_RESULT: ${{ needs.test-cluster.result }} @@ -881,5 +882,12 @@ jobs: esac test "$UNIT_RESULT" = "$expected" test "$SUMMARY_RESULT" = "$expected" - test "$CLUSTER_RESULT" = "$expected" - test "$CLUSTER_FOCUSED_RESULT" = "$expected" + # The cluster jobs run only when their inputs changed (and on + # pushes); a skip passes only when the classifier did not select them. + case "$CLUSTER_CHANGED" in + true) cluster_expected=success ;; + false) cluster_expected=skipped ;; + *) exit 1 ;; + esac + test "$CLUSTER_RESULT" = "$cluster_expected" + test "$CLUSTER_FOCUSED_RESULT" = "$cluster_expected" diff --git a/.github/workflows/component-changes.yml b/.github/workflows/component-changes.yml index b08aa8a116..1d2e566fb8 100644 --- a/.github/workflows/component-changes.yml +++ b/.github/workflows/component-changes.yml @@ -7,6 +7,8 @@ on: value: ${{ jobs.changes.outputs.provider }} sdk: value: ${{ jobs.changes.outputs.sdk }} + cluster: + value: ${{ jobs.changes.outputs.cluster }} permissions: contents: read @@ -20,6 +22,7 @@ jobs: outputs: provider: ${{ steps.paths.outputs.provider }} sdk: ${{ steps.paths.outputs.sdk }} + cluster: ${{ steps.paths.outputs.cluster }} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: diff --git a/docs/developer/test.md b/docs/developer/test.md index 402e13c991..b75795d532 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -112,7 +112,7 @@ snapshots. Preserve its watchdog, cleanup and state isolation when using a focus selector. Use `scripts/run-nested-suite.sh` for documented nested Swift Testing cases and `scripts/run-exclusive-native-gpu-test.sh` for exclusive native work. -CI runs the provider suite in eight shards (`Provider Unit Tests (shard K)`), one +CI runs the provider suite in three shards (`Provider Unit Tests (shard K)`), one Mac each. `PROVIDER_TEST_SHARD=K/N` selects a shard in `scripts/run-provider-tests.sh`, and `scripts/provider-test-shards.py` chooses its suites: @@ -1213,6 +1213,18 @@ what changed. The worker package's tests (built for macOS 26.2) need the GPU and exclusive device access. A loopback or fixture pass never counts as a two-Mac hardware pass. +The cluster jobs (Cluster Metadata Checks, Cluster Runtime Tests, Cluster GPU +Tests and Cluster Focused Checks) run when the classifier selects `cluster` +(`CLUSTER` in `scripts/ci-component-paths.py`): the cluster packages, the MLX +pins, the provider's Cluster, Distributed and NativePair sources and tests, the +other provider files the cluster runners compile, the cluster plan and the +shared build recipe. A push that runs the provider lanes also runs them. The +`Provider Tests` gate accepts a skipped cluster job only when `cluster` was not +selected. A provider-only pull request runs 5 Macs (3 provider shards, the +summary and the SDK lane when its inputs change; 4 without it); a cluster pull +request adds 7 (metadata checks, 3 runtime shards, 2 GPU shards, focused +checks). + CI runs the runtime test target (`DarkbloomClusterRuntimeTests`) on the provider's Blacksmith macOS runners, in selections that `scripts/cluster-test-plan.py` defines. Each selection runs in a process of its diff --git a/scripts/ci-component-paths.py b/scripts/ci-component-paths.py index f73b1cf9e2..afa1b729ec 100644 --- a/scripts/ci-component-paths.py +++ b/scripts/ci-component-paths.py @@ -10,7 +10,7 @@ import subprocess -COMPONENTS = ("provider", "sdk") +COMPONENTS = ("provider", "sdk", "cluster") COMMON = ( "Makefile", "mise.toml", ".gitmodules", ".github/workflows/component-changes.yml", ".github/workflows/darkbloom-route.yml", @@ -52,6 +52,34 @@ ) +# Inputs of the cluster jobs (Cluster Metadata Checks, Cluster Runtime Tests, +# Cluster GPU Tests, Cluster Focused Checks): the cluster packages and the MLX +# pins they build, the provider sources their runner scripts compile (every +# Cluster, Distributed and NativePair source, and the files the runners name), +# the cluster plan and the shared build recipe. Every cluster input is also a +# provider input. A push that selects the provider lanes also selects these. +CLUSTER = ( + "libs/darkbloom-cluster/**", "libs/darkbloom-cluster-worker/**", + "libs/mlx", "libs/mlx/**", "libs/mlx-swift", "libs/mlx-swift/**", "libs/mlx-swift-lm", "libs/mlx-swift-lm/**", + "provider-swift/Package.swift", "provider-swift/Package.resolved", + "provider-swift/Sources/*Cluster*", "provider-swift/Sources/*Distributed*", + "provider-swift/Sources/*NativePair*", + "provider-swift/Sources/ProviderCore/Protocol/ProviderExecutionRole.swift", + "provider-swift/Sources/ProviderCore/Config/ProviderConfigFile.swift", + "provider-swift/Sources/ProviderCore/Models/StreamingFileDownloadDelegate.swift", + "provider-swift/Sources/ProviderCoreFoundation/Manifest.swift", + "provider-swift/Tests/*Cluster*", "provider-swift/Tests/*cluster*", "provider-swift/Tests/*Distributed*", + ".github/workflows/ci.yml", ".github/actions/provider-ci-build/**", + "scripts/provider-ci-cache.py", "scripts/provider_ci_cache/**", + "scripts/provider-release-cache.py", "scripts/provider_release_cache/**", + "scripts/provider-release-swift.sh", "scripts/prepare-provider-release-toolchain.sh", + "scripts/install-release-cmake.sh", "scripts/prepare-metal-toolchain.py", + "scripts/fetch-metallib.sh", "scripts/stage-test-metallib.sh", "scripts/run-nested-suite.sh", + "scripts/cluster-test-plan.py", "scripts/cluster-test-weights.json", + "scripts/cluster-stage-content-inventory.py", +) + + def matches(path, patterns): return any(fnmatchcase(path, pattern) for pattern in patterns) @@ -67,6 +95,7 @@ def classify(paths): return dict.fromkeys(COMPONENTS, True) selected["provider"] |= matches(path, PROVIDER) selected["sdk"] |= matches(path, SDK) + selected["cluster"] |= matches(path, CLUSTER) return selected @@ -112,6 +141,9 @@ def main(): full = paths is None or (args.event_name == "push" and event.get("ref") in ("refs/heads/master", "refs/heads/main")) selected = dict.fromkeys(COMPONENTS, True) if full else classify(paths) + # Pushes keep the cluster jobs wherever they run the provider lanes. + if args.event_name == "push": + selected["cluster"] = selected["cluster"] or selected["provider"] output = "".join(f"{name}={str(enabled).lower()}\n" for name, enabled in selected.items()) if args.output: with open(args.output, "a") as destination: diff --git a/scripts/provider-test-shard-weights.json b/scripts/provider-test-shard-weights.json index 58e70a2918..ff09db7ffe 100644 --- a/scripts/provider-test-shard-weights.json +++ b/scripts/provider-test-shard-weights.json @@ -1,160 +1,164 @@ { -"DarkbloomCLITests.AccountCommandRunTests": 1.556, -"DarkbloomCLITests.AddonCommandTests": 0.014, +"DarkbloomCLITests.AccountCommandRunTests": 1.544, +"DarkbloomCLITests.AddonCommandTests": 0.03, "DarkbloomCLITests.AdvertisedModelSelectionTests": 0.001, -"DarkbloomCLITests.AppAttestQualificationCommandTests": 4.303, -"DarkbloomCLITests.AutoUpdateCommandTests": 0.165, -"DarkbloomCLITests.AutopilotCommandTests": 0.919, -"DarkbloomCLITests.AutopilotDownloadCommandTests": 0.333, -"DarkbloomCLITests.AutopilotInventoryTests": 0.019, -"DarkbloomCLITests.AutopilotReplacementTests": 0.169, -"DarkbloomCLITests.AutopilotStartupSelectionTests": 0.0, -"DarkbloomCLITests.BenchmarkArrivalPromptTests": 0.001, -"DarkbloomCLITests.BenchmarkKVQuantizationOptionsTests": 0.075, -"DarkbloomCLITests.BenchmarkNativeBlockModeTests": 0.037, -"DarkbloomCLITests.BenchmarkParityExitTests": 0.001, -"DarkbloomCLITests.BenchmarkRuntimeGenerationOptionsTests": 0.094, -"DarkbloomCLITests.BenchmarkSchedulerPrefillDecisionTests": 0.07, -"DarkbloomCLITests.BenchmarkSchedulerPrefillPromptTests": 0.081, -"DarkbloomCLITests.BenchmarkSweepExitTests": 0.031, -"DarkbloomCLITests.BenchmarkTeacherForcedOptionsTests": 0.048, -"DarkbloomCLITests.BetaCommandRunTests": 1.634, -"DarkbloomCLITests.BetaCommandTests": 1.121, -"DarkbloomCLITests.BootSecurityWarningTests": 0.014, +"DarkbloomCLITests.AppAttestQualificationCommandTests": 4.21, +"DarkbloomCLITests.AutoUpdateCommandTests": 0.265, +"DarkbloomCLITests.AutopilotCommandTests": 0.751, +"DarkbloomCLITests.AutopilotDownloadCommandTests": 0.255, +"DarkbloomCLITests.AutopilotInventoryTests": 0.013, +"DarkbloomCLITests.AutopilotReplacementTests": 0.165, +"DarkbloomCLITests.AutopilotStartupSelectionTests": 0.001, +"DarkbloomCLITests.BenchmarkArrivalPromptTests": 0.0, +"DarkbloomCLITests.BenchmarkKVQuantizationOptionsTests": 0.074, +"DarkbloomCLITests.BenchmarkNativeBlockModeTests": 0.029, +"DarkbloomCLITests.BenchmarkParityExitTests": 0.0, +"DarkbloomCLITests.BenchmarkRuntimeGenerationOptionsTests": 0.103, +"DarkbloomCLITests.BenchmarkSchedulerPrefillDecisionTests": 0.067, +"DarkbloomCLITests.BenchmarkSchedulerPrefillPromptTests": 0.085, +"DarkbloomCLITests.BenchmarkSweepExitTests": 0.029, +"DarkbloomCLITests.BenchmarkTeacherForcedOptionsTests": 0.055, +"DarkbloomCLITests.BetaCommandRunTests": 1.567, +"DarkbloomCLITests.BetaCommandTests": 1.004, +"DarkbloomCLITests.BootSecurityWarningTests": 0.012, "DarkbloomCLITests.CLIDispatchTests": 0.576, -"DarkbloomCLITests.CacheCommandTests": 0.512, -"DarkbloomCLITests.CatalogPickerFlowTests": 0.047, -"DarkbloomCLITests.ClusterCommandTests": 0.014, -"DarkbloomCLITests.ClusterConsoleCommandTests": 0.181, -"DarkbloomCLITests.ClusterMemberSupervisorTests": 10.162, -"DarkbloomCLITests.ClusterRuntimeFactsCommandTests": 0.015, -"DarkbloomCLITests.ClusterServiceLoginAgentTests": 2.552, -"DarkbloomCLITests.ClusterWorkerOwnerCommandTests": 0.019, -"DarkbloomCLITests.DesktopAccountCloudTests": 0.002, -"DarkbloomCLITests.DesktopAccountEarningsTests": 0.007, +"DarkbloomCLITests.CacheCommandTests": 0.416, +"DarkbloomCLITests.CatalogPickerFlowTests": 0.049, +"DarkbloomCLITests.ClusterCommandTests": 0.015, +"DarkbloomCLITests.ClusterConsoleCommandTests": 0.167, +"DarkbloomCLITests.ClusterMemberSupervisorTests": 10.06, +"DarkbloomCLITests.ClusterOnboardingScopeSettingsTests": 0.005, +"DarkbloomCLITests.ClusterRuntimeFactsCommandTests": 0.019, +"DarkbloomCLITests.ClusterServiceLoginAgentTests": 2.575, +"DarkbloomCLITests.ClusterServiceUpdateTests": 22.159, +"DarkbloomCLITests.ClusterWorkerOwnerCommandTests": 0.014, +"DarkbloomCLITests.DesktopAccountCloudTests": 0.003, +"DarkbloomCLITests.DesktopAccountEarningsTests": 0.01, "DarkbloomCLITests.DesktopAccountIdentityTests": 0.001, -"DarkbloomCLITests.DesktopActionArgumentsTests": 0.229, +"DarkbloomCLITests.DesktopActionArgumentsTests": 0.266, "DarkbloomCLITests.DesktopActivityTests": 0.001, -"DarkbloomCLITests.DesktopAutopilotTests": 0.026, -"DarkbloomCLITests.DesktopControlTests": 0.016, +"DarkbloomCLITests.DesktopAutopilotTests": 0.029, +"DarkbloomCLITests.DesktopControlTests": 0.011, "DarkbloomCLITests.DesktopCoolingAuthorizationTests": 0.0, -"DarkbloomCLITests.DesktopCoolingCacheTests": 0.998, -"DarkbloomCLITests.DesktopDownloadProgressTests": 0.0, -"DarkbloomCLITests.DesktopExecutableWatchTests": 0.003, +"DarkbloomCLITests.DesktopCoolingCacheTests": 0.999, +"DarkbloomCLITests.DesktopDownloadProgressTests": 0.002, +"DarkbloomCLITests.DesktopExecutableWatchTests": 0.005, "DarkbloomCLITests.DesktopHTTPErrorTests": 0.002, -"DarkbloomCLITests.DesktopHardwareRouteTests": 0.603, -"DarkbloomCLITests.DesktopMacStatsTests": 0.012, -"DarkbloomCLITests.DesktopRuntimeProfileTests": 1.299, -"DarkbloomCLITests.DesktopServiceTests": 0.005, -"DarkbloomCLITests.DesktopUsageHistoryTests": 0.019, -"DarkbloomCLITests.DesktopWorkerTests": 4.87, +"DarkbloomCLITests.DesktopHardwareRouteTests": 0.632, +"DarkbloomCLITests.DesktopMacStatsTests": 0.005, +"DarkbloomCLITests.DesktopRuntimeProfileTests": 1.319, +"DarkbloomCLITests.DesktopServiceTests": 0.006, +"DarkbloomCLITests.DesktopUsageHistoryTests": 0.016, +"DarkbloomCLITests.DesktopWorkerTests": 4.896, "DarkbloomCLITests.DeviceCheckEvidenceTests": 0.003, -"DarkbloomCLITests.DeviceCheckExtractionBoundsTests": 0.165, -"DarkbloomCLITests.DeviceCheckProcessTests": 0.628, +"DarkbloomCLITests.DeviceCheckExtractionBoundsTests": 0.18, +"DarkbloomCLITests.DeviceCheckProcessTests": 0.636, "DarkbloomCLITests.DiagnosticProbeTests": 0.001, -"DarkbloomCLITests.DistributedStartCommandTests": 0.078, -"DarkbloomCLITests.DistributedStartSessionFactoryTests": 0.012, -"DarkbloomCLITests.DistributedStartSignalLatchTests": 0.016, -"DarkbloomCLITests.DistributedStartSignalsTests": 0.983, +"DarkbloomCLITests.DistributedStartCommandTests": 0.076, +"DarkbloomCLITests.DistributedStartSessionFactoryTests": 0.013, +"DarkbloomCLITests.DistributedStartSignalLatchTests": 0.017, +"DarkbloomCLITests.DistributedStartSignalsTests": 0.988, "DarkbloomCLITests.DoctorAttestationTests": 0.001, -"DarkbloomCLITests.DoctorCaptureTests": 7.384, -"DarkbloomCLITests.DoctorChecksTests": 0.424, +"DarkbloomCLITests.DoctorCaptureTests": 6.084, +"DarkbloomCLITests.DoctorChecksTests": 0.41, "DarkbloomCLITests.DoctorClearBackendGuardFailureTests": 0.003, -"DarkbloomCLITests.DoctorClearBackendGuardTests": 0.003, -"DarkbloomCLITests.DoctorCommandRunTests": 4.69, -"DarkbloomCLITests.DoctorOperatorDiagnosisTests": 6.967, -"DarkbloomCLITests.EnrollCommandTests": 0.003, -"DarkbloomCLITests.FanActivityLeaseTests": 0.026, -"DarkbloomCLITests.FanCommandArgumentTests": 0.032, -"DarkbloomCLITests.FanCommandTests": 0.004, -"DarkbloomCLITests.FanHelperClientTests": 0.005, +"DarkbloomCLITests.DoctorClearBackendGuardTests": 0.004, +"DarkbloomCLITests.DoctorCommandRunTests": 3.667, +"DarkbloomCLITests.DoctorOperatorDiagnosisTests": 6.115, +"DarkbloomCLITests.EnrollCommandTests": 0.001, +"DarkbloomCLITests.FanActivityLeaseTests": 0.024, +"DarkbloomCLITests.FanCommandArgumentTests": 0.013, +"DarkbloomCLITests.FanCommandTests": 0.005, +"DarkbloomCLITests.FanHelperClientTests": 0.003, "DarkbloomCLITests.FanProcessRunnerTests": 1.03, -"DarkbloomCLITests.FanServiceDisableTests": 0.197, -"DarkbloomCLITests.FanServiceEnableTests": 0.321, -"DarkbloomCLITests.FanServiceInstallStepTests": 0.063, +"DarkbloomCLITests.FanServiceDisableTests": 0.2, +"DarkbloomCLITests.FanServiceEnableTests": 0.316, +"DarkbloomCLITests.FanServiceInstallStepTests": 0.058, "DarkbloomCLITests.FanStatusOutputTests": 0.002, "DarkbloomCLITests.GLMWiredLimitAdviceTests": 0.001, -"DarkbloomCLITests.IdleCommandTests": 0.411, -"DarkbloomCLITests.InstallerCoordinatorBindingTests": 0.386, +"DarkbloomCLITests.IdleCommandTests": 0.462, +"DarkbloomCLITests.InstallerCoordinatorBindingTests": 0.459, "DarkbloomCLITests.KVBackendGuardDiagnosticsTests": 0.001, "DarkbloomCLITests.KVBackendPostureTests": 0.003, -"DarkbloomCLITests.LifecycleRecoveryPublicationTests": 0.015, -"DarkbloomCLITests.LifecycleRecoveryRollbackTests": 0.991, -"DarkbloomCLITests.LocalEndpointCommandTests": 0.276, -"DarkbloomCLITests.LocalStartupPreloadGateTests": 0.277, -"DarkbloomCLITests.LogoutCommandTests": 0.095, +"DarkbloomCLITests.LifecycleRecoveryPublicationTests": 0.009, +"DarkbloomCLITests.LifecycleRecoveryRollbackTests": 1.223, +"DarkbloomCLITests.LocalEndpointCommandTests": 0.262, +"DarkbloomCLITests.LocalStartupPreloadGateTests": 0.294, +"DarkbloomCLITests.LogoutCommandTests": 0.161, "DarkbloomCLITests.LogsCommandArgvTests": 0.0, -"DarkbloomCLITests.LogsCommandOptionsTests": 0.007, -"DarkbloomCLITests.MacOSUpgradeNoticeTests": 1.161, -"DarkbloomCLITests.MiMoImageOnboardingCommandTests": 0.017, -"DarkbloomCLITests.ModelPickerInputEndTests": 2.301, -"DarkbloomCLITests.ModelPickerTerminalTests": 0.092, -"DarkbloomCLITests.ModelsCommandRunTests": 3.14, -"DarkbloomCLITests.ModelsLocationCommandTests": 2.867, -"DarkbloomCLITests.PickerCatalogRowTests": 0.003, -"DarkbloomCLITests.PickerDownloadOutputTests": 0.322, +"DarkbloomCLITests.LogsCommandOptionsTests": 0.006, +"DarkbloomCLITests.MacOSUpgradeNoticeTests": 1.238, +"DarkbloomCLITests.MiMoImageOnboardingCommandTests": 0.035, +"DarkbloomCLITests.ModelPickerInputEndTests": 2.348, +"DarkbloomCLITests.ModelPickerTerminalTests": 0.091, +"DarkbloomCLITests.ModelsCommandRunTests": 3.195, +"DarkbloomCLITests.ModelsLocationCommandTests": 3.187, +"DarkbloomCLITests.PickerCatalogRowTests": 0.006, +"DarkbloomCLITests.PickerDownloadOutputTests": 0.335, "DarkbloomCLITests.PickerEntryTests": 0.004, -"DarkbloomCLITests.PickerServingSetBudgetTests": 0.051, +"DarkbloomCLITests.PickerServingSetBudgetTests": 0.058, "DarkbloomCLITests.RegistrationWeightHashTests": 0.012, -"DarkbloomCLITests.ReportAppAttestEvidenceTests": 0.005, -"DarkbloomCLITests.ReportCommandRunTests": 0.597, -"DarkbloomCLITests.ReportCommandTests": 0.002, -"DarkbloomCLITests.ReportConfigPathTests": 0.004, -"DarkbloomCLITests.ReportPayloadTests": 0.022, -"DarkbloomCLITests.RestartCommandTests": 0.004, -"DarkbloomCLITests.RootCommandOutputTests": 0.509, -"DarkbloomCLITests.RuntimeSmokeKVOptionsTests": 0.002, -"DarkbloomCLITests.RuntimeSnapshotConfigTests": 0.334, -"DarkbloomCLITests.SandboxAddonTests": 5.545, -"DarkbloomCLITests.SandboxEligibilityTests": 0.025, -"DarkbloomCLITests.SandboxSetupTests": 2.135, -"DarkbloomCLITests.SandboxStatusTests": 0.01, -"DarkbloomCLITests.ScheduleCommandTests": 1.411, -"DarkbloomCLITests.ScheduledWindowSelectionTests": 0.164, -"DarkbloomCLITests.ScheduledWindowTimingTests": 0.003, -"DarkbloomCLITests.ServiceDrainTests": 0.275, -"DarkbloomCLITests.ServiceDrainWaitTests": 0.815, -"DarkbloomCLITests.StartCommandOptionsTests": 0.086, -"DarkbloomCLITests.StartCommandTests": 0.007, -"DarkbloomCLITests.StartLaunchdGuardTests": 0.784, -"DarkbloomCLITests.StartServingGuardTests": 1.109, -"DarkbloomCLITests.StatusCommandRunTests": 2.659, +"DarkbloomCLITests.ReportAppAttestEvidenceTests": 0.006, +"DarkbloomCLITests.ReportCommandRunTests": 0.613, +"DarkbloomCLITests.ReportCommandTests": 0.003, +"DarkbloomCLITests.ReportConfigPathTests": 0.003, +"DarkbloomCLITests.ReportPayloadTests": 0.019, +"DarkbloomCLITests.RestartCommandTests": 0.003, +"DarkbloomCLITests.RootCommandOutputTests": 0.49, +"DarkbloomCLITests.RuntimeSmokeKVOptionsTests": 0.001, +"DarkbloomCLITests.RuntimeSnapshotConfigTests": 0.388, +"DarkbloomCLITests.SandboxAddonTests": 5.607, +"DarkbloomCLITests.SandboxEligibilityTests": 0.026, +"DarkbloomCLITests.SandboxSetupTests": 3.281, +"DarkbloomCLITests.SandboxStatusTests": 0.011, +"DarkbloomCLITests.ScheduleCommandTests": 1.399, +"DarkbloomCLITests.ScheduledWindowSelectionTests": 0.162, +"DarkbloomCLITests.ScheduledWindowTimingTests": 0.005, +"DarkbloomCLITests.ServiceDrainTests": 0.278, +"DarkbloomCLITests.ServiceDrainWaitTests": 0.794, +"DarkbloomCLITests.StartCommandOptionsTests": 0.104, +"DarkbloomCLITests.StartCommandTests": 0.006, +"DarkbloomCLITests.StartLaunchdGuardTests": 0.793, +"DarkbloomCLITests.StartServingGuardTests": 1.133, +"DarkbloomCLITests.StatusCommandRunTests": 3.227, "DarkbloomCLITests.StatusDaemonHealthLineTests": 0.01, "DarkbloomCLITests.StatusLifecycleDrainLineTests": 0.0, -"DarkbloomCLITests.StatusResidencyTests": 0.979, -"DarkbloomCLITests.SwitchCommandTests": 0.382, -"DarkbloomCLITests.UnenrollChoiceTests": 0.026, -"DarkbloomCLITests.UnenrollKeepServingTests": 0.006, -"DarkbloomCLITests.UpdateCheckCommandTests": 1.07, -"DarkbloomCLITests.WatchdogCommandTests": 0.012, -"DarkbloomCLITests.WatchdogRecordRecoveryOutcomeTests": 0.002, -"DarkbloomCLITests.WatchdogRecoveryOutcomeDetailTests": 0.002, -"DarkbloomCLITests.WatchdogSignalTrapTests": 0.614, -"DarkbloomFanCoreTests.FanControllerTests": 0.626, -"DarkbloomFanCoreTests.FanHardwareTests": 0.248, -"DarkbloomFanCoreTests.FanPolicyTests": 0.193, -"DarkbloomFanCoreTests.SMCCodecTests": 0.178, -"DarkbloomFanHelperTests.FanDaemonTests": 0.272, -"DarkbloomFanHelperTests.FanStartupDiscoveryTests": 0.387, -"DarkbloomFanServiceTests.FanServiceTests": 0.288, -"DarkbloomHardwareLoadTests.CPUTopologyResolverTests": 0.221, -"DarkbloomHardwareLoadTests.CounterLivenessTests": 0.084, -"DarkbloomHardwareLoadTests.HardwareLoadMonitorTests": 0.926, -"DarkbloomHardwareLoadTests.IOReportMathTests": 0.249, -"DarkbloomHardwareLoadTests.LiveHardwareTests": 1.21, -"DarkbloomHardwareLoadTests.ProviderGPUShareTests": 0.152, -"DarkbloomHardwareLoadTests.ReaderParsingTests": 0.226, +"DarkbloomCLITests.StatusResidencyTests": 0.976, +"DarkbloomCLITests.SwitchCommandTests": 0.387, +"DarkbloomCLITests.UnenrollChoiceTests": 0.025, +"DarkbloomCLITests.UnenrollKeepServingTests": 0.009, +"DarkbloomCLITests.UpdateCheckCommandTests": 1.12, +"DarkbloomCLITests.UpdateRollbackCommandTests": 0.691, +"DarkbloomCLITests.UpdateRollbackEndToEndTests": 37.166, +"DarkbloomCLITests.WatchdogCommandTests": 0.014, +"DarkbloomCLITests.WatchdogRecordRecoveryOutcomeTests": 0.001, +"DarkbloomCLITests.WatchdogRecoveryOutcomeDetailTests": 0.004, +"DarkbloomCLITests.WatchdogSignalTrapTests": 0.655, +"DarkbloomFanCoreTests.FanControllerTests": 1.146, +"DarkbloomFanCoreTests.FanHardwareTests": 0.296, +"DarkbloomFanCoreTests.FanPolicyTests": 0.236, +"DarkbloomFanCoreTests.SMCCodecTests": 0.122, +"DarkbloomFanHelperTests.FanDaemonTests": 0.22, +"DarkbloomFanHelperTests.FanStartupDiscoveryTests": 0.33, +"DarkbloomFanServiceTests.FanServiceTests": 0.322, +"DarkbloomHardwareLoadTests.CPUTopologyResolverTests": 0.179, +"DarkbloomHardwareLoadTests.CounterLivenessTests": 0.061, +"DarkbloomHardwareLoadTests.HardwareLoadMonitorTests": 0.916, +"DarkbloomHardwareLoadTests.IOReportMathTests": 0.226, +"DarkbloomHardwareLoadTests.LiveHardwareTests": 1.196, +"DarkbloomHardwareLoadTests.ProviderGPUShareTests": 0.12, +"DarkbloomHardwareLoadTests.ReaderParsingTests": 0.139, "DarkbloomPublishTests.HashCommandTests": 0.014, -"GPTOSSOptimizationTests.CBv2Gemma4ScheduledPrefillTests": 4.162, -"GPTOSSOptimizationTests.CBv2ModelGPTOSSForwardTests": 4.11, -"GPTOSSOptimizationTests.CBv2ModelGemma4ForwardTests": 4.8, -"GPTOSSOptimizationTests.CBv2ModelLayerKindTests": 0.05, -"GPTOSSOptimizationTests.GPTOSSCompiledExpertsTests": 1.655, -"GPTOSSOptimizationTests.GPTOSSGateUpFusionTests": 3.414, -"GPTOSSOptimizationTests.GPTOSSPrefillOutputTests": 12.533, +"GPTOSSOptimizationTests.CBv2Gemma4ScheduledPrefillTests": 4.257, +"GPTOSSOptimizationTests.CBv2ModelGPTOSSForwardTests": 1.597, +"GPTOSSOptimizationTests.CBv2ModelGemma4ForwardTests": 4.885, +"GPTOSSOptimizationTests.CBv2ModelLayerKindTests": 0.052, +"GPTOSSOptimizationTests.GPTOSSCompiledExpertsTests": 3.379, +"GPTOSSOptimizationTests.GPTOSSGateUpFusionTests": 3.628, +"GPTOSSOptimizationTests.GPTOSSPrefillOutputTests": 15.629, "GPTOSSOptimizationTests.GPTOSSRealCheckpointParityTests": 0.0, -"GPTOSSOptimizationTests.IncrementalCheckpointMaterializationTests": 0.033, -"GPTOSSOptimizationTests.QuantizedSwitchLinearConstantCastTests": 1.078, +"GPTOSSOptimizationTests.IncrementalCheckpointMaterializationTests": 0.039, +"GPTOSSOptimizationTests.QuantizedSwitchLinearConstantCastTests": 1.148, "ProviderAppAttestTests.AppAttestEntitlementPolicyTests": 0.003, "ProviderAppAttestTests.AppAttestShadowTests": 0.055, "ProviderAppAttestTests.AppAttestStallRestartPolicyTests": 0.004, @@ -167,12 +171,12 @@ "ProviderAppAttestTests.WorkerProcessTests": 3.88, "ProviderAppAttestTests.WorkerRuntimeDiagnosticsTests": 0.001, "ProviderAppAttestTests.WorkerTransportTests": 0.068, -"ProviderCoreFoundationTests.CacheDirectoryResolutionTests": 0.694, +"ProviderCoreFoundationTests.CacheDirectoryResolutionTests": 0.621, "ProviderCoreFoundationTests.DiffusionGemmaMediaPolicyTests": 0.007, "ProviderCoreFoundationTests.EmptyFileTest": 0.003, "ProviderCoreFoundationTests.EnumerationOrderInvarianceTest": 0.014, -"ProviderCoreFoundationTests.FlintDiscoveryTests": 0.033, -"ProviderCoreFoundationTests.GLM5NextDiscoveryLoadFootprintTests": 1.067, +"ProviderCoreFoundationTests.FlintDiscoveryTests": 0.024, +"ProviderCoreFoundationTests.GLM5NextDiscoveryLoadFootprintTests": 1.052, "ProviderCoreFoundationTests.GoldenVectorTest": 0.003, "ProviderCoreFoundationTests.HarmonySanitizationTests": 0.002, "ProviderCoreFoundationTests.HashAllowlistTests": 0.025, @@ -185,10 +189,10 @@ "ProviderCoreFoundationTests.ModelScannerSnapshotSymlinkTests": 0.033, "ProviderCoreFoundationTests.NemotronSuperDistributionManifestTests": 0.177, "ProviderCoreFoundationTests.NemotronSuperMediaPolicyTests": 0.001, -"ProviderCoreFoundationTests.NemotronTemplateFiltersTests": 0.195, +"ProviderCoreFoundationTests.NemotronTemplateFiltersTests": 0.16, "ProviderCoreFoundationTests.PageCacheTests": 0.066, -"ProviderCoreFoundationTests.PromptContractIdentityTests": 0.196, -"ProviderCoreFoundationTests.PromptRenderDateTests": 0.097, +"ProviderCoreFoundationTests.PromptContractIdentityTests": 0.154, +"ProviderCoreFoundationTests.PromptRenderDateTests": 0.088, "ProviderCoreFoundationTests.Qwen4MediaPolicyTests": 0.011, "ProviderCoreFoundationTests.RoleClassificationTests": 0.0, "ProviderCoreFoundationTests.StaleHashRecomputeTest": 0.013, @@ -198,322 +202,335 @@ "ProviderCoreFoundationTests.WeightHasherConcurrencyTests": 0.112, "ProviderCoreFoundationTests.WeightHasherMemoryTests": 0.07, "ProviderCoreFoundationTests.WeightHasherStreamParityTests": 0.538, -"ProviderCoreTests.APNsPushHistoryTests": 0.027, +"ProviderCoreTests.APNsPushHistoryTests": 0.036, "ProviderCoreTests.AddonHoldDrainOwnershipTests": 0.0, -"ProviderCoreTests.AddonHoldLoopTests": 2.094, -"ProviderCoreTests.AddonHoldServeLoopTests": 1.636, -"ProviderCoreTests.AddonHoldStoreTests": 0.031, -"ProviderCoreTests.AddonIPCServerTests": 1.155, -"ProviderCoreTests.AddonIPCTests": 0.003, -"ProviderCoreTests.AddonPeerPolicyTests": 0.001, -"ProviderCoreTests.AdmissionRateEstimatorTests": 0.006, +"ProviderCoreTests.AddonHoldLoopTests": 2.183, +"ProviderCoreTests.AddonHoldServeLoopTests": 1.424, +"ProviderCoreTests.AddonHoldStoreTests": 0.032, +"ProviderCoreTests.AddonIPCServerTests": 1.15, +"ProviderCoreTests.AddonIPCTests": 0.002, +"ProviderCoreTests.AddonPeerPolicyTests": 0.002, +"ProviderCoreTests.AdmissionRateEstimatorTests": 0.008, "ProviderCoreTests.AdvertisedModelStoreTests": 0.0, "ProviderCoreTests.AppAttestDeepDiagnosisTests": 0.004, -"ProviderCoreTests.AppAttestLocalDiagnosisTests": 0.006, -"ProviderCoreTests.AppAttestProcessProbeTests": 0.432, -"ProviderCoreTests.AppAttestResumeTests": 0.036, -"ProviderCoreTests.AppAttestResumeTransportTests": 1.11, -"ProviderCoreTests.AppAttestShadowReplyTests": 4.484, -"ProviderCoreTests.AppAttestUpdateLifecycleTests": 3.125, -"ProviderCoreTests.ArrivalInvarianceMeasurementTests": 0.554, -"ProviderCoreTests.AttentionMetadataProductionOwnerTests": 5.039, -"ProviderCoreTests.AudioInputRejectionTests": 0.024, -"ProviderCoreTests.AutoUpdateClaimTests": 0.072, -"ProviderCoreTests.AutoUpdateControllerTests": 0.003, -"ProviderCoreTests.AutoUpdateCycleTests": 0.433, +"ProviderCoreTests.AppAttestLocalDiagnosisTests": 0.004, +"ProviderCoreTests.AppAttestProcessProbeTests": 0.469, +"ProviderCoreTests.AppAttestResumeTests": 0.039, +"ProviderCoreTests.AppAttestResumeTransportTests": 0.799, +"ProviderCoreTests.AppAttestShadowReplyTests": 3.924, +"ProviderCoreTests.AppAttestUnsupportedRestartTests": 0.064, +"ProviderCoreTests.AppAttestUpdateLifecycleTests": 2.147, +"ProviderCoreTests.AppAttestVerifiedSeedTests": 0.033, +"ProviderCoreTests.ArrivalInvarianceMeasurementTests": 0.545, +"ProviderCoreTests.AttentionMetadataProductionOwnerTests": 4.961, +"ProviderCoreTests.AudioInputRejectionTests": 0.018, +"ProviderCoreTests.AutoUpdateClaimTests": 0.077, +"ProviderCoreTests.AutoUpdateControllerTests": 0.002, +"ProviderCoreTests.AutoUpdateCycleTests": 0.168, "ProviderCoreTests.AutoUpdateJitterSequencingTests": 0.0, "ProviderCoreTests.AutoUpdateLifecycleOverlapTests": 0.0, -"ProviderCoreTests.AutoUpdateMonitorStartTests": 0.002, -"ProviderCoreTests.AutopilotAdoptionTests": 0.119, +"ProviderCoreTests.AutoUpdateMonitorStartTests": 0.005, +"ProviderCoreTests.AutopilotAdoptionTests": 0.127, "ProviderCoreTests.AutopilotBuildEligibilityTests": 0.001, -"ProviderCoreTests.AutopilotBusyReasonTests": 0.335, -"ProviderCoreTests.AutopilotDownloadLedgerTests": 0.015, +"ProviderCoreTests.AutopilotBusyReasonTests": 0.19, +"ProviderCoreTests.AutopilotDownloadLedgerTests": 0.008, "ProviderCoreTests.AutopilotDownloadPrefetcherTests": 0.001, -"ProviderCoreTests.AutopilotDownloadTests": 1.319, -"ProviderCoreTests.AutopilotInventoryTests": 0.048, +"ProviderCoreTests.AutopilotDownloadTests": 1.132, +"ProviderCoreTests.AutopilotInventoryTests": 0.031, "ProviderCoreTests.AutopilotModelSetTests": 0.001, "ProviderCoreTests.AutopilotModelSwitchOwnershipTests": 0.003, -"ProviderCoreTests.AutopilotPlacementHoldTests": 0.04, +"ProviderCoreTests.AutopilotPlacementHoldTests": 0.081, "ProviderCoreTests.AutopilotSnapshotCodingTests": 0.009, "ProviderCoreTests.AutopilotStartInventoryTests": 0.002, -"ProviderCoreTests.AutopilotStartupPreferencesTests": 0.036, -"ProviderCoreTests.AutopilotStartupTests": 0.02, +"ProviderCoreTests.AutopilotStartupPreferencesTests": 0.032, +"ProviderCoreTests.AutopilotStartupTests": 0.026, "ProviderCoreTests.BackendParityHarnessProbeTests": 0.003, -"ProviderCoreTests.BackendParityReportTests": 0.011, +"ProviderCoreTests.BackendParityReportTests": 0.01, "ProviderCoreTests.BenchmarkCheckpointPartitionTests": 0.0, -"ProviderCoreTests.BenchmarkEntryPointRefusalTests": 0.01, -"ProviderCoreTests.BenchmarkProductionGrantTests": 0.004, -"ProviderCoreTests.BenchmarkProductionInputTests": 0.013, +"ProviderCoreTests.BenchmarkEntryPointRefusalTests": 0.009, +"ProviderCoreTests.BenchmarkProductionGrantTests": 0.003, +"ProviderCoreTests.BenchmarkProductionInputTests": 0.014, "ProviderCoreTests.BenchmarkSessionDonationDemandTests": 0.014, "ProviderCoreTests.BetaFeaturesTests": 0.002, -"ProviderCoreTests.Bonsai9BContextTests": 0.005, +"ProviderCoreTests.Bonsai9BContextTests": 0.004, "ProviderCoreTests.Bonsai9BMTPPolicyTests": 0.003, -"ProviderCoreTests.Bonsai9BRequestPolicyTests": 0.004, -"ProviderCoreTests.BonsaiDemandedShortCheckpointTests": 0.023, +"ProviderCoreTests.Bonsai9BRequestPolicyTests": 0.003, +"ProviderCoreTests.BonsaiDemandedShortCheckpointTests": 0.048, "ProviderCoreTests.BonsaiEncryptedCheckpointLiveTests": 0.0, "ProviderCoreTests.BootSecurityTests": 0.0, +"ProviderCoreTests.BoundedProcessTests": 3.331, "ProviderCoreTests.BuildEnvironmentTests": 0.001, -"ProviderCoreTests.CacheDirectoryPermissionsTests": 0.03, -"ProviderCoreTests.CachePromptParityTests": 0.01, +"ProviderCoreTests.CacheDirectoryPermissionsTests": 0.023, +"ProviderCoreTests.CachePromptParityTests": 0.012, "ProviderCoreTests.CacheSettingsTests": 0.003, -"ProviderCoreTests.CacheStorageEnvironmentTests": 0.005, -"ProviderCoreTests.CacheVolumeTests": 0.021, +"ProviderCoreTests.CacheStorageEnvironmentTests": 0.006, +"ProviderCoreTests.CacheVolumeTests": 0.03, "ProviderCoreTests.CancelledSettlementLifecycleTests": 0.002, -"ProviderCoreTests.ChatRequestExtraFieldsTests": 0.002, -"ProviderCoreTests.ChatTemplateLoopRewritesTests": 5.332, +"ProviderCoreTests.ChatRequestExtraFieldsTests": 0.003, +"ProviderCoreTests.ChatTemplateLoopRewritesTests": 5.586, +"ProviderCoreTests.ChildExitWaitConventionTests": 0.394, "ProviderCoreTests.ChunkBatcherLifecycleTests": 0.003, "ProviderCoreTests.ChunkSenderTests": 0.903, "ProviderCoreTests.ClusterAPIDecorationTests": 0.002, -"ProviderCoreTests.ClusterAPIParityTests": 3.181, +"ProviderCoreTests.ClusterAPIParityTests": 3.159, "ProviderCoreTests.ClusterApprovalAnyNumericsClassTests": 0.002, -"ProviderCoreTests.ClusterApprovalFetchTests": 0.993, -"ProviderCoreTests.ClusterApprovalLifetimeTests": 0.453, -"ProviderCoreTests.ClusterApprovalServiceStartTests": 11.878, -"ProviderCoreTests.ClusterApprovalSyncTests": 5.91, -"ProviderCoreTests.ClusterApprovalWatchTests": 5.82, +"ProviderCoreTests.ClusterApprovalFetchTests": 0.936, +"ProviderCoreTests.ClusterApprovalLifetimeTests": 0.515, +"ProviderCoreTests.ClusterApprovalServiceStartTests": 11.887, +"ProviderCoreTests.ClusterApprovalSyncTests": 5.607, +"ProviderCoreTests.ClusterApprovalTensorAssistantTests": 1.438, +"ProviderCoreTests.ClusterApprovalTensorSharesTests": 1.407, +"ProviderCoreTests.ClusterApprovalWatchTests": 7.854, "ProviderCoreTests.ClusterCacheOwnershipTests": 0.001, "ProviderCoreTests.ClusterChipAgnosticGrantTests": 0.005, -"ProviderCoreTests.ClusterConfigurationTests": 0.005, -"ProviderCoreTests.ClusterDerivedTimeBudgetTests": 0.001, -"ProviderCoreTests.ClusterGLMManifestPinTests": 2.616, -"ProviderCoreTests.ClusterInstalledReferenceTests": 0.011, -"ProviderCoreTests.ClusterLeaderFailoverFinishTests": 1.645, +"ProviderCoreTests.ClusterConfigurationTests": 0.006, +"ProviderCoreTests.ClusterDerivedTimeBudgetTests": 0.002, +"ProviderCoreTests.ClusterGLMManifestPinTests": 2.461, +"ProviderCoreTests.ClusterInstalledReferenceTests": 0.008, +"ProviderCoreTests.ClusterLeaderFailoverFinishTests": 1.618, "ProviderCoreTests.ClusterLinkControlHostTests": 0.005, "ProviderCoreTests.ClusterLocalServingTests": 0.001, -"ProviderCoreTests.ClusterMemberLoopTests": 0.015, -"ProviderCoreTests.ClusterMemberNegotiationTests": 0.969, -"ProviderCoreTests.ClusterMemberRegistrationTests": 10.122, -"ProviderCoreTests.ClusterMemberServeLoopTests": 21.62, -"ProviderCoreTests.ClusterMemberSupervisionTests": 0.002, +"ProviderCoreTests.ClusterMemberLoopTests": 0.017, +"ProviderCoreTests.ClusterMemberNegotiationTests": 1.057, +"ProviderCoreTests.ClusterMemberRegistrationTests": 10.11, +"ProviderCoreTests.ClusterMemberServeLoopTests": 22.235, +"ProviderCoreTests.ClusterMemberSupervisionTests": 0.004, "ProviderCoreTests.ClusterMembershipTests": 0.004, "ProviderCoreTests.ClusterModelApprovalTests": 0.007, -"ProviderCoreTests.ClusterNativeMemberAttachmentTests": 0.028, -"ProviderCoreTests.ClusterObservabilityTests": 0.018, -"ProviderCoreTests.ClusterOnboardingPeerLabelTests": 0.093, -"ProviderCoreTests.ClusterOwnerCommittedBootstrapTests": 1.707, -"ProviderCoreTests.ClusterOwnerServingTests": 0.031, -"ProviderCoreTests.ClusterPairApprovalTests": 0.009, -"ProviderCoreTests.ClusterPairMediaRegistrationTests": 0.001, -"ProviderCoreTests.ClusterPairServingDecisionsTests": 0.006, -"ProviderCoreTests.ClusterPairServingTests": 0.602, +"ProviderCoreTests.ClusterNativeMemberAttachmentTests": 0.027, +"ProviderCoreTests.ClusterObservabilityTests": 0.016, +"ProviderCoreTests.ClusterOnboardingPeerLabelTests": 0.101, +"ProviderCoreTests.ClusterOwnerCommittedBootstrapTests": 1.745, +"ProviderCoreTests.ClusterOwnerServingTests": 0.037, +"ProviderCoreTests.ClusterPairApprovalTests": 0.008, +"ProviderCoreTests.ClusterPairMediaRegistrationTests": 0.002, +"ProviderCoreTests.ClusterPairServingDecisionsTests": 0.003, +"ProviderCoreTests.ClusterPairServingTests": 0.806, "ProviderCoreTests.ClusterPairSlotOwnerLanesTests": 0.0, -"ProviderCoreTests.ClusterPairSlotServeTests": 1.455, -"ProviderCoreTests.ClusterPairSlotTests": 1.41, -"ProviderCoreTests.ClusterPairingProviderTests": 1.516, -"ProviderCoreTests.ClusterPrefixCacheSettingsTests": 0.012, -"ProviderCoreTests.ClusterPrefixSSDKeyMaterialTests": 0.208, -"ProviderCoreTests.ClusterRosterMemberTests": 0.041, -"ProviderCoreTests.ClusterRuntimeApprovalFactsTests": 3.322, -"ProviderCoreTests.ClusterServiceAgentTests": 0.019, -"ProviderCoreTests.ClusterServiceDescriptorTests": 0.895, -"ProviderCoreTests.ClusterServicePowerAssertionTests": 0.005, -"ProviderCoreTests.ClusterServiceRecoveryTests": 7.638, -"ProviderCoreTests.ClusterSetupProbeRequestTests": 0.006, -"ProviderCoreTests.ClusterStatusSpeculationTests": 0.002, -"ProviderCoreTests.ClusterStoreManifestRepairTests": 3.661, +"ProviderCoreTests.ClusterPairSlotServeTests": 1.475, +"ProviderCoreTests.ClusterPairSlotTests": 1.415, +"ProviderCoreTests.ClusterPairUpdateTests": 12.976, +"ProviderCoreTests.ClusterPairingProviderTests": 1.756, +"ProviderCoreTests.ClusterPlacementTensorWidthRegisteredTests": 2.558, +"ProviderCoreTests.ClusterPlacementTensorWidthTests": 0.546, +"ProviderCoreTests.ClusterPrefixCacheSettingsTests": 0.005, +"ProviderCoreTests.ClusterPrefixSSDKeyMaterialTests": 0.217, +"ProviderCoreTests.ClusterRosterMemberTests": 0.044, +"ProviderCoreTests.ClusterRuntimeApprovalFactsTests": 3.886, +"ProviderCoreTests.ClusterServiceAgentTests": 0.016, +"ProviderCoreTests.ClusterServiceDescriptorTests": 0.92, +"ProviderCoreTests.ClusterServicePairingChangeTests": 15.996, +"ProviderCoreTests.ClusterServicePowerAssertionTests": 0.006, +"ProviderCoreTests.ClusterServiceRecoveryTests": 7.84, +"ProviderCoreTests.ClusterSetupProbeRequestTests": 0.003, +"ProviderCoreTests.ClusterStatusSpeculationTests": 0.003, +"ProviderCoreTests.ClusterStoreManifestRepairTests": 3.607, "ProviderCoreTests.ClusterTransferReportsTests": 0.0, -"ProviderCoreTests.CompletePrefixCacheCapabilityTests": 0.001, -"ProviderCoreTests.ConfigValidationTests": 0.006, -"ProviderCoreTests.CoordinatorAdvertiseTests": 0.001, -"ProviderCoreTests.CoordinatorHandshakeDeadlineTests": 3.471, -"ProviderCoreTests.CoordinatorIntegrationTests": 10.106, -"ProviderCoreTests.CoordinatorLifecycleBarrierTests": 0.141, -"ProviderCoreTests.CoordinatorModelSwitchTests": 0.438, +"ProviderCoreTests.CompletePrefixCacheCapabilityTests": 0.0, +"ProviderCoreTests.ConfigValidationTests": 0.009, +"ProviderCoreTests.CoordinatorAdvertiseTests": 0.0, +"ProviderCoreTests.CoordinatorHandshakeDeadlineTests": 3.664, +"ProviderCoreTests.CoordinatorIntegrationTests": 10.207, +"ProviderCoreTests.CoordinatorLifecycleBarrierTests": 0.173, +"ProviderCoreTests.CoordinatorModelSwitchTests": 1.4, "ProviderCoreTests.CoordinatorReconnectPolicyTests": 0.001, "ProviderCoreTests.CoordinatorWireVectorTests": 0.019, "ProviderCoreTests.CrashLoopGuardPredicateTests": 0.0, -"ProviderCoreTests.CrashLoopGuardRecoveryWiringTests": 0.282, -"ProviderCoreTests.CrashLoopGuardTripTests": 0.009, -"ProviderCoreTests.DaemonStateServedCountTests": 0.003, +"ProviderCoreTests.CrashLoopGuardRecoveryWiringTests": 0.162, +"ProviderCoreTests.CrashLoopGuardTripTests": 0.004, +"ProviderCoreTests.DaemonStateServedCountTests": 0.01, "ProviderCoreTests.DarkbloomMDMRemovalTests": 0.002, -"ProviderCoreTests.DeadlineDecisionBridgeTests": 0.016, -"ProviderCoreTests.DeadlineDecisionProfileTests": 0.001, +"ProviderCoreTests.DeadlineDecisionBridgeTests": 0.015, +"ProviderCoreTests.DeadlineDecisionProfileTests": 0.002, "ProviderCoreTests.DecodeBandwidthModelTests": 0.001, -"ProviderCoreTests.DecodeInterleaveDeadlineAdmissionTests": 0.335, +"ProviderCoreTests.DecodeInterleaveDeadlineAdmissionTests": 0.478, "ProviderCoreTests.DesiredModelsForPostureTests": 0.004, -"ProviderCoreTests.DeviceCodeLoginTests": 4.029, -"ProviderCoreTests.DiffusionBenchmarkRouteProbeTests": 0.002, -"ProviderCoreTests.DiffusionBenchmarkTests": 0.001, -"ProviderCoreTests.DiffusionCheckpointEnvelopeTests": 0.089, +"ProviderCoreTests.DeviceCodeLoginTests": 4.161, +"ProviderCoreTests.DiffusionBenchmarkRouteProbeTests": 0.001, +"ProviderCoreTests.DiffusionBenchmarkTests": 0.002, +"ProviderCoreTests.DiffusionCheckpointEnvelopeTests": 0.105, "ProviderCoreTests.DiffusionGemmaBenchmarkRowTests": 0.002, "ProviderCoreTests.DiffusionGemmaConcurrencyLiveTests": 0.001, "ProviderCoreTests.DiffusionGemmaEncryptedHandlerLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaFourCallDiagnosticLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaFourCallFixtureTests": 0.001, "ProviderCoreTests.DiffusionGemmaMediaLiveTests": 0.0, -"ProviderCoreTests.DiffusionGemmaMediaNormalizationTests": 0.044, +"ProviderCoreTests.DiffusionGemmaMediaNormalizationTests": 0.024, "ProviderCoreTests.DiffusionGemmaMediaPrefixLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaNamedToolDiagnosticLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaPrefixLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaPromptParityLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaProtocolLiveTests": 0.0, -"ProviderCoreTests.DiffusionGemmaProviderBridgeTests": 48.52, +"ProviderCoreTests.DiffusionGemmaProviderBridgeTests": 48.273, "ProviderCoreTests.DiffusionGemmaProviderLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaRawCaseLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaReasoningControlTests": 0.002, -"ProviderCoreTests.DiffusionGemmaReasoningEmissionTests": 0.05, +"ProviderCoreTests.DiffusionGemmaReasoningEmissionTests": 0.048, "ProviderCoreTests.DiffusionGemmaStandaloneLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaStopLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaTokenizerParityLiveTests": 0.0, "ProviderCoreTests.DiffusionLongContextLiveTests": 0.0, -"ProviderCoreTests.DiffusionToolResultMediaTests": 0.127, -"ProviderCoreTests.DiffusionVisibleThroughputLiveTests": 0.001, -"ProviderCoreTests.DistributedAutomaticBatchPlannerTests": 0.458, -"ProviderCoreTests.DistributedCBv2CleanStopTests": 0.059, +"ProviderCoreTests.DiffusionToolResultMediaTests": 0.129, +"ProviderCoreTests.DiffusionVisibleThroughputLiveTests": 0.002, +"ProviderCoreTests.DistributedAutomaticBatchPlannerTests": 0.574, +"ProviderCoreTests.DistributedCBv2CancellationDeadlockTests": 0.48, +"ProviderCoreTests.DistributedCBv2CleanStopTests": 0.057, "ProviderCoreTests.DistributedCBv2DeadlineTests": 0.003, -"ProviderCoreTests.DistributedCBv2EngineTests": 0.006, -"ProviderCoreTests.DistributedHTTPCleanStopTests": 1.072, -"ProviderCoreTests.DistributedHTTPCompletionTests": 2.364, -"ProviderCoreTests.DistributedHTTPDeliveryLifecycleTests": 1.83, -"ProviderCoreTests.DistributedHTTPDisconnectTests": 1.631, -"ProviderCoreTests.DistributedHTTPFrameWakeupTests": 0.297, -"ProviderCoreTests.DistributedHTTPOriginTests": 0.235, -"ProviderCoreTests.DistributedHTTPRetirementTests": 0.013, -"ProviderCoreTests.DistributedHTTPTerminalIntegrationTests": 0.937, -"ProviderCoreTests.DistributedHTTPVisibleContentTests": 0.439, -"ProviderCoreTests.DistributedInstalledCancellationTests": 0.001, -"ProviderCoreTests.DistributedInstalledFilesTests": 0.005, -"ProviderCoreTests.DistributedInstalledKVQuantizationTests": 0.007, +"ProviderCoreTests.DistributedCBv2EngineTests": 0.008, +"ProviderCoreTests.DistributedHTTPCleanStopTests": 1.091, +"ProviderCoreTests.DistributedHTTPCompletionTests": 2.334, +"ProviderCoreTests.DistributedHTTPDeliveryLifecycleTests": 1.814, +"ProviderCoreTests.DistributedHTTPDisconnectTests": 1.667, +"ProviderCoreTests.DistributedHTTPFrameWakeupTests": 0.282, +"ProviderCoreTests.DistributedHTTPOriginTests": 0.282, +"ProviderCoreTests.DistributedHTTPRetirementTests": 0.015, +"ProviderCoreTests.DistributedHTTPTerminalIntegrationTests": 0.93, +"ProviderCoreTests.DistributedHTTPVisibleContentTests": 0.451, +"ProviderCoreTests.DistributedInstalledCancellationTests": 0.002, +"ProviderCoreTests.DistributedInstalledFilesTests": 0.002, +"ProviderCoreTests.DistributedInstalledKVQuantizationTests": 0.006, "ProviderCoreTests.DistributedInstalledLanesTests": 0.001, -"ProviderCoreTests.DistributedLogprobAdmissionTests": 0.004, +"ProviderCoreTests.DistributedLogprobAdmissionTests": 0.003, "ProviderCoreTests.DistributedMiMoImageRefusalTests": 0.0, "ProviderCoreTests.DistributedPrefixPartitionTests": 0.003, -"ProviderCoreTests.DistributedQwenMediaHostMemoryTests": 0.003, -"ProviderCoreTests.DistributedQwenMediaIngressTests": 1.252, -"ProviderCoreTests.DistributedQwenMediaLifetimeTests": 0.002, +"ProviderCoreTests.DistributedQwenMediaHostMemoryTests": 0.001, +"ProviderCoreTests.DistributedQwenMediaIngressTests": 1.261, +"ProviderCoreTests.DistributedQwenMediaLifetimeTests": 0.004, "ProviderCoreTests.DistributedRequestObservationSinkTests": 0.007, -"ProviderCoreTests.DistributedRequestObservationTests": 0.004, +"ProviderCoreTests.DistributedRequestObservationTests": 0.008, "ProviderCoreTests.DistributedRequestOriginDeadlineTests": 0.003, "ProviderCoreTests.DistributedRequestQueueTests": 0.0, "ProviderCoreTests.DistributedServingEligibilityTests": 0.004, "ProviderCoreTests.DistributedStopStringScopeTests": 0.002, "ProviderCoreTests.EmbeddedQwen38RuntimeRequirementsTests": 0.0, -"ProviderCoreTests.EngineDeadlineRetirementBridgeTests": 0.009, +"ProviderCoreTests.EngineDeadlineRetirementBridgeTests": 0.011, "ProviderCoreTests.EngineEarlyPerformanceTests": 0.002, -"ProviderCoreTests.EngineMeasurementOrderingTests": 0.159, -"ProviderCoreTests.EnginePerformanceHeartbeatTests": 0.048, -"ProviderCoreTests.EngineProfileCancelTests": 0.01, -"ProviderCoreTests.EngineProfileMappingTests": 0.0, -"ProviderCoreTests.EngineTransferredRetirementWorkTests": 1.554, -"ProviderCoreTests.EngineV2BenchmarkMTPAcceptanceTests": 1.413, -"ProviderCoreTests.EngineV2BenchmarkMTPVerificationTests": 3.601, +"ProviderCoreTests.EngineMeasurementOrderingTests": 0.155, +"ProviderCoreTests.EnginePerformanceHeartbeatTests": 0.046, +"ProviderCoreTests.EngineProfileCancelTests": 0.014, +"ProviderCoreTests.EngineProfileMappingTests": 0.001, +"ProviderCoreTests.EngineTransferredRetirementWorkTests": 1.65, +"ProviderCoreTests.EngineV2BenchmarkMTPAcceptanceTests": 1.401, +"ProviderCoreTests.EngineV2BenchmarkMTPVerificationTests": 0.78, "ProviderCoreTests.EngineV2BridgeCheckpointTargetTests": 0.002, -"ProviderCoreTests.EngineV2BridgeMultimodalTests": 0.005, -"ProviderCoreTests.EngineV2BridgePagedKVTests": 0.004, -"ProviderCoreTests.EngineV2BridgePumpReceiptTests": 0.158, -"ProviderCoreTests.EngineV2CancellationTests": 0.001, -"ProviderCoreTests.EngineV2CapacityTests": 0.011, -"ProviderCoreTests.EngineV2CoResidencyLiveTests": 0.001, -"ProviderCoreTests.EngineV2ContiguousAdmissionTests": 1.592, -"ProviderCoreTests.EngineV2DiffusionMediaChunkBoundTests": 0.004, -"ProviderCoreTests.EngineV2DiffusionPrefixPrecisionTests": 0.062, +"ProviderCoreTests.EngineV2BridgeMultimodalTests": 0.008, +"ProviderCoreTests.EngineV2BridgePagedKVTests": 0.006, +"ProviderCoreTests.EngineV2BridgePumpReceiptTests": 0.438, +"ProviderCoreTests.EngineV2CancellationTests": 0.002, +"ProviderCoreTests.EngineV2CapacityTests": 0.007, +"ProviderCoreTests.EngineV2CoResidencyLiveTests": 0.0, +"ProviderCoreTests.EngineV2ContiguousAdmissionTests": 3.645, +"ProviderCoreTests.EngineV2DiffusionMediaChunkBoundTests": 0.003, +"ProviderCoreTests.EngineV2DiffusionPrefixPrecisionTests": 0.061, "ProviderCoreTests.EngineV2ErrorMappingTests": 0.002, -"ProviderCoreTests.EngineV2EventFramingTests": 0.007, +"ProviderCoreTests.EngineV2EventFramingTests": 0.011, "ProviderCoreTests.EngineV2FP32PagedRateTests": 0.001, -"ProviderCoreTests.EngineV2FailLoudFactoryTests": 0.008, -"ProviderCoreTests.EngineV2FirstTokenDeadlineAdmissionTests": 0.04, -"ProviderCoreTests.EngineV2HardeningTests": 0.001, -"ProviderCoreTests.EngineV2HybridPrefixIdentityTests": 0.184, +"ProviderCoreTests.EngineV2FailLoudFactoryTests": 0.007, +"ProviderCoreTests.EngineV2FirstTokenDeadlineAdmissionTests": 0.045, +"ProviderCoreTests.EngineV2HardeningTests": 0.002, +"ProviderCoreTests.EngineV2HybridPrefixIdentityTests": 0.181, "ProviderCoreTests.EngineV2KVBackendFallbackHeartbeatTests": 0.003, -"ProviderCoreTests.EngineV2KVBackendGateTests": 20.974, +"ProviderCoreTests.EngineV2KVBackendGateTests": 22.214, "ProviderCoreTests.EngineV2KVBackendPolicyTests": 0.003, -"ProviderCoreTests.EngineV2KVQuantizationPolicyTests": 0.001, -"ProviderCoreTests.EngineV2LivenessRecoveryTests": 0.04, +"ProviderCoreTests.EngineV2KVQuantizationPolicyTests": 0.002, +"ProviderCoreTests.EngineV2LivenessRecoveryTests": 0.05, "ProviderCoreTests.EngineV2LivenessVerdictTests": 0.002, -"ProviderCoreTests.EngineV2LogprobsChannelCapTests": 0.003, -"ProviderCoreTests.EngineV2LogprobsPassthroughTests": 0.127, -"ProviderCoreTests.EngineV2LookupReceiptCoverageTests": 0.009, +"ProviderCoreTests.EngineV2LogprobsChannelCapTests": 0.002, +"ProviderCoreTests.EngineV2LogprobsPassthroughTests": 0.114, +"ProviderCoreTests.EngineV2LookupReceiptCoverageTests": 0.014, "ProviderCoreTests.EngineV2MTPAdmissionChargesTests": 0.001, "ProviderCoreTests.EngineV2MTPProductionAdmissionTests": 0.01, -"ProviderCoreTests.EngineV2MatchedStopSequenceTests": 0.002, -"ProviderCoreTests.EngineV2MemoryConcurrencyTests": 0.023, +"ProviderCoreTests.EngineV2MatchedStopSequenceTests": 0.004, +"ProviderCoreTests.EngineV2MemoryConcurrencyTests": 0.38, "ProviderCoreTests.EngineV2NativeBlockTimingTests": 0.0, "ProviderCoreTests.EngineV2PagedParityLiveTests": 0.001, -"ProviderCoreTests.EngineV2PagedPoolDTypeEnvTests": 0.93, -"ProviderCoreTests.EngineV2PrefillGeometryEngineTests": 2.831, -"ProviderCoreTests.EngineV2PrefillGeometryTests": 0.052, -"ProviderCoreTests.EngineV2PrefillSamplingTests": 0.035, -"ProviderCoreTests.EngineV2PrefixCacheUsageTests": 0.004, -"ProviderCoreTests.EngineV2RequestRoutingTests": 0.034, +"ProviderCoreTests.EngineV2PagedPoolDTypeEnvTests": 2.05, +"ProviderCoreTests.EngineV2PrefillGeometryEngineTests": 3.7, +"ProviderCoreTests.EngineV2PrefillGeometryTests": 0.041, +"ProviderCoreTests.EngineV2PrefillSamplingTests": 0.025, +"ProviderCoreTests.EngineV2PrefixCacheUsageTests": 0.003, +"ProviderCoreTests.EngineV2RequestRoutingTests": 0.036, +"ProviderCoreTests.EngineV2ResliceFloorTests": 0.009, +"ProviderCoreTests.EngineV2ResliceFloorWiringTests": 0.047, "ProviderCoreTests.EngineV2ResliceTests": 0.001, -"ProviderCoreTests.EngineV2ResliceUnwindTests": 0.008, -"ProviderCoreTests.EngineV2ReslicingWiringTests": 0.132, -"ProviderCoreTests.EngineV2RuntimeGuardTests": 0.035, +"ProviderCoreTests.EngineV2ResliceUnwindTests": 0.017, +"ProviderCoreTests.EngineV2ReslicingWiringTests": 0.15, +"ProviderCoreTests.EngineV2RuntimeGuardTests": 0.033, "ProviderCoreTests.EngineV2SSDPrefixCacheLiveTests": 0.0, -"ProviderCoreTests.EngineV2SamplingDefaultsTests": 0.004, -"ProviderCoreTests.EngineV2SeededSamplingTests": 0.29, -"ProviderCoreTests.EngineV2ServiceabilityPolicyTests": 0.003, -"ProviderCoreTests.EngineV2ServiceableGrantTests": 1.419, -"ProviderCoreTests.EngineV2ServiceableLoadTests": 0.072, -"ProviderCoreTests.EngineV2SharedBudgetTests": 0.303, -"ProviderCoreTests.EngineV2ShutdownTests": 0.001, -"ProviderCoreTests.EngineV2SlotBuildTests": 0.026, -"ProviderCoreTests.EngineV2SupportedSetGateTests": 0.018, -"ProviderCoreTests.EngineV2TranslationTests": 0.002, +"ProviderCoreTests.EngineV2SamplingDefaultsTests": 0.003, +"ProviderCoreTests.EngineV2SeededSamplingTests": 0.947, +"ProviderCoreTests.EngineV2ServiceabilityPolicyTests": 0.005, +"ProviderCoreTests.EngineV2ServiceableGrantTests": 0.071, +"ProviderCoreTests.EngineV2ServiceableLoadTests": 1.392, +"ProviderCoreTests.EngineV2SharedBudgetTests": 0.282, +"ProviderCoreTests.EngineV2ShutdownTests": 0.0, +"ProviderCoreTests.EngineV2SlotBuildTests": 0.024, +"ProviderCoreTests.EngineV2SupportedSetGateTests": 0.015, +"ProviderCoreTests.EngineV2TranslationTests": 0.003, "ProviderCoreTests.EngineV2VisionMLXFaultTests": 0.001, -"ProviderCoreTests.EngineV2VisionPixelRunTests": 0.005, -"ProviderCoreTests.EngineV2VisionRoutingTests": 0.057, -"ProviderCoreTests.EngineV2VisionSpanCarvingTests": 0.003, -"ProviderCoreTests.EnrollmentTests": 0.023, +"ProviderCoreTests.EngineV2VisionPixelRunTests": 0.002, +"ProviderCoreTests.EngineV2VisionRoutingTests": 0.056, +"ProviderCoreTests.EngineV2VisionSpanCarvingTests": 0.004, +"ProviderCoreTests.EnrollmentTests": 0.026, "ProviderCoreTests.EvalProbeTests": 0.007, -"ProviderCoreTests.FirstContentDeadlineTests": 0.042, +"ProviderCoreTests.FirstContentDeadlineTests": 0.024, "ProviderCoreTests.FlashNextEncryptedHandlerLiveTests": 0.0, "ProviderCoreTests.FlashNextQuietCancellationReloadLiveTests": 0.0, "ProviderCoreTests.FlashNextReclaimDiagnostics": 0.0, -"ProviderCoreTests.FlintAnswerStopServingTests": 0.931, -"ProviderCoreTests.FlintAnswerStopTests": 1.847, -"ProviderCoreTests.FlintContextAdmissionTests": 1.24, +"ProviderCoreTests.FlintAnswerStopServingTests": 0.979, +"ProviderCoreTests.FlintAnswerStopTests": 1.962, +"ProviderCoreTests.FlintContextAdmissionTests": 1.308, "ProviderCoreTests.FlintLiveTests": 0.0, -"ProviderCoreTests.FlintNativeProtocolFactoryTests": 0.862, -"ProviderCoreTests.FlintNativeProtocolTests": 0.509, +"ProviderCoreTests.FlintNativeProtocolFactoryTests": 0.856, +"ProviderCoreTests.FlintNativeProtocolTests": 0.538, "ProviderCoreTests.FlintOpenRouterLiveTests": 0.0, -"ProviderCoreTests.FlintPagedOnlyBackendTests": 0.521, -"ProviderCoreTests.FlintPolicyTests": 0.188, +"ProviderCoreTests.FlintPagedOnlyBackendTests": 0.478, +"ProviderCoreTests.FlintPolicyTests": 0.169, "ProviderCoreTests.FlintR2InstallTests": 0.0, -"ProviderCoreTests.FlintReasoningVisibilityTests": 2.321, +"ProviderCoreTests.FlintReasoningVisibilityTests": 2.382, "ProviderCoreTests.FlintRelayLogprobsLiveTests": 0.0, -"ProviderCoreTests.FlintResponseFormatConstraintTests": 0.338, +"ProviderCoreTests.FlintResponseFormatConstraintTests": 0.362, "ProviderCoreTests.FlintResponseFormatOutputTests": 0.004, -"ProviderCoreTests.FlintResponseFormatPolicyTests": 0.433, -"ProviderCoreTests.FlintTemplateReplayTests": 0.049, -"ProviderCoreTests.FlintToolChoicePromptPolicyTests": 0.018, +"ProviderCoreTests.FlintResponseFormatPolicyTests": 0.429, +"ProviderCoreTests.FlintTemplateReplayTests": 0.054, +"ProviderCoreTests.FlintToolChoicePromptPolicyTests": 0.011, "ProviderCoreTests.FrozenReplayRealModelTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationAuthorizerTests": 0.019, -"ProviderCoreTests.GLM5NextCalibrationBindingWireTests": 0.004, +"ProviderCoreTests.GLM5NextCalibrationBindingWireTests": 0.005, "ProviderCoreTests.GLM5NextCalibrationBootstrapDeadlineTests": 0.0, -"ProviderCoreTests.GLM5NextCalibrationDispatchDigestTests": 0.0, +"ProviderCoreTests.GLM5NextCalibrationDispatchDigestTests": 0.001, "ProviderCoreTests.GLM5NextCalibrationDispatchResultTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationDispatchRunTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationDispatchWireTests": 0.002, "ProviderCoreTests.GLM5NextCalibrationInstalledOwnerTests": 0.0, -"ProviderCoreTests.GLM5NextCalibrationInstalledPairTests": 0.018, +"ProviderCoreTests.GLM5NextCalibrationInstalledPairTests": 0.021, "ProviderCoreTests.GLM5NextCalibrationInstalledQuoteCompletedTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationLaunchTests": 0.019, "ProviderCoreTests.GLM5NextCalibrationNativeCodecTests": 0.003, -"ProviderCoreTests.GLM5NextCalibrationNativeDocumentsTests": 0.08, +"ProviderCoreTests.GLM5NextCalibrationNativeDocumentsTests": 0.078, "ProviderCoreTests.GLM5NextCalibrationNativeStartTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationPairedControlTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationPeerQuoteTests": 0.0, -"ProviderCoreTests.GLM5NextCalibrationPublicQuoteValidationTests": 0.008, -"ProviderCoreTests.GLM5NextCalibrationQuoteAuthorizerTests": 0.046, +"ProviderCoreTests.GLM5NextCalibrationPublicQuoteValidationTests": 0.018, +"ProviderCoreTests.GLM5NextCalibrationQuoteAuthorizerTests": 0.057, "ProviderCoreTests.GLM5NextCalibrationQuoteLaunchTests": 0.006, -"ProviderCoreTests.GLM5NextCalibrationQuoteOutputTests": 0.103, -"ProviderCoreTests.GLM5NextCalibrationQuoteOwnershipTests": 0.568, -"ProviderCoreTests.GLM5NextCalibrationQuoteProcessTests": 3.624, +"ProviderCoreTests.GLM5NextCalibrationQuoteOutputTests": 0.102, +"ProviderCoreTests.GLM5NextCalibrationQuoteOwnershipTests": 0.567, +"ProviderCoreTests.GLM5NextCalibrationQuoteProcessTests": 3.664, "ProviderCoreTests.GLM5NextCalibrationReportTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationResultPublicationTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationTerminalStatusRaceTests": 0.0, -"ProviderCoreTests.GLM5NextCoordinatorServingTests": 0.063, -"ProviderCoreTests.GLM5NextDiscoveryTests": 0.296, -"ProviderCoreTests.GLM5NextEncryptedCheckpointTests": 30.805, +"ProviderCoreTests.GLM5NextCoordinatorServingTests": 0.062, +"ProviderCoreTests.GLM5NextDiscoveryTests": 0.328, +"ProviderCoreTests.GLM5NextEncryptedCheckpointTests": 32.596, "ProviderCoreTests.GLM5NextHardwareGateTests": 0.0, -"ProviderCoreTests.GLM5NextLocalQualificationTests": 0.105, +"ProviderCoreTests.GLM5NextLocalQualificationTests": 0.107, "ProviderCoreTests.GLM5NextLogprobsTests": 0.0, "ProviderCoreTests.GLM5NextManagedKernelTests": 0.0, -"ProviderCoreTests.GLM5NextManagedMetadataTests": 1.317, -"ProviderCoreTests.GLM5NextMediaRoutingTests": 15.836, -"ProviderCoreTests.GLM5NextOpenRouterCapabilityTests": 1.072, -"ProviderCoreTests.GLM5NextPromptPolicyTests": 0.892, +"ProviderCoreTests.GLM5NextManagedMetadataTests": 1.329, +"ProviderCoreTests.GLM5NextMediaRoutingTests": 15.977, +"ProviderCoreTests.GLM5NextOpenRouterCapabilityTests": 1.117, +"ProviderCoreTests.GLM5NextPromptPolicyTests": 0.842, "ProviderCoreTests.GLM5NextProtectedFactoryTests": 0.0, "ProviderCoreTests.GLM5NextProviderLoopTests": 0.0, "ProviderCoreTests.GLM5NextRealArtifactQualificationTests": 0.0, @@ -521,27 +538,27 @@ "ProviderCoreTests.GLM5NextRealLogprobsQualificationTests": 0.0, "ProviderCoreTests.GLM5NextRealTeacherLogitsTests": 0.0, "ProviderCoreTests.GLM5NextRealTimingMatrixTests": 0.0, -"ProviderCoreTests.GLM5NextReasoningVisibilityTests": 0.071, -"ProviderCoreTests.GLM5NextRelayLogprobsTests": 0.114, +"ProviderCoreTests.GLM5NextReasoningVisibilityTests": 0.074, +"ProviderCoreTests.GLM5NextRelayLogprobsTests": 0.118, "ProviderCoreTests.GLM5NextResidencyIntegrationTests": 0.0, "ProviderCoreTests.GLM5NextStandaloneLoadPolicyTests": 0.0, "ProviderCoreTests.GLM5NextWiredLimitTests": 0.002, "ProviderCoreTests.GLM5NextWiredResidencyTests": 0.001, -"ProviderCoreTests.GLM5ToolFailureTests": 0.1, -"ProviderCoreTests.GLMClusterImageReasoningTests": 0.012, -"ProviderCoreTests.GLMClusterTensorParallelMediaTests": 0.042, -"ProviderCoreTests.GLMImageAdmissionTests": 0.001, -"ProviderCoreTests.GLMPairForcedOutputTests": 0.059, -"ProviderCoreTests.GLMSlotParityTests": 0.216, +"ProviderCoreTests.GLM5ToolFailureTests": 0.102, +"ProviderCoreTests.GLMClusterImageReasoningTests": 0.011, +"ProviderCoreTests.GLMClusterTensorParallelMediaTests": 0.041, +"ProviderCoreTests.GLMImageAdmissionTests": 0.002, +"ProviderCoreTests.GLMPairForcedOutputTests": 0.058, +"ProviderCoreTests.GLMSlotParityTests": 0.225, "ProviderCoreTests.GPTOSSCheckpointRestartLiveTests": 0.0, -"ProviderCoreTests.GPTOSSDefaultPrefixCacheWiringTests": 1.52, -"ProviderCoreTests.GPTOSSHarmonyTemplateFixesTests": 0.004, +"ProviderCoreTests.GPTOSSDefaultPrefixCacheWiringTests": 2.316, +"ProviderCoreTests.GPTOSSHarmonyTemplateFixesTests": 0.003, "ProviderCoreTests.GPTOSSMixedPrefixCacheLiveTests": 0.0, -"ProviderCoreTests.GPUEnforcementTests": 0.286, -"ProviderCoreTests.Gemma4ServedTemplateRenderTests": 0.202, -"ProviderCoreTests.Gemma4ToolCallArgumentsTests": 0.002, +"ProviderCoreTests.GPUEnforcementTests": 0.305, +"ProviderCoreTests.Gemma4ServedTemplateRenderTests": 0.207, +"ProviderCoreTests.Gemma4ToolCallArgumentsTests": 0.001, "ProviderCoreTests.Gemma4ToolSchemaEnforcementTests": 0.001, -"ProviderCoreTests.Gemma4TurnStructureTests": 0.003, +"ProviderCoreTests.Gemma4TurnStructureTests": 0.002, "ProviderCoreTests.GemmaMTPPerformanceLiveTests": 0.0, "ProviderCoreTests.GemmaMTPProductionLiveTests": 0.0, "ProviderCoreTests.GemmaOpenRouterLiveTests": 0.0, @@ -550,7 +567,7 @@ "ProviderCoreTests.GemmaOptimizationReportingTests": 0.001, "ProviderCoreTests.GemmaQATCheckpointRestartLiveTests": 0.0, "ProviderCoreTests.GemmaToolCallLiveTests": 0.0, -"ProviderCoreTests.GemmaToolConstraintTests": 0.46, +"ProviderCoreTests.GemmaToolConstraintTests": 0.491, "ProviderCoreTests.GemmaVLMEngineV2LiveTests": 0.0, "ProviderCoreTests.GemmaVLMSharedTowerMemoryLiveTests": 0.0, "ProviderCoreTests.GemmaVLMVideoEngineV2LiveTests": 0.0, @@ -558,68 +575,71 @@ "ProviderCoreTests.GlobalKVCacheBudgetAuditTests": 0.003, "ProviderCoreTests.HardwareDetectorTests": 0.0, "ProviderCoreTests.HeartbeatClusterSessionTests": 0.001, -"ProviderCoreTests.HeartbeatIdlePolicyTests": 0.0, +"ProviderCoreTests.HeartbeatIdlePolicyTests": 0.001, "ProviderCoreTests.HuggingFaceDownloadTests": 0.068, -"ProviderCoreTests.IdleCalibrationCoordinatorTests": 0.067, +"ProviderCoreTests.IdleCalibrationCoordinatorTests": 0.06, "ProviderCoreTests.IdleTimeoutPolicyTests": 0.0, -"ProviderCoreTests.InboundChatRequestDecodeTests": 0.01, +"ProviderCoreTests.InboundChatRequestDecodeTests": 0.011, "ProviderCoreTests.InboundDecodeTests": 0.005, "ProviderCoreTests.InferenceLiveTests": 0.0, "ProviderCoreTests.InferenceRefusalLoggingTests": 0.073, -"ProviderCoreTests.InlineDeclarationProbeTests": 0.06, +"ProviderCoreTests.InlineDeclarationProbeTests": 0.053, "ProviderCoreTests.JinjaSanitizationLiveTests": 0.0, "ProviderCoreTests.JinjaSanitizationTests": 0.008, -"ProviderCoreTests.KVBackendGuardStoreTests": 0.006, +"ProviderCoreTests.KVBackendGuardStoreTests": 0.007, "ProviderCoreTests.KVCheckpointPostureTests": 0.0, -"ProviderCoreTests.KVPoolIdleSweepTests": 0.118, +"ProviderCoreTests.KVPoolIdleSweepTests": 0.703, "ProviderCoreTests.KVPoolReclaimerNativeGateTests": 0.001, -"ProviderCoreTests.KVPoolReclaimerTests": 0.011, -"ProviderCoreTests.KVPoolSweepWiringTests": 0.217, -"ProviderCoreTests.KVQuantizationConfigTests": 0.004, -"ProviderCoreTests.KernelTests": 1.616, +"ProviderCoreTests.KVPoolReclaimerTests": 0.009, +"ProviderCoreTests.KVPoolSweepWiringTests": 0.214, +"ProviderCoreTests.KVQuantizationConfigTests": 0.003, +"ProviderCoreTests.KernelTests": 1.622, "ProviderCoreTests.LaunchAgentDrainAllowanceTests": 0.001, "ProviderCoreTests.LaunchAgentDrainIntegrationTests": 0.0, -"ProviderCoreTests.LaunchAgentEnvironmentTests": 0.003, -"ProviderCoreTests.LaunchAgentLifecycleTests": 0.015, -"ProviderCoreTests.LaunchAgentPathsAndErrorsTests": 0.003, -"ProviderCoreTests.LaunchAgentRemovalTests": 0.023, +"ProviderCoreTests.LaunchAgentEnvironmentTests": 0.004, +"ProviderCoreTests.LaunchAgentLifecycleTests": 0.014, +"ProviderCoreTests.LaunchAgentPathsAndErrorsTests": 0.002, +"ProviderCoreTests.LaunchAgentRemovalTests": 0.022, "ProviderCoreTests.LaunchAgentRestartTests": 0.0, -"ProviderCoreTests.LaunchAgentServicePlistTests": 0.003, -"ProviderCoreTests.LifecycleMailboxTests": 0.032, -"ProviderCoreTests.LiveInferenceMetallibSourceTests": 0.018, -"ProviderCoreTests.LoadedModelsPersistenceWiringTests": 0.025, -"ProviderCoreTests.LoadedModelsStoreTests": 0.004, +"ProviderCoreTests.LaunchAgentServicePlistTests": 0.006, +"ProviderCoreTests.LaunchctlControlTests": 0.015, +"ProviderCoreTests.LifecycleMailboxTests": 0.033, +"ProviderCoreTests.LiveInferenceMetallibSourceTests": 0.025, +"ProviderCoreTests.LoadedModelsPersistenceWiringTests": 0.024, +"ProviderCoreTests.LoadedModelsStoreTests": 0.002, "ProviderCoreTests.LocalChatRequestTests": 0.006, -"ProviderCoreTests.LocalContentPartRefusalTests": 0.006, +"ProviderCoreTests.LocalContentPartRefusalTests": 0.008, "ProviderCoreTests.LocalDisconnectTests": 0.003, -"ProviderCoreTests.LocalDrainHTTPTests": 0.009, +"ProviderCoreTests.LocalDrainHTTPTests": 0.01, "ProviderCoreTests.LocalEndpointFileTests": 0.003, "ProviderCoreTests.LocalOpenAIObjectCompatibilityTests": 0.002, -"ProviderCoreTests.LocalOutputTokenLimitTests": 0.005, -"ProviderCoreTests.LocalResponseConversationTests": 0.012, -"ProviderCoreTests.LocalResponseTrackerTests": 0.014, +"ProviderCoreTests.LocalOutputTokenLimitTests": 0.006, +"ProviderCoreTests.LocalResponseConversationTests": 0.015, +"ProviderCoreTests.LocalResponseTrackerTests": 0.017, "ProviderCoreTests.LocalServingPostureTests": 0.001, "ProviderCoreTests.LocalStreamingFailureTests": 0.003, +"ProviderCoreTests.LocalTokenizerByteFallbackTests": 0.547, +"ProviderCoreTests.LocalTokenizerDecodeSpacingTests": 0.015, "ProviderCoreTests.MDMEnrollmentTests": 0.001, "ProviderCoreTests.MDMTrustDiagnosisTests": 0.001, "ProviderCoreTests.MLXMemoryGuardConfigureOnceTests": 0.001, "ProviderCoreTests.MTPAcceptanceConfigTests": 0.002, -"ProviderCoreTests.MTPBenchmarkTests": 0.166, +"ProviderCoreTests.MTPBenchmarkTests": 0.169, "ProviderCoreTests.MTPBetaFeatureTests": 0.0, "ProviderCoreTests.MTPConfigKeyTests": 0.004, "ProviderCoreTests.MTPIdleUpgradeTests": 0.001, -"ProviderCoreTests.MTPPostureTelemetryTests": 1.117, -"ProviderCoreTests.MTPResliceFallbackTests": 0.097, +"ProviderCoreTests.MTPPostureTelemetryTests": 1.077, +"ProviderCoreTests.MTPResliceFallbackTests": 0.044, "ProviderCoreTests.MTPStagingReservationsTests": 0.0, "ProviderCoreTests.MTPSupportedModelsTests": 0.0, -"ProviderCoreTests.MediaKindClassificationTests": 0.003, -"ProviderCoreTests.MediaToolMetadataTests": 0.002, -"ProviderCoreTests.MetallibHashTests": 0.009, +"ProviderCoreTests.MediaKindClassificationTests": 0.007, +"ProviderCoreTests.MediaToolMetadataTests": 0.001, +"ProviderCoreTests.MetallibHashTests": 0.008, "ProviderCoreTests.MiMoCompleteCheckpointIdentityTests": 0.002, -"ProviderCoreTests.MiMoImageHTTPIngressTests": 1.184, -"ProviderCoreTests.MiMoImageOnboardingSelectionTests": 0.112, -"ProviderCoreTests.MiMoInstalledEncryptedLinkPolicyTests": 0.289, -"ProviderCoreTests.MiMoInstalledImagePolicyTests": 0.218, +"ProviderCoreTests.MiMoImageHTTPIngressTests": 1.185, +"ProviderCoreTests.MiMoImageOnboardingSelectionTests": 0.13, +"ProviderCoreTests.MiMoInstalledEncryptedLinkPolicyTests": 0.298, +"ProviderCoreTests.MiMoInstalledImagePolicyTests": 0.226, "ProviderCoreTests.MiMoMediaDecodeMemoryTests": 0.818, "ProviderCoreTests.MiMoMemoryAdmissionTests": 0.001, "ProviderCoreTests.MiMoTestPrerequisitesTests": 0.001, @@ -656,166 +676,168 @@ "ProviderCoreTests.MiMoV26TemplateFixTests": 0.009, "ProviderCoreTests.MiMoV26WiredDeviceContextTests": 0.001, "ProviderCoreTests.MiMoV26WiredResidencyTests": 0.046, -"ProviderCoreTests.ModelArtifactPublicationTests": 0.024, -"ProviderCoreTests.ModelArtifactReceiptTests": 0.626, +"ProviderCoreTests.ModelArtifactPublicationTests": 0.026, +"ProviderCoreTests.ModelArtifactReceiptTests": 0.61, "ProviderCoreTests.ModelArtifactWriteLeaseTests": 0.003, "ProviderCoreTests.ModelAutopilotHistoryTests": 0.002, -"ProviderCoreTests.ModelAutopilotOperationOwnershipTests": 0.019, -"ProviderCoreTests.ModelAutopilotRuntimeTests": 0.32, -"ProviderCoreTests.ModelAutopilotShadowTests": 0.027, -"ProviderCoreTests.ModelAutopilotTests": 0.003, -"ProviderCoreTests.ModelAutopilotUnloadTests": 0.196, +"ProviderCoreTests.ModelAutopilotOperationOwnershipTests": 0.008, +"ProviderCoreTests.ModelAutopilotRuntimeTests": 0.314, +"ProviderCoreTests.ModelAutopilotShadowTests": 0.03, +"ProviderCoreTests.ModelAutopilotTests": 0.004, +"ProviderCoreTests.ModelAutopilotUnloadTests": 0.136, "ProviderCoreTests.ModelBenchmarkDispatchTests": 0.003, "ProviderCoreTests.ModelBenchmarkReportTests": 0.001, -"ProviderCoreTests.ModelCacheConfigurationTests": 0.003, +"ProviderCoreTests.ModelCacheConfigurationTests": 0.004, "ProviderCoreTests.ModelCalibrationPolicyTests": 0.001, -"ProviderCoreTests.ModelCalibrationTests": 6.22, -"ProviderCoreTests.ModelCatalogTests": 2.472, +"ProviderCoreTests.ModelCalibrationTests": 6.25, +"ProviderCoreTests.ModelCatalogTests": 2.715, "ProviderCoreTests.ModelCheckpointConversationLiveTests": 0.0, -"ProviderCoreTests.ModelCheckpointDonationControlTests": 0.005, -"ProviderCoreTests.ModelCheckpointObservationLifetimeTests": 0.11, +"ProviderCoreTests.ModelCheckpointDonationControlTests": 0.004, +"ProviderCoreTests.ModelCheckpointObservationLifetimeTests": 0.097, "ProviderCoreTests.ModelCheckpointRestoreContentionLiveTests": 0.0, "ProviderCoreTests.ModelCheckpointStorageLiveTests": 0.0, -"ProviderCoreTests.ModelCheckpointStorageSpecificationTests": 0.004, +"ProviderCoreTests.ModelCheckpointStorageSpecificationTests": 0.003, "ProviderCoreTests.ModelDownloadCacheTests": 0.006, -"ProviderCoreTests.ModelDownloadProgressDownloaderTests": 4.492, -"ProviderCoreTests.ModelDownloadProgressTests": 0.17, -"ProviderCoreTests.ModelLoadEvictionAndAdmissionTests": 1.106, -"ProviderCoreTests.ModelLoadRefusalTests": 0.121, -"ProviderCoreTests.ModelPrefetchCoordinatorTests": 0.272, -"ProviderCoreTests.ModelPrefetchDownloaderTests": 0.854, -"ProviderCoreTests.ModelPrefixBenchmarkAdjacentForkTests": 0.009, -"ProviderCoreTests.ModelPrefixBenchmarkCleanupTests": 0.001, +"ProviderCoreTests.ModelDownloadProgressDownloaderTests": 4.298, +"ProviderCoreTests.ModelDownloadProgressTests": 0.18, +"ProviderCoreTests.ModelLoadEvictionAndAdmissionTests": 0.559, +"ProviderCoreTests.ModelLoadRefusalTests": 0.131, +"ProviderCoreTests.ModelPrefetchCoordinatorTests": 0.337, +"ProviderCoreTests.ModelPrefetchDownloaderTests": 0.79, +"ProviderCoreTests.ModelPrefixBenchmarkAdjacentForkTests": 0.007, +"ProviderCoreTests.ModelPrefixBenchmarkCleanupTests": 0.002, "ProviderCoreTests.ModelPrefixBenchmarkDiagnosticsTests": 0.001, "ProviderCoreTests.ModelPrefixBenchmarkLiveTests": 0.0, -"ProviderCoreTests.ModelPrefixBenchmarkMTPObservationTests": 0.002, +"ProviderCoreTests.ModelPrefixBenchmarkMTPObservationTests": 0.0, "ProviderCoreTests.ModelPrefixBenchmarkOutputTimingTests": 0.0, -"ProviderCoreTests.ModelPrefixBenchmarkQuiescenceTimingTests": 0.001, +"ProviderCoreTests.ModelPrefixBenchmarkQuiescenceTimingTests": 0.002, "ProviderCoreTests.ModelPrefixBenchmarkTerminalTests": 0.001, "ProviderCoreTests.ModelRequirementLineTests": 0.001, -"ProviderCoreTests.ModelRevisionActivationTests": 0.05, -"ProviderCoreTests.ModelRevisionPreparationTests": 0.091, -"ProviderCoreTests.ModelRevisionPublicationTests": 0.07, -"ProviderCoreTests.ModelScannerArchitectureTests": 0.005, -"ProviderCoreTests.ModelScannerMemoryFilterTests": 0.004, -"ProviderCoreTests.ModelSelectionDownloadTests": 0.031, -"ProviderCoreTests.ModelSlotBookkeepingTests": 0.031, +"ProviderCoreTests.ModelRevisionActivationTests": 0.055, +"ProviderCoreTests.ModelRevisionPreparationTests": 0.092, +"ProviderCoreTests.ModelRevisionPublicationTests": 0.063, +"ProviderCoreTests.ModelScannerArchitectureTests": 0.004, +"ProviderCoreTests.ModelScannerMemoryFilterTests": 0.006, +"ProviderCoreTests.ModelSelectionDownloadTests": 0.039, +"ProviderCoreTests.ModelSlotBookkeepingTests": 0.025, "ProviderCoreTests.MultimodalErrorMappingTests": 0.0, -"ProviderCoreTests.NativeBlockRetirementBridgeTests": 0.115, -"ProviderCoreTests.NativeChannelSplitterTests": 0.023, -"ProviderCoreTests.NativeCheckpointQuantizationTests": 0.093, +"ProviderCoreTests.NativeBlockRetirementBridgeTests": 0.114, +"ProviderCoreTests.NativeChannelSplitterTests": 0.016, +"ProviderCoreTests.NativeCheckpointQuantizationTests": 0.09, "ProviderCoreTests.NativeDiffusionCheckpointKeysTests": 0.003, -"ProviderCoreTests.NativeDiffusionCheckpointStoreTests": 0.865, +"ProviderCoreTests.NativeDiffusionCheckpointStoreTests": 1.863, "ProviderCoreTests.NativeLocalConsumerOwnershipTests": 0.014, -"ProviderCoreTests.NativeMediaToolPreparationTests": 0.001, +"ProviderCoreTests.NativeMediaToolPreparationTests": 0.002, "ProviderCoreTests.NativeMediaToolsCapabilityTests": 0.001, "ProviderCoreTests.NativeMemoryReclamationTests": 0.0, "ProviderCoreTests.NativeMemoryRetirementWindowTests": 0.0, "ProviderCoreTests.NativeModelToolChoiceTests": 0.002, "ProviderCoreTests.NativeOutputControlRefusalTests": 0.0, -"ProviderCoreTests.NativePairMemberContractTests": 0.032, -"ProviderCoreTests.NativePairMemberControlTests": 0.178, +"ProviderCoreTests.NativePairMemberContractTests": 0.03, +"ProviderCoreTests.NativePairMemberControlTests": 0.186, "ProviderCoreTests.NativePairMemberInstallTests": 0.01, -"ProviderCoreTests.NativePairMemberInvocationTests": 0.962, -"ProviderCoreTests.NativePairMemberServingTests": 2.897, -"ProviderCoreTests.NativePairMessageTests": 0.001, -"ProviderCoreTests.NativePairSessionHeartbeatTests": 0.394, -"ProviderCoreTests.NativeServeQualificationTests": 0.006, +"ProviderCoreTests.NativePairMemberInvocationTests": 1.088, +"ProviderCoreTests.NativePairMemberServingTests": 2.998, +"ProviderCoreTests.NativePairMessageTests": 0.002, +"ProviderCoreTests.NativePairSessionHeartbeatTests": 0.426, +"ProviderCoreTests.NativeServeQualificationTests": 0.004, "ProviderCoreTests.NativeServeRunLifetimeTests": 0.004, "ProviderCoreTests.NativeToolCapabilityAdvertisementTests": 0.002, -"ProviderCoreTests.NativeToolStreamRouterTests": 0.02, +"ProviderCoreTests.NativeToolStreamRouterTests": 0.018, "ProviderCoreTests.NativeWorkerServeQualificationTests": 0.002, "ProviderCoreTests.Nemotron35ArchitectureTests": 0.001, -"ProviderCoreTests.NemotronDemandedShortCheckpointTests": 0.029, +"ProviderCoreTests.NemotronDemandedShortCheckpointTests": 0.038, "ProviderCoreTests.NemotronMTPDeclarationTests": 0.0, -"ProviderCoreTests.NemotronPagingPrefixIntegrationTests": 15.772, -"ProviderCoreTests.NemotronStandaloneAdmissionTests": 0.01, -"ProviderCoreTests.NemotronSuperDurablePrefixCacheTests": 5.702, -"ProviderCoreTests.NemotronSuperImageDecodeTests": 1.258, -"ProviderCoreTests.NemotronSuperImageFormatHTTPTests": 7.671, -"ProviderCoreTests.NemotronSuperImageGoldenTests": 16.983, +"ProviderCoreTests.NemotronPagingPrefixIntegrationTests": 16.923, +"ProviderCoreTests.NemotronStandaloneAdmissionTests": 0.011, +"ProviderCoreTests.NemotronSuperDurablePrefixCacheTests": 6.67, +"ProviderCoreTests.NemotronSuperImageDecodeTests": 1.292, +"ProviderCoreTests.NemotronSuperImageFormatHTTPTests": 10.289, +"ProviderCoreTests.NemotronSuperImageGoldenTests": 17.305, "ProviderCoreTests.NemotronSuperImageHTTPRelayTests": 0.001, -"ProviderCoreTests.NemotronSuperImagePlanTests": 1.13, -"ProviderCoreTests.NemotronSuperJPEGContainerTests": 0.012, +"ProviderCoreTests.NemotronSuperImagePlanTests": 2.385, +"ProviderCoreTests.NemotronSuperJPEGContainerTests": 0.018, "ProviderCoreTests.NemotronSuperLoadAdmissionTests": 0.002, -"ProviderCoreTests.NemotronSuperLocalBindingTests": 3.053, -"ProviderCoreTests.NemotronSuperLocalHTTPAdmissionTests": 7.535, -"ProviderCoreTests.NemotronSuperLocalHTTPTests": 3.352, -"ProviderCoreTests.NemotronSuperLocalImageBindingTests": 0.664, -"ProviderCoreTests.NemotronSuperLocalMTPBatchedTests": 5.659, -"ProviderCoreTests.NemotronSuperLocalMTPTests": 6.49, +"ProviderCoreTests.NemotronSuperLocalBindingTests": 4.099, +"ProviderCoreTests.NemotronSuperLocalHTTPAdmissionTests": 5.767, +"ProviderCoreTests.NemotronSuperLocalHTTPTests": 5.576, +"ProviderCoreTests.NemotronSuperLocalImageBindingTests": 4.548, +"ProviderCoreTests.NemotronSuperLocalMTPBatchedTests": 5.29, +"ProviderCoreTests.NemotronSuperLocalMTPTests": 9.016, "ProviderCoreTests.NemotronSuperLocalOutputTests": 0.055, -"ProviderCoreTests.NemotronSuperLocalOwnerTests": 1.325, -"ProviderCoreTests.NemotronSuperLocalPagedTests": 2.634, -"ProviderCoreTests.NemotronSuperLocalPrefillTests": 3.447, -"ProviderCoreTests.NemotronSuperLocalPrefixCacheTests": 5.213, +"ProviderCoreTests.NemotronSuperLocalOwnerTests": 0.883, +"ProviderCoreTests.NemotronSuperLocalPagedTests": 2.662, +"ProviderCoreTests.NemotronSuperLocalPrefillTests": 3.095, +"ProviderCoreTests.NemotronSuperLocalPrefixCacheTests": 4.145, "ProviderCoreTests.NemotronSuperLongContextLiveTests": 0.0, -"ProviderCoreTests.NemotronSuperLongContextTests": 0.581, -"ProviderCoreTests.NemotronSuperManagedSlotTests": 26.678, -"ProviderCoreTests.NemotronSuperMediaChargeTests": 1.521, +"ProviderCoreTests.NemotronSuperLongContextTests": 0.124, +"ProviderCoreTests.NemotronSuperManagedSlotTests": 26.522, +"ProviderCoreTests.NemotronSuperMediaChargeTests": 1.526, "ProviderCoreTests.NemotronSuperMemoryLiveTests": 0.0, -"ProviderCoreTests.NemotronSuperOpenRouterCapabilityTests": 0.477, -"ProviderCoreTests.NemotronSuperOpenRouterVideoTests": 51.872, -"ProviderCoreTests.NemotronSuperPNGTextTests": 0.058, +"ProviderCoreTests.NemotronSuperOpenRouterCapabilityTests": 0.529, +"ProviderCoreTests.NemotronSuperOpenRouterVideoTests": 52.283, +"ProviderCoreTests.NemotronSuperPNGTextTests": 0.057, "ProviderCoreTests.NemotronSuperPagedLiveTests": 0.0, -"ProviderCoreTests.NemotronSuperPrefixCacheEvidenceTests": 1.091, +"ProviderCoreTests.NemotronSuperPrefixCacheEvidenceTests": 1.288, "ProviderCoreTests.NemotronSuperPromptContractTests": 0.433, "ProviderCoreTests.NemotronSuperPromptGoldenTests": 0.651, "ProviderCoreTests.NemotronSuperRecurrentAdmissionTests": 0.001, -"ProviderCoreTests.NemotronSuperServingPolicyTests": 0.258, -"ProviderCoreTests.NemotronSuperVideoBindingTests": 10.119, -"ProviderCoreTests.NemotronSuperVideoDecodeTests": 2.353, -"ProviderCoreTests.NemotronSuperVideoGoldenTests": 8.707, +"ProviderCoreTests.NemotronSuperServingPolicyTests": 0.263, +"ProviderCoreTests.NemotronSuperVideoBindingTests": 10.324, +"ProviderCoreTests.NemotronSuperVideoDecodeTests": 2.507, +"ProviderCoreTests.NemotronSuperVideoGoldenTests": 8.201, "ProviderCoreTests.NemotronTemplateParityLiveTests": 0.001, -"ProviderCoreTests.NetworkFrameworkCloseCodeTests": 0.012, -"ProviderCoreTests.ObservedRateDeadlineAdmissionTests": 0.009, -"ProviderCoreTests.OuterPrefixCacheReceiptTests": 0.005, -"ProviderCoreTests.PackagedRetainedGemmaSmokeTests": 0.001, -"ProviderCoreTests.PagedFootprintTelemetryTests": 0.001, -"ProviderCoreTests.PagedKernelPreflightTests": 4.99, +"ProviderCoreTests.NetworkFrameworkCloseCodeTests": 0.011, +"ProviderCoreTests.ObservedRateDeadlineAdmissionTests": 0.006, +"ProviderCoreTests.OperatorModelFilterTests": 2.713, +"ProviderCoreTests.OuterPrefixCacheReceiptTests": 0.003, +"ProviderCoreTests.PackagedRetainedGemmaSmokeTests": 0.002, +"ProviderCoreTests.PagedFootprintTelemetryTests": 0.002, +"ProviderCoreTests.PagedKernelPreflightTests": 4.4, "ProviderCoreTests.PagedStorageTelemetryTests": 0.001, "ProviderCoreTests.PagedTeacherForcedAgreementTests": 0.0, "ProviderCoreTests.PerformanceHeartbeatMaterialityTests": 0.0, "ProviderCoreTests.PersistentEnclaveKeyErrorTests": 0.0, -"ProviderCoreTests.PlannedProviderDisconnectTests": 2.407, +"ProviderCoreTests.PlannedProviderDisconnectTests": 2.53, "ProviderCoreTests.PrefillDeadlineProductionConfigTests": 0.005, "ProviderCoreTests.PrefillEvidenceRecoveryStateTests": 0.0, -"ProviderCoreTests.PrefillEvidenceRecoveryTests": 0.669, -"ProviderCoreTests.PrefixCacheCheckpointIdentityTests": 0.016, +"ProviderCoreTests.PrefillEvidenceRecoveryTests": 0.649, +"ProviderCoreTests.PrefixCacheCheckpointIdentityTests": 0.014, "ProviderCoreTests.PrefixCacheDiagnosisTests": 0.0, -"ProviderCoreTests.PrefixCacheEvidenceSequencerTests": 0.029, -"ProviderCoreTests.PrefixCacheLoadHashTests": 0.018, -"ProviderCoreTests.PrefixCachePolicyTests": 0.007, -"ProviderCoreTests.PrefixCacheReceiptTests": 0.064, +"ProviderCoreTests.PrefixCacheEvidenceSequencerTests": 0.034, +"ProviderCoreTests.PrefixCacheLoadHashTests": 0.016, +"ProviderCoreTests.PrefixCachePolicyTests": 0.006, +"ProviderCoreTests.PrefixCacheReceiptTests": 0.056, +"ProviderCoreTests.ProcessExitObserverTests": 2.011, "ProviderCoreTests.ProcessLifecycleTests": 0.008, "ProviderCoreTests.ProcessMemoryNativeIntegrationTests": 0.719, "ProviderCoreTests.ProcessMemoryTelemetryTests": 0.001, -"ProviderCoreTests.ProductionModelCalibrationTests": 51.267, +"ProviderCoreTests.ProductionModelCalibrationTests": 51.477, "ProviderCoreTests.ProductionPromptParityTests": 0.0, -"ProviderCoreTests.PromptDateRenderingTests": 0.003, -"ProviderCoreTests.PromptTokenCacheTests": 1.088, -"ProviderCoreTests.ProviderAuthorizationConnectionTests": 0.004, +"ProviderCoreTests.PromptDateRenderingTests": 0.006, +"ProviderCoreTests.PromptTokenCacheTests": 1.107, +"ProviderCoreTests.ProviderAuthorizationConnectionTests": 0.007, "ProviderCoreTests.ProviderAuthorizationProtocolTests": 0.001, -"ProviderCoreTests.ProviderAuthorizationReadinessTests": 0.003, +"ProviderCoreTests.ProviderAuthorizationReadinessTests": 0.004, "ProviderCoreTests.ProviderAutoRestartConfigTests": 0.001, "ProviderCoreTests.ProviderBusyWireTests": 0.002, -"ProviderCoreTests.ProviderCancelledPrefixCacheTests": 0.282, +"ProviderCoreTests.ProviderCancelledPrefixCacheTests": 0.279, "ProviderCoreTests.ProviderCapabilityLabelsTests": 0.0, -"ProviderCoreTests.ProviderConfigParseGrowthTests": 0.007, +"ProviderCoreTests.ProviderConfigParseGrowthTests": 0.006, "ProviderCoreTests.ProviderLaunchSnapshotTests": 0.0, -"ProviderCoreTests.ProviderLifecycleTests": 2.447, -"ProviderCoreTests.ProviderLogoutTests": 0.773, -"ProviderCoreTests.ProviderLoopCalibrationTests": 3.038, -"ProviderCoreTests.ProviderLoopMTPUpgradeTests": 0.144, +"ProviderCoreTests.ProviderLifecycleTests": 2.445, +"ProviderCoreTests.ProviderLogoutTests": 0.8, +"ProviderCoreTests.ProviderLoopCalibrationTests": 2.998, +"ProviderCoreTests.ProviderLoopMTPUpgradeTests": 0.135, "ProviderCoreTests.ProviderLoopNativeMiMoLifetimeTests": 1.618, -"ProviderCoreTests.ProviderLoopPrefetchTests": 0.864, -"ProviderCoreTests.ProviderMTPFactoryTests": 0.027, -"ProviderCoreTests.ProviderModelSwitchTests": 1.689, -"ProviderCoreTests.ProviderRunMarkerTests": 0.015, +"ProviderCoreTests.ProviderLoopPrefetchTests": 0.887, +"ProviderCoreTests.ProviderMTPFactoryTests": 0.031, +"ProviderCoreTests.ProviderModelSwitchTests": 1.563, +"ProviderCoreTests.ProviderRunMarkerTests": 0.016, "ProviderCoreTests.ProviderRuntimeCapabilityTests": 0.006, -"ProviderCoreTests.ProviderSignalTests": 3.083, +"ProviderCoreTests.ProviderSignalTests": 3.045, "ProviderCoreTests.ProviderStopSignalsTests": 0.0, -"ProviderCoreTests.QMVWideMetalTests": 0.996, +"ProviderCoreTests.QMVWideMetalTests": 0.999, "ProviderCoreTests.Qwen35AdjacentCheckpointLiveTests": 0.0, "ProviderCoreTests.Qwen35CBv2FixedRequestAccountingTests": 0.001, "ProviderCoreTests.Qwen35CheckpointRetentionLiveTests": 0.0, @@ -825,217 +847,220 @@ "ProviderCoreTests.Qwen38ProductionCanaryTests": 0.0, "ProviderCoreTests.Qwen4CanonicalMediaPositionsTests": 0.002, "ProviderCoreTests.Qwen4DefaultProfilePerformanceTests": 0.001, -"ProviderCoreTests.Qwen4EmbeddedMTPTests": 0.013, +"ProviderCoreTests.Qwen4EmbeddedMTPTests": 0.01, "ProviderCoreTests.Qwen4ExecutionPolicyTests": 0.0, -"ProviderCoreTests.Qwen4ExpLoadFootprintTests": 0.009, -"ProviderCoreTests.Qwen4ExpMmapFootprintTests": 0.015, -"ProviderCoreTests.Qwen4FactorySelectionTests": 0.002, +"ProviderCoreTests.Qwen4ExpLoadFootprintTests": 0.017, +"ProviderCoreTests.Qwen4ExpMmapFootprintTests": 0.011, +"ProviderCoreTests.Qwen4FactorySelectionTests": 0.004, "ProviderCoreTests.Qwen4FixedDepthPerformanceProbeTests": 0.001, "ProviderCoreTests.Qwen4LayerSubmissionSafetyProbeTests": 0.001, "ProviderCoreTests.Qwen4LayerSubmissionStateProbeTests": 0.0, -"ProviderCoreTests.Qwen4NativeMediaPrefixPositionsTests": 0.272, +"ProviderCoreTests.Qwen4NativeMediaPrefixPositionsTests": 0.247, "ProviderCoreTests.Qwen4NativeToolConstraintTests": 0.005, -"ProviderCoreTests.Qwen4OwnedVLMRoutingTests": 0.008, -"ProviderCoreTests.Qwen4PagingPrefixIntegrationTests": 18.933, +"ProviderCoreTests.Qwen4OwnedVLMRoutingTests": 0.006, +"ProviderCoreTests.Qwen4PagingPrefixIntegrationTests": 18.251, "ProviderCoreTests.Qwen4ReasoningControlTests": 0.0, -"ProviderCoreTests.Qwen4ReasoningEffortValidationTests": 0.004, -"ProviderCoreTests.Qwen4ReclaimAdmissionTests": 0.133, +"ProviderCoreTests.Qwen4ReasoningEffortValidationTests": 0.003, +"ProviderCoreTests.Qwen4ReclaimAdmissionTests": 0.164, "ProviderCoreTests.Qwen4SparseParallelProbeTests": 0.001, -"ProviderCoreTests.Qwen4StandaloneAdmissionTests": 0.027, -"ProviderCoreTests.Qwen4SupportPolicyTests": 0.01, +"ProviderCoreTests.Qwen4StandaloneAdmissionTests": 0.054, +"ProviderCoreTests.Qwen4SupportPolicyTests": 0.009, "ProviderCoreTests.Qwen4ToolChoicePromptPolicyTests": 0.002, "ProviderCoreTests.Qwen4ToolFramingVocabularyTests": 0.002, -"ProviderCoreTests.QwenJSONAnswerConstraintTests": 4.233, -"ProviderCoreTests.QwenJSONAnswerOutputTests": 0.003, -"ProviderCoreTests.QwenJSONAnswerPolicyTests": 0.606, +"ProviderCoreTests.QwenJSONAnswerConstraintTests": 3.918, +"ProviderCoreTests.QwenJSONAnswerOutputTests": 0.004, +"ProviderCoreTests.QwenJSONAnswerPolicyTests": 0.547, "ProviderCoreTests.QwenJSONAnswerRealTokenizerTests": 0.0, -"ProviderCoreTests.QwenJSONAnswerServingTests": 0.555, +"ProviderCoreTests.QwenJSONAnswerServingTests": 0.549, "ProviderCoreTests.QwenPerImageVisionEquivalenceTests": 0.0, -"ProviderCoreTests.QwenVLMTargetExtractionTests": 2.747, +"ProviderCoreTests.QwenVLMTargetExtractionTests": 3.011, "ProviderCoreTests.ReasoningEffortLiveTests": 0.0, "ProviderCoreTests.ReasoningParserSelectionTests": 0.0, "ProviderCoreTests.ReasoningPromptProbeTests": 0.003, +"ProviderCoreTests.ReasoningStopScopeTests": 0.001, "ProviderCoreTests.ReleaseCoResidencyLiveTests": 0.0, "ProviderCoreTests.RequestProfileBuilderTests": 0.046, -"ProviderCoreTests.ReserveRaisePreflightTests": 1.089, -"ProviderCoreTests.ResidentPrefixCacheEvidenceTests": 0.02, +"ProviderCoreTests.ReserveRaisePreflightTests": 1.093, +"ProviderCoreTests.ResidentPrefixCacheEvidenceTests": 0.026, "ProviderCoreTests.RetirementGateTests": 0.001, -"ProviderCoreTests.RuntimeConcurrencyBenchmarkTests": 0.053, -"ProviderCoreTests.RuntimeGenerationBenchmarkTests": 0.002, -"ProviderCoreTests.RuntimeMetallibTemporaryDirectoryTests": 0.004, +"ProviderCoreTests.RuntimeConcurrencyBenchmarkTests": 0.049, +"ProviderCoreTests.RuntimeGenerationBenchmarkTests": 0.003, +"ProviderCoreTests.RuntimeMetallibTemporaryDirectoryTests": 0.003, "ProviderCoreTests.SDPAPartialPrecisionTests": 1.324, -"ProviderCoreTests.SSDBlockIndexTests": 0.763, -"ProviderCoreTests.SSDBlockStoreTests": 0.063, -"ProviderCoreTests.SSDBlockStreamingTests": 0.027, -"ProviderCoreTests.SSDCacheEpochStoreRecoveryTests": 0.289, -"ProviderCoreTests.SSDCacheEpochStoreTests": 0.309, -"ProviderCoreTests.SSDCheckpointCPUAcceptanceTests": 0.314, -"ProviderCoreTests.SSDCheckpointCommitRetirementTests": 0.044, -"ProviderCoreTests.SSDCheckpointDeltaTests": 0.504, -"ProviderCoreTests.SSDCheckpointDemandAdmissionTests": 0.04, +"ProviderCoreTests.SSDBlockIndexTests": 0.798, +"ProviderCoreTests.SSDBlockStoreTests": 0.065, +"ProviderCoreTests.SSDBlockStreamingTests": 0.024, +"ProviderCoreTests.SSDCacheEpochStoreRecoveryTests": 0.292, +"ProviderCoreTests.SSDCacheEpochStoreTests": 0.307, +"ProviderCoreTests.SSDCheckpointCPUAcceptanceTests": 0.319, +"ProviderCoreTests.SSDCheckpointCommitRetirementTests": 0.046, +"ProviderCoreTests.SSDCheckpointDeltaTests": 0.502, +"ProviderCoreTests.SSDCheckpointDemandAdmissionTests": 0.045, "ProviderCoreTests.SSDCheckpointDemandTests": 0.011, "ProviderCoreTests.SSDCheckpointDonationHashBenchmarkTests": 0.0, -"ProviderCoreTests.SSDCheckpointDonationHashTests": 0.019, +"ProviderCoreTests.SSDCheckpointDonationHashTests": 0.02, "ProviderCoreTests.SSDCheckpointFileCoordinatorPathTests": 0.004, -"ProviderCoreTests.SSDCheckpointFileCoordinatorTests": 0.194, -"ProviderCoreTests.SSDCheckpointFleetWritePriorityTests": 0.113, +"ProviderCoreTests.SSDCheckpointFileCoordinatorTests": 0.196, +"ProviderCoreTests.SSDCheckpointFleetWritePriorityTests": 0.116, "ProviderCoreTests.SSDCheckpointLookupTests": 0.0, -"ProviderCoreTests.SSDCheckpointMaintenanceEpochTests": 0.058, -"ProviderCoreTests.SSDCheckpointPublicationCPUTests": 0.015, +"ProviderCoreTests.SSDCheckpointMaintenanceEpochTests": 0.067, +"ProviderCoreTests.SSDCheckpointPublicationCPUTests": 0.016, "ProviderCoreTests.SSDCheckpointPublicationTests": 0.015, -"ProviderCoreTests.SSDCheckpointReadBudgetTests": 0.006, -"ProviderCoreTests.SSDCheckpointRecencyCoordinationTests": 0.013, -"ProviderCoreTests.SSDCheckpointRemovalRaceTests": 0.162, -"ProviderCoreTests.SSDCheckpointStageCostTests": 0.025, -"ProviderCoreTests.SSDCheckpointStageReservationTests": 0.007, -"ProviderCoreTests.SSDCheckpointWriteRecoveryTests": 0.148, -"ProviderCoreTests.SSDClosedStoreEvictionTests": 1.257, +"ProviderCoreTests.SSDCheckpointReadBudgetTests": 0.005, +"ProviderCoreTests.SSDCheckpointRecencyCoordinationTests": 0.012, +"ProviderCoreTests.SSDCheckpointRemovalRaceTests": 0.17, +"ProviderCoreTests.SSDCheckpointStageCostTests": 0.029, +"ProviderCoreTests.SSDCheckpointStageReservationTests": 0.005, +"ProviderCoreTests.SSDCheckpointWriteRecoveryTests": 0.159, +"ProviderCoreTests.SSDClosedStoreEvictionTests": 1.33, "ProviderCoreTests.SSDCompleteCheckpointStageCapTests": 0.001, -"ProviderCoreTests.SSDCompleteDonationTelemetryTests": 0.033, -"ProviderCoreTests.SSDDebugCacheKeyFileTests": 0.035, +"ProviderCoreTests.SSDCompleteDonationTelemetryTests": 0.031, +"ProviderCoreTests.SSDDebugCacheKeyFileTests": 0.042, "ProviderCoreTests.SSDEpochContinuityTests": 0.061, -"ProviderCoreTests.SSDHybridCheckpointCoordinationTests": 0.123, -"ProviderCoreTests.SSDHybridCheckpointDuplicateTests": 0.16, -"ProviderCoreTests.SSDHybridCheckpointRecencyTests": 0.071, -"ProviderCoreTests.SSDHybridCheckpointStoreFactoryFailureTests": 0.02, -"ProviderCoreTests.SSDHybridCheckpointStoreTests": 0.119, -"ProviderCoreTests.SSDHybridMediaIdentityTests": 0.014, +"ProviderCoreTests.SSDHybridCheckpointCoordinationTests": 0.125, +"ProviderCoreTests.SSDHybridCheckpointDuplicateTests": 0.163, +"ProviderCoreTests.SSDHybridCheckpointRecencyTests": 0.075, +"ProviderCoreTests.SSDHybridCheckpointStoreFactoryFailureTests": 0.017, +"ProviderCoreTests.SSDHybridCheckpointStoreTests": 0.124, +"ProviderCoreTests.SSDHybridMediaIdentityTests": 0.011, "ProviderCoreTests.SSDLookupKeysTests": 0.0, "ProviderCoreTests.SSDNativeCheckpointOracleTests": 1.07, "ProviderCoreTests.SSDNativePrefixBuilderTests": 0.014, -"ProviderCoreTests.SSDNoFollowIOSpecialFileTests": 0.495, -"ProviderCoreTests.SSDOwnedEntryRetirementTests": 0.112, +"ProviderCoreTests.SSDNoFollowIOSpecialFileTests": 0.5, +"ProviderCoreTests.SSDOwnedEntryRetirementTests": 0.111, "ProviderCoreTests.SSDPersistentTestKeyNamespaceTests": 0.007, -"ProviderCoreTests.SSDPrefixCacheDonationGateTests": 0.48, -"ProviderCoreTests.SSDPrefixCacheDonationOutcomeTests": 0.053, +"ProviderCoreTests.SSDPrefixCacheDonationGateTests": 0.622, +"ProviderCoreTests.SSDPrefixCacheDonationOutcomeTests": 0.054, "ProviderCoreTests.SSDPrefixCacheFactoryConstructionTests": 0.059, -"ProviderCoreTests.SSDPrefixCacheFactoryMaintenanceTests": 0.024, +"ProviderCoreTests.SSDPrefixCacheFactoryMaintenanceTests": 0.023, "ProviderCoreTests.SSDPrefixCacheFactoryPathTests": 0.001, -"ProviderCoreTests.SSDPrefixCacheFactoryRefusalTests": 0.003, -"ProviderCoreTests.SSDPrefixCacheLifecycleTests": 1.681, +"ProviderCoreTests.SSDPrefixCacheFactoryRefusalTests": 0.002, +"ProviderCoreTests.SSDPrefixCacheLifecycleTests": 1.961, "ProviderCoreTests.SSDPrefixCacheMetadataPlanningTests": 0.002, "ProviderCoreTests.SSDPrefixCacheModeTests": 0.001, -"ProviderCoreTests.SSDPrefixCacheReadyReceiptTests": 0.21, -"ProviderCoreTests.SSDPrefixCacheReservationTests": 0.799, -"ProviderCoreTests.SSDPrefixCacheTelemetryTests": 0.004, -"ProviderCoreTests.SSDReadyWriteBarrierTests": 0.056, +"ProviderCoreTests.SSDPrefixCacheReadyReceiptTests": 0.266, +"ProviderCoreTests.SSDPrefixCacheReservationTests": 0.787, +"ProviderCoreTests.SSDPrefixCacheTelemetryTests": 0.005, +"ProviderCoreTests.SSDReadyWriteBarrierTests": 0.054, "ProviderCoreTests.SSDRootIsolationTests": 0.0, -"ProviderCoreTests.SSDSharedProcessCheckpointTests": 0.048, -"ProviderCoreTests.SSDShorterCheckpointRestoreTests": 0.832, +"ProviderCoreTests.SSDSharedProcessCheckpointTests": 0.053, +"ProviderCoreTests.SSDShorterCheckpointRestoreTests": 0.827, "ProviderCoreTests.SSDShorterNativeBlockRestoreTests": 2.004, -"ProviderCoreTests.SSDShorterRestoreClockTests": 0.047, -"ProviderCoreTests.SSDTestDirectoryTests": 0.002, -"ProviderCoreTests.SSDTrackedNativeRetryTests": 0.015, -"ProviderCoreTests.SSDWholeRootMaintenanceTests": 0.283, -"ProviderCoreTests.SSDWholeRootTelemetryConcurrencyTests": 0.012, -"ProviderCoreTests.SSDWindowSidecarTests": 0.796, -"ProviderCoreTests.SSDWriteBehindLedgerChargeTests": 0.121, -"ProviderCoreTests.SSDWriteBudgetTests": 0.278, -"ProviderCoreTests.SSDWriteEnduranceTests": 1.874, -"ProviderCoreTests.ScheduleTests": 0.009, +"ProviderCoreTests.SSDShorterRestoreClockTests": 0.052, +"ProviderCoreTests.SSDTestDirectoryTests": 0.001, +"ProviderCoreTests.SSDTrackedNativeRetryTests": 0.013, +"ProviderCoreTests.SSDWholeRootMaintenanceTests": 0.14, +"ProviderCoreTests.SSDWholeRootTelemetryConcurrencyTests": 0.007, +"ProviderCoreTests.SSDWindowSidecarTests": 0.833, +"ProviderCoreTests.SSDWriteBehindLedgerChargeTests": 0.113, +"ProviderCoreTests.SSDWriteBudgetTests": 0.255, +"ProviderCoreTests.SSDWriteEnduranceTests": 1.93, +"ProviderCoreTests.ScheduleTests": 0.01, "ProviderCoreTests.SchedulerPrefillBenchmarkTests": 0.0, -"ProviderCoreTests.SchedulerPrefillDecisionBenchmarkTests": 0.06, +"ProviderCoreTests.SchedulerPrefillDecisionBenchmarkTests": 0.063, "ProviderCoreTests.SchedulerPrefillDecisionEvaluatorTests": 0.14, "ProviderCoreTests.SchedulerPrefillDecisionKVProvenanceTests": 0.001, -"ProviderCoreTests.SchedulerPrefillDecisionLiveRunnerTests": 0.095, +"ProviderCoreTests.SchedulerPrefillDecisionLiveRunnerTests": 0.091, "ProviderCoreTests.SchedulerPrefillDecisionLiveTests": 0.0, -"ProviderCoreTests.SchedulerPrefillDecisionMetadataTests": 0.186, -"ProviderCoreTests.SchedulerPrefillPromptTests": 0.003, -"ProviderCoreTests.SecurityCommandRunnerTests": 0.229, -"ProviderCoreTests.SegmentedProductionGrantTests": 0.032, +"ProviderCoreTests.SchedulerPrefillDecisionMetadataTests": 0.1, +"ProviderCoreTests.SchedulerPrefillPromptTests": 0.004, +"ProviderCoreTests.SecurityCommandRunnerTests": 0.226, +"ProviderCoreTests.SegmentedProductionGrantTests": 0.036, "ProviderCoreTests.SelfUpdaterInstallRootTests": 0.002, -"ProviderCoreTests.SelfUpdaterTests": 41.12, -"ProviderCoreTests.SequenceStateMachineTests": 0.0, +"ProviderCoreTests.SelfUpdaterTests": 40.269, +"ProviderCoreTests.SequenceStateMachineTests": 0.001, "ProviderCoreTests.ServeLoopAppAttestInteropTests": 0.0, -"ProviderCoreTests.ServeLoopAppAttestTests": 2.151, -"ProviderCoreTests.ServeLoopColdLoadTests": 2.788, -"ProviderCoreTests.ServeLoopConnectionTests": 6.565, -"ProviderCoreTests.ServeLoopDispatchTests": 1.483, -"ProviderCoreTests.ServiceReservationHandlerTests": 0.007, -"ProviderCoreTests.ServiceReservationInboundTests": 0.003, +"ProviderCoreTests.ServeLoopAppAttestTests": 2.179, +"ProviderCoreTests.ServeLoopColdLoadTests": 2.603, +"ProviderCoreTests.ServeLoopConnectionTests": 7.033, +"ProviderCoreTests.ServeLoopDispatchTests": 1.445, +"ProviderCoreTests.ServiceReservationHandlerTests": 0.006, +"ProviderCoreTests.ServiceReservationInboundTests": 0.002, "ProviderCoreTests.ServiceReservationLifetimeTests": 0.001, "ProviderCoreTests.ServiceReservationRequestProtocolTests": 0.0, -"ProviderCoreTests.ServingReadinessTests": 0.006, -"ProviderCoreTests.SignedReleaseIdentityTests": 0.003, +"ProviderCoreTests.ServingReadinessTests": 0.007, +"ProviderCoreTests.SignedReleaseIdentityTests": 0.002, "ProviderCoreTests.SingleProbeInlineDecisionTests": 0.001, "ProviderCoreTests.SlotSizingDriftTests": 0.002, -"ProviderCoreTests.SpecDecArtifactFunnelTests": 0.05, +"ProviderCoreTests.SpecDecArtifactFunnelTests": 0.063, "ProviderCoreTests.SpecDecHuggingFaceTests": 3.213, "ProviderCoreTests.SpecDecLoadGateTests": 0.001, -"ProviderCoreTests.SpecDecResolverTests": 5.566, -"ProviderCoreTests.SpecDecSizingSnapshotTests": 0.001, +"ProviderCoreTests.SpecDecResolverTests": 5.394, +"ProviderCoreTests.SpecDecSizingSnapshotTests": 0.002, "ProviderCoreTests.SpecDecSlotTeardownTests": 0.005, -"ProviderCoreTests.StandaloneEvictionOwnershipTests": 0.004, -"ProviderCoreTests.StandaloneLifecycleControlTests": 0.806, -"ProviderCoreTests.StandaloneMTPUpgradeTests": 0.14, -"ProviderCoreTests.StandaloneServerDrainTests": 0.695, -"ProviderCoreTests.StandaloneServerModelAdmissionTests": 2.043, +"ProviderCoreTests.StandaloneEvictionOwnershipTests": 0.007, +"ProviderCoreTests.StandaloneLifecycleControlTests": 0.771, +"ProviderCoreTests.StandaloneMTPUpgradeTests": 0.146, +"ProviderCoreTests.StandaloneServerDrainTests": 0.731, +"ProviderCoreTests.StandaloneServerModelAdmissionTests": 2.049, "ProviderCoreTests.StartupPerformanceEvidenceTests": 0.004, -"ProviderCoreTests.StartupPreloadGateTests": 1.292, -"ProviderCoreTests.StartupPreloadNoEvictTests": 0.042, -"ProviderCoreTests.StartupPreloadPlanTests": 0.036, -"ProviderCoreTests.StartupPreloadPostRegistrationRetirementTests": 0.734, +"ProviderCoreTests.StartupPreloadGateTests": 1.203, +"ProviderCoreTests.StartupPreloadNoEvictTests": 0.04, +"ProviderCoreTests.StartupPreloadPlanTests": 0.025, +"ProviderCoreTests.StartupPreloadPostRegistrationRetirementTests": 1.011, "ProviderCoreTests.StartupPreloaderTests": 0.003, "ProviderCoreTests.StartupSelfTestDecodeLiveTests": 0.0, -"ProviderCoreTests.StreamedToolCallTests": 0.034, -"ProviderCoreTests.StreamingFileDownloadDelegateTests": 0.023, -"ProviderCoreTests.StructuredForcedToolAdmissionTests": 0.044, -"ProviderCoreTests.SwiftJinjaCompatibilityTests": 0.008, -"ProviderCoreTests.SwiftJinjaLoopContextTests": 0.005, -"ProviderCoreTests.TeacherForcedBenchmarkTests": 0.004, +"ProviderCoreTests.StreamedToolCallTests": 0.032, +"ProviderCoreTests.StreamingFileDownloadDelegateTests": 0.024, +"ProviderCoreTests.StructuredForcedToolAdmissionTests": 0.048, +"ProviderCoreTests.SwiftJinjaCompatibilityTests": 0.004, +"ProviderCoreTests.SwiftJinjaLoopContextTests": 0.007, +"ProviderCoreTests.TeacherForcedBenchmarkTests": 0.007, "ProviderCoreTests.TelemetryClientTests": 0.0, -"ProviderCoreTests.TelemetryOverflowQueueTests": 0.004, +"ProviderCoreTests.TelemetryOverflowQueueTests": 0.002, "ProviderCoreTests.TelemetrySymmetryTests": 0.001, "ProviderCoreTests.ThinkStreamingLatencyTests": 0.001, -"ProviderCoreTests.ThroughputSweepDecodeTimingTests": 0.001, -"ProviderCoreTests.ThroughputSweepDecodeWarmupTests": 0.002, -"ProviderCoreTests.ThroughputSweepMedianTests": 0.002, -"ProviderCoreTests.ThroughputSweepNotesTests": 0.006, -"ProviderCoreTests.ThroughputSweepReportTests": 0.002, +"ProviderCoreTests.ThroughputSweepDecodeTimingTests": 0.002, +"ProviderCoreTests.ThroughputSweepDecodeWarmupTests": 0.001, +"ProviderCoreTests.ThroughputSweepMedianTests": 0.003, +"ProviderCoreTests.ThroughputSweepNotesTests": 0.009, +"ProviderCoreTests.ThroughputSweepReportTests": 0.003, "ProviderCoreTests.ThroughputSweepRowAggregationTests": 0.0, "ProviderCoreTests.ThroughputSweepTilingTests": 0.0, -"ProviderCoreTests.TinyModelLoadTests": 3.176, +"ProviderCoreTests.TinyModelLoadTests": 4.129, "ProviderCoreTests.ToolCallTemplateArgumentsTests": 0.0, -"ProviderCoreTests.ToolChoicePromptPolicyTests": 0.002, -"ProviderCoreTests.ToolChoiceViolationErrorTests": 0.001, -"ProviderCoreTests.ToolSchemaNormalizationCorpusTests": 0.002, +"ProviderCoreTests.ToolChoicePromptPolicyTests": 0.003, +"ProviderCoreTests.ToolChoiceViolationErrorTests": 0.002, +"ProviderCoreTests.ToolSchemaNormalizationCorpusTests": 0.003, "ProviderCoreTests.ToolSchemaNormalizationTests": 0.004, -"ProviderCoreTests.TransitionWatchdogSupervisionTests": 2.226, +"ProviderCoreTests.TransitionWatchdogSupervisionTests": 2.245, "ProviderCoreTests.TransitionWatchdogTests": 0.001, "ProviderCoreTests.UnauthorizedConnectionRecoveryTests": 0.001, -"ProviderCoreTests.UnauthorizedConnectionSupervisionTests": 0.061, -"ProviderCoreTests.UnevictableResidentReportTests": 0.08, -"ProviderCoreTests.UnitTests": 4.398, +"ProviderCoreTests.UnauthorizedConnectionSupervisionTests": 0.067, +"ProviderCoreTests.UnevictableResidentReportTests": 0.083, +"ProviderCoreTests.UnitTests": 4.489, "ProviderCoreTests.UnreclaimableLoadMemoryTests": 0.105, -"ProviderCoreTests.UnsupportedContentPartIngressTests": 0.003, +"ProviderCoreTests.UnsupportedContentPartIngressTests": 0.004, "ProviderCoreTests.UpdateBannerTests": 0.001, -"ProviderCoreTests.UpdateDrainAwarenessTests": 0.074, -"ProviderCoreTests.UpdateJitterTests": 0.003, -"ProviderCoreTests.UpdateProcessLockTests": 1.035, -"ProviderCoreTests.UpdateRecoveryStateTests": 0.002, -"ProviderCoreTests.VerifiedWeightHashStoreTests": 0.01, -"ProviderCoreTests.VisionTowerBudgetArithmeticTests": 0.001, +"ProviderCoreTests.UpdateDrainAwarenessTests": 0.073, +"ProviderCoreTests.UpdateJitterTests": 0.001, +"ProviderCoreTests.UpdateProcessLockTests": 1.037, +"ProviderCoreTests.UpdateRecoveryStateTests": 0.001, +"ProviderCoreTests.UpdateRollbackPlanTests": 0.375, +"ProviderCoreTests.UpdateRollbackRecoveryTests": 0.329, +"ProviderCoreTests.VerifiedWeightHashStoreTests": 0.022, +"ProviderCoreTests.VisionTowerBudgetArithmeticTests": 0.0, "ProviderCoreTests.VisionTowerBudgetIncidentTests": 0.001, "ProviderCoreTests.VisionTowerHeadFactorTests": 0.0, "ProviderCoreTests.WatchdogAgentPlistTests": 0.0, "ProviderCoreTests.WatchdogCrashLoopCountTests": 0.001, -"ProviderCoreTests.WatchdogCrashLoopNextStateTests": 0.005, -"ProviderCoreTests.WatchdogDecisionTests": 0.001, +"ProviderCoreTests.WatchdogCrashLoopNextStateTests": 0.002, +"ProviderCoreTests.WatchdogDecisionTests": 0.0, "ProviderCoreTests.WatchdogEffectiveDownSinceTests": 0.0, -"ProviderCoreTests.WatchdogLaunchAdapterTests": 0.172, +"ProviderCoreTests.WatchdogLaunchAdapterTests": 0.189, "ProviderCoreTests.WatchdogNextStateTests": 0.0, "ProviderCoreTests.WatchdogProbeParseTests": 0.001, "ProviderCoreTests.WatchdogProviderIdentityTests": 0.002, "ProviderCoreTests.WatchdogRearmActionTests": 0.0, -"ProviderCoreTests.WatchdogRecoveryIntegrationTests": 11.164, -"ProviderCoreTests.WatchdogSchedulerTests": 0.042, -"ProviderCoreTests.WatchdogStateTests": 0.001, +"ProviderCoreTests.WatchdogRecoveryIntegrationTests": 5.602, +"ProviderCoreTests.WatchdogSchedulerTests": 0.062, +"ProviderCoreTests.WatchdogStateTests": 0.003, "ProviderCoreTests.WedgeMonitorTests": 0.001, "ProviderCoreTests.WeightHashCacheEligibilityTests": 0.027, -"ProviderCoreTests.WholeMacServiceHeartbeatTests": 0.014, -"ProviderCoreTests.WholeMacServiceReservationTests": 0.044, +"ProviderCoreTests.WholeMacServiceHeartbeatTests": 0.018, +"ProviderCoreTests.WholeMacServiceReservationTests": 0.048, "ServingQualificationTests.FlintHTTPBenchmarkTests": 0.0, -"ServingQualificationTests.ServingPromptCountArtifactTests": 0.003, +"ServingQualificationTests.ServingPromptCountArtifactTests": 0.004, "ServingQualificationTests.ServingPromptCountQualificationTests": 0.0, "ServingQualificationTests.ServingQualificationCollectorTests": 0.0, "ServingQualificationTests.ServingQualificationCompetingModelsTests": 0.0, @@ -1043,5 +1068,5 @@ "ServingQualificationTests.ServingQualificationLifecycleOutcomeTests": 0.0, "ServingQualificationTests.ServingQualificationLifecycleTests": 0.0, "ServingQualificationTests.ServingQualificationLiveTests": 0.0, -"ServingQualificationTests.ServingQualificationPostureTests": 0.001 +"ServingQualificationTests.ServingQualificationPostureTests": 0.002 } diff --git a/scripts/test-ci-component-paths.py b/scripts/test-ci-component-paths.py index dffb99c951..b8b8f1d986 100644 --- a/scripts/test-ci-component-paths.py +++ b/scripts/test-ci-component-paths.py @@ -37,16 +37,30 @@ def test_instructions_and_docs_never_select_expensive_lanes(self): def test_component_and_shared_dependency_matrix(self): cases = { "provider-swift/Sources/ProviderCore/ProviderCore.swift": {"provider"}, - "libs/mlx-swift-lm": {"provider", "sdk"}, - "libs/mlx-swift-lm/Libraries/MLXLMCommon/Generate.swift": {"provider", "sdk"}, - "libs/mlx-swift": {"provider", "sdk"}, - "libs/mlx": {"provider"}, - "libs/darkbloom-cluster/Package.swift": {"provider"}, + "provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2.swift": {"provider"}, + "provider-swift/Tests/ProviderCoreTests/Inference/EngineV2Tests.swift": {"provider"}, + "provider-swift/Sources/ProviderCore/Inference/Distributed/DistributedPipeExecutionOwner.swift": + {"provider", "cluster"}, + "provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift": {"provider", "cluster"}, + "provider-swift/Sources/darkbloom/ClusterCommand.swift": {"provider", "cluster"}, + "provider-swift/Sources/ProviderCore/Protocol/NativePairMessages.swift": {"provider", "cluster"}, + "provider-swift/Sources/ProviderCoreFoundation/Manifest.swift": {"provider", "cluster"}, + "provider-swift/Tests/ClusterOnboardingChecks/run.sh": {"provider", "cluster"}, + "provider-swift/Tests/ProviderCoreTests/Inference/DistributedServeLoopTests.swift": {"provider", "cluster"}, + "provider-swift/Package.swift": {"provider", "cluster"}, + "libs/mlx-swift-lm": {"provider", "sdk", "cluster"}, + "libs/mlx-swift-lm/Libraries/MLXLMCommon/Generate.swift": {"provider", "sdk", "cluster"}, + "libs/mlx-swift": {"provider", "sdk", "cluster"}, + "libs/mlx": {"provider", "cluster"}, + "libs/darkbloom-cluster/Package.swift": {"provider", "cluster"}, + "libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh": {"provider", "cluster"}, "fixtures/prompt-contract/v1/corpus.json": {"provider"}, - ".github/actions/provider-ci-build/action.yml": {"provider", "sdk"}, - ".github/workflows/ci.yml": {"provider", "sdk"}, + ".github/actions/provider-ci-build/action.yml": {"provider", "sdk", "cluster"}, + ".github/workflows/ci.yml": {"provider", "sdk", "cluster"}, "scripts/run-paged-kernel-tests.sh": {"provider", "sdk"}, "scripts/run-provider-tests.sh": {"provider"}, + "scripts/provider-test-shards.py": {"provider"}, + "scripts/cluster-test-plan.py": {"provider", "cluster"}, "coordinator/store/postgres/users.go": set(), "coordinator/protocol/messages.go": set(), "console-ui/package-lock.json": set(), @@ -60,9 +74,9 @@ def test_component_and_shared_dependency_matrix(self): self.assertEqual({name for name, value in routing.classify([path]).items() if value}, expected) for path in routing.COMMON: self.assertTrue(all(routing.classify([path]).values()), path) - # Every SDK-lane input is also a provider input. - for pattern in routing.SDK: - path = pattern.replace("**", "x") + # Every SDK-lane and cluster input is also a provider input. + for pattern in (*routing.SDK, *routing.CLUSTER): + path = pattern.replace("**", "x").replace("*", "Cluster") self.assertTrue(routing.classify([path])["provider"], path) def test_swift_prompt_corpora_select_provider(self): @@ -199,6 +213,16 @@ def test_push_before_after_and_new_branch_and_manual(self): head = self.commit() event = {"before": self.base, "after": head, "ref": "refs/heads/topic"} self.assertFalse(any(self.run_detector("push", event).values())) + # A provider-only change: a pull request skips the cluster jobs, a + # push that runs the provider lanes runs them too. + self.write("provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2.swift") + provider_only = self.commit() + self.assertEqual(self.pr(head, provider_only), {"provider": True, "sdk": False, "cluster": False}) + self.assertEqual(self.run_detector("push", {"before": head, "after": provider_only, "ref": "refs/heads/dev"}), + {"provider": True, "sdk": False, "cluster": True}) + self.write("libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/New.swift") + cluster = self.commit() + self.assertEqual(self.pr(provider_only, cluster), {"provider": True, "sdk": False, "cluster": True}) for ref in ("refs/heads/master", "refs/heads/main"): self.assertTrue(all(self.run_detector("push", {**event, "ref": ref}).values())) self.assertTrue(all(self.run_detector("push", {**event, "before": "0" * 40}).values())) @@ -231,7 +255,8 @@ def test_public_provider_workflows_have_no_backend_execution_or_private_access(s def test_expensive_jobs_depend_on_successful_classifier(self): expected = { - "ci.yml": {"test-provider": "provider", "test-cluster-checks": "provider"}, + "ci.yml": {"test-provider": "provider", "test-cluster-checks": "cluster", "test-cluster": "cluster", + "test-cluster-gpu": "cluster", "test-cluster-focused": "cluster"}, } for name, lanes in expected.items(): jobs = workflow.job_blocks((ROOT / ".github/workflows" / name).read_text()) @@ -283,6 +308,7 @@ def test_provider_aggregate_exhaustive_truth_table(self): step = workflow.step_blocks(gate)[0] for name, expression in { "CHANGES_RESULT": "needs.changes.result", "PROVIDER_CHANGED": "needs.changes.outputs.provider", + "CLUSTER_CHANGED": "needs.changes.outputs.cluster", "UNIT_RESULT": "needs.test-provider.result", "SUMMARY_RESULT": "needs.test-provider-summary.result", "CLUSTER_RESULT": "needs.test-cluster.result", "CLUSTER_FOCUSED_RESULT": "needs.test-cluster-focused.result", @@ -293,14 +319,21 @@ def test_provider_aggregate_exhaustive_truth_table(self): # Prompt Parity runs in a provider shard, so UNIT_RESULT carries it. self.assertNotIn("PARITY_RESULT", step) names = ("UNIT_RESULT", "SUMMARY_RESULT", "CLUSTER_RESULT", "CLUSTER_FOCUSED_RESULT") - for detector, changed, *lanes in itertools.product( - results, ("true", "false", ""), *[results] * len(names)): + selections = ("true", "false", "") + + def passes(selected, lanes): + return (selected == "true" and set(lanes) == {"success"}) or \ + (selected == "false" and set(lanes) == {"skipped"}) + + for detector, changed, cluster, *lanes in itertools.product( + results, selections, selections, *[results] * len(names)): result = subprocess.run(["bash", "-e", "-c", command], capture_output=True, timeout=5, env={**os.environ, "CHANGES_RESULT": detector, "PROVIDER_CHANGED": changed, - **dict(zip(names, lanes))}) - expected = detector == "success" and ((changed == "true" and set(lanes) == {"success"}) or - (changed == "false" and set(lanes) == {"skipped"})) - self.assertEqual(result.returncode == 0, expected, (detector, changed, *lanes)) + "CLUSTER_CHANGED": cluster, **dict(zip(names, lanes))}) + # A skipped cluster job passes only when the classifier did not + # select the cluster jobs; a failed or cancelled one never passes. + expected = detector == "success" and passes(changed, lanes[:2]) and passes(cluster, lanes[2:]) + self.assertEqual(result.returncode == 0, expected, (detector, changed, cluster, *lanes)) if __name__ == "__main__": diff --git a/scripts/test-cluster-test-plan.py b/scripts/test-cluster-test-plan.py index 983e5666b3..f9aae9202c 100755 --- a/scripts/test-cluster-test-plan.py +++ b/scripts/test-cluster-test-plan.py @@ -67,6 +67,22 @@ def test_every_selection_runs_through_the_zero_skip_wrapper_serially(self): self.assertEqual(cwd, ROOT) self.assertTrue(Path(argv[1]).is_file(), argv) + def test_order_dependent_selections_keep_their_process_and_order(self): + # Some GPU and peer tests pass only after earlier work in the same + # process or on the same Mac (PR 1745 runs 41692814231, 41700931534). + # Every base suite but the CPU batch-session suite runs in one process, + # so each model family shares a process. + base = [selection for selection in plan.SELECTIONS if selection.base] + self.assertEqual([(selection.name, selection.suites) for selection in base], + [("base-batch-session", ("QwenTensorParallelBatchSessionTests",)), ("base", None)]) + # The share probe's 1.5 s budget includes the first use of the Qwen TP + # kernels on the Mac: it runs in the shard of qwen-tp-batch-gpu, after it. + order = [selection.name for selection in plan.SELECTIONS] + probe = next(selection for selection in plan.SELECTIONS if selection.name == "qwen-tp-share-probe-gpu") + batch = next(selection for selection in plan.SELECTIONS if selection.name == "qwen-tp-batch-gpu") + self.assertEqual((probe.lane, probe.shard), (batch.lane, batch.shard)) + self.assertGreater(order.index(probe.name), order.index(batch.name)) + def test_each_process_has_only_its_own_switches(self): switches = {name: "1" for selection in plan.SELECTIONS for name in selection.environment} switches.update({"GLM53_WINDOW_CENSUS_LONG": "1", "DARKBLOOM_PAGED_BENCH_CTX": "4096"}) diff --git a/scripts/test-provider-ci-workflow.py b/scripts/test-provider-ci-workflow.py index ed6a3aeb78..c51a499e52 100644 --- a/scripts/test-provider-ci-workflow.py +++ b/scripts/test-provider-ci-workflow.py @@ -78,7 +78,7 @@ "test-provider": "provider", "test-provider-sdk": "sdk", } -PROVIDER_SHARDS = [1, 2, 3, 4, 5, 6, 7, 8] +PROVIDER_SHARDS = [1, 2, 3] # Prompt Parity runs in a provider shard (scripts/provider-test-shards.py PARITY_SHARD). PARITY_STEPS = { "Verify public prompt golden vectors": ("./scripts/verify-prompt-parity.sh", "ProductionPromptParityTests", "prompt"), @@ -246,7 +246,7 @@ def test_existing_required_check_requires_every_lane_even_after_failures(self): for outcome in ("failure", "skipped", "cancelled"): results = {lane: outcome if lane == failed else "success" for lane in lanes} result = subprocess.run(["bash", "-e", "-c", command], - env={**os.environ, "CHANGES_RESULT": "success", "PROVIDER_CHANGED": "true", + env={**os.environ, "CHANGES_RESULT": "success", "PROVIDER_CHANGED": "true", "CLUSTER_CHANGED": "true", **results}, capture_output=True, timeout=5) self.assertEqual(result.returncode == 0, failed is None, results) @@ -656,7 +656,7 @@ def test_cluster_metadata_runners_run_every_runner_and_fail_on_any(self): job = self.jobs["test-cluster-checks"] self.assertIn(" name: Cluster Metadata Checks\n", job) self.assertIn(" needs: changes\n", job) - self.assertIn(" if: ${{ needs.changes.outputs.provider == 'true' }}\n", job) + self.assertIn(" if: ${{ needs.changes.outputs.cluster == 'true' }}\n", job) self.assertIn(" runs-on: blacksmith-12vcpu-macos-27\n", job) self.assertNotIn(" test-cluster-checks ", self.jobs["route"]) for forbidden in ("continue-on-error:", "secrets.", "DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST:"): From b1b542b2eec0ebce3c2c01d9bc328bfed14145f9 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 14:03:11 -0600 Subject: [PATCH 0251/1441] ci: refactor pass: cluster inventory script is a provider input, cluster tests narrowed to the runners, GPU job pins, docs Co-Authored-By: Claude Opus 5.5 --- docs/developer/test.md | 14 +++++++------- scripts/ci-component-paths.py | 10 ++++++---- scripts/test-ci-component-paths.py | 9 +++++++-- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/docs/developer/test.md b/docs/developer/test.md index b75795d532..79a3ef80ad 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1192,8 +1192,8 @@ with isolated fixture runners: each `provider-swift/Tests/Cluster*Checks/run.sh` `libs/darkbloom-cluster/Tests/*Checks/run.sh` and `libs/darkbloom-cluster-worker/Tests/*Checks/run.sh` prints its pass count and exits non-zero on a failure. The CI job `test-cluster-checks` (Cluster Metadata -Checks, `.github/workflows/ci.yml`) runs these runners on every pull request that -changes provider code: `libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh`, +Checks, `.github/workflows/ci.yml`) runs these runners when the classifier +selects `cluster` (see below): `libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh`, `libs/darkbloom-cluster/Tests/PrefillScheduleChecks/run.sh`, `libs/darkbloom-cluster/Tests/StageMetadataChecks/run.py`, `libs/darkbloom-cluster/Tests/GPTOSSStageChecks/run.sh`, @@ -1216,14 +1216,14 @@ two-Mac hardware pass. The cluster jobs (Cluster Metadata Checks, Cluster Runtime Tests, Cluster GPU Tests and Cluster Focused Checks) run when the classifier selects `cluster` (`CLUSTER` in `scripts/ci-component-paths.py`): the cluster packages, the MLX -pins, the provider's Cluster, Distributed and NativePair sources and tests, the +pins, the provider's Cluster, Distributed and NativePair sources, the +provider-side cluster runners (`provider-swift/Tests/Cluster*Checks`), the other provider files the cluster runners compile, the cluster plan and the shared build recipe. A push that runs the provider lanes also runs them. The `Provider Tests` gate accepts a skipped cluster job only when `cluster` was not -selected. A provider-only pull request runs 5 Macs (3 provider shards, the -summary and the SDK lane when its inputs change; 4 without it); a cluster pull -request adds 7 (metadata checks, 3 runtime shards, 2 GPU shards, focused -checks). +selected. A provider-only pull request runs 4 Macs (3 provider shards and the +summary), or 5 when an SDK-lane input changes. A cluster pull request adds 7 +Macs (metadata checks, 3 runtime shards, 2 GPU shards and focused checks). CI runs the runtime test target (`DarkbloomClusterRuntimeTests`) on the provider's Blacksmith macOS runners, in selections that diff --git a/scripts/ci-component-paths.py b/scripts/ci-component-paths.py index afa1b729ec..b6dcab5918 100644 --- a/scripts/ci-component-paths.py +++ b/scripts/ci-component-paths.py @@ -28,7 +28,7 @@ "scripts/run-paged-kernel-tests.sh", "scripts/run-provider-test-watchdog.py", "scripts/run-exclusive-native-gpu-test.sh", "scripts/provider-test-shards.py", "scripts/provider-test-shard-weights.json", - "scripts/cluster-test-plan.py", + "scripts/cluster-test-plan.py", "scripts/cluster-stage-content-inventory.py", "scripts/prepare-mimo-*-fixtures.py", "scripts/verify-*-prompt-parity.sh", "scripts/prepare-prompt-fixtures.py", "scripts/test-prepare-prompt-fixtures.py", "scripts/verify-prompt-parity.sh", "scripts/test-qwen4-packaged-resources.py", @@ -68,15 +68,17 @@ "provider-swift/Sources/ProviderCore/Config/ProviderConfigFile.swift", "provider-swift/Sources/ProviderCore/Models/StreamingFileDownloadDelegate.swift", "provider-swift/Sources/ProviderCoreFoundation/Manifest.swift", - "provider-swift/Tests/*Cluster*", "provider-swift/Tests/*cluster*", "provider-swift/Tests/*Distributed*", + # The provider-side cluster runners and the fixture one of them reads; the + # provider unit tests of cluster code run in the provider lane. + "provider-swift/Tests/Cluster*Checks/**", + "provider-swift/Tests/ProviderCoreTests/Fixtures/coordinator-wire/cluster_registration_vector.json", ".github/workflows/ci.yml", ".github/actions/provider-ci-build/**", "scripts/provider-ci-cache.py", "scripts/provider_ci_cache/**", "scripts/provider-release-cache.py", "scripts/provider_release_cache/**", "scripts/provider-release-swift.sh", "scripts/prepare-provider-release-toolchain.sh", "scripts/install-release-cmake.sh", "scripts/prepare-metal-toolchain.py", "scripts/fetch-metallib.sh", "scripts/stage-test-metallib.sh", "scripts/run-nested-suite.sh", - "scripts/cluster-test-plan.py", "scripts/cluster-test-weights.json", - "scripts/cluster-stage-content-inventory.py", + "scripts/cluster-test-plan.py", "scripts/cluster-stage-content-inventory.py", ) diff --git a/scripts/test-ci-component-paths.py b/scripts/test-ci-component-paths.py index b8b8f1d986..01ba22c42b 100644 --- a/scripts/test-ci-component-paths.py +++ b/scripts/test-ci-component-paths.py @@ -46,7 +46,7 @@ def test_component_and_shared_dependency_matrix(self): "provider-swift/Sources/ProviderCore/Protocol/NativePairMessages.swift": {"provider", "cluster"}, "provider-swift/Sources/ProviderCoreFoundation/Manifest.swift": {"provider", "cluster"}, "provider-swift/Tests/ClusterOnboardingChecks/run.sh": {"provider", "cluster"}, - "provider-swift/Tests/ProviderCoreTests/Inference/DistributedServeLoopTests.swift": {"provider", "cluster"}, + "provider-swift/Tests/ProviderCoreTests/Inference/DistributedServeLoopTests.swift": {"provider"}, "provider-swift/Package.swift": {"provider", "cluster"}, "libs/mlx-swift-lm": {"provider", "sdk", "cluster"}, "libs/mlx-swift-lm/Libraries/MLXLMCommon/Generate.swift": {"provider", "sdk", "cluster"}, @@ -77,6 +77,8 @@ def test_component_and_shared_dependency_matrix(self): # Every SDK-lane and cluster input is also a provider input. for pattern in (*routing.SDK, *routing.CLUSTER): path = pattern.replace("**", "x").replace("*", "Cluster") + self.assertTrue(routing.classify([path])[ + "sdk" if pattern in routing.SDK else "cluster"], path) self.assertTrue(routing.classify([path])["provider"], path) def test_swift_prompt_corpora_select_provider(self): @@ -256,7 +258,7 @@ def test_public_provider_workflows_have_no_backend_execution_or_private_access(s def test_expensive_jobs_depend_on_successful_classifier(self): expected = { "ci.yml": {"test-provider": "provider", "test-cluster-checks": "cluster", "test-cluster": "cluster", - "test-cluster-gpu": "cluster", "test-cluster-focused": "cluster"}, + "test-cluster-focused": "cluster"}, } for name, lanes in expected.items(): jobs = workflow.job_blocks((ROOT / ".github/workflows" / name).read_text()) @@ -269,6 +271,9 @@ def test_expensive_jobs_depend_on_successful_classifier(self): self.assertIn(" if: ${{ needs.changes.outputs." + component + " == 'true' }}\n", jobs[lane]) self.assertNotIn("continue-on-error:", jobs[lane]) ci = workflow.job_blocks((ROOT / ".github/workflows/ci.yml").read_text()) + # The GPU job's test step continues on error (scripts/test-cluster-test-plan.py). + self.assertIn(" needs: changes\n", ci["test-cluster-gpu"]) + self.assertIn(" if: ${{ needs.changes.outputs.cluster == 'true' }}\n", ci["test-cluster-gpu"]) # The SDK lane runs on every push and on pull requests that change its inputs. self.assertIn(" needs: changes\n", ci["test-provider-sdk"]) self.assertIn(" if: ${{ github.event_name == 'push' || needs.changes.outputs.sdk == 'true' }}\n", From 64e3a421bd14198105700b3f287f739643604cb7 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 14:08:04 -0600 Subject: [PATCH 0252/1441] ci: keep dev's provider shard weights (the release lane's 5 shards read them) The release qualification lane (release-provider.yml, 5 shards) reads the same weights file, and a weights change there moved suites next to Qwen4PagingPrefixIntegrationTests. PR CI's 3 shards use dev's weights. Co-Authored-By: Claude Opus 5.5 --- scripts/provider-test-shard-weights.json | 1297 +++++++++++----------- 1 file changed, 636 insertions(+), 661 deletions(-) diff --git a/scripts/provider-test-shard-weights.json b/scripts/provider-test-shard-weights.json index ff09db7ffe..58e70a2918 100644 --- a/scripts/provider-test-shard-weights.json +++ b/scripts/provider-test-shard-weights.json @@ -1,164 +1,160 @@ { -"DarkbloomCLITests.AccountCommandRunTests": 1.544, -"DarkbloomCLITests.AddonCommandTests": 0.03, +"DarkbloomCLITests.AccountCommandRunTests": 1.556, +"DarkbloomCLITests.AddonCommandTests": 0.014, "DarkbloomCLITests.AdvertisedModelSelectionTests": 0.001, -"DarkbloomCLITests.AppAttestQualificationCommandTests": 4.21, -"DarkbloomCLITests.AutoUpdateCommandTests": 0.265, -"DarkbloomCLITests.AutopilotCommandTests": 0.751, -"DarkbloomCLITests.AutopilotDownloadCommandTests": 0.255, -"DarkbloomCLITests.AutopilotInventoryTests": 0.013, -"DarkbloomCLITests.AutopilotReplacementTests": 0.165, -"DarkbloomCLITests.AutopilotStartupSelectionTests": 0.001, -"DarkbloomCLITests.BenchmarkArrivalPromptTests": 0.0, -"DarkbloomCLITests.BenchmarkKVQuantizationOptionsTests": 0.074, -"DarkbloomCLITests.BenchmarkNativeBlockModeTests": 0.029, -"DarkbloomCLITests.BenchmarkParityExitTests": 0.0, -"DarkbloomCLITests.BenchmarkRuntimeGenerationOptionsTests": 0.103, -"DarkbloomCLITests.BenchmarkSchedulerPrefillDecisionTests": 0.067, -"DarkbloomCLITests.BenchmarkSchedulerPrefillPromptTests": 0.085, -"DarkbloomCLITests.BenchmarkSweepExitTests": 0.029, -"DarkbloomCLITests.BenchmarkTeacherForcedOptionsTests": 0.055, -"DarkbloomCLITests.BetaCommandRunTests": 1.567, -"DarkbloomCLITests.BetaCommandTests": 1.004, -"DarkbloomCLITests.BootSecurityWarningTests": 0.012, +"DarkbloomCLITests.AppAttestQualificationCommandTests": 4.303, +"DarkbloomCLITests.AutoUpdateCommandTests": 0.165, +"DarkbloomCLITests.AutopilotCommandTests": 0.919, +"DarkbloomCLITests.AutopilotDownloadCommandTests": 0.333, +"DarkbloomCLITests.AutopilotInventoryTests": 0.019, +"DarkbloomCLITests.AutopilotReplacementTests": 0.169, +"DarkbloomCLITests.AutopilotStartupSelectionTests": 0.0, +"DarkbloomCLITests.BenchmarkArrivalPromptTests": 0.001, +"DarkbloomCLITests.BenchmarkKVQuantizationOptionsTests": 0.075, +"DarkbloomCLITests.BenchmarkNativeBlockModeTests": 0.037, +"DarkbloomCLITests.BenchmarkParityExitTests": 0.001, +"DarkbloomCLITests.BenchmarkRuntimeGenerationOptionsTests": 0.094, +"DarkbloomCLITests.BenchmarkSchedulerPrefillDecisionTests": 0.07, +"DarkbloomCLITests.BenchmarkSchedulerPrefillPromptTests": 0.081, +"DarkbloomCLITests.BenchmarkSweepExitTests": 0.031, +"DarkbloomCLITests.BenchmarkTeacherForcedOptionsTests": 0.048, +"DarkbloomCLITests.BetaCommandRunTests": 1.634, +"DarkbloomCLITests.BetaCommandTests": 1.121, +"DarkbloomCLITests.BootSecurityWarningTests": 0.014, "DarkbloomCLITests.CLIDispatchTests": 0.576, -"DarkbloomCLITests.CacheCommandTests": 0.416, -"DarkbloomCLITests.CatalogPickerFlowTests": 0.049, -"DarkbloomCLITests.ClusterCommandTests": 0.015, -"DarkbloomCLITests.ClusterConsoleCommandTests": 0.167, -"DarkbloomCLITests.ClusterMemberSupervisorTests": 10.06, -"DarkbloomCLITests.ClusterOnboardingScopeSettingsTests": 0.005, -"DarkbloomCLITests.ClusterRuntimeFactsCommandTests": 0.019, -"DarkbloomCLITests.ClusterServiceLoginAgentTests": 2.575, -"DarkbloomCLITests.ClusterServiceUpdateTests": 22.159, -"DarkbloomCLITests.ClusterWorkerOwnerCommandTests": 0.014, -"DarkbloomCLITests.DesktopAccountCloudTests": 0.003, -"DarkbloomCLITests.DesktopAccountEarningsTests": 0.01, +"DarkbloomCLITests.CacheCommandTests": 0.512, +"DarkbloomCLITests.CatalogPickerFlowTests": 0.047, +"DarkbloomCLITests.ClusterCommandTests": 0.014, +"DarkbloomCLITests.ClusterConsoleCommandTests": 0.181, +"DarkbloomCLITests.ClusterMemberSupervisorTests": 10.162, +"DarkbloomCLITests.ClusterRuntimeFactsCommandTests": 0.015, +"DarkbloomCLITests.ClusterServiceLoginAgentTests": 2.552, +"DarkbloomCLITests.ClusterWorkerOwnerCommandTests": 0.019, +"DarkbloomCLITests.DesktopAccountCloudTests": 0.002, +"DarkbloomCLITests.DesktopAccountEarningsTests": 0.007, "DarkbloomCLITests.DesktopAccountIdentityTests": 0.001, -"DarkbloomCLITests.DesktopActionArgumentsTests": 0.266, +"DarkbloomCLITests.DesktopActionArgumentsTests": 0.229, "DarkbloomCLITests.DesktopActivityTests": 0.001, -"DarkbloomCLITests.DesktopAutopilotTests": 0.029, -"DarkbloomCLITests.DesktopControlTests": 0.011, +"DarkbloomCLITests.DesktopAutopilotTests": 0.026, +"DarkbloomCLITests.DesktopControlTests": 0.016, "DarkbloomCLITests.DesktopCoolingAuthorizationTests": 0.0, -"DarkbloomCLITests.DesktopCoolingCacheTests": 0.999, -"DarkbloomCLITests.DesktopDownloadProgressTests": 0.002, -"DarkbloomCLITests.DesktopExecutableWatchTests": 0.005, +"DarkbloomCLITests.DesktopCoolingCacheTests": 0.998, +"DarkbloomCLITests.DesktopDownloadProgressTests": 0.0, +"DarkbloomCLITests.DesktopExecutableWatchTests": 0.003, "DarkbloomCLITests.DesktopHTTPErrorTests": 0.002, -"DarkbloomCLITests.DesktopHardwareRouteTests": 0.632, -"DarkbloomCLITests.DesktopMacStatsTests": 0.005, -"DarkbloomCLITests.DesktopRuntimeProfileTests": 1.319, -"DarkbloomCLITests.DesktopServiceTests": 0.006, -"DarkbloomCLITests.DesktopUsageHistoryTests": 0.016, -"DarkbloomCLITests.DesktopWorkerTests": 4.896, +"DarkbloomCLITests.DesktopHardwareRouteTests": 0.603, +"DarkbloomCLITests.DesktopMacStatsTests": 0.012, +"DarkbloomCLITests.DesktopRuntimeProfileTests": 1.299, +"DarkbloomCLITests.DesktopServiceTests": 0.005, +"DarkbloomCLITests.DesktopUsageHistoryTests": 0.019, +"DarkbloomCLITests.DesktopWorkerTests": 4.87, "DarkbloomCLITests.DeviceCheckEvidenceTests": 0.003, -"DarkbloomCLITests.DeviceCheckExtractionBoundsTests": 0.18, -"DarkbloomCLITests.DeviceCheckProcessTests": 0.636, +"DarkbloomCLITests.DeviceCheckExtractionBoundsTests": 0.165, +"DarkbloomCLITests.DeviceCheckProcessTests": 0.628, "DarkbloomCLITests.DiagnosticProbeTests": 0.001, -"DarkbloomCLITests.DistributedStartCommandTests": 0.076, -"DarkbloomCLITests.DistributedStartSessionFactoryTests": 0.013, -"DarkbloomCLITests.DistributedStartSignalLatchTests": 0.017, -"DarkbloomCLITests.DistributedStartSignalsTests": 0.988, +"DarkbloomCLITests.DistributedStartCommandTests": 0.078, +"DarkbloomCLITests.DistributedStartSessionFactoryTests": 0.012, +"DarkbloomCLITests.DistributedStartSignalLatchTests": 0.016, +"DarkbloomCLITests.DistributedStartSignalsTests": 0.983, "DarkbloomCLITests.DoctorAttestationTests": 0.001, -"DarkbloomCLITests.DoctorCaptureTests": 6.084, -"DarkbloomCLITests.DoctorChecksTests": 0.41, +"DarkbloomCLITests.DoctorCaptureTests": 7.384, +"DarkbloomCLITests.DoctorChecksTests": 0.424, "DarkbloomCLITests.DoctorClearBackendGuardFailureTests": 0.003, -"DarkbloomCLITests.DoctorClearBackendGuardTests": 0.004, -"DarkbloomCLITests.DoctorCommandRunTests": 3.667, -"DarkbloomCLITests.DoctorOperatorDiagnosisTests": 6.115, -"DarkbloomCLITests.EnrollCommandTests": 0.001, -"DarkbloomCLITests.FanActivityLeaseTests": 0.024, -"DarkbloomCLITests.FanCommandArgumentTests": 0.013, -"DarkbloomCLITests.FanCommandTests": 0.005, -"DarkbloomCLITests.FanHelperClientTests": 0.003, +"DarkbloomCLITests.DoctorClearBackendGuardTests": 0.003, +"DarkbloomCLITests.DoctorCommandRunTests": 4.69, +"DarkbloomCLITests.DoctorOperatorDiagnosisTests": 6.967, +"DarkbloomCLITests.EnrollCommandTests": 0.003, +"DarkbloomCLITests.FanActivityLeaseTests": 0.026, +"DarkbloomCLITests.FanCommandArgumentTests": 0.032, +"DarkbloomCLITests.FanCommandTests": 0.004, +"DarkbloomCLITests.FanHelperClientTests": 0.005, "DarkbloomCLITests.FanProcessRunnerTests": 1.03, -"DarkbloomCLITests.FanServiceDisableTests": 0.2, -"DarkbloomCLITests.FanServiceEnableTests": 0.316, -"DarkbloomCLITests.FanServiceInstallStepTests": 0.058, +"DarkbloomCLITests.FanServiceDisableTests": 0.197, +"DarkbloomCLITests.FanServiceEnableTests": 0.321, +"DarkbloomCLITests.FanServiceInstallStepTests": 0.063, "DarkbloomCLITests.FanStatusOutputTests": 0.002, "DarkbloomCLITests.GLMWiredLimitAdviceTests": 0.001, -"DarkbloomCLITests.IdleCommandTests": 0.462, -"DarkbloomCLITests.InstallerCoordinatorBindingTests": 0.459, +"DarkbloomCLITests.IdleCommandTests": 0.411, +"DarkbloomCLITests.InstallerCoordinatorBindingTests": 0.386, "DarkbloomCLITests.KVBackendGuardDiagnosticsTests": 0.001, "DarkbloomCLITests.KVBackendPostureTests": 0.003, -"DarkbloomCLITests.LifecycleRecoveryPublicationTests": 0.009, -"DarkbloomCLITests.LifecycleRecoveryRollbackTests": 1.223, -"DarkbloomCLITests.LocalEndpointCommandTests": 0.262, -"DarkbloomCLITests.LocalStartupPreloadGateTests": 0.294, -"DarkbloomCLITests.LogoutCommandTests": 0.161, +"DarkbloomCLITests.LifecycleRecoveryPublicationTests": 0.015, +"DarkbloomCLITests.LifecycleRecoveryRollbackTests": 0.991, +"DarkbloomCLITests.LocalEndpointCommandTests": 0.276, +"DarkbloomCLITests.LocalStartupPreloadGateTests": 0.277, +"DarkbloomCLITests.LogoutCommandTests": 0.095, "DarkbloomCLITests.LogsCommandArgvTests": 0.0, -"DarkbloomCLITests.LogsCommandOptionsTests": 0.006, -"DarkbloomCLITests.MacOSUpgradeNoticeTests": 1.238, -"DarkbloomCLITests.MiMoImageOnboardingCommandTests": 0.035, -"DarkbloomCLITests.ModelPickerInputEndTests": 2.348, -"DarkbloomCLITests.ModelPickerTerminalTests": 0.091, -"DarkbloomCLITests.ModelsCommandRunTests": 3.195, -"DarkbloomCLITests.ModelsLocationCommandTests": 3.187, -"DarkbloomCLITests.PickerCatalogRowTests": 0.006, -"DarkbloomCLITests.PickerDownloadOutputTests": 0.335, +"DarkbloomCLITests.LogsCommandOptionsTests": 0.007, +"DarkbloomCLITests.MacOSUpgradeNoticeTests": 1.161, +"DarkbloomCLITests.MiMoImageOnboardingCommandTests": 0.017, +"DarkbloomCLITests.ModelPickerInputEndTests": 2.301, +"DarkbloomCLITests.ModelPickerTerminalTests": 0.092, +"DarkbloomCLITests.ModelsCommandRunTests": 3.14, +"DarkbloomCLITests.ModelsLocationCommandTests": 2.867, +"DarkbloomCLITests.PickerCatalogRowTests": 0.003, +"DarkbloomCLITests.PickerDownloadOutputTests": 0.322, "DarkbloomCLITests.PickerEntryTests": 0.004, -"DarkbloomCLITests.PickerServingSetBudgetTests": 0.058, +"DarkbloomCLITests.PickerServingSetBudgetTests": 0.051, "DarkbloomCLITests.RegistrationWeightHashTests": 0.012, -"DarkbloomCLITests.ReportAppAttestEvidenceTests": 0.006, -"DarkbloomCLITests.ReportCommandRunTests": 0.613, -"DarkbloomCLITests.ReportCommandTests": 0.003, -"DarkbloomCLITests.ReportConfigPathTests": 0.003, -"DarkbloomCLITests.ReportPayloadTests": 0.019, -"DarkbloomCLITests.RestartCommandTests": 0.003, -"DarkbloomCLITests.RootCommandOutputTests": 0.49, -"DarkbloomCLITests.RuntimeSmokeKVOptionsTests": 0.001, -"DarkbloomCLITests.RuntimeSnapshotConfigTests": 0.388, -"DarkbloomCLITests.SandboxAddonTests": 5.607, -"DarkbloomCLITests.SandboxEligibilityTests": 0.026, -"DarkbloomCLITests.SandboxSetupTests": 3.281, -"DarkbloomCLITests.SandboxStatusTests": 0.011, -"DarkbloomCLITests.ScheduleCommandTests": 1.399, -"DarkbloomCLITests.ScheduledWindowSelectionTests": 0.162, -"DarkbloomCLITests.ScheduledWindowTimingTests": 0.005, -"DarkbloomCLITests.ServiceDrainTests": 0.278, -"DarkbloomCLITests.ServiceDrainWaitTests": 0.794, -"DarkbloomCLITests.StartCommandOptionsTests": 0.104, -"DarkbloomCLITests.StartCommandTests": 0.006, -"DarkbloomCLITests.StartLaunchdGuardTests": 0.793, -"DarkbloomCLITests.StartServingGuardTests": 1.133, -"DarkbloomCLITests.StatusCommandRunTests": 3.227, +"DarkbloomCLITests.ReportAppAttestEvidenceTests": 0.005, +"DarkbloomCLITests.ReportCommandRunTests": 0.597, +"DarkbloomCLITests.ReportCommandTests": 0.002, +"DarkbloomCLITests.ReportConfigPathTests": 0.004, +"DarkbloomCLITests.ReportPayloadTests": 0.022, +"DarkbloomCLITests.RestartCommandTests": 0.004, +"DarkbloomCLITests.RootCommandOutputTests": 0.509, +"DarkbloomCLITests.RuntimeSmokeKVOptionsTests": 0.002, +"DarkbloomCLITests.RuntimeSnapshotConfigTests": 0.334, +"DarkbloomCLITests.SandboxAddonTests": 5.545, +"DarkbloomCLITests.SandboxEligibilityTests": 0.025, +"DarkbloomCLITests.SandboxSetupTests": 2.135, +"DarkbloomCLITests.SandboxStatusTests": 0.01, +"DarkbloomCLITests.ScheduleCommandTests": 1.411, +"DarkbloomCLITests.ScheduledWindowSelectionTests": 0.164, +"DarkbloomCLITests.ScheduledWindowTimingTests": 0.003, +"DarkbloomCLITests.ServiceDrainTests": 0.275, +"DarkbloomCLITests.ServiceDrainWaitTests": 0.815, +"DarkbloomCLITests.StartCommandOptionsTests": 0.086, +"DarkbloomCLITests.StartCommandTests": 0.007, +"DarkbloomCLITests.StartLaunchdGuardTests": 0.784, +"DarkbloomCLITests.StartServingGuardTests": 1.109, +"DarkbloomCLITests.StatusCommandRunTests": 2.659, "DarkbloomCLITests.StatusDaemonHealthLineTests": 0.01, "DarkbloomCLITests.StatusLifecycleDrainLineTests": 0.0, -"DarkbloomCLITests.StatusResidencyTests": 0.976, -"DarkbloomCLITests.SwitchCommandTests": 0.387, -"DarkbloomCLITests.UnenrollChoiceTests": 0.025, -"DarkbloomCLITests.UnenrollKeepServingTests": 0.009, -"DarkbloomCLITests.UpdateCheckCommandTests": 1.12, -"DarkbloomCLITests.UpdateRollbackCommandTests": 0.691, -"DarkbloomCLITests.UpdateRollbackEndToEndTests": 37.166, -"DarkbloomCLITests.WatchdogCommandTests": 0.014, -"DarkbloomCLITests.WatchdogRecordRecoveryOutcomeTests": 0.001, -"DarkbloomCLITests.WatchdogRecoveryOutcomeDetailTests": 0.004, -"DarkbloomCLITests.WatchdogSignalTrapTests": 0.655, -"DarkbloomFanCoreTests.FanControllerTests": 1.146, -"DarkbloomFanCoreTests.FanHardwareTests": 0.296, -"DarkbloomFanCoreTests.FanPolicyTests": 0.236, -"DarkbloomFanCoreTests.SMCCodecTests": 0.122, -"DarkbloomFanHelperTests.FanDaemonTests": 0.22, -"DarkbloomFanHelperTests.FanStartupDiscoveryTests": 0.33, -"DarkbloomFanServiceTests.FanServiceTests": 0.322, -"DarkbloomHardwareLoadTests.CPUTopologyResolverTests": 0.179, -"DarkbloomHardwareLoadTests.CounterLivenessTests": 0.061, -"DarkbloomHardwareLoadTests.HardwareLoadMonitorTests": 0.916, -"DarkbloomHardwareLoadTests.IOReportMathTests": 0.226, -"DarkbloomHardwareLoadTests.LiveHardwareTests": 1.196, -"DarkbloomHardwareLoadTests.ProviderGPUShareTests": 0.12, -"DarkbloomHardwareLoadTests.ReaderParsingTests": 0.139, +"DarkbloomCLITests.StatusResidencyTests": 0.979, +"DarkbloomCLITests.SwitchCommandTests": 0.382, +"DarkbloomCLITests.UnenrollChoiceTests": 0.026, +"DarkbloomCLITests.UnenrollKeepServingTests": 0.006, +"DarkbloomCLITests.UpdateCheckCommandTests": 1.07, +"DarkbloomCLITests.WatchdogCommandTests": 0.012, +"DarkbloomCLITests.WatchdogRecordRecoveryOutcomeTests": 0.002, +"DarkbloomCLITests.WatchdogRecoveryOutcomeDetailTests": 0.002, +"DarkbloomCLITests.WatchdogSignalTrapTests": 0.614, +"DarkbloomFanCoreTests.FanControllerTests": 0.626, +"DarkbloomFanCoreTests.FanHardwareTests": 0.248, +"DarkbloomFanCoreTests.FanPolicyTests": 0.193, +"DarkbloomFanCoreTests.SMCCodecTests": 0.178, +"DarkbloomFanHelperTests.FanDaemonTests": 0.272, +"DarkbloomFanHelperTests.FanStartupDiscoveryTests": 0.387, +"DarkbloomFanServiceTests.FanServiceTests": 0.288, +"DarkbloomHardwareLoadTests.CPUTopologyResolverTests": 0.221, +"DarkbloomHardwareLoadTests.CounterLivenessTests": 0.084, +"DarkbloomHardwareLoadTests.HardwareLoadMonitorTests": 0.926, +"DarkbloomHardwareLoadTests.IOReportMathTests": 0.249, +"DarkbloomHardwareLoadTests.LiveHardwareTests": 1.21, +"DarkbloomHardwareLoadTests.ProviderGPUShareTests": 0.152, +"DarkbloomHardwareLoadTests.ReaderParsingTests": 0.226, "DarkbloomPublishTests.HashCommandTests": 0.014, -"GPTOSSOptimizationTests.CBv2Gemma4ScheduledPrefillTests": 4.257, -"GPTOSSOptimizationTests.CBv2ModelGPTOSSForwardTests": 1.597, -"GPTOSSOptimizationTests.CBv2ModelGemma4ForwardTests": 4.885, -"GPTOSSOptimizationTests.CBv2ModelLayerKindTests": 0.052, -"GPTOSSOptimizationTests.GPTOSSCompiledExpertsTests": 3.379, -"GPTOSSOptimizationTests.GPTOSSGateUpFusionTests": 3.628, -"GPTOSSOptimizationTests.GPTOSSPrefillOutputTests": 15.629, +"GPTOSSOptimizationTests.CBv2Gemma4ScheduledPrefillTests": 4.162, +"GPTOSSOptimizationTests.CBv2ModelGPTOSSForwardTests": 4.11, +"GPTOSSOptimizationTests.CBv2ModelGemma4ForwardTests": 4.8, +"GPTOSSOptimizationTests.CBv2ModelLayerKindTests": 0.05, +"GPTOSSOptimizationTests.GPTOSSCompiledExpertsTests": 1.655, +"GPTOSSOptimizationTests.GPTOSSGateUpFusionTests": 3.414, +"GPTOSSOptimizationTests.GPTOSSPrefillOutputTests": 12.533, "GPTOSSOptimizationTests.GPTOSSRealCheckpointParityTests": 0.0, -"GPTOSSOptimizationTests.IncrementalCheckpointMaterializationTests": 0.039, -"GPTOSSOptimizationTests.QuantizedSwitchLinearConstantCastTests": 1.148, +"GPTOSSOptimizationTests.IncrementalCheckpointMaterializationTests": 0.033, +"GPTOSSOptimizationTests.QuantizedSwitchLinearConstantCastTests": 1.078, "ProviderAppAttestTests.AppAttestEntitlementPolicyTests": 0.003, "ProviderAppAttestTests.AppAttestShadowTests": 0.055, "ProviderAppAttestTests.AppAttestStallRestartPolicyTests": 0.004, @@ -171,12 +167,12 @@ "ProviderAppAttestTests.WorkerProcessTests": 3.88, "ProviderAppAttestTests.WorkerRuntimeDiagnosticsTests": 0.001, "ProviderAppAttestTests.WorkerTransportTests": 0.068, -"ProviderCoreFoundationTests.CacheDirectoryResolutionTests": 0.621, +"ProviderCoreFoundationTests.CacheDirectoryResolutionTests": 0.694, "ProviderCoreFoundationTests.DiffusionGemmaMediaPolicyTests": 0.007, "ProviderCoreFoundationTests.EmptyFileTest": 0.003, "ProviderCoreFoundationTests.EnumerationOrderInvarianceTest": 0.014, -"ProviderCoreFoundationTests.FlintDiscoveryTests": 0.024, -"ProviderCoreFoundationTests.GLM5NextDiscoveryLoadFootprintTests": 1.052, +"ProviderCoreFoundationTests.FlintDiscoveryTests": 0.033, +"ProviderCoreFoundationTests.GLM5NextDiscoveryLoadFootprintTests": 1.067, "ProviderCoreFoundationTests.GoldenVectorTest": 0.003, "ProviderCoreFoundationTests.HarmonySanitizationTests": 0.002, "ProviderCoreFoundationTests.HashAllowlistTests": 0.025, @@ -189,10 +185,10 @@ "ProviderCoreFoundationTests.ModelScannerSnapshotSymlinkTests": 0.033, "ProviderCoreFoundationTests.NemotronSuperDistributionManifestTests": 0.177, "ProviderCoreFoundationTests.NemotronSuperMediaPolicyTests": 0.001, -"ProviderCoreFoundationTests.NemotronTemplateFiltersTests": 0.16, +"ProviderCoreFoundationTests.NemotronTemplateFiltersTests": 0.195, "ProviderCoreFoundationTests.PageCacheTests": 0.066, -"ProviderCoreFoundationTests.PromptContractIdentityTests": 0.154, -"ProviderCoreFoundationTests.PromptRenderDateTests": 0.088, +"ProviderCoreFoundationTests.PromptContractIdentityTests": 0.196, +"ProviderCoreFoundationTests.PromptRenderDateTests": 0.097, "ProviderCoreFoundationTests.Qwen4MediaPolicyTests": 0.011, "ProviderCoreFoundationTests.RoleClassificationTests": 0.0, "ProviderCoreFoundationTests.StaleHashRecomputeTest": 0.013, @@ -202,335 +198,322 @@ "ProviderCoreFoundationTests.WeightHasherConcurrencyTests": 0.112, "ProviderCoreFoundationTests.WeightHasherMemoryTests": 0.07, "ProviderCoreFoundationTests.WeightHasherStreamParityTests": 0.538, -"ProviderCoreTests.APNsPushHistoryTests": 0.036, +"ProviderCoreTests.APNsPushHistoryTests": 0.027, "ProviderCoreTests.AddonHoldDrainOwnershipTests": 0.0, -"ProviderCoreTests.AddonHoldLoopTests": 2.183, -"ProviderCoreTests.AddonHoldServeLoopTests": 1.424, -"ProviderCoreTests.AddonHoldStoreTests": 0.032, -"ProviderCoreTests.AddonIPCServerTests": 1.15, -"ProviderCoreTests.AddonIPCTests": 0.002, -"ProviderCoreTests.AddonPeerPolicyTests": 0.002, -"ProviderCoreTests.AdmissionRateEstimatorTests": 0.008, +"ProviderCoreTests.AddonHoldLoopTests": 2.094, +"ProviderCoreTests.AddonHoldServeLoopTests": 1.636, +"ProviderCoreTests.AddonHoldStoreTests": 0.031, +"ProviderCoreTests.AddonIPCServerTests": 1.155, +"ProviderCoreTests.AddonIPCTests": 0.003, +"ProviderCoreTests.AddonPeerPolicyTests": 0.001, +"ProviderCoreTests.AdmissionRateEstimatorTests": 0.006, "ProviderCoreTests.AdvertisedModelStoreTests": 0.0, "ProviderCoreTests.AppAttestDeepDiagnosisTests": 0.004, -"ProviderCoreTests.AppAttestLocalDiagnosisTests": 0.004, -"ProviderCoreTests.AppAttestProcessProbeTests": 0.469, -"ProviderCoreTests.AppAttestResumeTests": 0.039, -"ProviderCoreTests.AppAttestResumeTransportTests": 0.799, -"ProviderCoreTests.AppAttestShadowReplyTests": 3.924, -"ProviderCoreTests.AppAttestUnsupportedRestartTests": 0.064, -"ProviderCoreTests.AppAttestUpdateLifecycleTests": 2.147, -"ProviderCoreTests.AppAttestVerifiedSeedTests": 0.033, -"ProviderCoreTests.ArrivalInvarianceMeasurementTests": 0.545, -"ProviderCoreTests.AttentionMetadataProductionOwnerTests": 4.961, -"ProviderCoreTests.AudioInputRejectionTests": 0.018, -"ProviderCoreTests.AutoUpdateClaimTests": 0.077, -"ProviderCoreTests.AutoUpdateControllerTests": 0.002, -"ProviderCoreTests.AutoUpdateCycleTests": 0.168, +"ProviderCoreTests.AppAttestLocalDiagnosisTests": 0.006, +"ProviderCoreTests.AppAttestProcessProbeTests": 0.432, +"ProviderCoreTests.AppAttestResumeTests": 0.036, +"ProviderCoreTests.AppAttestResumeTransportTests": 1.11, +"ProviderCoreTests.AppAttestShadowReplyTests": 4.484, +"ProviderCoreTests.AppAttestUpdateLifecycleTests": 3.125, +"ProviderCoreTests.ArrivalInvarianceMeasurementTests": 0.554, +"ProviderCoreTests.AttentionMetadataProductionOwnerTests": 5.039, +"ProviderCoreTests.AudioInputRejectionTests": 0.024, +"ProviderCoreTests.AutoUpdateClaimTests": 0.072, +"ProviderCoreTests.AutoUpdateControllerTests": 0.003, +"ProviderCoreTests.AutoUpdateCycleTests": 0.433, "ProviderCoreTests.AutoUpdateJitterSequencingTests": 0.0, "ProviderCoreTests.AutoUpdateLifecycleOverlapTests": 0.0, -"ProviderCoreTests.AutoUpdateMonitorStartTests": 0.005, -"ProviderCoreTests.AutopilotAdoptionTests": 0.127, +"ProviderCoreTests.AutoUpdateMonitorStartTests": 0.002, +"ProviderCoreTests.AutopilotAdoptionTests": 0.119, "ProviderCoreTests.AutopilotBuildEligibilityTests": 0.001, -"ProviderCoreTests.AutopilotBusyReasonTests": 0.19, -"ProviderCoreTests.AutopilotDownloadLedgerTests": 0.008, +"ProviderCoreTests.AutopilotBusyReasonTests": 0.335, +"ProviderCoreTests.AutopilotDownloadLedgerTests": 0.015, "ProviderCoreTests.AutopilotDownloadPrefetcherTests": 0.001, -"ProviderCoreTests.AutopilotDownloadTests": 1.132, -"ProviderCoreTests.AutopilotInventoryTests": 0.031, +"ProviderCoreTests.AutopilotDownloadTests": 1.319, +"ProviderCoreTests.AutopilotInventoryTests": 0.048, "ProviderCoreTests.AutopilotModelSetTests": 0.001, "ProviderCoreTests.AutopilotModelSwitchOwnershipTests": 0.003, -"ProviderCoreTests.AutopilotPlacementHoldTests": 0.081, +"ProviderCoreTests.AutopilotPlacementHoldTests": 0.04, "ProviderCoreTests.AutopilotSnapshotCodingTests": 0.009, "ProviderCoreTests.AutopilotStartInventoryTests": 0.002, -"ProviderCoreTests.AutopilotStartupPreferencesTests": 0.032, -"ProviderCoreTests.AutopilotStartupTests": 0.026, +"ProviderCoreTests.AutopilotStartupPreferencesTests": 0.036, +"ProviderCoreTests.AutopilotStartupTests": 0.02, "ProviderCoreTests.BackendParityHarnessProbeTests": 0.003, -"ProviderCoreTests.BackendParityReportTests": 0.01, +"ProviderCoreTests.BackendParityReportTests": 0.011, "ProviderCoreTests.BenchmarkCheckpointPartitionTests": 0.0, -"ProviderCoreTests.BenchmarkEntryPointRefusalTests": 0.009, -"ProviderCoreTests.BenchmarkProductionGrantTests": 0.003, -"ProviderCoreTests.BenchmarkProductionInputTests": 0.014, +"ProviderCoreTests.BenchmarkEntryPointRefusalTests": 0.01, +"ProviderCoreTests.BenchmarkProductionGrantTests": 0.004, +"ProviderCoreTests.BenchmarkProductionInputTests": 0.013, "ProviderCoreTests.BenchmarkSessionDonationDemandTests": 0.014, "ProviderCoreTests.BetaFeaturesTests": 0.002, -"ProviderCoreTests.Bonsai9BContextTests": 0.004, +"ProviderCoreTests.Bonsai9BContextTests": 0.005, "ProviderCoreTests.Bonsai9BMTPPolicyTests": 0.003, -"ProviderCoreTests.Bonsai9BRequestPolicyTests": 0.003, -"ProviderCoreTests.BonsaiDemandedShortCheckpointTests": 0.048, +"ProviderCoreTests.Bonsai9BRequestPolicyTests": 0.004, +"ProviderCoreTests.BonsaiDemandedShortCheckpointTests": 0.023, "ProviderCoreTests.BonsaiEncryptedCheckpointLiveTests": 0.0, "ProviderCoreTests.BootSecurityTests": 0.0, -"ProviderCoreTests.BoundedProcessTests": 3.331, "ProviderCoreTests.BuildEnvironmentTests": 0.001, -"ProviderCoreTests.CacheDirectoryPermissionsTests": 0.023, -"ProviderCoreTests.CachePromptParityTests": 0.012, +"ProviderCoreTests.CacheDirectoryPermissionsTests": 0.03, +"ProviderCoreTests.CachePromptParityTests": 0.01, "ProviderCoreTests.CacheSettingsTests": 0.003, -"ProviderCoreTests.CacheStorageEnvironmentTests": 0.006, -"ProviderCoreTests.CacheVolumeTests": 0.03, +"ProviderCoreTests.CacheStorageEnvironmentTests": 0.005, +"ProviderCoreTests.CacheVolumeTests": 0.021, "ProviderCoreTests.CancelledSettlementLifecycleTests": 0.002, -"ProviderCoreTests.ChatRequestExtraFieldsTests": 0.003, -"ProviderCoreTests.ChatTemplateLoopRewritesTests": 5.586, -"ProviderCoreTests.ChildExitWaitConventionTests": 0.394, +"ProviderCoreTests.ChatRequestExtraFieldsTests": 0.002, +"ProviderCoreTests.ChatTemplateLoopRewritesTests": 5.332, "ProviderCoreTests.ChunkBatcherLifecycleTests": 0.003, "ProviderCoreTests.ChunkSenderTests": 0.903, "ProviderCoreTests.ClusterAPIDecorationTests": 0.002, -"ProviderCoreTests.ClusterAPIParityTests": 3.159, +"ProviderCoreTests.ClusterAPIParityTests": 3.181, "ProviderCoreTests.ClusterApprovalAnyNumericsClassTests": 0.002, -"ProviderCoreTests.ClusterApprovalFetchTests": 0.936, -"ProviderCoreTests.ClusterApprovalLifetimeTests": 0.515, -"ProviderCoreTests.ClusterApprovalServiceStartTests": 11.887, -"ProviderCoreTests.ClusterApprovalSyncTests": 5.607, -"ProviderCoreTests.ClusterApprovalTensorAssistantTests": 1.438, -"ProviderCoreTests.ClusterApprovalTensorSharesTests": 1.407, -"ProviderCoreTests.ClusterApprovalWatchTests": 7.854, +"ProviderCoreTests.ClusterApprovalFetchTests": 0.993, +"ProviderCoreTests.ClusterApprovalLifetimeTests": 0.453, +"ProviderCoreTests.ClusterApprovalServiceStartTests": 11.878, +"ProviderCoreTests.ClusterApprovalSyncTests": 5.91, +"ProviderCoreTests.ClusterApprovalWatchTests": 5.82, "ProviderCoreTests.ClusterCacheOwnershipTests": 0.001, "ProviderCoreTests.ClusterChipAgnosticGrantTests": 0.005, -"ProviderCoreTests.ClusterConfigurationTests": 0.006, -"ProviderCoreTests.ClusterDerivedTimeBudgetTests": 0.002, -"ProviderCoreTests.ClusterGLMManifestPinTests": 2.461, -"ProviderCoreTests.ClusterInstalledReferenceTests": 0.008, -"ProviderCoreTests.ClusterLeaderFailoverFinishTests": 1.618, +"ProviderCoreTests.ClusterConfigurationTests": 0.005, +"ProviderCoreTests.ClusterDerivedTimeBudgetTests": 0.001, +"ProviderCoreTests.ClusterGLMManifestPinTests": 2.616, +"ProviderCoreTests.ClusterInstalledReferenceTests": 0.011, +"ProviderCoreTests.ClusterLeaderFailoverFinishTests": 1.645, "ProviderCoreTests.ClusterLinkControlHostTests": 0.005, "ProviderCoreTests.ClusterLocalServingTests": 0.001, -"ProviderCoreTests.ClusterMemberLoopTests": 0.017, -"ProviderCoreTests.ClusterMemberNegotiationTests": 1.057, -"ProviderCoreTests.ClusterMemberRegistrationTests": 10.11, -"ProviderCoreTests.ClusterMemberServeLoopTests": 22.235, -"ProviderCoreTests.ClusterMemberSupervisionTests": 0.004, +"ProviderCoreTests.ClusterMemberLoopTests": 0.015, +"ProviderCoreTests.ClusterMemberNegotiationTests": 0.969, +"ProviderCoreTests.ClusterMemberRegistrationTests": 10.122, +"ProviderCoreTests.ClusterMemberServeLoopTests": 21.62, +"ProviderCoreTests.ClusterMemberSupervisionTests": 0.002, "ProviderCoreTests.ClusterMembershipTests": 0.004, "ProviderCoreTests.ClusterModelApprovalTests": 0.007, -"ProviderCoreTests.ClusterNativeMemberAttachmentTests": 0.027, -"ProviderCoreTests.ClusterObservabilityTests": 0.016, -"ProviderCoreTests.ClusterOnboardingPeerLabelTests": 0.101, -"ProviderCoreTests.ClusterOwnerCommittedBootstrapTests": 1.745, -"ProviderCoreTests.ClusterOwnerServingTests": 0.037, -"ProviderCoreTests.ClusterPairApprovalTests": 0.008, -"ProviderCoreTests.ClusterPairMediaRegistrationTests": 0.002, -"ProviderCoreTests.ClusterPairServingDecisionsTests": 0.003, -"ProviderCoreTests.ClusterPairServingTests": 0.806, +"ProviderCoreTests.ClusterNativeMemberAttachmentTests": 0.028, +"ProviderCoreTests.ClusterObservabilityTests": 0.018, +"ProviderCoreTests.ClusterOnboardingPeerLabelTests": 0.093, +"ProviderCoreTests.ClusterOwnerCommittedBootstrapTests": 1.707, +"ProviderCoreTests.ClusterOwnerServingTests": 0.031, +"ProviderCoreTests.ClusterPairApprovalTests": 0.009, +"ProviderCoreTests.ClusterPairMediaRegistrationTests": 0.001, +"ProviderCoreTests.ClusterPairServingDecisionsTests": 0.006, +"ProviderCoreTests.ClusterPairServingTests": 0.602, "ProviderCoreTests.ClusterPairSlotOwnerLanesTests": 0.0, -"ProviderCoreTests.ClusterPairSlotServeTests": 1.475, -"ProviderCoreTests.ClusterPairSlotTests": 1.415, -"ProviderCoreTests.ClusterPairUpdateTests": 12.976, -"ProviderCoreTests.ClusterPairingProviderTests": 1.756, -"ProviderCoreTests.ClusterPlacementTensorWidthRegisteredTests": 2.558, -"ProviderCoreTests.ClusterPlacementTensorWidthTests": 0.546, -"ProviderCoreTests.ClusterPrefixCacheSettingsTests": 0.005, -"ProviderCoreTests.ClusterPrefixSSDKeyMaterialTests": 0.217, -"ProviderCoreTests.ClusterRosterMemberTests": 0.044, -"ProviderCoreTests.ClusterRuntimeApprovalFactsTests": 3.886, -"ProviderCoreTests.ClusterServiceAgentTests": 0.016, -"ProviderCoreTests.ClusterServiceDescriptorTests": 0.92, -"ProviderCoreTests.ClusterServicePairingChangeTests": 15.996, -"ProviderCoreTests.ClusterServicePowerAssertionTests": 0.006, -"ProviderCoreTests.ClusterServiceRecoveryTests": 7.84, -"ProviderCoreTests.ClusterSetupProbeRequestTests": 0.003, -"ProviderCoreTests.ClusterStatusSpeculationTests": 0.003, -"ProviderCoreTests.ClusterStoreManifestRepairTests": 3.607, +"ProviderCoreTests.ClusterPairSlotServeTests": 1.455, +"ProviderCoreTests.ClusterPairSlotTests": 1.41, +"ProviderCoreTests.ClusterPairingProviderTests": 1.516, +"ProviderCoreTests.ClusterPrefixCacheSettingsTests": 0.012, +"ProviderCoreTests.ClusterPrefixSSDKeyMaterialTests": 0.208, +"ProviderCoreTests.ClusterRosterMemberTests": 0.041, +"ProviderCoreTests.ClusterRuntimeApprovalFactsTests": 3.322, +"ProviderCoreTests.ClusterServiceAgentTests": 0.019, +"ProviderCoreTests.ClusterServiceDescriptorTests": 0.895, +"ProviderCoreTests.ClusterServicePowerAssertionTests": 0.005, +"ProviderCoreTests.ClusterServiceRecoveryTests": 7.638, +"ProviderCoreTests.ClusterSetupProbeRequestTests": 0.006, +"ProviderCoreTests.ClusterStatusSpeculationTests": 0.002, +"ProviderCoreTests.ClusterStoreManifestRepairTests": 3.661, "ProviderCoreTests.ClusterTransferReportsTests": 0.0, -"ProviderCoreTests.CompletePrefixCacheCapabilityTests": 0.0, -"ProviderCoreTests.ConfigValidationTests": 0.009, -"ProviderCoreTests.CoordinatorAdvertiseTests": 0.0, -"ProviderCoreTests.CoordinatorHandshakeDeadlineTests": 3.664, -"ProviderCoreTests.CoordinatorIntegrationTests": 10.207, -"ProviderCoreTests.CoordinatorLifecycleBarrierTests": 0.173, -"ProviderCoreTests.CoordinatorModelSwitchTests": 1.4, +"ProviderCoreTests.CompletePrefixCacheCapabilityTests": 0.001, +"ProviderCoreTests.ConfigValidationTests": 0.006, +"ProviderCoreTests.CoordinatorAdvertiseTests": 0.001, +"ProviderCoreTests.CoordinatorHandshakeDeadlineTests": 3.471, +"ProviderCoreTests.CoordinatorIntegrationTests": 10.106, +"ProviderCoreTests.CoordinatorLifecycleBarrierTests": 0.141, +"ProviderCoreTests.CoordinatorModelSwitchTests": 0.438, "ProviderCoreTests.CoordinatorReconnectPolicyTests": 0.001, "ProviderCoreTests.CoordinatorWireVectorTests": 0.019, "ProviderCoreTests.CrashLoopGuardPredicateTests": 0.0, -"ProviderCoreTests.CrashLoopGuardRecoveryWiringTests": 0.162, -"ProviderCoreTests.CrashLoopGuardTripTests": 0.004, -"ProviderCoreTests.DaemonStateServedCountTests": 0.01, +"ProviderCoreTests.CrashLoopGuardRecoveryWiringTests": 0.282, +"ProviderCoreTests.CrashLoopGuardTripTests": 0.009, +"ProviderCoreTests.DaemonStateServedCountTests": 0.003, "ProviderCoreTests.DarkbloomMDMRemovalTests": 0.002, -"ProviderCoreTests.DeadlineDecisionBridgeTests": 0.015, -"ProviderCoreTests.DeadlineDecisionProfileTests": 0.002, +"ProviderCoreTests.DeadlineDecisionBridgeTests": 0.016, +"ProviderCoreTests.DeadlineDecisionProfileTests": 0.001, "ProviderCoreTests.DecodeBandwidthModelTests": 0.001, -"ProviderCoreTests.DecodeInterleaveDeadlineAdmissionTests": 0.478, +"ProviderCoreTests.DecodeInterleaveDeadlineAdmissionTests": 0.335, "ProviderCoreTests.DesiredModelsForPostureTests": 0.004, -"ProviderCoreTests.DeviceCodeLoginTests": 4.161, -"ProviderCoreTests.DiffusionBenchmarkRouteProbeTests": 0.001, -"ProviderCoreTests.DiffusionBenchmarkTests": 0.002, -"ProviderCoreTests.DiffusionCheckpointEnvelopeTests": 0.105, +"ProviderCoreTests.DeviceCodeLoginTests": 4.029, +"ProviderCoreTests.DiffusionBenchmarkRouteProbeTests": 0.002, +"ProviderCoreTests.DiffusionBenchmarkTests": 0.001, +"ProviderCoreTests.DiffusionCheckpointEnvelopeTests": 0.089, "ProviderCoreTests.DiffusionGemmaBenchmarkRowTests": 0.002, "ProviderCoreTests.DiffusionGemmaConcurrencyLiveTests": 0.001, "ProviderCoreTests.DiffusionGemmaEncryptedHandlerLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaFourCallDiagnosticLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaFourCallFixtureTests": 0.001, "ProviderCoreTests.DiffusionGemmaMediaLiveTests": 0.0, -"ProviderCoreTests.DiffusionGemmaMediaNormalizationTests": 0.024, +"ProviderCoreTests.DiffusionGemmaMediaNormalizationTests": 0.044, "ProviderCoreTests.DiffusionGemmaMediaPrefixLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaNamedToolDiagnosticLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaPrefixLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaPromptParityLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaProtocolLiveTests": 0.0, -"ProviderCoreTests.DiffusionGemmaProviderBridgeTests": 48.273, +"ProviderCoreTests.DiffusionGemmaProviderBridgeTests": 48.52, "ProviderCoreTests.DiffusionGemmaProviderLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaRawCaseLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaReasoningControlTests": 0.002, -"ProviderCoreTests.DiffusionGemmaReasoningEmissionTests": 0.048, +"ProviderCoreTests.DiffusionGemmaReasoningEmissionTests": 0.05, "ProviderCoreTests.DiffusionGemmaStandaloneLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaStopLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaTokenizerParityLiveTests": 0.0, "ProviderCoreTests.DiffusionLongContextLiveTests": 0.0, -"ProviderCoreTests.DiffusionToolResultMediaTests": 0.129, -"ProviderCoreTests.DiffusionVisibleThroughputLiveTests": 0.002, -"ProviderCoreTests.DistributedAutomaticBatchPlannerTests": 0.574, -"ProviderCoreTests.DistributedCBv2CancellationDeadlockTests": 0.48, -"ProviderCoreTests.DistributedCBv2CleanStopTests": 0.057, +"ProviderCoreTests.DiffusionToolResultMediaTests": 0.127, +"ProviderCoreTests.DiffusionVisibleThroughputLiveTests": 0.001, +"ProviderCoreTests.DistributedAutomaticBatchPlannerTests": 0.458, +"ProviderCoreTests.DistributedCBv2CleanStopTests": 0.059, "ProviderCoreTests.DistributedCBv2DeadlineTests": 0.003, -"ProviderCoreTests.DistributedCBv2EngineTests": 0.008, -"ProviderCoreTests.DistributedHTTPCleanStopTests": 1.091, -"ProviderCoreTests.DistributedHTTPCompletionTests": 2.334, -"ProviderCoreTests.DistributedHTTPDeliveryLifecycleTests": 1.814, -"ProviderCoreTests.DistributedHTTPDisconnectTests": 1.667, -"ProviderCoreTests.DistributedHTTPFrameWakeupTests": 0.282, -"ProviderCoreTests.DistributedHTTPOriginTests": 0.282, -"ProviderCoreTests.DistributedHTTPRetirementTests": 0.015, -"ProviderCoreTests.DistributedHTTPTerminalIntegrationTests": 0.93, -"ProviderCoreTests.DistributedHTTPVisibleContentTests": 0.451, -"ProviderCoreTests.DistributedInstalledCancellationTests": 0.002, -"ProviderCoreTests.DistributedInstalledFilesTests": 0.002, -"ProviderCoreTests.DistributedInstalledKVQuantizationTests": 0.006, +"ProviderCoreTests.DistributedCBv2EngineTests": 0.006, +"ProviderCoreTests.DistributedHTTPCleanStopTests": 1.072, +"ProviderCoreTests.DistributedHTTPCompletionTests": 2.364, +"ProviderCoreTests.DistributedHTTPDeliveryLifecycleTests": 1.83, +"ProviderCoreTests.DistributedHTTPDisconnectTests": 1.631, +"ProviderCoreTests.DistributedHTTPFrameWakeupTests": 0.297, +"ProviderCoreTests.DistributedHTTPOriginTests": 0.235, +"ProviderCoreTests.DistributedHTTPRetirementTests": 0.013, +"ProviderCoreTests.DistributedHTTPTerminalIntegrationTests": 0.937, +"ProviderCoreTests.DistributedHTTPVisibleContentTests": 0.439, +"ProviderCoreTests.DistributedInstalledCancellationTests": 0.001, +"ProviderCoreTests.DistributedInstalledFilesTests": 0.005, +"ProviderCoreTests.DistributedInstalledKVQuantizationTests": 0.007, "ProviderCoreTests.DistributedInstalledLanesTests": 0.001, -"ProviderCoreTests.DistributedLogprobAdmissionTests": 0.003, +"ProviderCoreTests.DistributedLogprobAdmissionTests": 0.004, "ProviderCoreTests.DistributedMiMoImageRefusalTests": 0.0, "ProviderCoreTests.DistributedPrefixPartitionTests": 0.003, -"ProviderCoreTests.DistributedQwenMediaHostMemoryTests": 0.001, -"ProviderCoreTests.DistributedQwenMediaIngressTests": 1.261, -"ProviderCoreTests.DistributedQwenMediaLifetimeTests": 0.004, +"ProviderCoreTests.DistributedQwenMediaHostMemoryTests": 0.003, +"ProviderCoreTests.DistributedQwenMediaIngressTests": 1.252, +"ProviderCoreTests.DistributedQwenMediaLifetimeTests": 0.002, "ProviderCoreTests.DistributedRequestObservationSinkTests": 0.007, -"ProviderCoreTests.DistributedRequestObservationTests": 0.008, +"ProviderCoreTests.DistributedRequestObservationTests": 0.004, "ProviderCoreTests.DistributedRequestOriginDeadlineTests": 0.003, "ProviderCoreTests.DistributedRequestQueueTests": 0.0, "ProviderCoreTests.DistributedServingEligibilityTests": 0.004, "ProviderCoreTests.DistributedStopStringScopeTests": 0.002, "ProviderCoreTests.EmbeddedQwen38RuntimeRequirementsTests": 0.0, -"ProviderCoreTests.EngineDeadlineRetirementBridgeTests": 0.011, +"ProviderCoreTests.EngineDeadlineRetirementBridgeTests": 0.009, "ProviderCoreTests.EngineEarlyPerformanceTests": 0.002, -"ProviderCoreTests.EngineMeasurementOrderingTests": 0.155, -"ProviderCoreTests.EnginePerformanceHeartbeatTests": 0.046, -"ProviderCoreTests.EngineProfileCancelTests": 0.014, -"ProviderCoreTests.EngineProfileMappingTests": 0.001, -"ProviderCoreTests.EngineTransferredRetirementWorkTests": 1.65, -"ProviderCoreTests.EngineV2BenchmarkMTPAcceptanceTests": 1.401, -"ProviderCoreTests.EngineV2BenchmarkMTPVerificationTests": 0.78, +"ProviderCoreTests.EngineMeasurementOrderingTests": 0.159, +"ProviderCoreTests.EnginePerformanceHeartbeatTests": 0.048, +"ProviderCoreTests.EngineProfileCancelTests": 0.01, +"ProviderCoreTests.EngineProfileMappingTests": 0.0, +"ProviderCoreTests.EngineTransferredRetirementWorkTests": 1.554, +"ProviderCoreTests.EngineV2BenchmarkMTPAcceptanceTests": 1.413, +"ProviderCoreTests.EngineV2BenchmarkMTPVerificationTests": 3.601, "ProviderCoreTests.EngineV2BridgeCheckpointTargetTests": 0.002, -"ProviderCoreTests.EngineV2BridgeMultimodalTests": 0.008, -"ProviderCoreTests.EngineV2BridgePagedKVTests": 0.006, -"ProviderCoreTests.EngineV2BridgePumpReceiptTests": 0.438, -"ProviderCoreTests.EngineV2CancellationTests": 0.002, -"ProviderCoreTests.EngineV2CapacityTests": 0.007, -"ProviderCoreTests.EngineV2CoResidencyLiveTests": 0.0, -"ProviderCoreTests.EngineV2ContiguousAdmissionTests": 3.645, -"ProviderCoreTests.EngineV2DiffusionMediaChunkBoundTests": 0.003, -"ProviderCoreTests.EngineV2DiffusionPrefixPrecisionTests": 0.061, +"ProviderCoreTests.EngineV2BridgeMultimodalTests": 0.005, +"ProviderCoreTests.EngineV2BridgePagedKVTests": 0.004, +"ProviderCoreTests.EngineV2BridgePumpReceiptTests": 0.158, +"ProviderCoreTests.EngineV2CancellationTests": 0.001, +"ProviderCoreTests.EngineV2CapacityTests": 0.011, +"ProviderCoreTests.EngineV2CoResidencyLiveTests": 0.001, +"ProviderCoreTests.EngineV2ContiguousAdmissionTests": 1.592, +"ProviderCoreTests.EngineV2DiffusionMediaChunkBoundTests": 0.004, +"ProviderCoreTests.EngineV2DiffusionPrefixPrecisionTests": 0.062, "ProviderCoreTests.EngineV2ErrorMappingTests": 0.002, -"ProviderCoreTests.EngineV2EventFramingTests": 0.011, +"ProviderCoreTests.EngineV2EventFramingTests": 0.007, "ProviderCoreTests.EngineV2FP32PagedRateTests": 0.001, -"ProviderCoreTests.EngineV2FailLoudFactoryTests": 0.007, -"ProviderCoreTests.EngineV2FirstTokenDeadlineAdmissionTests": 0.045, -"ProviderCoreTests.EngineV2HardeningTests": 0.002, -"ProviderCoreTests.EngineV2HybridPrefixIdentityTests": 0.181, +"ProviderCoreTests.EngineV2FailLoudFactoryTests": 0.008, +"ProviderCoreTests.EngineV2FirstTokenDeadlineAdmissionTests": 0.04, +"ProviderCoreTests.EngineV2HardeningTests": 0.001, +"ProviderCoreTests.EngineV2HybridPrefixIdentityTests": 0.184, "ProviderCoreTests.EngineV2KVBackendFallbackHeartbeatTests": 0.003, -"ProviderCoreTests.EngineV2KVBackendGateTests": 22.214, +"ProviderCoreTests.EngineV2KVBackendGateTests": 20.974, "ProviderCoreTests.EngineV2KVBackendPolicyTests": 0.003, -"ProviderCoreTests.EngineV2KVQuantizationPolicyTests": 0.002, -"ProviderCoreTests.EngineV2LivenessRecoveryTests": 0.05, +"ProviderCoreTests.EngineV2KVQuantizationPolicyTests": 0.001, +"ProviderCoreTests.EngineV2LivenessRecoveryTests": 0.04, "ProviderCoreTests.EngineV2LivenessVerdictTests": 0.002, -"ProviderCoreTests.EngineV2LogprobsChannelCapTests": 0.002, -"ProviderCoreTests.EngineV2LogprobsPassthroughTests": 0.114, -"ProviderCoreTests.EngineV2LookupReceiptCoverageTests": 0.014, +"ProviderCoreTests.EngineV2LogprobsChannelCapTests": 0.003, +"ProviderCoreTests.EngineV2LogprobsPassthroughTests": 0.127, +"ProviderCoreTests.EngineV2LookupReceiptCoverageTests": 0.009, "ProviderCoreTests.EngineV2MTPAdmissionChargesTests": 0.001, "ProviderCoreTests.EngineV2MTPProductionAdmissionTests": 0.01, -"ProviderCoreTests.EngineV2MatchedStopSequenceTests": 0.004, -"ProviderCoreTests.EngineV2MemoryConcurrencyTests": 0.38, +"ProviderCoreTests.EngineV2MatchedStopSequenceTests": 0.002, +"ProviderCoreTests.EngineV2MemoryConcurrencyTests": 0.023, "ProviderCoreTests.EngineV2NativeBlockTimingTests": 0.0, "ProviderCoreTests.EngineV2PagedParityLiveTests": 0.001, -"ProviderCoreTests.EngineV2PagedPoolDTypeEnvTests": 2.05, -"ProviderCoreTests.EngineV2PrefillGeometryEngineTests": 3.7, -"ProviderCoreTests.EngineV2PrefillGeometryTests": 0.041, -"ProviderCoreTests.EngineV2PrefillSamplingTests": 0.025, -"ProviderCoreTests.EngineV2PrefixCacheUsageTests": 0.003, -"ProviderCoreTests.EngineV2RequestRoutingTests": 0.036, -"ProviderCoreTests.EngineV2ResliceFloorTests": 0.009, -"ProviderCoreTests.EngineV2ResliceFloorWiringTests": 0.047, +"ProviderCoreTests.EngineV2PagedPoolDTypeEnvTests": 0.93, +"ProviderCoreTests.EngineV2PrefillGeometryEngineTests": 2.831, +"ProviderCoreTests.EngineV2PrefillGeometryTests": 0.052, +"ProviderCoreTests.EngineV2PrefillSamplingTests": 0.035, +"ProviderCoreTests.EngineV2PrefixCacheUsageTests": 0.004, +"ProviderCoreTests.EngineV2RequestRoutingTests": 0.034, "ProviderCoreTests.EngineV2ResliceTests": 0.001, -"ProviderCoreTests.EngineV2ResliceUnwindTests": 0.017, -"ProviderCoreTests.EngineV2ReslicingWiringTests": 0.15, -"ProviderCoreTests.EngineV2RuntimeGuardTests": 0.033, +"ProviderCoreTests.EngineV2ResliceUnwindTests": 0.008, +"ProviderCoreTests.EngineV2ReslicingWiringTests": 0.132, +"ProviderCoreTests.EngineV2RuntimeGuardTests": 0.035, "ProviderCoreTests.EngineV2SSDPrefixCacheLiveTests": 0.0, -"ProviderCoreTests.EngineV2SamplingDefaultsTests": 0.003, -"ProviderCoreTests.EngineV2SeededSamplingTests": 0.947, -"ProviderCoreTests.EngineV2ServiceabilityPolicyTests": 0.005, -"ProviderCoreTests.EngineV2ServiceableGrantTests": 0.071, -"ProviderCoreTests.EngineV2ServiceableLoadTests": 1.392, -"ProviderCoreTests.EngineV2SharedBudgetTests": 0.282, -"ProviderCoreTests.EngineV2ShutdownTests": 0.0, -"ProviderCoreTests.EngineV2SlotBuildTests": 0.024, -"ProviderCoreTests.EngineV2SupportedSetGateTests": 0.015, -"ProviderCoreTests.EngineV2TranslationTests": 0.003, +"ProviderCoreTests.EngineV2SamplingDefaultsTests": 0.004, +"ProviderCoreTests.EngineV2SeededSamplingTests": 0.29, +"ProviderCoreTests.EngineV2ServiceabilityPolicyTests": 0.003, +"ProviderCoreTests.EngineV2ServiceableGrantTests": 1.419, +"ProviderCoreTests.EngineV2ServiceableLoadTests": 0.072, +"ProviderCoreTests.EngineV2SharedBudgetTests": 0.303, +"ProviderCoreTests.EngineV2ShutdownTests": 0.001, +"ProviderCoreTests.EngineV2SlotBuildTests": 0.026, +"ProviderCoreTests.EngineV2SupportedSetGateTests": 0.018, +"ProviderCoreTests.EngineV2TranslationTests": 0.002, "ProviderCoreTests.EngineV2VisionMLXFaultTests": 0.001, -"ProviderCoreTests.EngineV2VisionPixelRunTests": 0.002, -"ProviderCoreTests.EngineV2VisionRoutingTests": 0.056, -"ProviderCoreTests.EngineV2VisionSpanCarvingTests": 0.004, -"ProviderCoreTests.EnrollmentTests": 0.026, +"ProviderCoreTests.EngineV2VisionPixelRunTests": 0.005, +"ProviderCoreTests.EngineV2VisionRoutingTests": 0.057, +"ProviderCoreTests.EngineV2VisionSpanCarvingTests": 0.003, +"ProviderCoreTests.EnrollmentTests": 0.023, "ProviderCoreTests.EvalProbeTests": 0.007, -"ProviderCoreTests.FirstContentDeadlineTests": 0.024, +"ProviderCoreTests.FirstContentDeadlineTests": 0.042, "ProviderCoreTests.FlashNextEncryptedHandlerLiveTests": 0.0, "ProviderCoreTests.FlashNextQuietCancellationReloadLiveTests": 0.0, "ProviderCoreTests.FlashNextReclaimDiagnostics": 0.0, -"ProviderCoreTests.FlintAnswerStopServingTests": 0.979, -"ProviderCoreTests.FlintAnswerStopTests": 1.962, -"ProviderCoreTests.FlintContextAdmissionTests": 1.308, +"ProviderCoreTests.FlintAnswerStopServingTests": 0.931, +"ProviderCoreTests.FlintAnswerStopTests": 1.847, +"ProviderCoreTests.FlintContextAdmissionTests": 1.24, "ProviderCoreTests.FlintLiveTests": 0.0, -"ProviderCoreTests.FlintNativeProtocolFactoryTests": 0.856, -"ProviderCoreTests.FlintNativeProtocolTests": 0.538, +"ProviderCoreTests.FlintNativeProtocolFactoryTests": 0.862, +"ProviderCoreTests.FlintNativeProtocolTests": 0.509, "ProviderCoreTests.FlintOpenRouterLiveTests": 0.0, -"ProviderCoreTests.FlintPagedOnlyBackendTests": 0.478, -"ProviderCoreTests.FlintPolicyTests": 0.169, +"ProviderCoreTests.FlintPagedOnlyBackendTests": 0.521, +"ProviderCoreTests.FlintPolicyTests": 0.188, "ProviderCoreTests.FlintR2InstallTests": 0.0, -"ProviderCoreTests.FlintReasoningVisibilityTests": 2.382, +"ProviderCoreTests.FlintReasoningVisibilityTests": 2.321, "ProviderCoreTests.FlintRelayLogprobsLiveTests": 0.0, -"ProviderCoreTests.FlintResponseFormatConstraintTests": 0.362, +"ProviderCoreTests.FlintResponseFormatConstraintTests": 0.338, "ProviderCoreTests.FlintResponseFormatOutputTests": 0.004, -"ProviderCoreTests.FlintResponseFormatPolicyTests": 0.429, -"ProviderCoreTests.FlintTemplateReplayTests": 0.054, -"ProviderCoreTests.FlintToolChoicePromptPolicyTests": 0.011, +"ProviderCoreTests.FlintResponseFormatPolicyTests": 0.433, +"ProviderCoreTests.FlintTemplateReplayTests": 0.049, +"ProviderCoreTests.FlintToolChoicePromptPolicyTests": 0.018, "ProviderCoreTests.FrozenReplayRealModelTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationAuthorizerTests": 0.019, -"ProviderCoreTests.GLM5NextCalibrationBindingWireTests": 0.005, +"ProviderCoreTests.GLM5NextCalibrationBindingWireTests": 0.004, "ProviderCoreTests.GLM5NextCalibrationBootstrapDeadlineTests": 0.0, -"ProviderCoreTests.GLM5NextCalibrationDispatchDigestTests": 0.001, +"ProviderCoreTests.GLM5NextCalibrationDispatchDigestTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationDispatchResultTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationDispatchRunTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationDispatchWireTests": 0.002, "ProviderCoreTests.GLM5NextCalibrationInstalledOwnerTests": 0.0, -"ProviderCoreTests.GLM5NextCalibrationInstalledPairTests": 0.021, +"ProviderCoreTests.GLM5NextCalibrationInstalledPairTests": 0.018, "ProviderCoreTests.GLM5NextCalibrationInstalledQuoteCompletedTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationLaunchTests": 0.019, "ProviderCoreTests.GLM5NextCalibrationNativeCodecTests": 0.003, -"ProviderCoreTests.GLM5NextCalibrationNativeDocumentsTests": 0.078, +"ProviderCoreTests.GLM5NextCalibrationNativeDocumentsTests": 0.08, "ProviderCoreTests.GLM5NextCalibrationNativeStartTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationPairedControlTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationPeerQuoteTests": 0.0, -"ProviderCoreTests.GLM5NextCalibrationPublicQuoteValidationTests": 0.018, -"ProviderCoreTests.GLM5NextCalibrationQuoteAuthorizerTests": 0.057, +"ProviderCoreTests.GLM5NextCalibrationPublicQuoteValidationTests": 0.008, +"ProviderCoreTests.GLM5NextCalibrationQuoteAuthorizerTests": 0.046, "ProviderCoreTests.GLM5NextCalibrationQuoteLaunchTests": 0.006, -"ProviderCoreTests.GLM5NextCalibrationQuoteOutputTests": 0.102, -"ProviderCoreTests.GLM5NextCalibrationQuoteOwnershipTests": 0.567, -"ProviderCoreTests.GLM5NextCalibrationQuoteProcessTests": 3.664, +"ProviderCoreTests.GLM5NextCalibrationQuoteOutputTests": 0.103, +"ProviderCoreTests.GLM5NextCalibrationQuoteOwnershipTests": 0.568, +"ProviderCoreTests.GLM5NextCalibrationQuoteProcessTests": 3.624, "ProviderCoreTests.GLM5NextCalibrationReportTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationResultPublicationTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationTerminalStatusRaceTests": 0.0, -"ProviderCoreTests.GLM5NextCoordinatorServingTests": 0.062, -"ProviderCoreTests.GLM5NextDiscoveryTests": 0.328, -"ProviderCoreTests.GLM5NextEncryptedCheckpointTests": 32.596, +"ProviderCoreTests.GLM5NextCoordinatorServingTests": 0.063, +"ProviderCoreTests.GLM5NextDiscoveryTests": 0.296, +"ProviderCoreTests.GLM5NextEncryptedCheckpointTests": 30.805, "ProviderCoreTests.GLM5NextHardwareGateTests": 0.0, -"ProviderCoreTests.GLM5NextLocalQualificationTests": 0.107, +"ProviderCoreTests.GLM5NextLocalQualificationTests": 0.105, "ProviderCoreTests.GLM5NextLogprobsTests": 0.0, "ProviderCoreTests.GLM5NextManagedKernelTests": 0.0, -"ProviderCoreTests.GLM5NextManagedMetadataTests": 1.329, -"ProviderCoreTests.GLM5NextMediaRoutingTests": 15.977, -"ProviderCoreTests.GLM5NextOpenRouterCapabilityTests": 1.117, -"ProviderCoreTests.GLM5NextPromptPolicyTests": 0.842, +"ProviderCoreTests.GLM5NextManagedMetadataTests": 1.317, +"ProviderCoreTests.GLM5NextMediaRoutingTests": 15.836, +"ProviderCoreTests.GLM5NextOpenRouterCapabilityTests": 1.072, +"ProviderCoreTests.GLM5NextPromptPolicyTests": 0.892, "ProviderCoreTests.GLM5NextProtectedFactoryTests": 0.0, "ProviderCoreTests.GLM5NextProviderLoopTests": 0.0, "ProviderCoreTests.GLM5NextRealArtifactQualificationTests": 0.0, @@ -538,27 +521,27 @@ "ProviderCoreTests.GLM5NextRealLogprobsQualificationTests": 0.0, "ProviderCoreTests.GLM5NextRealTeacherLogitsTests": 0.0, "ProviderCoreTests.GLM5NextRealTimingMatrixTests": 0.0, -"ProviderCoreTests.GLM5NextReasoningVisibilityTests": 0.074, -"ProviderCoreTests.GLM5NextRelayLogprobsTests": 0.118, +"ProviderCoreTests.GLM5NextReasoningVisibilityTests": 0.071, +"ProviderCoreTests.GLM5NextRelayLogprobsTests": 0.114, "ProviderCoreTests.GLM5NextResidencyIntegrationTests": 0.0, "ProviderCoreTests.GLM5NextStandaloneLoadPolicyTests": 0.0, "ProviderCoreTests.GLM5NextWiredLimitTests": 0.002, "ProviderCoreTests.GLM5NextWiredResidencyTests": 0.001, -"ProviderCoreTests.GLM5ToolFailureTests": 0.102, -"ProviderCoreTests.GLMClusterImageReasoningTests": 0.011, -"ProviderCoreTests.GLMClusterTensorParallelMediaTests": 0.041, -"ProviderCoreTests.GLMImageAdmissionTests": 0.002, -"ProviderCoreTests.GLMPairForcedOutputTests": 0.058, -"ProviderCoreTests.GLMSlotParityTests": 0.225, +"ProviderCoreTests.GLM5ToolFailureTests": 0.1, +"ProviderCoreTests.GLMClusterImageReasoningTests": 0.012, +"ProviderCoreTests.GLMClusterTensorParallelMediaTests": 0.042, +"ProviderCoreTests.GLMImageAdmissionTests": 0.001, +"ProviderCoreTests.GLMPairForcedOutputTests": 0.059, +"ProviderCoreTests.GLMSlotParityTests": 0.216, "ProviderCoreTests.GPTOSSCheckpointRestartLiveTests": 0.0, -"ProviderCoreTests.GPTOSSDefaultPrefixCacheWiringTests": 2.316, -"ProviderCoreTests.GPTOSSHarmonyTemplateFixesTests": 0.003, +"ProviderCoreTests.GPTOSSDefaultPrefixCacheWiringTests": 1.52, +"ProviderCoreTests.GPTOSSHarmonyTemplateFixesTests": 0.004, "ProviderCoreTests.GPTOSSMixedPrefixCacheLiveTests": 0.0, -"ProviderCoreTests.GPUEnforcementTests": 0.305, -"ProviderCoreTests.Gemma4ServedTemplateRenderTests": 0.207, -"ProviderCoreTests.Gemma4ToolCallArgumentsTests": 0.001, +"ProviderCoreTests.GPUEnforcementTests": 0.286, +"ProviderCoreTests.Gemma4ServedTemplateRenderTests": 0.202, +"ProviderCoreTests.Gemma4ToolCallArgumentsTests": 0.002, "ProviderCoreTests.Gemma4ToolSchemaEnforcementTests": 0.001, -"ProviderCoreTests.Gemma4TurnStructureTests": 0.002, +"ProviderCoreTests.Gemma4TurnStructureTests": 0.003, "ProviderCoreTests.GemmaMTPPerformanceLiveTests": 0.0, "ProviderCoreTests.GemmaMTPProductionLiveTests": 0.0, "ProviderCoreTests.GemmaOpenRouterLiveTests": 0.0, @@ -567,7 +550,7 @@ "ProviderCoreTests.GemmaOptimizationReportingTests": 0.001, "ProviderCoreTests.GemmaQATCheckpointRestartLiveTests": 0.0, "ProviderCoreTests.GemmaToolCallLiveTests": 0.0, -"ProviderCoreTests.GemmaToolConstraintTests": 0.491, +"ProviderCoreTests.GemmaToolConstraintTests": 0.46, "ProviderCoreTests.GemmaVLMEngineV2LiveTests": 0.0, "ProviderCoreTests.GemmaVLMSharedTowerMemoryLiveTests": 0.0, "ProviderCoreTests.GemmaVLMVideoEngineV2LiveTests": 0.0, @@ -575,71 +558,68 @@ "ProviderCoreTests.GlobalKVCacheBudgetAuditTests": 0.003, "ProviderCoreTests.HardwareDetectorTests": 0.0, "ProviderCoreTests.HeartbeatClusterSessionTests": 0.001, -"ProviderCoreTests.HeartbeatIdlePolicyTests": 0.001, +"ProviderCoreTests.HeartbeatIdlePolicyTests": 0.0, "ProviderCoreTests.HuggingFaceDownloadTests": 0.068, -"ProviderCoreTests.IdleCalibrationCoordinatorTests": 0.06, +"ProviderCoreTests.IdleCalibrationCoordinatorTests": 0.067, "ProviderCoreTests.IdleTimeoutPolicyTests": 0.0, -"ProviderCoreTests.InboundChatRequestDecodeTests": 0.011, +"ProviderCoreTests.InboundChatRequestDecodeTests": 0.01, "ProviderCoreTests.InboundDecodeTests": 0.005, "ProviderCoreTests.InferenceLiveTests": 0.0, "ProviderCoreTests.InferenceRefusalLoggingTests": 0.073, -"ProviderCoreTests.InlineDeclarationProbeTests": 0.053, +"ProviderCoreTests.InlineDeclarationProbeTests": 0.06, "ProviderCoreTests.JinjaSanitizationLiveTests": 0.0, "ProviderCoreTests.JinjaSanitizationTests": 0.008, -"ProviderCoreTests.KVBackendGuardStoreTests": 0.007, +"ProviderCoreTests.KVBackendGuardStoreTests": 0.006, "ProviderCoreTests.KVCheckpointPostureTests": 0.0, -"ProviderCoreTests.KVPoolIdleSweepTests": 0.703, +"ProviderCoreTests.KVPoolIdleSweepTests": 0.118, "ProviderCoreTests.KVPoolReclaimerNativeGateTests": 0.001, -"ProviderCoreTests.KVPoolReclaimerTests": 0.009, -"ProviderCoreTests.KVPoolSweepWiringTests": 0.214, -"ProviderCoreTests.KVQuantizationConfigTests": 0.003, -"ProviderCoreTests.KernelTests": 1.622, +"ProviderCoreTests.KVPoolReclaimerTests": 0.011, +"ProviderCoreTests.KVPoolSweepWiringTests": 0.217, +"ProviderCoreTests.KVQuantizationConfigTests": 0.004, +"ProviderCoreTests.KernelTests": 1.616, "ProviderCoreTests.LaunchAgentDrainAllowanceTests": 0.001, "ProviderCoreTests.LaunchAgentDrainIntegrationTests": 0.0, -"ProviderCoreTests.LaunchAgentEnvironmentTests": 0.004, -"ProviderCoreTests.LaunchAgentLifecycleTests": 0.014, -"ProviderCoreTests.LaunchAgentPathsAndErrorsTests": 0.002, -"ProviderCoreTests.LaunchAgentRemovalTests": 0.022, +"ProviderCoreTests.LaunchAgentEnvironmentTests": 0.003, +"ProviderCoreTests.LaunchAgentLifecycleTests": 0.015, +"ProviderCoreTests.LaunchAgentPathsAndErrorsTests": 0.003, +"ProviderCoreTests.LaunchAgentRemovalTests": 0.023, "ProviderCoreTests.LaunchAgentRestartTests": 0.0, -"ProviderCoreTests.LaunchAgentServicePlistTests": 0.006, -"ProviderCoreTests.LaunchctlControlTests": 0.015, -"ProviderCoreTests.LifecycleMailboxTests": 0.033, -"ProviderCoreTests.LiveInferenceMetallibSourceTests": 0.025, -"ProviderCoreTests.LoadedModelsPersistenceWiringTests": 0.024, -"ProviderCoreTests.LoadedModelsStoreTests": 0.002, +"ProviderCoreTests.LaunchAgentServicePlistTests": 0.003, +"ProviderCoreTests.LifecycleMailboxTests": 0.032, +"ProviderCoreTests.LiveInferenceMetallibSourceTests": 0.018, +"ProviderCoreTests.LoadedModelsPersistenceWiringTests": 0.025, +"ProviderCoreTests.LoadedModelsStoreTests": 0.004, "ProviderCoreTests.LocalChatRequestTests": 0.006, -"ProviderCoreTests.LocalContentPartRefusalTests": 0.008, +"ProviderCoreTests.LocalContentPartRefusalTests": 0.006, "ProviderCoreTests.LocalDisconnectTests": 0.003, -"ProviderCoreTests.LocalDrainHTTPTests": 0.01, +"ProviderCoreTests.LocalDrainHTTPTests": 0.009, "ProviderCoreTests.LocalEndpointFileTests": 0.003, "ProviderCoreTests.LocalOpenAIObjectCompatibilityTests": 0.002, -"ProviderCoreTests.LocalOutputTokenLimitTests": 0.006, -"ProviderCoreTests.LocalResponseConversationTests": 0.015, -"ProviderCoreTests.LocalResponseTrackerTests": 0.017, +"ProviderCoreTests.LocalOutputTokenLimitTests": 0.005, +"ProviderCoreTests.LocalResponseConversationTests": 0.012, +"ProviderCoreTests.LocalResponseTrackerTests": 0.014, "ProviderCoreTests.LocalServingPostureTests": 0.001, "ProviderCoreTests.LocalStreamingFailureTests": 0.003, -"ProviderCoreTests.LocalTokenizerByteFallbackTests": 0.547, -"ProviderCoreTests.LocalTokenizerDecodeSpacingTests": 0.015, "ProviderCoreTests.MDMEnrollmentTests": 0.001, "ProviderCoreTests.MDMTrustDiagnosisTests": 0.001, "ProviderCoreTests.MLXMemoryGuardConfigureOnceTests": 0.001, "ProviderCoreTests.MTPAcceptanceConfigTests": 0.002, -"ProviderCoreTests.MTPBenchmarkTests": 0.169, +"ProviderCoreTests.MTPBenchmarkTests": 0.166, "ProviderCoreTests.MTPBetaFeatureTests": 0.0, "ProviderCoreTests.MTPConfigKeyTests": 0.004, "ProviderCoreTests.MTPIdleUpgradeTests": 0.001, -"ProviderCoreTests.MTPPostureTelemetryTests": 1.077, -"ProviderCoreTests.MTPResliceFallbackTests": 0.044, +"ProviderCoreTests.MTPPostureTelemetryTests": 1.117, +"ProviderCoreTests.MTPResliceFallbackTests": 0.097, "ProviderCoreTests.MTPStagingReservationsTests": 0.0, "ProviderCoreTests.MTPSupportedModelsTests": 0.0, -"ProviderCoreTests.MediaKindClassificationTests": 0.007, -"ProviderCoreTests.MediaToolMetadataTests": 0.001, -"ProviderCoreTests.MetallibHashTests": 0.008, +"ProviderCoreTests.MediaKindClassificationTests": 0.003, +"ProviderCoreTests.MediaToolMetadataTests": 0.002, +"ProviderCoreTests.MetallibHashTests": 0.009, "ProviderCoreTests.MiMoCompleteCheckpointIdentityTests": 0.002, -"ProviderCoreTests.MiMoImageHTTPIngressTests": 1.185, -"ProviderCoreTests.MiMoImageOnboardingSelectionTests": 0.13, -"ProviderCoreTests.MiMoInstalledEncryptedLinkPolicyTests": 0.298, -"ProviderCoreTests.MiMoInstalledImagePolicyTests": 0.226, +"ProviderCoreTests.MiMoImageHTTPIngressTests": 1.184, +"ProviderCoreTests.MiMoImageOnboardingSelectionTests": 0.112, +"ProviderCoreTests.MiMoInstalledEncryptedLinkPolicyTests": 0.289, +"ProviderCoreTests.MiMoInstalledImagePolicyTests": 0.218, "ProviderCoreTests.MiMoMediaDecodeMemoryTests": 0.818, "ProviderCoreTests.MiMoMemoryAdmissionTests": 0.001, "ProviderCoreTests.MiMoTestPrerequisitesTests": 0.001, @@ -676,168 +656,166 @@ "ProviderCoreTests.MiMoV26TemplateFixTests": 0.009, "ProviderCoreTests.MiMoV26WiredDeviceContextTests": 0.001, "ProviderCoreTests.MiMoV26WiredResidencyTests": 0.046, -"ProviderCoreTests.ModelArtifactPublicationTests": 0.026, -"ProviderCoreTests.ModelArtifactReceiptTests": 0.61, +"ProviderCoreTests.ModelArtifactPublicationTests": 0.024, +"ProviderCoreTests.ModelArtifactReceiptTests": 0.626, "ProviderCoreTests.ModelArtifactWriteLeaseTests": 0.003, "ProviderCoreTests.ModelAutopilotHistoryTests": 0.002, -"ProviderCoreTests.ModelAutopilotOperationOwnershipTests": 0.008, -"ProviderCoreTests.ModelAutopilotRuntimeTests": 0.314, -"ProviderCoreTests.ModelAutopilotShadowTests": 0.03, -"ProviderCoreTests.ModelAutopilotTests": 0.004, -"ProviderCoreTests.ModelAutopilotUnloadTests": 0.136, +"ProviderCoreTests.ModelAutopilotOperationOwnershipTests": 0.019, +"ProviderCoreTests.ModelAutopilotRuntimeTests": 0.32, +"ProviderCoreTests.ModelAutopilotShadowTests": 0.027, +"ProviderCoreTests.ModelAutopilotTests": 0.003, +"ProviderCoreTests.ModelAutopilotUnloadTests": 0.196, "ProviderCoreTests.ModelBenchmarkDispatchTests": 0.003, "ProviderCoreTests.ModelBenchmarkReportTests": 0.001, -"ProviderCoreTests.ModelCacheConfigurationTests": 0.004, +"ProviderCoreTests.ModelCacheConfigurationTests": 0.003, "ProviderCoreTests.ModelCalibrationPolicyTests": 0.001, -"ProviderCoreTests.ModelCalibrationTests": 6.25, -"ProviderCoreTests.ModelCatalogTests": 2.715, +"ProviderCoreTests.ModelCalibrationTests": 6.22, +"ProviderCoreTests.ModelCatalogTests": 2.472, "ProviderCoreTests.ModelCheckpointConversationLiveTests": 0.0, -"ProviderCoreTests.ModelCheckpointDonationControlTests": 0.004, -"ProviderCoreTests.ModelCheckpointObservationLifetimeTests": 0.097, +"ProviderCoreTests.ModelCheckpointDonationControlTests": 0.005, +"ProviderCoreTests.ModelCheckpointObservationLifetimeTests": 0.11, "ProviderCoreTests.ModelCheckpointRestoreContentionLiveTests": 0.0, "ProviderCoreTests.ModelCheckpointStorageLiveTests": 0.0, -"ProviderCoreTests.ModelCheckpointStorageSpecificationTests": 0.003, +"ProviderCoreTests.ModelCheckpointStorageSpecificationTests": 0.004, "ProviderCoreTests.ModelDownloadCacheTests": 0.006, -"ProviderCoreTests.ModelDownloadProgressDownloaderTests": 4.298, -"ProviderCoreTests.ModelDownloadProgressTests": 0.18, -"ProviderCoreTests.ModelLoadEvictionAndAdmissionTests": 0.559, -"ProviderCoreTests.ModelLoadRefusalTests": 0.131, -"ProviderCoreTests.ModelPrefetchCoordinatorTests": 0.337, -"ProviderCoreTests.ModelPrefetchDownloaderTests": 0.79, -"ProviderCoreTests.ModelPrefixBenchmarkAdjacentForkTests": 0.007, -"ProviderCoreTests.ModelPrefixBenchmarkCleanupTests": 0.002, +"ProviderCoreTests.ModelDownloadProgressDownloaderTests": 4.492, +"ProviderCoreTests.ModelDownloadProgressTests": 0.17, +"ProviderCoreTests.ModelLoadEvictionAndAdmissionTests": 1.106, +"ProviderCoreTests.ModelLoadRefusalTests": 0.121, +"ProviderCoreTests.ModelPrefetchCoordinatorTests": 0.272, +"ProviderCoreTests.ModelPrefetchDownloaderTests": 0.854, +"ProviderCoreTests.ModelPrefixBenchmarkAdjacentForkTests": 0.009, +"ProviderCoreTests.ModelPrefixBenchmarkCleanupTests": 0.001, "ProviderCoreTests.ModelPrefixBenchmarkDiagnosticsTests": 0.001, "ProviderCoreTests.ModelPrefixBenchmarkLiveTests": 0.0, -"ProviderCoreTests.ModelPrefixBenchmarkMTPObservationTests": 0.0, +"ProviderCoreTests.ModelPrefixBenchmarkMTPObservationTests": 0.002, "ProviderCoreTests.ModelPrefixBenchmarkOutputTimingTests": 0.0, -"ProviderCoreTests.ModelPrefixBenchmarkQuiescenceTimingTests": 0.002, +"ProviderCoreTests.ModelPrefixBenchmarkQuiescenceTimingTests": 0.001, "ProviderCoreTests.ModelPrefixBenchmarkTerminalTests": 0.001, "ProviderCoreTests.ModelRequirementLineTests": 0.001, -"ProviderCoreTests.ModelRevisionActivationTests": 0.055, -"ProviderCoreTests.ModelRevisionPreparationTests": 0.092, -"ProviderCoreTests.ModelRevisionPublicationTests": 0.063, -"ProviderCoreTests.ModelScannerArchitectureTests": 0.004, -"ProviderCoreTests.ModelScannerMemoryFilterTests": 0.006, -"ProviderCoreTests.ModelSelectionDownloadTests": 0.039, -"ProviderCoreTests.ModelSlotBookkeepingTests": 0.025, +"ProviderCoreTests.ModelRevisionActivationTests": 0.05, +"ProviderCoreTests.ModelRevisionPreparationTests": 0.091, +"ProviderCoreTests.ModelRevisionPublicationTests": 0.07, +"ProviderCoreTests.ModelScannerArchitectureTests": 0.005, +"ProviderCoreTests.ModelScannerMemoryFilterTests": 0.004, +"ProviderCoreTests.ModelSelectionDownloadTests": 0.031, +"ProviderCoreTests.ModelSlotBookkeepingTests": 0.031, "ProviderCoreTests.MultimodalErrorMappingTests": 0.0, -"ProviderCoreTests.NativeBlockRetirementBridgeTests": 0.114, -"ProviderCoreTests.NativeChannelSplitterTests": 0.016, -"ProviderCoreTests.NativeCheckpointQuantizationTests": 0.09, +"ProviderCoreTests.NativeBlockRetirementBridgeTests": 0.115, +"ProviderCoreTests.NativeChannelSplitterTests": 0.023, +"ProviderCoreTests.NativeCheckpointQuantizationTests": 0.093, "ProviderCoreTests.NativeDiffusionCheckpointKeysTests": 0.003, -"ProviderCoreTests.NativeDiffusionCheckpointStoreTests": 1.863, +"ProviderCoreTests.NativeDiffusionCheckpointStoreTests": 0.865, "ProviderCoreTests.NativeLocalConsumerOwnershipTests": 0.014, -"ProviderCoreTests.NativeMediaToolPreparationTests": 0.002, +"ProviderCoreTests.NativeMediaToolPreparationTests": 0.001, "ProviderCoreTests.NativeMediaToolsCapabilityTests": 0.001, "ProviderCoreTests.NativeMemoryReclamationTests": 0.0, "ProviderCoreTests.NativeMemoryRetirementWindowTests": 0.0, "ProviderCoreTests.NativeModelToolChoiceTests": 0.002, "ProviderCoreTests.NativeOutputControlRefusalTests": 0.0, -"ProviderCoreTests.NativePairMemberContractTests": 0.03, -"ProviderCoreTests.NativePairMemberControlTests": 0.186, +"ProviderCoreTests.NativePairMemberContractTests": 0.032, +"ProviderCoreTests.NativePairMemberControlTests": 0.178, "ProviderCoreTests.NativePairMemberInstallTests": 0.01, -"ProviderCoreTests.NativePairMemberInvocationTests": 1.088, -"ProviderCoreTests.NativePairMemberServingTests": 2.998, -"ProviderCoreTests.NativePairMessageTests": 0.002, -"ProviderCoreTests.NativePairSessionHeartbeatTests": 0.426, -"ProviderCoreTests.NativeServeQualificationTests": 0.004, +"ProviderCoreTests.NativePairMemberInvocationTests": 0.962, +"ProviderCoreTests.NativePairMemberServingTests": 2.897, +"ProviderCoreTests.NativePairMessageTests": 0.001, +"ProviderCoreTests.NativePairSessionHeartbeatTests": 0.394, +"ProviderCoreTests.NativeServeQualificationTests": 0.006, "ProviderCoreTests.NativeServeRunLifetimeTests": 0.004, "ProviderCoreTests.NativeToolCapabilityAdvertisementTests": 0.002, -"ProviderCoreTests.NativeToolStreamRouterTests": 0.018, +"ProviderCoreTests.NativeToolStreamRouterTests": 0.02, "ProviderCoreTests.NativeWorkerServeQualificationTests": 0.002, "ProviderCoreTests.Nemotron35ArchitectureTests": 0.001, -"ProviderCoreTests.NemotronDemandedShortCheckpointTests": 0.038, +"ProviderCoreTests.NemotronDemandedShortCheckpointTests": 0.029, "ProviderCoreTests.NemotronMTPDeclarationTests": 0.0, -"ProviderCoreTests.NemotronPagingPrefixIntegrationTests": 16.923, -"ProviderCoreTests.NemotronStandaloneAdmissionTests": 0.011, -"ProviderCoreTests.NemotronSuperDurablePrefixCacheTests": 6.67, -"ProviderCoreTests.NemotronSuperImageDecodeTests": 1.292, -"ProviderCoreTests.NemotronSuperImageFormatHTTPTests": 10.289, -"ProviderCoreTests.NemotronSuperImageGoldenTests": 17.305, +"ProviderCoreTests.NemotronPagingPrefixIntegrationTests": 15.772, +"ProviderCoreTests.NemotronStandaloneAdmissionTests": 0.01, +"ProviderCoreTests.NemotronSuperDurablePrefixCacheTests": 5.702, +"ProviderCoreTests.NemotronSuperImageDecodeTests": 1.258, +"ProviderCoreTests.NemotronSuperImageFormatHTTPTests": 7.671, +"ProviderCoreTests.NemotronSuperImageGoldenTests": 16.983, "ProviderCoreTests.NemotronSuperImageHTTPRelayTests": 0.001, -"ProviderCoreTests.NemotronSuperImagePlanTests": 2.385, -"ProviderCoreTests.NemotronSuperJPEGContainerTests": 0.018, +"ProviderCoreTests.NemotronSuperImagePlanTests": 1.13, +"ProviderCoreTests.NemotronSuperJPEGContainerTests": 0.012, "ProviderCoreTests.NemotronSuperLoadAdmissionTests": 0.002, -"ProviderCoreTests.NemotronSuperLocalBindingTests": 4.099, -"ProviderCoreTests.NemotronSuperLocalHTTPAdmissionTests": 5.767, -"ProviderCoreTests.NemotronSuperLocalHTTPTests": 5.576, -"ProviderCoreTests.NemotronSuperLocalImageBindingTests": 4.548, -"ProviderCoreTests.NemotronSuperLocalMTPBatchedTests": 5.29, -"ProviderCoreTests.NemotronSuperLocalMTPTests": 9.016, +"ProviderCoreTests.NemotronSuperLocalBindingTests": 3.053, +"ProviderCoreTests.NemotronSuperLocalHTTPAdmissionTests": 7.535, +"ProviderCoreTests.NemotronSuperLocalHTTPTests": 3.352, +"ProviderCoreTests.NemotronSuperLocalImageBindingTests": 0.664, +"ProviderCoreTests.NemotronSuperLocalMTPBatchedTests": 5.659, +"ProviderCoreTests.NemotronSuperLocalMTPTests": 6.49, "ProviderCoreTests.NemotronSuperLocalOutputTests": 0.055, -"ProviderCoreTests.NemotronSuperLocalOwnerTests": 0.883, -"ProviderCoreTests.NemotronSuperLocalPagedTests": 2.662, -"ProviderCoreTests.NemotronSuperLocalPrefillTests": 3.095, -"ProviderCoreTests.NemotronSuperLocalPrefixCacheTests": 4.145, +"ProviderCoreTests.NemotronSuperLocalOwnerTests": 1.325, +"ProviderCoreTests.NemotronSuperLocalPagedTests": 2.634, +"ProviderCoreTests.NemotronSuperLocalPrefillTests": 3.447, +"ProviderCoreTests.NemotronSuperLocalPrefixCacheTests": 5.213, "ProviderCoreTests.NemotronSuperLongContextLiveTests": 0.0, -"ProviderCoreTests.NemotronSuperLongContextTests": 0.124, -"ProviderCoreTests.NemotronSuperManagedSlotTests": 26.522, -"ProviderCoreTests.NemotronSuperMediaChargeTests": 1.526, +"ProviderCoreTests.NemotronSuperLongContextTests": 0.581, +"ProviderCoreTests.NemotronSuperManagedSlotTests": 26.678, +"ProviderCoreTests.NemotronSuperMediaChargeTests": 1.521, "ProviderCoreTests.NemotronSuperMemoryLiveTests": 0.0, -"ProviderCoreTests.NemotronSuperOpenRouterCapabilityTests": 0.529, -"ProviderCoreTests.NemotronSuperOpenRouterVideoTests": 52.283, -"ProviderCoreTests.NemotronSuperPNGTextTests": 0.057, +"ProviderCoreTests.NemotronSuperOpenRouterCapabilityTests": 0.477, +"ProviderCoreTests.NemotronSuperOpenRouterVideoTests": 51.872, +"ProviderCoreTests.NemotronSuperPNGTextTests": 0.058, "ProviderCoreTests.NemotronSuperPagedLiveTests": 0.0, -"ProviderCoreTests.NemotronSuperPrefixCacheEvidenceTests": 1.288, +"ProviderCoreTests.NemotronSuperPrefixCacheEvidenceTests": 1.091, "ProviderCoreTests.NemotronSuperPromptContractTests": 0.433, "ProviderCoreTests.NemotronSuperPromptGoldenTests": 0.651, "ProviderCoreTests.NemotronSuperRecurrentAdmissionTests": 0.001, -"ProviderCoreTests.NemotronSuperServingPolicyTests": 0.263, -"ProviderCoreTests.NemotronSuperVideoBindingTests": 10.324, -"ProviderCoreTests.NemotronSuperVideoDecodeTests": 2.507, -"ProviderCoreTests.NemotronSuperVideoGoldenTests": 8.201, +"ProviderCoreTests.NemotronSuperServingPolicyTests": 0.258, +"ProviderCoreTests.NemotronSuperVideoBindingTests": 10.119, +"ProviderCoreTests.NemotronSuperVideoDecodeTests": 2.353, +"ProviderCoreTests.NemotronSuperVideoGoldenTests": 8.707, "ProviderCoreTests.NemotronTemplateParityLiveTests": 0.001, -"ProviderCoreTests.NetworkFrameworkCloseCodeTests": 0.011, -"ProviderCoreTests.ObservedRateDeadlineAdmissionTests": 0.006, -"ProviderCoreTests.OperatorModelFilterTests": 2.713, -"ProviderCoreTests.OuterPrefixCacheReceiptTests": 0.003, -"ProviderCoreTests.PackagedRetainedGemmaSmokeTests": 0.002, -"ProviderCoreTests.PagedFootprintTelemetryTests": 0.002, -"ProviderCoreTests.PagedKernelPreflightTests": 4.4, +"ProviderCoreTests.NetworkFrameworkCloseCodeTests": 0.012, +"ProviderCoreTests.ObservedRateDeadlineAdmissionTests": 0.009, +"ProviderCoreTests.OuterPrefixCacheReceiptTests": 0.005, +"ProviderCoreTests.PackagedRetainedGemmaSmokeTests": 0.001, +"ProviderCoreTests.PagedFootprintTelemetryTests": 0.001, +"ProviderCoreTests.PagedKernelPreflightTests": 4.99, "ProviderCoreTests.PagedStorageTelemetryTests": 0.001, "ProviderCoreTests.PagedTeacherForcedAgreementTests": 0.0, "ProviderCoreTests.PerformanceHeartbeatMaterialityTests": 0.0, "ProviderCoreTests.PersistentEnclaveKeyErrorTests": 0.0, -"ProviderCoreTests.PlannedProviderDisconnectTests": 2.53, +"ProviderCoreTests.PlannedProviderDisconnectTests": 2.407, "ProviderCoreTests.PrefillDeadlineProductionConfigTests": 0.005, "ProviderCoreTests.PrefillEvidenceRecoveryStateTests": 0.0, -"ProviderCoreTests.PrefillEvidenceRecoveryTests": 0.649, -"ProviderCoreTests.PrefixCacheCheckpointIdentityTests": 0.014, +"ProviderCoreTests.PrefillEvidenceRecoveryTests": 0.669, +"ProviderCoreTests.PrefixCacheCheckpointIdentityTests": 0.016, "ProviderCoreTests.PrefixCacheDiagnosisTests": 0.0, -"ProviderCoreTests.PrefixCacheEvidenceSequencerTests": 0.034, -"ProviderCoreTests.PrefixCacheLoadHashTests": 0.016, -"ProviderCoreTests.PrefixCachePolicyTests": 0.006, -"ProviderCoreTests.PrefixCacheReceiptTests": 0.056, -"ProviderCoreTests.ProcessExitObserverTests": 2.011, +"ProviderCoreTests.PrefixCacheEvidenceSequencerTests": 0.029, +"ProviderCoreTests.PrefixCacheLoadHashTests": 0.018, +"ProviderCoreTests.PrefixCachePolicyTests": 0.007, +"ProviderCoreTests.PrefixCacheReceiptTests": 0.064, "ProviderCoreTests.ProcessLifecycleTests": 0.008, "ProviderCoreTests.ProcessMemoryNativeIntegrationTests": 0.719, "ProviderCoreTests.ProcessMemoryTelemetryTests": 0.001, -"ProviderCoreTests.ProductionModelCalibrationTests": 51.477, +"ProviderCoreTests.ProductionModelCalibrationTests": 51.267, "ProviderCoreTests.ProductionPromptParityTests": 0.0, -"ProviderCoreTests.PromptDateRenderingTests": 0.006, -"ProviderCoreTests.PromptTokenCacheTests": 1.107, -"ProviderCoreTests.ProviderAuthorizationConnectionTests": 0.007, +"ProviderCoreTests.PromptDateRenderingTests": 0.003, +"ProviderCoreTests.PromptTokenCacheTests": 1.088, +"ProviderCoreTests.ProviderAuthorizationConnectionTests": 0.004, "ProviderCoreTests.ProviderAuthorizationProtocolTests": 0.001, -"ProviderCoreTests.ProviderAuthorizationReadinessTests": 0.004, +"ProviderCoreTests.ProviderAuthorizationReadinessTests": 0.003, "ProviderCoreTests.ProviderAutoRestartConfigTests": 0.001, "ProviderCoreTests.ProviderBusyWireTests": 0.002, -"ProviderCoreTests.ProviderCancelledPrefixCacheTests": 0.279, +"ProviderCoreTests.ProviderCancelledPrefixCacheTests": 0.282, "ProviderCoreTests.ProviderCapabilityLabelsTests": 0.0, -"ProviderCoreTests.ProviderConfigParseGrowthTests": 0.006, +"ProviderCoreTests.ProviderConfigParseGrowthTests": 0.007, "ProviderCoreTests.ProviderLaunchSnapshotTests": 0.0, -"ProviderCoreTests.ProviderLifecycleTests": 2.445, -"ProviderCoreTests.ProviderLogoutTests": 0.8, -"ProviderCoreTests.ProviderLoopCalibrationTests": 2.998, -"ProviderCoreTests.ProviderLoopMTPUpgradeTests": 0.135, +"ProviderCoreTests.ProviderLifecycleTests": 2.447, +"ProviderCoreTests.ProviderLogoutTests": 0.773, +"ProviderCoreTests.ProviderLoopCalibrationTests": 3.038, +"ProviderCoreTests.ProviderLoopMTPUpgradeTests": 0.144, "ProviderCoreTests.ProviderLoopNativeMiMoLifetimeTests": 1.618, -"ProviderCoreTests.ProviderLoopPrefetchTests": 0.887, -"ProviderCoreTests.ProviderMTPFactoryTests": 0.031, -"ProviderCoreTests.ProviderModelSwitchTests": 1.563, -"ProviderCoreTests.ProviderRunMarkerTests": 0.016, +"ProviderCoreTests.ProviderLoopPrefetchTests": 0.864, +"ProviderCoreTests.ProviderMTPFactoryTests": 0.027, +"ProviderCoreTests.ProviderModelSwitchTests": 1.689, +"ProviderCoreTests.ProviderRunMarkerTests": 0.015, "ProviderCoreTests.ProviderRuntimeCapabilityTests": 0.006, -"ProviderCoreTests.ProviderSignalTests": 3.045, +"ProviderCoreTests.ProviderSignalTests": 3.083, "ProviderCoreTests.ProviderStopSignalsTests": 0.0, -"ProviderCoreTests.QMVWideMetalTests": 0.999, +"ProviderCoreTests.QMVWideMetalTests": 0.996, "ProviderCoreTests.Qwen35AdjacentCheckpointLiveTests": 0.0, "ProviderCoreTests.Qwen35CBv2FixedRequestAccountingTests": 0.001, "ProviderCoreTests.Qwen35CheckpointRetentionLiveTests": 0.0, @@ -847,220 +825,217 @@ "ProviderCoreTests.Qwen38ProductionCanaryTests": 0.0, "ProviderCoreTests.Qwen4CanonicalMediaPositionsTests": 0.002, "ProviderCoreTests.Qwen4DefaultProfilePerformanceTests": 0.001, -"ProviderCoreTests.Qwen4EmbeddedMTPTests": 0.01, +"ProviderCoreTests.Qwen4EmbeddedMTPTests": 0.013, "ProviderCoreTests.Qwen4ExecutionPolicyTests": 0.0, -"ProviderCoreTests.Qwen4ExpLoadFootprintTests": 0.017, -"ProviderCoreTests.Qwen4ExpMmapFootprintTests": 0.011, -"ProviderCoreTests.Qwen4FactorySelectionTests": 0.004, +"ProviderCoreTests.Qwen4ExpLoadFootprintTests": 0.009, +"ProviderCoreTests.Qwen4ExpMmapFootprintTests": 0.015, +"ProviderCoreTests.Qwen4FactorySelectionTests": 0.002, "ProviderCoreTests.Qwen4FixedDepthPerformanceProbeTests": 0.001, "ProviderCoreTests.Qwen4LayerSubmissionSafetyProbeTests": 0.001, "ProviderCoreTests.Qwen4LayerSubmissionStateProbeTests": 0.0, -"ProviderCoreTests.Qwen4NativeMediaPrefixPositionsTests": 0.247, +"ProviderCoreTests.Qwen4NativeMediaPrefixPositionsTests": 0.272, "ProviderCoreTests.Qwen4NativeToolConstraintTests": 0.005, -"ProviderCoreTests.Qwen4OwnedVLMRoutingTests": 0.006, -"ProviderCoreTests.Qwen4PagingPrefixIntegrationTests": 18.251, +"ProviderCoreTests.Qwen4OwnedVLMRoutingTests": 0.008, +"ProviderCoreTests.Qwen4PagingPrefixIntegrationTests": 18.933, "ProviderCoreTests.Qwen4ReasoningControlTests": 0.0, -"ProviderCoreTests.Qwen4ReasoningEffortValidationTests": 0.003, -"ProviderCoreTests.Qwen4ReclaimAdmissionTests": 0.164, +"ProviderCoreTests.Qwen4ReasoningEffortValidationTests": 0.004, +"ProviderCoreTests.Qwen4ReclaimAdmissionTests": 0.133, "ProviderCoreTests.Qwen4SparseParallelProbeTests": 0.001, -"ProviderCoreTests.Qwen4StandaloneAdmissionTests": 0.054, -"ProviderCoreTests.Qwen4SupportPolicyTests": 0.009, +"ProviderCoreTests.Qwen4StandaloneAdmissionTests": 0.027, +"ProviderCoreTests.Qwen4SupportPolicyTests": 0.01, "ProviderCoreTests.Qwen4ToolChoicePromptPolicyTests": 0.002, "ProviderCoreTests.Qwen4ToolFramingVocabularyTests": 0.002, -"ProviderCoreTests.QwenJSONAnswerConstraintTests": 3.918, -"ProviderCoreTests.QwenJSONAnswerOutputTests": 0.004, -"ProviderCoreTests.QwenJSONAnswerPolicyTests": 0.547, +"ProviderCoreTests.QwenJSONAnswerConstraintTests": 4.233, +"ProviderCoreTests.QwenJSONAnswerOutputTests": 0.003, +"ProviderCoreTests.QwenJSONAnswerPolicyTests": 0.606, "ProviderCoreTests.QwenJSONAnswerRealTokenizerTests": 0.0, -"ProviderCoreTests.QwenJSONAnswerServingTests": 0.549, +"ProviderCoreTests.QwenJSONAnswerServingTests": 0.555, "ProviderCoreTests.QwenPerImageVisionEquivalenceTests": 0.0, -"ProviderCoreTests.QwenVLMTargetExtractionTests": 3.011, +"ProviderCoreTests.QwenVLMTargetExtractionTests": 2.747, "ProviderCoreTests.ReasoningEffortLiveTests": 0.0, "ProviderCoreTests.ReasoningParserSelectionTests": 0.0, "ProviderCoreTests.ReasoningPromptProbeTests": 0.003, -"ProviderCoreTests.ReasoningStopScopeTests": 0.001, "ProviderCoreTests.ReleaseCoResidencyLiveTests": 0.0, "ProviderCoreTests.RequestProfileBuilderTests": 0.046, -"ProviderCoreTests.ReserveRaisePreflightTests": 1.093, -"ProviderCoreTests.ResidentPrefixCacheEvidenceTests": 0.026, +"ProviderCoreTests.ReserveRaisePreflightTests": 1.089, +"ProviderCoreTests.ResidentPrefixCacheEvidenceTests": 0.02, "ProviderCoreTests.RetirementGateTests": 0.001, -"ProviderCoreTests.RuntimeConcurrencyBenchmarkTests": 0.049, -"ProviderCoreTests.RuntimeGenerationBenchmarkTests": 0.003, -"ProviderCoreTests.RuntimeMetallibTemporaryDirectoryTests": 0.003, +"ProviderCoreTests.RuntimeConcurrencyBenchmarkTests": 0.053, +"ProviderCoreTests.RuntimeGenerationBenchmarkTests": 0.002, +"ProviderCoreTests.RuntimeMetallibTemporaryDirectoryTests": 0.004, "ProviderCoreTests.SDPAPartialPrecisionTests": 1.324, -"ProviderCoreTests.SSDBlockIndexTests": 0.798, -"ProviderCoreTests.SSDBlockStoreTests": 0.065, -"ProviderCoreTests.SSDBlockStreamingTests": 0.024, -"ProviderCoreTests.SSDCacheEpochStoreRecoveryTests": 0.292, -"ProviderCoreTests.SSDCacheEpochStoreTests": 0.307, -"ProviderCoreTests.SSDCheckpointCPUAcceptanceTests": 0.319, -"ProviderCoreTests.SSDCheckpointCommitRetirementTests": 0.046, -"ProviderCoreTests.SSDCheckpointDeltaTests": 0.502, -"ProviderCoreTests.SSDCheckpointDemandAdmissionTests": 0.045, +"ProviderCoreTests.SSDBlockIndexTests": 0.763, +"ProviderCoreTests.SSDBlockStoreTests": 0.063, +"ProviderCoreTests.SSDBlockStreamingTests": 0.027, +"ProviderCoreTests.SSDCacheEpochStoreRecoveryTests": 0.289, +"ProviderCoreTests.SSDCacheEpochStoreTests": 0.309, +"ProviderCoreTests.SSDCheckpointCPUAcceptanceTests": 0.314, +"ProviderCoreTests.SSDCheckpointCommitRetirementTests": 0.044, +"ProviderCoreTests.SSDCheckpointDeltaTests": 0.504, +"ProviderCoreTests.SSDCheckpointDemandAdmissionTests": 0.04, "ProviderCoreTests.SSDCheckpointDemandTests": 0.011, "ProviderCoreTests.SSDCheckpointDonationHashBenchmarkTests": 0.0, -"ProviderCoreTests.SSDCheckpointDonationHashTests": 0.02, +"ProviderCoreTests.SSDCheckpointDonationHashTests": 0.019, "ProviderCoreTests.SSDCheckpointFileCoordinatorPathTests": 0.004, -"ProviderCoreTests.SSDCheckpointFileCoordinatorTests": 0.196, -"ProviderCoreTests.SSDCheckpointFleetWritePriorityTests": 0.116, +"ProviderCoreTests.SSDCheckpointFileCoordinatorTests": 0.194, +"ProviderCoreTests.SSDCheckpointFleetWritePriorityTests": 0.113, "ProviderCoreTests.SSDCheckpointLookupTests": 0.0, -"ProviderCoreTests.SSDCheckpointMaintenanceEpochTests": 0.067, -"ProviderCoreTests.SSDCheckpointPublicationCPUTests": 0.016, +"ProviderCoreTests.SSDCheckpointMaintenanceEpochTests": 0.058, +"ProviderCoreTests.SSDCheckpointPublicationCPUTests": 0.015, "ProviderCoreTests.SSDCheckpointPublicationTests": 0.015, -"ProviderCoreTests.SSDCheckpointReadBudgetTests": 0.005, -"ProviderCoreTests.SSDCheckpointRecencyCoordinationTests": 0.012, -"ProviderCoreTests.SSDCheckpointRemovalRaceTests": 0.17, -"ProviderCoreTests.SSDCheckpointStageCostTests": 0.029, -"ProviderCoreTests.SSDCheckpointStageReservationTests": 0.005, -"ProviderCoreTests.SSDCheckpointWriteRecoveryTests": 0.159, -"ProviderCoreTests.SSDClosedStoreEvictionTests": 1.33, +"ProviderCoreTests.SSDCheckpointReadBudgetTests": 0.006, +"ProviderCoreTests.SSDCheckpointRecencyCoordinationTests": 0.013, +"ProviderCoreTests.SSDCheckpointRemovalRaceTests": 0.162, +"ProviderCoreTests.SSDCheckpointStageCostTests": 0.025, +"ProviderCoreTests.SSDCheckpointStageReservationTests": 0.007, +"ProviderCoreTests.SSDCheckpointWriteRecoveryTests": 0.148, +"ProviderCoreTests.SSDClosedStoreEvictionTests": 1.257, "ProviderCoreTests.SSDCompleteCheckpointStageCapTests": 0.001, -"ProviderCoreTests.SSDCompleteDonationTelemetryTests": 0.031, -"ProviderCoreTests.SSDDebugCacheKeyFileTests": 0.042, +"ProviderCoreTests.SSDCompleteDonationTelemetryTests": 0.033, +"ProviderCoreTests.SSDDebugCacheKeyFileTests": 0.035, "ProviderCoreTests.SSDEpochContinuityTests": 0.061, -"ProviderCoreTests.SSDHybridCheckpointCoordinationTests": 0.125, -"ProviderCoreTests.SSDHybridCheckpointDuplicateTests": 0.163, -"ProviderCoreTests.SSDHybridCheckpointRecencyTests": 0.075, -"ProviderCoreTests.SSDHybridCheckpointStoreFactoryFailureTests": 0.017, -"ProviderCoreTests.SSDHybridCheckpointStoreTests": 0.124, -"ProviderCoreTests.SSDHybridMediaIdentityTests": 0.011, +"ProviderCoreTests.SSDHybridCheckpointCoordinationTests": 0.123, +"ProviderCoreTests.SSDHybridCheckpointDuplicateTests": 0.16, +"ProviderCoreTests.SSDHybridCheckpointRecencyTests": 0.071, +"ProviderCoreTests.SSDHybridCheckpointStoreFactoryFailureTests": 0.02, +"ProviderCoreTests.SSDHybridCheckpointStoreTests": 0.119, +"ProviderCoreTests.SSDHybridMediaIdentityTests": 0.014, "ProviderCoreTests.SSDLookupKeysTests": 0.0, "ProviderCoreTests.SSDNativeCheckpointOracleTests": 1.07, "ProviderCoreTests.SSDNativePrefixBuilderTests": 0.014, -"ProviderCoreTests.SSDNoFollowIOSpecialFileTests": 0.5, -"ProviderCoreTests.SSDOwnedEntryRetirementTests": 0.111, +"ProviderCoreTests.SSDNoFollowIOSpecialFileTests": 0.495, +"ProviderCoreTests.SSDOwnedEntryRetirementTests": 0.112, "ProviderCoreTests.SSDPersistentTestKeyNamespaceTests": 0.007, -"ProviderCoreTests.SSDPrefixCacheDonationGateTests": 0.622, -"ProviderCoreTests.SSDPrefixCacheDonationOutcomeTests": 0.054, +"ProviderCoreTests.SSDPrefixCacheDonationGateTests": 0.48, +"ProviderCoreTests.SSDPrefixCacheDonationOutcomeTests": 0.053, "ProviderCoreTests.SSDPrefixCacheFactoryConstructionTests": 0.059, -"ProviderCoreTests.SSDPrefixCacheFactoryMaintenanceTests": 0.023, +"ProviderCoreTests.SSDPrefixCacheFactoryMaintenanceTests": 0.024, "ProviderCoreTests.SSDPrefixCacheFactoryPathTests": 0.001, -"ProviderCoreTests.SSDPrefixCacheFactoryRefusalTests": 0.002, -"ProviderCoreTests.SSDPrefixCacheLifecycleTests": 1.961, +"ProviderCoreTests.SSDPrefixCacheFactoryRefusalTests": 0.003, +"ProviderCoreTests.SSDPrefixCacheLifecycleTests": 1.681, "ProviderCoreTests.SSDPrefixCacheMetadataPlanningTests": 0.002, "ProviderCoreTests.SSDPrefixCacheModeTests": 0.001, -"ProviderCoreTests.SSDPrefixCacheReadyReceiptTests": 0.266, -"ProviderCoreTests.SSDPrefixCacheReservationTests": 0.787, -"ProviderCoreTests.SSDPrefixCacheTelemetryTests": 0.005, -"ProviderCoreTests.SSDReadyWriteBarrierTests": 0.054, +"ProviderCoreTests.SSDPrefixCacheReadyReceiptTests": 0.21, +"ProviderCoreTests.SSDPrefixCacheReservationTests": 0.799, +"ProviderCoreTests.SSDPrefixCacheTelemetryTests": 0.004, +"ProviderCoreTests.SSDReadyWriteBarrierTests": 0.056, "ProviderCoreTests.SSDRootIsolationTests": 0.0, -"ProviderCoreTests.SSDSharedProcessCheckpointTests": 0.053, -"ProviderCoreTests.SSDShorterCheckpointRestoreTests": 0.827, +"ProviderCoreTests.SSDSharedProcessCheckpointTests": 0.048, +"ProviderCoreTests.SSDShorterCheckpointRestoreTests": 0.832, "ProviderCoreTests.SSDShorterNativeBlockRestoreTests": 2.004, -"ProviderCoreTests.SSDShorterRestoreClockTests": 0.052, -"ProviderCoreTests.SSDTestDirectoryTests": 0.001, -"ProviderCoreTests.SSDTrackedNativeRetryTests": 0.013, -"ProviderCoreTests.SSDWholeRootMaintenanceTests": 0.14, -"ProviderCoreTests.SSDWholeRootTelemetryConcurrencyTests": 0.007, -"ProviderCoreTests.SSDWindowSidecarTests": 0.833, -"ProviderCoreTests.SSDWriteBehindLedgerChargeTests": 0.113, -"ProviderCoreTests.SSDWriteBudgetTests": 0.255, -"ProviderCoreTests.SSDWriteEnduranceTests": 1.93, -"ProviderCoreTests.ScheduleTests": 0.01, +"ProviderCoreTests.SSDShorterRestoreClockTests": 0.047, +"ProviderCoreTests.SSDTestDirectoryTests": 0.002, +"ProviderCoreTests.SSDTrackedNativeRetryTests": 0.015, +"ProviderCoreTests.SSDWholeRootMaintenanceTests": 0.283, +"ProviderCoreTests.SSDWholeRootTelemetryConcurrencyTests": 0.012, +"ProviderCoreTests.SSDWindowSidecarTests": 0.796, +"ProviderCoreTests.SSDWriteBehindLedgerChargeTests": 0.121, +"ProviderCoreTests.SSDWriteBudgetTests": 0.278, +"ProviderCoreTests.SSDWriteEnduranceTests": 1.874, +"ProviderCoreTests.ScheduleTests": 0.009, "ProviderCoreTests.SchedulerPrefillBenchmarkTests": 0.0, -"ProviderCoreTests.SchedulerPrefillDecisionBenchmarkTests": 0.063, +"ProviderCoreTests.SchedulerPrefillDecisionBenchmarkTests": 0.06, "ProviderCoreTests.SchedulerPrefillDecisionEvaluatorTests": 0.14, "ProviderCoreTests.SchedulerPrefillDecisionKVProvenanceTests": 0.001, -"ProviderCoreTests.SchedulerPrefillDecisionLiveRunnerTests": 0.091, +"ProviderCoreTests.SchedulerPrefillDecisionLiveRunnerTests": 0.095, "ProviderCoreTests.SchedulerPrefillDecisionLiveTests": 0.0, -"ProviderCoreTests.SchedulerPrefillDecisionMetadataTests": 0.1, -"ProviderCoreTests.SchedulerPrefillPromptTests": 0.004, -"ProviderCoreTests.SecurityCommandRunnerTests": 0.226, -"ProviderCoreTests.SegmentedProductionGrantTests": 0.036, +"ProviderCoreTests.SchedulerPrefillDecisionMetadataTests": 0.186, +"ProviderCoreTests.SchedulerPrefillPromptTests": 0.003, +"ProviderCoreTests.SecurityCommandRunnerTests": 0.229, +"ProviderCoreTests.SegmentedProductionGrantTests": 0.032, "ProviderCoreTests.SelfUpdaterInstallRootTests": 0.002, -"ProviderCoreTests.SelfUpdaterTests": 40.269, -"ProviderCoreTests.SequenceStateMachineTests": 0.001, +"ProviderCoreTests.SelfUpdaterTests": 41.12, +"ProviderCoreTests.SequenceStateMachineTests": 0.0, "ProviderCoreTests.ServeLoopAppAttestInteropTests": 0.0, -"ProviderCoreTests.ServeLoopAppAttestTests": 2.179, -"ProviderCoreTests.ServeLoopColdLoadTests": 2.603, -"ProviderCoreTests.ServeLoopConnectionTests": 7.033, -"ProviderCoreTests.ServeLoopDispatchTests": 1.445, -"ProviderCoreTests.ServiceReservationHandlerTests": 0.006, -"ProviderCoreTests.ServiceReservationInboundTests": 0.002, +"ProviderCoreTests.ServeLoopAppAttestTests": 2.151, +"ProviderCoreTests.ServeLoopColdLoadTests": 2.788, +"ProviderCoreTests.ServeLoopConnectionTests": 6.565, +"ProviderCoreTests.ServeLoopDispatchTests": 1.483, +"ProviderCoreTests.ServiceReservationHandlerTests": 0.007, +"ProviderCoreTests.ServiceReservationInboundTests": 0.003, "ProviderCoreTests.ServiceReservationLifetimeTests": 0.001, "ProviderCoreTests.ServiceReservationRequestProtocolTests": 0.0, -"ProviderCoreTests.ServingReadinessTests": 0.007, -"ProviderCoreTests.SignedReleaseIdentityTests": 0.002, +"ProviderCoreTests.ServingReadinessTests": 0.006, +"ProviderCoreTests.SignedReleaseIdentityTests": 0.003, "ProviderCoreTests.SingleProbeInlineDecisionTests": 0.001, "ProviderCoreTests.SlotSizingDriftTests": 0.002, -"ProviderCoreTests.SpecDecArtifactFunnelTests": 0.063, +"ProviderCoreTests.SpecDecArtifactFunnelTests": 0.05, "ProviderCoreTests.SpecDecHuggingFaceTests": 3.213, "ProviderCoreTests.SpecDecLoadGateTests": 0.001, -"ProviderCoreTests.SpecDecResolverTests": 5.394, -"ProviderCoreTests.SpecDecSizingSnapshotTests": 0.002, +"ProviderCoreTests.SpecDecResolverTests": 5.566, +"ProviderCoreTests.SpecDecSizingSnapshotTests": 0.001, "ProviderCoreTests.SpecDecSlotTeardownTests": 0.005, -"ProviderCoreTests.StandaloneEvictionOwnershipTests": 0.007, -"ProviderCoreTests.StandaloneLifecycleControlTests": 0.771, -"ProviderCoreTests.StandaloneMTPUpgradeTests": 0.146, -"ProviderCoreTests.StandaloneServerDrainTests": 0.731, -"ProviderCoreTests.StandaloneServerModelAdmissionTests": 2.049, +"ProviderCoreTests.StandaloneEvictionOwnershipTests": 0.004, +"ProviderCoreTests.StandaloneLifecycleControlTests": 0.806, +"ProviderCoreTests.StandaloneMTPUpgradeTests": 0.14, +"ProviderCoreTests.StandaloneServerDrainTests": 0.695, +"ProviderCoreTests.StandaloneServerModelAdmissionTests": 2.043, "ProviderCoreTests.StartupPerformanceEvidenceTests": 0.004, -"ProviderCoreTests.StartupPreloadGateTests": 1.203, -"ProviderCoreTests.StartupPreloadNoEvictTests": 0.04, -"ProviderCoreTests.StartupPreloadPlanTests": 0.025, -"ProviderCoreTests.StartupPreloadPostRegistrationRetirementTests": 1.011, +"ProviderCoreTests.StartupPreloadGateTests": 1.292, +"ProviderCoreTests.StartupPreloadNoEvictTests": 0.042, +"ProviderCoreTests.StartupPreloadPlanTests": 0.036, +"ProviderCoreTests.StartupPreloadPostRegistrationRetirementTests": 0.734, "ProviderCoreTests.StartupPreloaderTests": 0.003, "ProviderCoreTests.StartupSelfTestDecodeLiveTests": 0.0, -"ProviderCoreTests.StreamedToolCallTests": 0.032, -"ProviderCoreTests.StreamingFileDownloadDelegateTests": 0.024, -"ProviderCoreTests.StructuredForcedToolAdmissionTests": 0.048, -"ProviderCoreTests.SwiftJinjaCompatibilityTests": 0.004, -"ProviderCoreTests.SwiftJinjaLoopContextTests": 0.007, -"ProviderCoreTests.TeacherForcedBenchmarkTests": 0.007, +"ProviderCoreTests.StreamedToolCallTests": 0.034, +"ProviderCoreTests.StreamingFileDownloadDelegateTests": 0.023, +"ProviderCoreTests.StructuredForcedToolAdmissionTests": 0.044, +"ProviderCoreTests.SwiftJinjaCompatibilityTests": 0.008, +"ProviderCoreTests.SwiftJinjaLoopContextTests": 0.005, +"ProviderCoreTests.TeacherForcedBenchmarkTests": 0.004, "ProviderCoreTests.TelemetryClientTests": 0.0, -"ProviderCoreTests.TelemetryOverflowQueueTests": 0.002, +"ProviderCoreTests.TelemetryOverflowQueueTests": 0.004, "ProviderCoreTests.TelemetrySymmetryTests": 0.001, "ProviderCoreTests.ThinkStreamingLatencyTests": 0.001, -"ProviderCoreTests.ThroughputSweepDecodeTimingTests": 0.002, -"ProviderCoreTests.ThroughputSweepDecodeWarmupTests": 0.001, -"ProviderCoreTests.ThroughputSweepMedianTests": 0.003, -"ProviderCoreTests.ThroughputSweepNotesTests": 0.009, -"ProviderCoreTests.ThroughputSweepReportTests": 0.003, +"ProviderCoreTests.ThroughputSweepDecodeTimingTests": 0.001, +"ProviderCoreTests.ThroughputSweepDecodeWarmupTests": 0.002, +"ProviderCoreTests.ThroughputSweepMedianTests": 0.002, +"ProviderCoreTests.ThroughputSweepNotesTests": 0.006, +"ProviderCoreTests.ThroughputSweepReportTests": 0.002, "ProviderCoreTests.ThroughputSweepRowAggregationTests": 0.0, "ProviderCoreTests.ThroughputSweepTilingTests": 0.0, -"ProviderCoreTests.TinyModelLoadTests": 4.129, +"ProviderCoreTests.TinyModelLoadTests": 3.176, "ProviderCoreTests.ToolCallTemplateArgumentsTests": 0.0, -"ProviderCoreTests.ToolChoicePromptPolicyTests": 0.003, -"ProviderCoreTests.ToolChoiceViolationErrorTests": 0.002, -"ProviderCoreTests.ToolSchemaNormalizationCorpusTests": 0.003, +"ProviderCoreTests.ToolChoicePromptPolicyTests": 0.002, +"ProviderCoreTests.ToolChoiceViolationErrorTests": 0.001, +"ProviderCoreTests.ToolSchemaNormalizationCorpusTests": 0.002, "ProviderCoreTests.ToolSchemaNormalizationTests": 0.004, -"ProviderCoreTests.TransitionWatchdogSupervisionTests": 2.245, +"ProviderCoreTests.TransitionWatchdogSupervisionTests": 2.226, "ProviderCoreTests.TransitionWatchdogTests": 0.001, "ProviderCoreTests.UnauthorizedConnectionRecoveryTests": 0.001, -"ProviderCoreTests.UnauthorizedConnectionSupervisionTests": 0.067, -"ProviderCoreTests.UnevictableResidentReportTests": 0.083, -"ProviderCoreTests.UnitTests": 4.489, +"ProviderCoreTests.UnauthorizedConnectionSupervisionTests": 0.061, +"ProviderCoreTests.UnevictableResidentReportTests": 0.08, +"ProviderCoreTests.UnitTests": 4.398, "ProviderCoreTests.UnreclaimableLoadMemoryTests": 0.105, -"ProviderCoreTests.UnsupportedContentPartIngressTests": 0.004, +"ProviderCoreTests.UnsupportedContentPartIngressTests": 0.003, "ProviderCoreTests.UpdateBannerTests": 0.001, -"ProviderCoreTests.UpdateDrainAwarenessTests": 0.073, -"ProviderCoreTests.UpdateJitterTests": 0.001, -"ProviderCoreTests.UpdateProcessLockTests": 1.037, -"ProviderCoreTests.UpdateRecoveryStateTests": 0.001, -"ProviderCoreTests.UpdateRollbackPlanTests": 0.375, -"ProviderCoreTests.UpdateRollbackRecoveryTests": 0.329, -"ProviderCoreTests.VerifiedWeightHashStoreTests": 0.022, -"ProviderCoreTests.VisionTowerBudgetArithmeticTests": 0.0, +"ProviderCoreTests.UpdateDrainAwarenessTests": 0.074, +"ProviderCoreTests.UpdateJitterTests": 0.003, +"ProviderCoreTests.UpdateProcessLockTests": 1.035, +"ProviderCoreTests.UpdateRecoveryStateTests": 0.002, +"ProviderCoreTests.VerifiedWeightHashStoreTests": 0.01, +"ProviderCoreTests.VisionTowerBudgetArithmeticTests": 0.001, "ProviderCoreTests.VisionTowerBudgetIncidentTests": 0.001, "ProviderCoreTests.VisionTowerHeadFactorTests": 0.0, "ProviderCoreTests.WatchdogAgentPlistTests": 0.0, "ProviderCoreTests.WatchdogCrashLoopCountTests": 0.001, -"ProviderCoreTests.WatchdogCrashLoopNextStateTests": 0.002, -"ProviderCoreTests.WatchdogDecisionTests": 0.0, +"ProviderCoreTests.WatchdogCrashLoopNextStateTests": 0.005, +"ProviderCoreTests.WatchdogDecisionTests": 0.001, "ProviderCoreTests.WatchdogEffectiveDownSinceTests": 0.0, -"ProviderCoreTests.WatchdogLaunchAdapterTests": 0.189, +"ProviderCoreTests.WatchdogLaunchAdapterTests": 0.172, "ProviderCoreTests.WatchdogNextStateTests": 0.0, "ProviderCoreTests.WatchdogProbeParseTests": 0.001, "ProviderCoreTests.WatchdogProviderIdentityTests": 0.002, "ProviderCoreTests.WatchdogRearmActionTests": 0.0, -"ProviderCoreTests.WatchdogRecoveryIntegrationTests": 5.602, -"ProviderCoreTests.WatchdogSchedulerTests": 0.062, -"ProviderCoreTests.WatchdogStateTests": 0.003, +"ProviderCoreTests.WatchdogRecoveryIntegrationTests": 11.164, +"ProviderCoreTests.WatchdogSchedulerTests": 0.042, +"ProviderCoreTests.WatchdogStateTests": 0.001, "ProviderCoreTests.WedgeMonitorTests": 0.001, "ProviderCoreTests.WeightHashCacheEligibilityTests": 0.027, -"ProviderCoreTests.WholeMacServiceHeartbeatTests": 0.018, -"ProviderCoreTests.WholeMacServiceReservationTests": 0.048, +"ProviderCoreTests.WholeMacServiceHeartbeatTests": 0.014, +"ProviderCoreTests.WholeMacServiceReservationTests": 0.044, "ServingQualificationTests.FlintHTTPBenchmarkTests": 0.0, -"ServingQualificationTests.ServingPromptCountArtifactTests": 0.004, +"ServingQualificationTests.ServingPromptCountArtifactTests": 0.003, "ServingQualificationTests.ServingPromptCountQualificationTests": 0.0, "ServingQualificationTests.ServingQualificationCollectorTests": 0.0, "ServingQualificationTests.ServingQualificationCompetingModelsTests": 0.0, @@ -1068,5 +1043,5 @@ "ServingQualificationTests.ServingQualificationLifecycleOutcomeTests": 0.0, "ServingQualificationTests.ServingQualificationLifecycleTests": 0.0, "ServingQualificationTests.ServingQualificationLiveTests": 0.0, -"ServingQualificationTests.ServingQualificationPostureTests": 0.002 +"ServingQualificationTests.ServingQualificationPostureTests": 0.001 } From dc1573d0e44b7212e21ad116c895941a36ffb81f Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 14:09:44 -0600 Subject: [PATCH 0253/1441] ci: restore the .48 provider shard weights to unblock dev release qualification Release qualification (release-provider.yml, 5 shards) and CI (ci.yml, 8 shards) share scripts/provider-test-shard-weights.json. The weights from 6bba9acb6 (#1733) moved ProviderCoreTests.Qwen4PagingPrefixIntegrationTests into release shard 2, behind about 85 suites it never shared a process with. There "Balanced Flash-Next keeps indexer/recurrent state and uses packed complete attention" kills swiftpm-testing-helper with SIGBUS (signal 10), on dev b4800a5d5 (run 41692426003) and 70b2f6dc9 (run 41704012078). No code or MLX pin changed between the last good release (1adb32d84, run 41683110072) and those heads in the paths that test uses. The same test passes in .48's release shard 4 and in dev CI shard 5 on b4800a5d5. So the crash depends on test order; the root cause is pending a bisect of the neighbors. This restores the weights file as it was at 1adb32d84. The planner is unchanged, so release qualification places every suite in the same 5-shard processes as the .48 release that passed. Suites added since .48 have no weight and run in the last shard, as before. CI keeps 8 shards and its shard audit; only the balance changes. Co-Authored-By: Claude Opus 5.5 --- scripts/provider-test-shard-weights.json | 1260 +++++++++++----------- 1 file changed, 625 insertions(+), 635 deletions(-) diff --git a/scripts/provider-test-shard-weights.json b/scripts/provider-test-shard-weights.json index 58e70a2918..d3722085a0 100644 --- a/scripts/provider-test-shard-weights.json +++ b/scripts/provider-test-shard-weights.json @@ -1,160 +1,158 @@ { -"DarkbloomCLITests.AccountCommandRunTests": 1.556, -"DarkbloomCLITests.AddonCommandTests": 0.014, +"DarkbloomCLITests.AccountCommandRunTests": 1.571, +"DarkbloomCLITests.AddonCommandTests": 0.031, "DarkbloomCLITests.AdvertisedModelSelectionTests": 0.001, -"DarkbloomCLITests.AppAttestQualificationCommandTests": 4.303, -"DarkbloomCLITests.AutoUpdateCommandTests": 0.165, -"DarkbloomCLITests.AutopilotCommandTests": 0.919, -"DarkbloomCLITests.AutopilotDownloadCommandTests": 0.333, -"DarkbloomCLITests.AutopilotInventoryTests": 0.019, -"DarkbloomCLITests.AutopilotReplacementTests": 0.169, -"DarkbloomCLITests.AutopilotStartupSelectionTests": 0.0, -"DarkbloomCLITests.BenchmarkArrivalPromptTests": 0.001, -"DarkbloomCLITests.BenchmarkKVQuantizationOptionsTests": 0.075, -"DarkbloomCLITests.BenchmarkNativeBlockModeTests": 0.037, +"DarkbloomCLITests.AppAttestQualificationCommandTests": 4.258, +"DarkbloomCLITests.AutoUpdateCommandTests": 0.236, +"DarkbloomCLITests.AutopilotCommandTests": 0.915, +"DarkbloomCLITests.AutopilotDownloadCommandTests": 0.442, +"DarkbloomCLITests.AutopilotInventoryTests": 0.015, +"DarkbloomCLITests.AutopilotReplacementTests": 0.297, +"DarkbloomCLITests.AutopilotStartupSelectionTests": 0.001, +"DarkbloomCLITests.BenchmarkArrivalPromptTests": 0.0, +"DarkbloomCLITests.BenchmarkKVQuantizationOptionsTests": 0.07, +"DarkbloomCLITests.BenchmarkNativeBlockModeTests": 0.031, "DarkbloomCLITests.BenchmarkParityExitTests": 0.001, "DarkbloomCLITests.BenchmarkRuntimeGenerationOptionsTests": 0.094, -"DarkbloomCLITests.BenchmarkSchedulerPrefillDecisionTests": 0.07, -"DarkbloomCLITests.BenchmarkSchedulerPrefillPromptTests": 0.081, -"DarkbloomCLITests.BenchmarkSweepExitTests": 0.031, -"DarkbloomCLITests.BenchmarkTeacherForcedOptionsTests": 0.048, -"DarkbloomCLITests.BetaCommandRunTests": 1.634, -"DarkbloomCLITests.BetaCommandTests": 1.121, -"DarkbloomCLITests.BootSecurityWarningTests": 0.014, -"DarkbloomCLITests.CLIDispatchTests": 0.576, -"DarkbloomCLITests.CacheCommandTests": 0.512, -"DarkbloomCLITests.CatalogPickerFlowTests": 0.047, -"DarkbloomCLITests.ClusterCommandTests": 0.014, -"DarkbloomCLITests.ClusterConsoleCommandTests": 0.181, -"DarkbloomCLITests.ClusterMemberSupervisorTests": 10.162, -"DarkbloomCLITests.ClusterRuntimeFactsCommandTests": 0.015, -"DarkbloomCLITests.ClusterServiceLoginAgentTests": 2.552, -"DarkbloomCLITests.ClusterWorkerOwnerCommandTests": 0.019, +"DarkbloomCLITests.BenchmarkSchedulerPrefillDecisionTests": 0.066, +"DarkbloomCLITests.BenchmarkSchedulerPrefillPromptTests": 0.073, +"DarkbloomCLITests.BenchmarkSweepExitTests": 0.027, +"DarkbloomCLITests.BenchmarkTeacherForcedOptionsTests": 0.05, +"DarkbloomCLITests.BetaCommandRunTests": 1.454, +"DarkbloomCLITests.BetaCommandTests": 1.044, +"DarkbloomCLITests.BootSecurityWarningTests": 0.011, +"DarkbloomCLITests.CLIDispatchTests": 0.55, +"DarkbloomCLITests.CacheCommandTests": 0.457, +"DarkbloomCLITests.CatalogPickerFlowTests": 0.045, +"DarkbloomCLITests.ClusterCommandTests": 0.017, +"DarkbloomCLITests.ClusterConsoleCommandTests": 0.153, +"DarkbloomCLITests.ClusterMemberSupervisorTests": 10.295, +"DarkbloomCLITests.ClusterRuntimeFactsCommandTests": 0.006, +"DarkbloomCLITests.ClusterServiceLoginAgentTests": 2.531, +"DarkbloomCLITests.ClusterWorkerOwnerCommandTests": 0.007, "DarkbloomCLITests.DesktopAccountCloudTests": 0.002, -"DarkbloomCLITests.DesktopAccountEarningsTests": 0.007, +"DarkbloomCLITests.DesktopAccountEarningsTests": 0.006, "DarkbloomCLITests.DesktopAccountIdentityTests": 0.001, -"DarkbloomCLITests.DesktopActionArgumentsTests": 0.229, +"DarkbloomCLITests.DesktopActionArgumentsTests": 0.227, "DarkbloomCLITests.DesktopActivityTests": 0.001, -"DarkbloomCLITests.DesktopAutopilotTests": 0.026, -"DarkbloomCLITests.DesktopControlTests": 0.016, +"DarkbloomCLITests.DesktopAutopilotTests": 0.042, +"DarkbloomCLITests.DesktopControlTests": 0.012, "DarkbloomCLITests.DesktopCoolingAuthorizationTests": 0.0, -"DarkbloomCLITests.DesktopCoolingCacheTests": 0.998, -"DarkbloomCLITests.DesktopDownloadProgressTests": 0.0, +"DarkbloomCLITests.DesktopCoolingCacheTests": 0.988, "DarkbloomCLITests.DesktopExecutableWatchTests": 0.003, -"DarkbloomCLITests.DesktopHTTPErrorTests": 0.002, -"DarkbloomCLITests.DesktopHardwareRouteTests": 0.603, -"DarkbloomCLITests.DesktopMacStatsTests": 0.012, -"DarkbloomCLITests.DesktopRuntimeProfileTests": 1.299, -"DarkbloomCLITests.DesktopServiceTests": 0.005, -"DarkbloomCLITests.DesktopUsageHistoryTests": 0.019, -"DarkbloomCLITests.DesktopWorkerTests": 4.87, +"DarkbloomCLITests.DesktopHTTPErrorTests": 0.003, +"DarkbloomCLITests.DesktopHardwareRouteTests": 0.594, +"DarkbloomCLITests.DesktopMacStatsTests": 0.005, +"DarkbloomCLITests.DesktopRuntimeProfileTests": 1.247, +"DarkbloomCLITests.DesktopServiceTests": 0.004, +"DarkbloomCLITests.DesktopUsageHistoryTests": 0.015, +"DarkbloomCLITests.DesktopWorkerTests": 4.884, "DarkbloomCLITests.DeviceCheckEvidenceTests": 0.003, -"DarkbloomCLITests.DeviceCheckExtractionBoundsTests": 0.165, -"DarkbloomCLITests.DeviceCheckProcessTests": 0.628, -"DarkbloomCLITests.DiagnosticProbeTests": 0.001, -"DarkbloomCLITests.DistributedStartCommandTests": 0.078, -"DarkbloomCLITests.DistributedStartSessionFactoryTests": 0.012, -"DarkbloomCLITests.DistributedStartSignalLatchTests": 0.016, -"DarkbloomCLITests.DistributedStartSignalsTests": 0.983, +"DarkbloomCLITests.DeviceCheckExtractionBoundsTests": 0.162, +"DarkbloomCLITests.DeviceCheckProcessTests": 0.617, +"DarkbloomCLITests.DiagnosticProbeTests": 0.0, +"DarkbloomCLITests.DistributedStartCommandTests": 0.072, +"DarkbloomCLITests.DistributedStartSessionFactoryTests": 0.014, +"DarkbloomCLITests.DistributedStartSignalLatchTests": 0.012, +"DarkbloomCLITests.DistributedStartSignalsTests": 0.974, "DarkbloomCLITests.DoctorAttestationTests": 0.001, -"DarkbloomCLITests.DoctorCaptureTests": 7.384, -"DarkbloomCLITests.DoctorChecksTests": 0.424, -"DarkbloomCLITests.DoctorClearBackendGuardFailureTests": 0.003, -"DarkbloomCLITests.DoctorClearBackendGuardTests": 0.003, -"DarkbloomCLITests.DoctorCommandRunTests": 4.69, -"DarkbloomCLITests.DoctorOperatorDiagnosisTests": 6.967, -"DarkbloomCLITests.EnrollCommandTests": 0.003, -"DarkbloomCLITests.FanActivityLeaseTests": 0.026, -"DarkbloomCLITests.FanCommandArgumentTests": 0.032, -"DarkbloomCLITests.FanCommandTests": 0.004, -"DarkbloomCLITests.FanHelperClientTests": 0.005, -"DarkbloomCLITests.FanProcessRunnerTests": 1.03, +"DarkbloomCLITests.DoctorCaptureTests": 7.308, +"DarkbloomCLITests.DoctorChecksTests": 0.42, +"DarkbloomCLITests.DoctorClearBackendGuardFailureTests": 0.005, +"DarkbloomCLITests.DoctorClearBackendGuardTests": 0.013, +"DarkbloomCLITests.DoctorCommandRunTests": 4.456, +"DarkbloomCLITests.DoctorOperatorDiagnosisTests": 6.767, +"DarkbloomCLITests.EnrollCommandTests": 0.002, +"DarkbloomCLITests.FanActivityLeaseTests": 0.02, +"DarkbloomCLITests.FanCommandArgumentTests": 0.019, +"DarkbloomCLITests.FanCommandTests": 0.005, +"DarkbloomCLITests.FanHelperClientTests": 0.003, +"DarkbloomCLITests.FanProcessRunnerTests": 1.034, "DarkbloomCLITests.FanServiceDisableTests": 0.197, -"DarkbloomCLITests.FanServiceEnableTests": 0.321, -"DarkbloomCLITests.FanServiceInstallStepTests": 0.063, -"DarkbloomCLITests.FanStatusOutputTests": 0.002, +"DarkbloomCLITests.FanServiceEnableTests": 0.32, +"DarkbloomCLITests.FanServiceInstallStepTests": 0.054, +"DarkbloomCLITests.FanStatusOutputTests": 0.003, "DarkbloomCLITests.GLMWiredLimitAdviceTests": 0.001, -"DarkbloomCLITests.IdleCommandTests": 0.411, -"DarkbloomCLITests.InstallerCoordinatorBindingTests": 0.386, +"DarkbloomCLITests.IdleCommandTests": 0.402, +"DarkbloomCLITests.InstallerCoordinatorBindingTests": 0.36, "DarkbloomCLITests.KVBackendGuardDiagnosticsTests": 0.001, "DarkbloomCLITests.KVBackendPostureTests": 0.003, -"DarkbloomCLITests.LifecycleRecoveryPublicationTests": 0.015, -"DarkbloomCLITests.LifecycleRecoveryRollbackTests": 0.991, -"DarkbloomCLITests.LocalEndpointCommandTests": 0.276, +"DarkbloomCLITests.LifecycleRecoveryPublicationTests": 0.008, +"DarkbloomCLITests.LifecycleRecoveryRollbackTests": 0.843, +"DarkbloomCLITests.LocalEndpointCommandTests": 0.255, "DarkbloomCLITests.LocalStartupPreloadGateTests": 0.277, "DarkbloomCLITests.LogoutCommandTests": 0.095, "DarkbloomCLITests.LogsCommandArgvTests": 0.0, "DarkbloomCLITests.LogsCommandOptionsTests": 0.007, -"DarkbloomCLITests.MacOSUpgradeNoticeTests": 1.161, -"DarkbloomCLITests.MiMoImageOnboardingCommandTests": 0.017, -"DarkbloomCLITests.ModelPickerInputEndTests": 2.301, +"DarkbloomCLITests.MacOSUpgradeNoticeTests": 1.059, +"DarkbloomCLITests.MiMoImageOnboardingCommandTests": 0.014, +"DarkbloomCLITests.ModelPickerInputEndTests": 2.271, "DarkbloomCLITests.ModelPickerTerminalTests": 0.092, -"DarkbloomCLITests.ModelsCommandRunTests": 3.14, -"DarkbloomCLITests.ModelsLocationCommandTests": 2.867, +"DarkbloomCLITests.ModelsCommandRunTests": 3.187, +"DarkbloomCLITests.ModelsLocationCommandTests": 2.861, "DarkbloomCLITests.PickerCatalogRowTests": 0.003, -"DarkbloomCLITests.PickerDownloadOutputTests": 0.322, "DarkbloomCLITests.PickerEntryTests": 0.004, -"DarkbloomCLITests.PickerServingSetBudgetTests": 0.051, -"DarkbloomCLITests.RegistrationWeightHashTests": 0.012, +"DarkbloomCLITests.PickerServingSetBudgetTests": 0.05, +"DarkbloomCLITests.RegistrationWeightHashTests": 0.01, "DarkbloomCLITests.ReportAppAttestEvidenceTests": 0.005, -"DarkbloomCLITests.ReportCommandRunTests": 0.597, +"DarkbloomCLITests.ReportCommandRunTests": 0.521, "DarkbloomCLITests.ReportCommandTests": 0.002, -"DarkbloomCLITests.ReportConfigPathTests": 0.004, -"DarkbloomCLITests.ReportPayloadTests": 0.022, +"DarkbloomCLITests.ReportConfigPathTests": 0.001, +"DarkbloomCLITests.ReportPayloadTests": 0.02, "DarkbloomCLITests.RestartCommandTests": 0.004, -"DarkbloomCLITests.RootCommandOutputTests": 0.509, +"DarkbloomCLITests.RootCommandOutputTests": 0.5, "DarkbloomCLITests.RuntimeSmokeKVOptionsTests": 0.002, -"DarkbloomCLITests.RuntimeSnapshotConfigTests": 0.334, -"DarkbloomCLITests.SandboxAddonTests": 5.545, -"DarkbloomCLITests.SandboxEligibilityTests": 0.025, -"DarkbloomCLITests.SandboxSetupTests": 2.135, -"DarkbloomCLITests.SandboxStatusTests": 0.01, -"DarkbloomCLITests.ScheduleCommandTests": 1.411, -"DarkbloomCLITests.ScheduledWindowSelectionTests": 0.164, +"DarkbloomCLITests.RuntimeSnapshotConfigTests": 0.308, +"DarkbloomCLITests.SandboxAddonTests": 5.478, +"DarkbloomCLITests.SandboxEligibilityTests": 0.023, +"DarkbloomCLITests.SandboxSetupTests": 2.034, +"DarkbloomCLITests.SandboxStatusTests": 0.008, +"DarkbloomCLITests.ScheduleCommandTests": 1.391, +"DarkbloomCLITests.ScheduledWindowSelectionTests": 0.156, "DarkbloomCLITests.ScheduledWindowTimingTests": 0.003, -"DarkbloomCLITests.ServiceDrainTests": 0.275, -"DarkbloomCLITests.ServiceDrainWaitTests": 0.815, -"DarkbloomCLITests.StartCommandOptionsTests": 0.086, -"DarkbloomCLITests.StartCommandTests": 0.007, -"DarkbloomCLITests.StartLaunchdGuardTests": 0.784, -"DarkbloomCLITests.StartServingGuardTests": 1.109, -"DarkbloomCLITests.StatusCommandRunTests": 2.659, +"DarkbloomCLITests.ServiceDrainTests": 0.277, +"DarkbloomCLITests.ServiceDrainWaitTests": 0.804, +"DarkbloomCLITests.StartCommandOptionsTests": 0.092, +"DarkbloomCLITests.StartCommandTests": 0.006, +"DarkbloomCLITests.StartLaunchdGuardTests": 0.786, +"DarkbloomCLITests.StartServingGuardTests": 1.103, +"DarkbloomCLITests.StatusCommandRunTests": 2.793, "DarkbloomCLITests.StatusDaemonHealthLineTests": 0.01, "DarkbloomCLITests.StatusLifecycleDrainLineTests": 0.0, -"DarkbloomCLITests.StatusResidencyTests": 0.979, -"DarkbloomCLITests.SwitchCommandTests": 0.382, -"DarkbloomCLITests.UnenrollChoiceTests": 0.026, -"DarkbloomCLITests.UnenrollKeepServingTests": 0.006, -"DarkbloomCLITests.UpdateCheckCommandTests": 1.07, -"DarkbloomCLITests.WatchdogCommandTests": 0.012, +"DarkbloomCLITests.StatusResidencyTests": 1.009, +"DarkbloomCLITests.SwitchCommandTests": 0.376, +"DarkbloomCLITests.UnenrollChoiceTests": 0.025, +"DarkbloomCLITests.UnenrollKeepServingTests": 0.007, +"DarkbloomCLITests.UpdateCheckCommandTests": 1.187, +"DarkbloomCLITests.WatchdogCommandTests": 0.016, "DarkbloomCLITests.WatchdogRecordRecoveryOutcomeTests": 0.002, "DarkbloomCLITests.WatchdogRecoveryOutcomeDetailTests": 0.002, -"DarkbloomCLITests.WatchdogSignalTrapTests": 0.614, -"DarkbloomFanCoreTests.FanControllerTests": 0.626, -"DarkbloomFanCoreTests.FanHardwareTests": 0.248, -"DarkbloomFanCoreTests.FanPolicyTests": 0.193, -"DarkbloomFanCoreTests.SMCCodecTests": 0.178, -"DarkbloomFanHelperTests.FanDaemonTests": 0.272, -"DarkbloomFanHelperTests.FanStartupDiscoveryTests": 0.387, -"DarkbloomFanServiceTests.FanServiceTests": 0.288, -"DarkbloomHardwareLoadTests.CPUTopologyResolverTests": 0.221, -"DarkbloomHardwareLoadTests.CounterLivenessTests": 0.084, -"DarkbloomHardwareLoadTests.HardwareLoadMonitorTests": 0.926, -"DarkbloomHardwareLoadTests.IOReportMathTests": 0.249, -"DarkbloomHardwareLoadTests.LiveHardwareTests": 1.21, -"DarkbloomHardwareLoadTests.ProviderGPUShareTests": 0.152, -"DarkbloomHardwareLoadTests.ReaderParsingTests": 0.226, +"DarkbloomCLITests.WatchdogSignalTrapTests": 0.643, +"DarkbloomFanCoreTests.FanControllerTests": 1.306, +"DarkbloomFanCoreTests.FanHardwareTests": 0.326, +"DarkbloomFanCoreTests.FanPolicyTests": 0.09, +"DarkbloomFanCoreTests.SMCCodecTests": 0.192, +"DarkbloomFanHelperTests.FanDaemonTests": 0.32, +"DarkbloomFanHelperTests.FanStartupDiscoveryTests": 0.462, +"DarkbloomFanServiceTests.FanServiceTests": 0.346, +"DarkbloomHardwareLoadTests.CPUTopologyResolverTests": 0.224, +"DarkbloomHardwareLoadTests.CounterLivenessTests": 0.096, +"DarkbloomHardwareLoadTests.HardwareLoadMonitorTests": 0.818, +"DarkbloomHardwareLoadTests.IOReportMathTests": 0.261, +"DarkbloomHardwareLoadTests.LiveHardwareTests": 1.106, +"DarkbloomHardwareLoadTests.ProviderGPUShareTests": 0.19, +"DarkbloomHardwareLoadTests.ReaderParsingTests": 0.189, "DarkbloomPublishTests.HashCommandTests": 0.014, -"GPTOSSOptimizationTests.CBv2Gemma4ScheduledPrefillTests": 4.162, -"GPTOSSOptimizationTests.CBv2ModelGPTOSSForwardTests": 4.11, -"GPTOSSOptimizationTests.CBv2ModelGemma4ForwardTests": 4.8, -"GPTOSSOptimizationTests.CBv2ModelLayerKindTests": 0.05, -"GPTOSSOptimizationTests.GPTOSSCompiledExpertsTests": 1.655, -"GPTOSSOptimizationTests.GPTOSSGateUpFusionTests": 3.414, -"GPTOSSOptimizationTests.GPTOSSPrefillOutputTests": 12.533, +"GPTOSSOptimizationTests.CBv2Gemma4ScheduledPrefillTests": 4.401, +"GPTOSSOptimizationTests.CBv2ModelGPTOSSForwardTests": 1.576, +"GPTOSSOptimizationTests.CBv2ModelGemma4ForwardTests": 4.81, +"GPTOSSOptimizationTests.CBv2ModelLayerKindTests": 0.054, +"GPTOSSOptimizationTests.GPTOSSCompiledExpertsTests": 3.163, +"GPTOSSOptimizationTests.GPTOSSGateUpFusionTests": 1.836, +"GPTOSSOptimizationTests.GPTOSSPrefillOutputTests": 11.16, "GPTOSSOptimizationTests.GPTOSSRealCheckpointParityTests": 0.0, -"GPTOSSOptimizationTests.IncrementalCheckpointMaterializationTests": 0.033, -"GPTOSSOptimizationTests.QuantizedSwitchLinearConstantCastTests": 1.078, +"GPTOSSOptimizationTests.IncrementalCheckpointMaterializationTests": 0.039, +"GPTOSSOptimizationTests.QuantizedSwitchLinearConstantCastTests": 1.028, "ProviderAppAttestTests.AppAttestEntitlementPolicyTests": 0.003, "ProviderAppAttestTests.AppAttestShadowTests": 0.055, "ProviderAppAttestTests.AppAttestStallRestartPolicyTests": 0.004, @@ -167,12 +165,12 @@ "ProviderAppAttestTests.WorkerProcessTests": 3.88, "ProviderAppAttestTests.WorkerRuntimeDiagnosticsTests": 0.001, "ProviderAppAttestTests.WorkerTransportTests": 0.068, -"ProviderCoreFoundationTests.CacheDirectoryResolutionTests": 0.694, +"ProviderCoreFoundationTests.CacheDirectoryResolutionTests": 0.756, "ProviderCoreFoundationTests.DiffusionGemmaMediaPolicyTests": 0.007, "ProviderCoreFoundationTests.EmptyFileTest": 0.003, "ProviderCoreFoundationTests.EnumerationOrderInvarianceTest": 0.014, "ProviderCoreFoundationTests.FlintDiscoveryTests": 0.033, -"ProviderCoreFoundationTests.GLM5NextDiscoveryLoadFootprintTests": 1.067, +"ProviderCoreFoundationTests.GLM5NextDiscoveryLoadFootprintTests": 1.081, "ProviderCoreFoundationTests.GoldenVectorTest": 0.003, "ProviderCoreFoundationTests.HarmonySanitizationTests": 0.002, "ProviderCoreFoundationTests.HashAllowlistTests": 0.025, @@ -185,10 +183,10 @@ "ProviderCoreFoundationTests.ModelScannerSnapshotSymlinkTests": 0.033, "ProviderCoreFoundationTests.NemotronSuperDistributionManifestTests": 0.177, "ProviderCoreFoundationTests.NemotronSuperMediaPolicyTests": 0.001, -"ProviderCoreFoundationTests.NemotronTemplateFiltersTests": 0.195, +"ProviderCoreFoundationTests.NemotronTemplateFiltersTests": 0.2, "ProviderCoreFoundationTests.PageCacheTests": 0.066, -"ProviderCoreFoundationTests.PromptContractIdentityTests": 0.196, -"ProviderCoreFoundationTests.PromptRenderDateTests": 0.097, +"ProviderCoreFoundationTests.PromptContractIdentityTests": 0.201, +"ProviderCoreFoundationTests.PromptRenderDateTests": 0.05, "ProviderCoreFoundationTests.Qwen4MediaPolicyTests": 0.011, "ProviderCoreFoundationTests.RoleClassificationTests": 0.0, "ProviderCoreFoundationTests.StaleHashRecomputeTest": 0.013, @@ -198,288 +196,284 @@ "ProviderCoreFoundationTests.WeightHasherConcurrencyTests": 0.112, "ProviderCoreFoundationTests.WeightHasherMemoryTests": 0.07, "ProviderCoreFoundationTests.WeightHasherStreamParityTests": 0.538, -"ProviderCoreTests.APNsPushHistoryTests": 0.027, +"ProviderCoreTests.APNsPushHistoryTests": 0.028, "ProviderCoreTests.AddonHoldDrainOwnershipTests": 0.0, -"ProviderCoreTests.AddonHoldLoopTests": 2.094, -"ProviderCoreTests.AddonHoldServeLoopTests": 1.636, +"ProviderCoreTests.AddonHoldLoopTests": 2.092, +"ProviderCoreTests.AddonHoldServeLoopTests": 1.176, "ProviderCoreTests.AddonHoldStoreTests": 0.031, -"ProviderCoreTests.AddonIPCServerTests": 1.155, -"ProviderCoreTests.AddonIPCTests": 0.003, +"ProviderCoreTests.AddonIPCServerTests": 1.101, +"ProviderCoreTests.AddonIPCTests": 0.002, "ProviderCoreTests.AddonPeerPolicyTests": 0.001, "ProviderCoreTests.AdmissionRateEstimatorTests": 0.006, "ProviderCoreTests.AdvertisedModelStoreTests": 0.0, "ProviderCoreTests.AppAttestDeepDiagnosisTests": 0.004, -"ProviderCoreTests.AppAttestLocalDiagnosisTests": 0.006, -"ProviderCoreTests.AppAttestProcessProbeTests": 0.432, -"ProviderCoreTests.AppAttestResumeTests": 0.036, -"ProviderCoreTests.AppAttestResumeTransportTests": 1.11, -"ProviderCoreTests.AppAttestShadowReplyTests": 4.484, -"ProviderCoreTests.AppAttestUpdateLifecycleTests": 3.125, -"ProviderCoreTests.ArrivalInvarianceMeasurementTests": 0.554, -"ProviderCoreTests.AttentionMetadataProductionOwnerTests": 5.039, -"ProviderCoreTests.AudioInputRejectionTests": 0.024, -"ProviderCoreTests.AutoUpdateClaimTests": 0.072, -"ProviderCoreTests.AutoUpdateControllerTests": 0.003, -"ProviderCoreTests.AutoUpdateCycleTests": 0.433, +"ProviderCoreTests.AppAttestLocalDiagnosisTests": 0.003, +"ProviderCoreTests.AppAttestProcessProbeTests": 0.431, +"ProviderCoreTests.AppAttestResumeTests": 0.038, +"ProviderCoreTests.AppAttestResumeTransportTests": 0.86, +"ProviderCoreTests.AppAttestShadowReplyTests": 4.219, +"ProviderCoreTests.AppAttestUpdateLifecycleTests": 2.982, +"ProviderCoreTests.ArrivalInvarianceMeasurementTests": 0.551, +"ProviderCoreTests.AttentionMetadataProductionOwnerTests": 2.763, +"ProviderCoreTests.AudioInputRejectionTests": 0.02, +"ProviderCoreTests.AutoUpdateClaimTests": 0.064, +"ProviderCoreTests.AutoUpdateControllerTests": 0.002, +"ProviderCoreTests.AutoUpdateCycleTests": 0.409, "ProviderCoreTests.AutoUpdateJitterSequencingTests": 0.0, "ProviderCoreTests.AutoUpdateLifecycleOverlapTests": 0.0, -"ProviderCoreTests.AutoUpdateMonitorStartTests": 0.002, -"ProviderCoreTests.AutopilotAdoptionTests": 0.119, +"ProviderCoreTests.AutoUpdateMonitorStartTests": 0.005, +"ProviderCoreTests.AutopilotAdoptionTests": 0.063, "ProviderCoreTests.AutopilotBuildEligibilityTests": 0.001, -"ProviderCoreTests.AutopilotBusyReasonTests": 0.335, -"ProviderCoreTests.AutopilotDownloadLedgerTests": 0.015, +"ProviderCoreTests.AutopilotBusyReasonTests": 0.145, +"ProviderCoreTests.AutopilotDownloadLedgerTests": 0.006, "ProviderCoreTests.AutopilotDownloadPrefetcherTests": 0.001, -"ProviderCoreTests.AutopilotDownloadTests": 1.319, -"ProviderCoreTests.AutopilotInventoryTests": 0.048, +"ProviderCoreTests.AutopilotDownloadTests": 0.977, +"ProviderCoreTests.AutopilotInventoryTests": 0.023, "ProviderCoreTests.AutopilotModelSetTests": 0.001, "ProviderCoreTests.AutopilotModelSwitchOwnershipTests": 0.003, "ProviderCoreTests.AutopilotPlacementHoldTests": 0.04, -"ProviderCoreTests.AutopilotSnapshotCodingTests": 0.009, +"ProviderCoreTests.AutopilotSnapshotCodingTests": 0.016, "ProviderCoreTests.AutopilotStartInventoryTests": 0.002, -"ProviderCoreTests.AutopilotStartupPreferencesTests": 0.036, -"ProviderCoreTests.AutopilotStartupTests": 0.02, -"ProviderCoreTests.BackendParityHarnessProbeTests": 0.003, +"ProviderCoreTests.AutopilotStartupPreferencesTests": 0.031, +"ProviderCoreTests.AutopilotStartupTests": 0.024, +"ProviderCoreTests.BackendParityHarnessProbeTests": 0.004, "ProviderCoreTests.BackendParityReportTests": 0.011, "ProviderCoreTests.BenchmarkCheckpointPartitionTests": 0.0, -"ProviderCoreTests.BenchmarkEntryPointRefusalTests": 0.01, -"ProviderCoreTests.BenchmarkProductionGrantTests": 0.004, +"ProviderCoreTests.BenchmarkEntryPointRefusalTests": 0.009, +"ProviderCoreTests.BenchmarkProductionGrantTests": 0.003, "ProviderCoreTests.BenchmarkProductionInputTests": 0.013, -"ProviderCoreTests.BenchmarkSessionDonationDemandTests": 0.014, +"ProviderCoreTests.BenchmarkSessionDonationDemandTests": 0.015, "ProviderCoreTests.BetaFeaturesTests": 0.002, -"ProviderCoreTests.Bonsai9BContextTests": 0.005, +"ProviderCoreTests.Bonsai9BContextTests": 0.006, "ProviderCoreTests.Bonsai9BMTPPolicyTests": 0.003, -"ProviderCoreTests.Bonsai9BRequestPolicyTests": 0.004, -"ProviderCoreTests.BonsaiDemandedShortCheckpointTests": 0.023, +"ProviderCoreTests.Bonsai9BRequestPolicyTests": 0.002, +"ProviderCoreTests.BonsaiDemandedShortCheckpointTests": 0.045, "ProviderCoreTests.BonsaiEncryptedCheckpointLiveTests": 0.0, "ProviderCoreTests.BootSecurityTests": 0.0, "ProviderCoreTests.BuildEnvironmentTests": 0.001, -"ProviderCoreTests.CacheDirectoryPermissionsTests": 0.03, +"ProviderCoreTests.CacheDirectoryPermissionsTests": 0.023, "ProviderCoreTests.CachePromptParityTests": 0.01, -"ProviderCoreTests.CacheSettingsTests": 0.003, +"ProviderCoreTests.CacheSettingsTests": 0.002, "ProviderCoreTests.CacheStorageEnvironmentTests": 0.005, -"ProviderCoreTests.CacheVolumeTests": 0.021, -"ProviderCoreTests.CancelledSettlementLifecycleTests": 0.002, +"ProviderCoreTests.CacheVolumeTests": 0.026, +"ProviderCoreTests.CancelledSettlementLifecycleTests": 0.001, "ProviderCoreTests.ChatRequestExtraFieldsTests": 0.002, -"ProviderCoreTests.ChatTemplateLoopRewritesTests": 5.332, +"ProviderCoreTests.ChatTemplateLoopRewritesTests": 4.248, "ProviderCoreTests.ChunkBatcherLifecycleTests": 0.003, -"ProviderCoreTests.ChunkSenderTests": 0.903, +"ProviderCoreTests.ChunkSenderTests": 0.902, "ProviderCoreTests.ClusterAPIDecorationTests": 0.002, -"ProviderCoreTests.ClusterAPIParityTests": 3.181, -"ProviderCoreTests.ClusterApprovalAnyNumericsClassTests": 0.002, -"ProviderCoreTests.ClusterApprovalFetchTests": 0.993, -"ProviderCoreTests.ClusterApprovalLifetimeTests": 0.453, -"ProviderCoreTests.ClusterApprovalServiceStartTests": 11.878, -"ProviderCoreTests.ClusterApprovalSyncTests": 5.91, -"ProviderCoreTests.ClusterApprovalWatchTests": 5.82, +"ProviderCoreTests.ClusterAPIParityTests": 3.063, +"ProviderCoreTests.ClusterApprovalAnyNumericsClassTests": 0.001, +"ProviderCoreTests.ClusterApprovalFetchTests": 0.9, +"ProviderCoreTests.ClusterApprovalLifetimeTests": 0.475, +"ProviderCoreTests.ClusterApprovalServiceStartTests": 7.353, +"ProviderCoreTests.ClusterApprovalSyncTests": 3.901, +"ProviderCoreTests.ClusterApprovalWatchTests": 5.005, "ProviderCoreTests.ClusterCacheOwnershipTests": 0.001, -"ProviderCoreTests.ClusterChipAgnosticGrantTests": 0.005, -"ProviderCoreTests.ClusterConfigurationTests": 0.005, +"ProviderCoreTests.ClusterChipAgnosticGrantTests": 0.003, +"ProviderCoreTests.ClusterConfigurationTests": 0.004, "ProviderCoreTests.ClusterDerivedTimeBudgetTests": 0.001, -"ProviderCoreTests.ClusterGLMManifestPinTests": 2.616, -"ProviderCoreTests.ClusterInstalledReferenceTests": 0.011, -"ProviderCoreTests.ClusterLeaderFailoverFinishTests": 1.645, -"ProviderCoreTests.ClusterLinkControlHostTests": 0.005, +"ProviderCoreTests.ClusterGLMManifestPinTests": 2.443, +"ProviderCoreTests.ClusterInstalledReferenceTests": 0.009, +"ProviderCoreTests.ClusterLeaderFailoverFinishTests": 1.57, +"ProviderCoreTests.ClusterLinkControlHostTests": 0.007, "ProviderCoreTests.ClusterLocalServingTests": 0.001, -"ProviderCoreTests.ClusterMemberLoopTests": 0.015, -"ProviderCoreTests.ClusterMemberNegotiationTests": 0.969, -"ProviderCoreTests.ClusterMemberRegistrationTests": 10.122, -"ProviderCoreTests.ClusterMemberServeLoopTests": 21.62, -"ProviderCoreTests.ClusterMemberSupervisionTests": 0.002, -"ProviderCoreTests.ClusterMembershipTests": 0.004, -"ProviderCoreTests.ClusterModelApprovalTests": 0.007, -"ProviderCoreTests.ClusterNativeMemberAttachmentTests": 0.028, -"ProviderCoreTests.ClusterObservabilityTests": 0.018, -"ProviderCoreTests.ClusterOnboardingPeerLabelTests": 0.093, -"ProviderCoreTests.ClusterOwnerCommittedBootstrapTests": 1.707, -"ProviderCoreTests.ClusterOwnerServingTests": 0.031, -"ProviderCoreTests.ClusterPairApprovalTests": 0.009, +"ProviderCoreTests.ClusterMemberLoopTests": 0.017, +"ProviderCoreTests.ClusterMemberNegotiationTests": 0.951, +"ProviderCoreTests.ClusterMemberRegistrationTests": 10.115, +"ProviderCoreTests.ClusterMemberServeLoopTests": 22.626, +"ProviderCoreTests.ClusterMemberSupervisionTests": 0.003, +"ProviderCoreTests.ClusterMembershipTests": 0.003, +"ProviderCoreTests.ClusterNativeMemberAttachmentTests": 0.029, +"ProviderCoreTests.ClusterObservabilityTests": 0.015, +"ProviderCoreTests.ClusterOnboardingPeerLabelTests": 0.171, +"ProviderCoreTests.ClusterOwnerCommittedBootstrapTests": 1.714, +"ProviderCoreTests.ClusterOwnerServingTests": 0.004, +"ProviderCoreTests.ClusterPairApprovalTests": 0.02, "ProviderCoreTests.ClusterPairMediaRegistrationTests": 0.001, -"ProviderCoreTests.ClusterPairServingDecisionsTests": 0.006, -"ProviderCoreTests.ClusterPairServingTests": 0.602, +"ProviderCoreTests.ClusterPairServingDecisionsTests": 0.003, +"ProviderCoreTests.ClusterPairServingTests": 0.58, "ProviderCoreTests.ClusterPairSlotOwnerLanesTests": 0.0, -"ProviderCoreTests.ClusterPairSlotServeTests": 1.455, -"ProviderCoreTests.ClusterPairSlotTests": 1.41, -"ProviderCoreTests.ClusterPairingProviderTests": 1.516, -"ProviderCoreTests.ClusterPrefixCacheSettingsTests": 0.012, -"ProviderCoreTests.ClusterPrefixSSDKeyMaterialTests": 0.208, -"ProviderCoreTests.ClusterRosterMemberTests": 0.041, -"ProviderCoreTests.ClusterRuntimeApprovalFactsTests": 3.322, -"ProviderCoreTests.ClusterServiceAgentTests": 0.019, -"ProviderCoreTests.ClusterServiceDescriptorTests": 0.895, -"ProviderCoreTests.ClusterServicePowerAssertionTests": 0.005, -"ProviderCoreTests.ClusterServiceRecoveryTests": 7.638, -"ProviderCoreTests.ClusterSetupProbeRequestTests": 0.006, -"ProviderCoreTests.ClusterStatusSpeculationTests": 0.002, -"ProviderCoreTests.ClusterStoreManifestRepairTests": 3.661, -"ProviderCoreTests.ClusterTransferReportsTests": 0.0, +"ProviderCoreTests.ClusterPairSlotServeTests": 1.32, +"ProviderCoreTests.ClusterPairSlotTests": 1.387, +"ProviderCoreTests.ClusterPairingProviderTests": 1.451, +"ProviderCoreTests.ClusterPrefixCacheSettingsTests": 0.011, +"ProviderCoreTests.ClusterPrefixSSDKeyMaterialTests": 0.202, +"ProviderCoreTests.ClusterRosterMemberTests": 0.014, +"ProviderCoreTests.ClusterRuntimeApprovalFactsTests": 0.525, +"ProviderCoreTests.ClusterServiceAgentTests": 0.028, +"ProviderCoreTests.ClusterServiceDescriptorTests": 0.903, +"ProviderCoreTests.ClusterServicePowerAssertionTests": 0.006, +"ProviderCoreTests.ClusterServiceRecoveryTests": 7.49, +"ProviderCoreTests.ClusterSetupProbeRequestTests": 0.003, +"ProviderCoreTests.ClusterStatusSpeculationTests": 0.003, +"ProviderCoreTests.ClusterStoreManifestRepairTests": 3.471, "ProviderCoreTests.CompletePrefixCacheCapabilityTests": 0.001, -"ProviderCoreTests.ConfigValidationTests": 0.006, -"ProviderCoreTests.CoordinatorAdvertiseTests": 0.001, -"ProviderCoreTests.CoordinatorHandshakeDeadlineTests": 3.471, -"ProviderCoreTests.CoordinatorIntegrationTests": 10.106, -"ProviderCoreTests.CoordinatorLifecycleBarrierTests": 0.141, -"ProviderCoreTests.CoordinatorModelSwitchTests": 0.438, -"ProviderCoreTests.CoordinatorReconnectPolicyTests": 0.001, -"ProviderCoreTests.CoordinatorWireVectorTests": 0.019, +"ProviderCoreTests.ConfigValidationTests": 0.005, +"ProviderCoreTests.CoordinatorAdvertiseTests": 0.0, +"ProviderCoreTests.CoordinatorHandshakeDeadlineTests": 3.234, +"ProviderCoreTests.CoordinatorIntegrationTests": 2.389, +"ProviderCoreTests.CoordinatorLifecycleBarrierTests": 0.148, +"ProviderCoreTests.CoordinatorModelSwitchTests": 0.437, +"ProviderCoreTests.CoordinatorWireVectorTests": 0.026, "ProviderCoreTests.CrashLoopGuardPredicateTests": 0.0, "ProviderCoreTests.CrashLoopGuardRecoveryWiringTests": 0.282, -"ProviderCoreTests.CrashLoopGuardTripTests": 0.009, -"ProviderCoreTests.DaemonStateServedCountTests": 0.003, +"ProviderCoreTests.CrashLoopGuardTripTests": 0.005, +"ProviderCoreTests.DaemonStateServedCountTests": 0.006, "ProviderCoreTests.DarkbloomMDMRemovalTests": 0.002, -"ProviderCoreTests.DeadlineDecisionBridgeTests": 0.016, -"ProviderCoreTests.DeadlineDecisionProfileTests": 0.001, +"ProviderCoreTests.DeadlineDecisionBridgeTests": 0.012, +"ProviderCoreTests.DeadlineDecisionProfileTests": 0.002, "ProviderCoreTests.DecodeBandwidthModelTests": 0.001, -"ProviderCoreTests.DecodeInterleaveDeadlineAdmissionTests": 0.335, -"ProviderCoreTests.DesiredModelsForPostureTests": 0.004, -"ProviderCoreTests.DeviceCodeLoginTests": 4.029, -"ProviderCoreTests.DiffusionBenchmarkRouteProbeTests": 0.002, -"ProviderCoreTests.DiffusionBenchmarkTests": 0.001, -"ProviderCoreTests.DiffusionCheckpointEnvelopeTests": 0.089, -"ProviderCoreTests.DiffusionGemmaBenchmarkRowTests": 0.002, +"ProviderCoreTests.DecodeInterleaveDeadlineAdmissionTests": 0.044, +"ProviderCoreTests.DesiredModelsForPostureTests": 0.003, +"ProviderCoreTests.DeviceCodeLoginTests": 4.267, +"ProviderCoreTests.DiffusionBenchmarkRouteProbeTests": 0.001, +"ProviderCoreTests.DiffusionBenchmarkTests": 0.002, +"ProviderCoreTests.DiffusionCheckpointEnvelopeTests": 0.091, +"ProviderCoreTests.DiffusionGemmaBenchmarkRowTests": 0.001, "ProviderCoreTests.DiffusionGemmaConcurrencyLiveTests": 0.001, "ProviderCoreTests.DiffusionGemmaEncryptedHandlerLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaFourCallDiagnosticLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaFourCallFixtureTests": 0.001, "ProviderCoreTests.DiffusionGemmaMediaLiveTests": 0.0, -"ProviderCoreTests.DiffusionGemmaMediaNormalizationTests": 0.044, +"ProviderCoreTests.DiffusionGemmaMediaNormalizationTests": 0.089, "ProviderCoreTests.DiffusionGemmaMediaPrefixLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaNamedToolDiagnosticLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaPrefixLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaPromptParityLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaProtocolLiveTests": 0.0, -"ProviderCoreTests.DiffusionGemmaProviderBridgeTests": 48.52, +"ProviderCoreTests.DiffusionGemmaProviderBridgeTests": 45.968, "ProviderCoreTests.DiffusionGemmaProviderLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaRawCaseLiveTests": 0.0, -"ProviderCoreTests.DiffusionGemmaReasoningControlTests": 0.002, -"ProviderCoreTests.DiffusionGemmaReasoningEmissionTests": 0.05, +"ProviderCoreTests.DiffusionGemmaReasoningControlTests": 0.001, +"ProviderCoreTests.DiffusionGemmaReasoningEmissionTests": 0.049, "ProviderCoreTests.DiffusionGemmaStandaloneLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaStopLiveTests": 0.0, "ProviderCoreTests.DiffusionGemmaTokenizerParityLiveTests": 0.0, "ProviderCoreTests.DiffusionLongContextLiveTests": 0.0, -"ProviderCoreTests.DiffusionToolResultMediaTests": 0.127, +"ProviderCoreTests.DiffusionToolResultMediaTests": 0.128, "ProviderCoreTests.DiffusionVisibleThroughputLiveTests": 0.001, -"ProviderCoreTests.DistributedAutomaticBatchPlannerTests": 0.458, -"ProviderCoreTests.DistributedCBv2CleanStopTests": 0.059, -"ProviderCoreTests.DistributedCBv2DeadlineTests": 0.003, -"ProviderCoreTests.DistributedCBv2EngineTests": 0.006, -"ProviderCoreTests.DistributedHTTPCleanStopTests": 1.072, -"ProviderCoreTests.DistributedHTTPCompletionTests": 2.364, -"ProviderCoreTests.DistributedHTTPDeliveryLifecycleTests": 1.83, -"ProviderCoreTests.DistributedHTTPDisconnectTests": 1.631, -"ProviderCoreTests.DistributedHTTPFrameWakeupTests": 0.297, -"ProviderCoreTests.DistributedHTTPOriginTests": 0.235, +"ProviderCoreTests.DistributedAutomaticBatchPlannerTests": 0.508, +"ProviderCoreTests.DistributedCBv2CleanStopTests": 0.055, +"ProviderCoreTests.DistributedCBv2DeadlineTests": 0.002, +"ProviderCoreTests.DistributedCBv2EngineTests": 0.008, +"ProviderCoreTests.DistributedHTTPCleanStopTests": 1.08, +"ProviderCoreTests.DistributedHTTPCompletionTests": 2.324, +"ProviderCoreTests.DistributedHTTPDeliveryLifecycleTests": 1.95, +"ProviderCoreTests.DistributedHTTPDisconnectTests": 1.63, +"ProviderCoreTests.DistributedHTTPFrameWakeupTests": 0.275, +"ProviderCoreTests.DistributedHTTPOriginTests": 0.221, "ProviderCoreTests.DistributedHTTPRetirementTests": 0.013, -"ProviderCoreTests.DistributedHTTPTerminalIntegrationTests": 0.937, -"ProviderCoreTests.DistributedHTTPVisibleContentTests": 0.439, +"ProviderCoreTests.DistributedHTTPTerminalIntegrationTests": 0.923, +"ProviderCoreTests.DistributedHTTPVisibleContentTests": 0.421, "ProviderCoreTests.DistributedInstalledCancellationTests": 0.001, -"ProviderCoreTests.DistributedInstalledFilesTests": 0.005, -"ProviderCoreTests.DistributedInstalledKVQuantizationTests": 0.007, +"ProviderCoreTests.DistributedInstalledFilesTests": 0.004, +"ProviderCoreTests.DistributedInstalledKVQuantizationTests": 0.008, "ProviderCoreTests.DistributedInstalledLanesTests": 0.001, -"ProviderCoreTests.DistributedLogprobAdmissionTests": 0.004, +"ProviderCoreTests.DistributedLogprobAdmissionTests": 0.002, "ProviderCoreTests.DistributedMiMoImageRefusalTests": 0.0, "ProviderCoreTests.DistributedPrefixPartitionTests": 0.003, -"ProviderCoreTests.DistributedQwenMediaHostMemoryTests": 0.003, -"ProviderCoreTests.DistributedQwenMediaIngressTests": 1.252, -"ProviderCoreTests.DistributedQwenMediaLifetimeTests": 0.002, -"ProviderCoreTests.DistributedRequestObservationSinkTests": 0.007, -"ProviderCoreTests.DistributedRequestObservationTests": 0.004, -"ProviderCoreTests.DistributedRequestOriginDeadlineTests": 0.003, +"ProviderCoreTests.DistributedQwenMediaHostMemoryTests": 0.002, +"ProviderCoreTests.DistributedQwenMediaIngressTests": 1.199, +"ProviderCoreTests.DistributedQwenMediaLifetimeTests": 0.003, +"ProviderCoreTests.DistributedRequestObservationSinkTests": 0.006, +"ProviderCoreTests.DistributedRequestObservationTests": 0.007, +"ProviderCoreTests.DistributedRequestOriginDeadlineTests": 0.002, "ProviderCoreTests.DistributedRequestQueueTests": 0.0, -"ProviderCoreTests.DistributedServingEligibilityTests": 0.004, -"ProviderCoreTests.DistributedStopStringScopeTests": 0.002, +"ProviderCoreTests.DistributedServingEligibilityTests": 0.044, "ProviderCoreTests.EmbeddedQwen38RuntimeRequirementsTests": 0.0, -"ProviderCoreTests.EngineDeadlineRetirementBridgeTests": 0.009, +"ProviderCoreTests.EngineDeadlineRetirementBridgeTests": 0.008, "ProviderCoreTests.EngineEarlyPerformanceTests": 0.002, -"ProviderCoreTests.EngineMeasurementOrderingTests": 0.159, +"ProviderCoreTests.EngineMeasurementOrderingTests": 0.142, "ProviderCoreTests.EnginePerformanceHeartbeatTests": 0.048, -"ProviderCoreTests.EngineProfileCancelTests": 0.01, +"ProviderCoreTests.EngineProfileCancelTests": 0.009, "ProviderCoreTests.EngineProfileMappingTests": 0.0, -"ProviderCoreTests.EngineTransferredRetirementWorkTests": 1.554, -"ProviderCoreTests.EngineV2BenchmarkMTPAcceptanceTests": 1.413, -"ProviderCoreTests.EngineV2BenchmarkMTPVerificationTests": 3.601, -"ProviderCoreTests.EngineV2BridgeCheckpointTargetTests": 0.002, +"ProviderCoreTests.EngineTransferredRetirementWorkTests": 1.591, +"ProviderCoreTests.EngineV2BenchmarkMTPAcceptanceTests": 1.563, +"ProviderCoreTests.EngineV2BenchmarkMTPVerificationTests": 3.354, +"ProviderCoreTests.EngineV2BridgeCheckpointTargetTests": 0.004, "ProviderCoreTests.EngineV2BridgeMultimodalTests": 0.005, -"ProviderCoreTests.EngineV2BridgePagedKVTests": 0.004, -"ProviderCoreTests.EngineV2BridgePumpReceiptTests": 0.158, -"ProviderCoreTests.EngineV2CancellationTests": 0.001, -"ProviderCoreTests.EngineV2CapacityTests": 0.011, -"ProviderCoreTests.EngineV2CoResidencyLiveTests": 0.001, -"ProviderCoreTests.EngineV2ContiguousAdmissionTests": 1.592, -"ProviderCoreTests.EngineV2DiffusionMediaChunkBoundTests": 0.004, -"ProviderCoreTests.EngineV2DiffusionPrefixPrecisionTests": 0.062, +"ProviderCoreTests.EngineV2BridgePagedKVTests": 0.005, +"ProviderCoreTests.EngineV2BridgePumpReceiptTests": 1.461, +"ProviderCoreTests.EngineV2CancellationTests": 0.003, +"ProviderCoreTests.EngineV2CapacityTests": 0.005, +"ProviderCoreTests.EngineV2CoResidencyLiveTests": 0.0, +"ProviderCoreTests.EngineV2ContiguousAdmissionTests": 1.286, +"ProviderCoreTests.EngineV2DiffusionMediaChunkBoundTests": 0.002, +"ProviderCoreTests.EngineV2DiffusionPrefixPrecisionTests": 0.064, "ProviderCoreTests.EngineV2ErrorMappingTests": 0.002, -"ProviderCoreTests.EngineV2EventFramingTests": 0.007, +"ProviderCoreTests.EngineV2EventFramingTests": 0.006, "ProviderCoreTests.EngineV2FP32PagedRateTests": 0.001, -"ProviderCoreTests.EngineV2FailLoudFactoryTests": 0.008, -"ProviderCoreTests.EngineV2FirstTokenDeadlineAdmissionTests": 0.04, -"ProviderCoreTests.EngineV2HardeningTests": 0.001, -"ProviderCoreTests.EngineV2HybridPrefixIdentityTests": 0.184, +"ProviderCoreTests.EngineV2FailLoudFactoryTests": 0.005, +"ProviderCoreTests.EngineV2FirstTokenDeadlineAdmissionTests": 0.039, +"ProviderCoreTests.EngineV2HardeningTests": 0.002, +"ProviderCoreTests.EngineV2HybridPrefixIdentityTests": 0.178, "ProviderCoreTests.EngineV2KVBackendFallbackHeartbeatTests": 0.003, -"ProviderCoreTests.EngineV2KVBackendGateTests": 20.974, -"ProviderCoreTests.EngineV2KVBackendPolicyTests": 0.003, -"ProviderCoreTests.EngineV2KVQuantizationPolicyTests": 0.001, -"ProviderCoreTests.EngineV2LivenessRecoveryTests": 0.04, +"ProviderCoreTests.EngineV2KVBackendGateTests": 21.901, +"ProviderCoreTests.EngineV2KVBackendPolicyTests": 0.004, +"ProviderCoreTests.EngineV2KVQuantizationPolicyTests": 0.002, +"ProviderCoreTests.EngineV2LivenessRecoveryTests": 0.045, "ProviderCoreTests.EngineV2LivenessVerdictTests": 0.002, -"ProviderCoreTests.EngineV2LogprobsChannelCapTests": 0.003, -"ProviderCoreTests.EngineV2LogprobsPassthroughTests": 0.127, -"ProviderCoreTests.EngineV2LookupReceiptCoverageTests": 0.009, +"ProviderCoreTests.EngineV2LogprobsChannelCapTests": 0.002, +"ProviderCoreTests.EngineV2LogprobsPassthroughTests": 0.123, +"ProviderCoreTests.EngineV2LookupReceiptCoverageTests": 0.017, "ProviderCoreTests.EngineV2MTPAdmissionChargesTests": 0.001, "ProviderCoreTests.EngineV2MTPProductionAdmissionTests": 0.01, -"ProviderCoreTests.EngineV2MatchedStopSequenceTests": 0.002, -"ProviderCoreTests.EngineV2MemoryConcurrencyTests": 0.023, +"ProviderCoreTests.EngineV2MatchedStopSequenceTests": 0.001, +"ProviderCoreTests.EngineV2MemoryConcurrencyTests": 0.022, "ProviderCoreTests.EngineV2NativeBlockTimingTests": 0.0, "ProviderCoreTests.EngineV2PagedParityLiveTests": 0.001, -"ProviderCoreTests.EngineV2PagedPoolDTypeEnvTests": 0.93, -"ProviderCoreTests.EngineV2PrefillGeometryEngineTests": 2.831, -"ProviderCoreTests.EngineV2PrefillGeometryTests": 0.052, -"ProviderCoreTests.EngineV2PrefillSamplingTests": 0.035, -"ProviderCoreTests.EngineV2PrefixCacheUsageTests": 0.004, -"ProviderCoreTests.EngineV2RequestRoutingTests": 0.034, +"ProviderCoreTests.EngineV2PagedPoolDTypeEnvTests": 0.729, +"ProviderCoreTests.EngineV2PrefillGeometryEngineTests": 4.069, +"ProviderCoreTests.EngineV2PrefillGeometryTests": 0.041, +"ProviderCoreTests.EngineV2PrefillSamplingTests": 0.025, +"ProviderCoreTests.EngineV2PrefixCacheUsageTests": 0.003, +"ProviderCoreTests.EngineV2RequestRoutingTests": 0.037, "ProviderCoreTests.EngineV2ResliceTests": 0.001, -"ProviderCoreTests.EngineV2ResliceUnwindTests": 0.008, -"ProviderCoreTests.EngineV2ReslicingWiringTests": 0.132, -"ProviderCoreTests.EngineV2RuntimeGuardTests": 0.035, +"ProviderCoreTests.EngineV2ResliceUnwindTests": 0.016, +"ProviderCoreTests.EngineV2ReslicingWiringTests": 0.136, +"ProviderCoreTests.EngineV2RuntimeGuardTests": 0.026, "ProviderCoreTests.EngineV2SSDPrefixCacheLiveTests": 0.0, -"ProviderCoreTests.EngineV2SamplingDefaultsTests": 0.004, -"ProviderCoreTests.EngineV2SeededSamplingTests": 0.29, +"ProviderCoreTests.EngineV2SamplingDefaultsTests": 0.003, +"ProviderCoreTests.EngineV2SeededSamplingTests": 0.316, "ProviderCoreTests.EngineV2ServiceabilityPolicyTests": 0.003, -"ProviderCoreTests.EngineV2ServiceableGrantTests": 1.419, -"ProviderCoreTests.EngineV2ServiceableLoadTests": 0.072, -"ProviderCoreTests.EngineV2SharedBudgetTests": 0.303, -"ProviderCoreTests.EngineV2ShutdownTests": 0.001, -"ProviderCoreTests.EngineV2SlotBuildTests": 0.026, -"ProviderCoreTests.EngineV2SupportedSetGateTests": 0.018, +"ProviderCoreTests.EngineV2ServiceableGrantTests": 2.334, +"ProviderCoreTests.EngineV2ServiceableLoadTests": 1.403, +"ProviderCoreTests.EngineV2SharedBudgetTests": 0.276, +"ProviderCoreTests.EngineV2ShutdownTests": 0.0, +"ProviderCoreTests.EngineV2SlotBuildTests": 0.022, +"ProviderCoreTests.EngineV2SupportedSetGateTests": 0.013, "ProviderCoreTests.EngineV2TranslationTests": 0.002, "ProviderCoreTests.EngineV2VisionMLXFaultTests": 0.001, -"ProviderCoreTests.EngineV2VisionPixelRunTests": 0.005, -"ProviderCoreTests.EngineV2VisionRoutingTests": 0.057, -"ProviderCoreTests.EngineV2VisionSpanCarvingTests": 0.003, +"ProviderCoreTests.EngineV2VisionPixelRunTests": 0.002, +"ProviderCoreTests.EngineV2VisionRoutingTests": 0.053, +"ProviderCoreTests.EngineV2VisionSpanCarvingTests": 0.005, "ProviderCoreTests.EnrollmentTests": 0.023, -"ProviderCoreTests.EvalProbeTests": 0.007, -"ProviderCoreTests.FirstContentDeadlineTests": 0.042, +"ProviderCoreTests.EvalProbeTests": 0.005, +"ProviderCoreTests.FirstContentDeadlineTests": 0.032, "ProviderCoreTests.FlashNextEncryptedHandlerLiveTests": 0.0, "ProviderCoreTests.FlashNextQuietCancellationReloadLiveTests": 0.0, "ProviderCoreTests.FlashNextReclaimDiagnostics": 0.0, -"ProviderCoreTests.FlintAnswerStopServingTests": 0.931, -"ProviderCoreTests.FlintAnswerStopTests": 1.847, -"ProviderCoreTests.FlintContextAdmissionTests": 1.24, +"ProviderCoreTests.FlintAnswerStopServingTests": 0.976, +"ProviderCoreTests.FlintAnswerStopTests": 1.824, +"ProviderCoreTests.FlintContextAdmissionTests": 1.27, "ProviderCoreTests.FlintLiveTests": 0.0, -"ProviderCoreTests.FlintNativeProtocolFactoryTests": 0.862, -"ProviderCoreTests.FlintNativeProtocolTests": 0.509, +"ProviderCoreTests.FlintNativeProtocolFactoryTests": 0.802, +"ProviderCoreTests.FlintNativeProtocolTests": 0.51, "ProviderCoreTests.FlintOpenRouterLiveTests": 0.0, -"ProviderCoreTests.FlintPagedOnlyBackendTests": 0.521, -"ProviderCoreTests.FlintPolicyTests": 0.188, +"ProviderCoreTests.FlintPagedOnlyBackendTests": 0.816, +"ProviderCoreTests.FlintPolicyTests": 0.175, "ProviderCoreTests.FlintR2InstallTests": 0.0, -"ProviderCoreTests.FlintReasoningVisibilityTests": 2.321, +"ProviderCoreTests.FlintReasoningVisibilityTests": 2.36, "ProviderCoreTests.FlintRelayLogprobsLiveTests": 0.0, -"ProviderCoreTests.FlintResponseFormatConstraintTests": 0.338, +"ProviderCoreTests.FlintResponseFormatConstraintTests": 0.356, "ProviderCoreTests.FlintResponseFormatOutputTests": 0.004, -"ProviderCoreTests.FlintResponseFormatPolicyTests": 0.433, +"ProviderCoreTests.FlintResponseFormatPolicyTests": 0.413, "ProviderCoreTests.FlintTemplateReplayTests": 0.049, -"ProviderCoreTests.FlintToolChoicePromptPolicyTests": 0.018, +"ProviderCoreTests.FlintToolChoicePromptPolicyTests": 0.009, "ProviderCoreTests.FrozenReplayRealModelTests": 0.0, -"ProviderCoreTests.GLM5NextCalibrationAuthorizerTests": 0.019, -"ProviderCoreTests.GLM5NextCalibrationBindingWireTests": 0.004, +"ProviderCoreTests.GLM5NextCalibrationAuthorizerTests": 0.018, +"ProviderCoreTests.GLM5NextCalibrationBindingWireTests": 0.003, "ProviderCoreTests.GLM5NextCalibrationBootstrapDeadlineTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationDispatchDigestTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationDispatchResultTests": 0.0, @@ -488,32 +482,32 @@ "ProviderCoreTests.GLM5NextCalibrationInstalledOwnerTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationInstalledPairTests": 0.018, "ProviderCoreTests.GLM5NextCalibrationInstalledQuoteCompletedTests": 0.0, -"ProviderCoreTests.GLM5NextCalibrationLaunchTests": 0.019, -"ProviderCoreTests.GLM5NextCalibrationNativeCodecTests": 0.003, -"ProviderCoreTests.GLM5NextCalibrationNativeDocumentsTests": 0.08, +"ProviderCoreTests.GLM5NextCalibrationLaunchTests": 0.016, +"ProviderCoreTests.GLM5NextCalibrationNativeCodecTests": 0.002, +"ProviderCoreTests.GLM5NextCalibrationNativeDocumentsTests": 0.075, "ProviderCoreTests.GLM5NextCalibrationNativeStartTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationPairedControlTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationPeerQuoteTests": 0.0, -"ProviderCoreTests.GLM5NextCalibrationPublicQuoteValidationTests": 0.008, +"ProviderCoreTests.GLM5NextCalibrationPublicQuoteValidationTests": 0.007, "ProviderCoreTests.GLM5NextCalibrationQuoteAuthorizerTests": 0.046, -"ProviderCoreTests.GLM5NextCalibrationQuoteLaunchTests": 0.006, -"ProviderCoreTests.GLM5NextCalibrationQuoteOutputTests": 0.103, -"ProviderCoreTests.GLM5NextCalibrationQuoteOwnershipTests": 0.568, -"ProviderCoreTests.GLM5NextCalibrationQuoteProcessTests": 3.624, +"ProviderCoreTests.GLM5NextCalibrationQuoteLaunchTests": 0.005, +"ProviderCoreTests.GLM5NextCalibrationQuoteOutputTests": 0.102, +"ProviderCoreTests.GLM5NextCalibrationQuoteOwnershipTests": 0.526, +"ProviderCoreTests.GLM5NextCalibrationQuoteProcessTests": 3.569, "ProviderCoreTests.GLM5NextCalibrationReportTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationResultPublicationTests": 0.0, "ProviderCoreTests.GLM5NextCalibrationTerminalStatusRaceTests": 0.0, -"ProviderCoreTests.GLM5NextCoordinatorServingTests": 0.063, -"ProviderCoreTests.GLM5NextDiscoveryTests": 0.296, -"ProviderCoreTests.GLM5NextEncryptedCheckpointTests": 30.805, +"ProviderCoreTests.GLM5NextCoordinatorServingTests": 0.062, +"ProviderCoreTests.GLM5NextDiscoveryTests": 0.295, +"ProviderCoreTests.GLM5NextEncryptedCheckpointTests": 30.571, "ProviderCoreTests.GLM5NextHardwareGateTests": 0.0, -"ProviderCoreTests.GLM5NextLocalQualificationTests": 0.105, +"ProviderCoreTests.GLM5NextLocalQualificationTests": 0.099, "ProviderCoreTests.GLM5NextLogprobsTests": 0.0, "ProviderCoreTests.GLM5NextManagedKernelTests": 0.0, -"ProviderCoreTests.GLM5NextManagedMetadataTests": 1.317, -"ProviderCoreTests.GLM5NextMediaRoutingTests": 15.836, -"ProviderCoreTests.GLM5NextOpenRouterCapabilityTests": 1.072, -"ProviderCoreTests.GLM5NextPromptPolicyTests": 0.892, +"ProviderCoreTests.GLM5NextManagedMetadataTests": 1.293, +"ProviderCoreTests.GLM5NextMediaRoutingTests": 15.889, +"ProviderCoreTests.GLM5NextOpenRouterCapabilityTests": 1.028, +"ProviderCoreTests.GLM5NextPromptPolicyTests": 0.945, "ProviderCoreTests.GLM5NextProtectedFactoryTests": 0.0, "ProviderCoreTests.GLM5NextProviderLoopTests": 0.0, "ProviderCoreTests.GLM5NextRealArtifactQualificationTests": 0.0, @@ -521,25 +515,25 @@ "ProviderCoreTests.GLM5NextRealLogprobsQualificationTests": 0.0, "ProviderCoreTests.GLM5NextRealTeacherLogitsTests": 0.0, "ProviderCoreTests.GLM5NextRealTimingMatrixTests": 0.0, -"ProviderCoreTests.GLM5NextReasoningVisibilityTests": 0.071, -"ProviderCoreTests.GLM5NextRelayLogprobsTests": 0.114, +"ProviderCoreTests.GLM5NextReasoningVisibilityTests": 0.065, +"ProviderCoreTests.GLM5NextRelayLogprobsTests": 0.117, "ProviderCoreTests.GLM5NextResidencyIntegrationTests": 0.0, "ProviderCoreTests.GLM5NextStandaloneLoadPolicyTests": 0.0, -"ProviderCoreTests.GLM5NextWiredLimitTests": 0.002, +"ProviderCoreTests.GLM5NextWiredLimitTests": 0.001, "ProviderCoreTests.GLM5NextWiredResidencyTests": 0.001, -"ProviderCoreTests.GLM5ToolFailureTests": 0.1, -"ProviderCoreTests.GLMClusterImageReasoningTests": 0.012, -"ProviderCoreTests.GLMClusterTensorParallelMediaTests": 0.042, +"ProviderCoreTests.GLM5ToolFailureTests": 0.098, +"ProviderCoreTests.GLMClusterImageReasoningTests": 0.009, +"ProviderCoreTests.GLMClusterTensorParallelMediaTests": 0.04, "ProviderCoreTests.GLMImageAdmissionTests": 0.001, -"ProviderCoreTests.GLMPairForcedOutputTests": 0.059, -"ProviderCoreTests.GLMSlotParityTests": 0.216, +"ProviderCoreTests.GLMPairForcedOutputTests": 0.057, +"ProviderCoreTests.GLMSlotParityTests": 0.219, "ProviderCoreTests.GPTOSSCheckpointRestartLiveTests": 0.0, -"ProviderCoreTests.GPTOSSDefaultPrefixCacheWiringTests": 1.52, -"ProviderCoreTests.GPTOSSHarmonyTemplateFixesTests": 0.004, +"ProviderCoreTests.GPTOSSDefaultPrefixCacheWiringTests": 0.088, +"ProviderCoreTests.GPTOSSHarmonyTemplateFixesTests": 0.003, "ProviderCoreTests.GPTOSSMixedPrefixCacheLiveTests": 0.0, -"ProviderCoreTests.GPUEnforcementTests": 0.286, -"ProviderCoreTests.Gemma4ServedTemplateRenderTests": 0.202, -"ProviderCoreTests.Gemma4ToolCallArgumentsTests": 0.002, +"ProviderCoreTests.GPUEnforcementTests": 0.314, +"ProviderCoreTests.Gemma4ServedTemplateRenderTests": 0.205, +"ProviderCoreTests.Gemma4ToolCallArgumentsTests": 0.001, "ProviderCoreTests.Gemma4ToolSchemaEnforcementTests": 0.001, "ProviderCoreTests.Gemma4TurnStructureTests": 0.003, "ProviderCoreTests.GemmaMTPPerformanceLiveTests": 0.0, @@ -550,7 +544,7 @@ "ProviderCoreTests.GemmaOptimizationReportingTests": 0.001, "ProviderCoreTests.GemmaQATCheckpointRestartLiveTests": 0.0, "ProviderCoreTests.GemmaToolCallLiveTests": 0.0, -"ProviderCoreTests.GemmaToolConstraintTests": 0.46, +"ProviderCoreTests.GemmaToolConstraintTests": 0.452, "ProviderCoreTests.GemmaVLMEngineV2LiveTests": 0.0, "ProviderCoreTests.GemmaVLMSharedTowerMemoryLiveTests": 0.0, "ProviderCoreTests.GemmaVLMVideoEngineV2LiveTests": 0.0, @@ -558,68 +552,68 @@ "ProviderCoreTests.GlobalKVCacheBudgetAuditTests": 0.003, "ProviderCoreTests.HardwareDetectorTests": 0.0, "ProviderCoreTests.HeartbeatClusterSessionTests": 0.001, -"ProviderCoreTests.HeartbeatIdlePolicyTests": 0.0, -"ProviderCoreTests.HuggingFaceDownloadTests": 0.068, -"ProviderCoreTests.IdleCalibrationCoordinatorTests": 0.067, +"ProviderCoreTests.HeartbeatIdlePolicyTests": 0.001, +"ProviderCoreTests.HuggingFaceDownloadTests": 0.06, +"ProviderCoreTests.IdleCalibrationCoordinatorTests": 0.06, "ProviderCoreTests.IdleTimeoutPolicyTests": 0.0, -"ProviderCoreTests.InboundChatRequestDecodeTests": 0.01, -"ProviderCoreTests.InboundDecodeTests": 0.005, +"ProviderCoreTests.InboundChatRequestDecodeTests": 0.008, +"ProviderCoreTests.InboundDecodeTests": 0.006, "ProviderCoreTests.InferenceLiveTests": 0.0, -"ProviderCoreTests.InferenceRefusalLoggingTests": 0.073, -"ProviderCoreTests.InlineDeclarationProbeTests": 0.06, +"ProviderCoreTests.InferenceRefusalLoggingTests": 0.066, +"ProviderCoreTests.InlineDeclarationProbeTests": 0.052, "ProviderCoreTests.JinjaSanitizationLiveTests": 0.0, "ProviderCoreTests.JinjaSanitizationTests": 0.008, -"ProviderCoreTests.KVBackendGuardStoreTests": 0.006, +"ProviderCoreTests.KVBackendGuardStoreTests": 0.007, "ProviderCoreTests.KVCheckpointPostureTests": 0.0, -"ProviderCoreTests.KVPoolIdleSweepTests": 0.118, +"ProviderCoreTests.KVPoolIdleSweepTests": 0.123, "ProviderCoreTests.KVPoolReclaimerNativeGateTests": 0.001, -"ProviderCoreTests.KVPoolReclaimerTests": 0.011, -"ProviderCoreTests.KVPoolSweepWiringTests": 0.217, -"ProviderCoreTests.KVQuantizationConfigTests": 0.004, -"ProviderCoreTests.KernelTests": 1.616, -"ProviderCoreTests.LaunchAgentDrainAllowanceTests": 0.001, +"ProviderCoreTests.KVPoolReclaimerTests": 0.008, +"ProviderCoreTests.KVPoolSweepWiringTests": 0.23, +"ProviderCoreTests.KVQuantizationConfigTests": 0.003, +"ProviderCoreTests.KernelTests": 1.668, +"ProviderCoreTests.LaunchAgentDrainAllowanceTests": 0.002, "ProviderCoreTests.LaunchAgentDrainIntegrationTests": 0.0, "ProviderCoreTests.LaunchAgentEnvironmentTests": 0.003, -"ProviderCoreTests.LaunchAgentLifecycleTests": 0.015, +"ProviderCoreTests.LaunchAgentLifecycleTests": 0.014, "ProviderCoreTests.LaunchAgentPathsAndErrorsTests": 0.003, -"ProviderCoreTests.LaunchAgentRemovalTests": 0.023, +"ProviderCoreTests.LaunchAgentRemovalTests": 0.022, "ProviderCoreTests.LaunchAgentRestartTests": 0.0, -"ProviderCoreTests.LaunchAgentServicePlistTests": 0.003, -"ProviderCoreTests.LifecycleMailboxTests": 0.032, -"ProviderCoreTests.LiveInferenceMetallibSourceTests": 0.018, -"ProviderCoreTests.LoadedModelsPersistenceWiringTests": 0.025, -"ProviderCoreTests.LoadedModelsStoreTests": 0.004, -"ProviderCoreTests.LocalChatRequestTests": 0.006, -"ProviderCoreTests.LocalContentPartRefusalTests": 0.006, +"ProviderCoreTests.LaunchAgentServicePlistTests": 0.002, +"ProviderCoreTests.LifecycleMailboxTests": 0.029, +"ProviderCoreTests.LiveInferenceMetallibSourceTests": 0.022, +"ProviderCoreTests.LoadedModelsPersistenceWiringTests": 0.009, +"ProviderCoreTests.LoadedModelsStoreTests": 0.002, +"ProviderCoreTests.LocalChatRequestTests": 0.007, +"ProviderCoreTests.LocalContentPartRefusalTests": 0.008, "ProviderCoreTests.LocalDisconnectTests": 0.003, -"ProviderCoreTests.LocalDrainHTTPTests": 0.009, +"ProviderCoreTests.LocalDrainHTTPTests": 0.01, "ProviderCoreTests.LocalEndpointFileTests": 0.003, "ProviderCoreTests.LocalOpenAIObjectCompatibilityTests": 0.002, "ProviderCoreTests.LocalOutputTokenLimitTests": 0.005, -"ProviderCoreTests.LocalResponseConversationTests": 0.012, -"ProviderCoreTests.LocalResponseTrackerTests": 0.014, +"ProviderCoreTests.LocalResponseConversationTests": 0.014, +"ProviderCoreTests.LocalResponseTrackerTests": 0.013, "ProviderCoreTests.LocalServingPostureTests": 0.001, "ProviderCoreTests.LocalStreamingFailureTests": 0.003, "ProviderCoreTests.MDMEnrollmentTests": 0.001, "ProviderCoreTests.MDMTrustDiagnosisTests": 0.001, "ProviderCoreTests.MLXMemoryGuardConfigureOnceTests": 0.001, -"ProviderCoreTests.MTPAcceptanceConfigTests": 0.002, -"ProviderCoreTests.MTPBenchmarkTests": 0.166, +"ProviderCoreTests.MTPAcceptanceConfigTests": 0.001, +"ProviderCoreTests.MTPBenchmarkTests": 0.194, "ProviderCoreTests.MTPBetaFeatureTests": 0.0, "ProviderCoreTests.MTPConfigKeyTests": 0.004, "ProviderCoreTests.MTPIdleUpgradeTests": 0.001, -"ProviderCoreTests.MTPPostureTelemetryTests": 1.117, -"ProviderCoreTests.MTPResliceFallbackTests": 0.097, +"ProviderCoreTests.MTPPostureTelemetryTests": 1.029, +"ProviderCoreTests.MTPResliceFallbackTests": 0.046, "ProviderCoreTests.MTPStagingReservationsTests": 0.0, "ProviderCoreTests.MTPSupportedModelsTests": 0.0, -"ProviderCoreTests.MediaKindClassificationTests": 0.003, +"ProviderCoreTests.MediaKindClassificationTests": 0.002, "ProviderCoreTests.MediaToolMetadataTests": 0.002, -"ProviderCoreTests.MetallibHashTests": 0.009, +"ProviderCoreTests.MetallibHashTests": 0.007, "ProviderCoreTests.MiMoCompleteCheckpointIdentityTests": 0.002, -"ProviderCoreTests.MiMoImageHTTPIngressTests": 1.184, -"ProviderCoreTests.MiMoImageOnboardingSelectionTests": 0.112, -"ProviderCoreTests.MiMoInstalledEncryptedLinkPolicyTests": 0.289, -"ProviderCoreTests.MiMoInstalledImagePolicyTests": 0.218, +"ProviderCoreTests.MiMoImageHTTPIngressTests": 1.235, +"ProviderCoreTests.MiMoImageOnboardingSelectionTests": 0.107, +"ProviderCoreTests.MiMoInstalledEncryptedLinkPolicyTests": 0.269, +"ProviderCoreTests.MiMoInstalledImagePolicyTests": 0.213, "ProviderCoreTests.MiMoMediaDecodeMemoryTests": 0.818, "ProviderCoreTests.MiMoMemoryAdmissionTests": 0.001, "ProviderCoreTests.MiMoTestPrerequisitesTests": 0.001, @@ -656,166 +650,164 @@ "ProviderCoreTests.MiMoV26TemplateFixTests": 0.009, "ProviderCoreTests.MiMoV26WiredDeviceContextTests": 0.001, "ProviderCoreTests.MiMoV26WiredResidencyTests": 0.046, -"ProviderCoreTests.ModelArtifactPublicationTests": 0.024, -"ProviderCoreTests.ModelArtifactReceiptTests": 0.626, -"ProviderCoreTests.ModelArtifactWriteLeaseTests": 0.003, +"ProviderCoreTests.ModelArtifactPublicationTests": 0.025, +"ProviderCoreTests.ModelArtifactReceiptTests": 0.571, +"ProviderCoreTests.ModelArtifactWriteLeaseTests": 0.004, "ProviderCoreTests.ModelAutopilotHistoryTests": 0.002, -"ProviderCoreTests.ModelAutopilotOperationOwnershipTests": 0.019, -"ProviderCoreTests.ModelAutopilotRuntimeTests": 0.32, -"ProviderCoreTests.ModelAutopilotShadowTests": 0.027, +"ProviderCoreTests.ModelAutopilotOperationOwnershipTests": 0.012, +"ProviderCoreTests.ModelAutopilotRuntimeTests": 0.322, +"ProviderCoreTests.ModelAutopilotShadowTests": 0.028, "ProviderCoreTests.ModelAutopilotTests": 0.003, -"ProviderCoreTests.ModelAutopilotUnloadTests": 0.196, +"ProviderCoreTests.ModelAutopilotUnloadTests": 0.117, "ProviderCoreTests.ModelBenchmarkDispatchTests": 0.003, "ProviderCoreTests.ModelBenchmarkReportTests": 0.001, -"ProviderCoreTests.ModelCacheConfigurationTests": 0.003, +"ProviderCoreTests.ModelCacheConfigurationTests": 0.002, "ProviderCoreTests.ModelCalibrationPolicyTests": 0.001, -"ProviderCoreTests.ModelCalibrationTests": 6.22, -"ProviderCoreTests.ModelCatalogTests": 2.472, +"ProviderCoreTests.ModelCalibrationTests": 5.721, +"ProviderCoreTests.ModelCatalogTests": 2.463, "ProviderCoreTests.ModelCheckpointConversationLiveTests": 0.0, -"ProviderCoreTests.ModelCheckpointDonationControlTests": 0.005, -"ProviderCoreTests.ModelCheckpointObservationLifetimeTests": 0.11, +"ProviderCoreTests.ModelCheckpointDonationControlTests": 0.003, +"ProviderCoreTests.ModelCheckpointObservationLifetimeTests": 0.098, "ProviderCoreTests.ModelCheckpointRestoreContentionLiveTests": 0.0, "ProviderCoreTests.ModelCheckpointStorageLiveTests": 0.0, -"ProviderCoreTests.ModelCheckpointStorageSpecificationTests": 0.004, -"ProviderCoreTests.ModelDownloadCacheTests": 0.006, -"ProviderCoreTests.ModelDownloadProgressDownloaderTests": 4.492, -"ProviderCoreTests.ModelDownloadProgressTests": 0.17, -"ProviderCoreTests.ModelLoadEvictionAndAdmissionTests": 1.106, -"ProviderCoreTests.ModelLoadRefusalTests": 0.121, -"ProviderCoreTests.ModelPrefetchCoordinatorTests": 0.272, -"ProviderCoreTests.ModelPrefetchDownloaderTests": 0.854, -"ProviderCoreTests.ModelPrefixBenchmarkAdjacentForkTests": 0.009, -"ProviderCoreTests.ModelPrefixBenchmarkCleanupTests": 0.001, +"ProviderCoreTests.ModelCheckpointStorageSpecificationTests": 0.005, +"ProviderCoreTests.ModelDownloadCacheTests": 0.005, +"ProviderCoreTests.ModelDownloadProgressTests": 0.305, +"ProviderCoreTests.ModelLoadEvictionAndAdmissionTests": 0.554, +"ProviderCoreTests.ModelLoadRefusalTests": 0.123, +"ProviderCoreTests.ModelPrefetchCoordinatorTests": 0.275, +"ProviderCoreTests.ModelPrefetchDownloaderTests": 0.759, +"ProviderCoreTests.ModelPrefixBenchmarkAdjacentForkTests": 0.014, +"ProviderCoreTests.ModelPrefixBenchmarkCleanupTests": 0.002, "ProviderCoreTests.ModelPrefixBenchmarkDiagnosticsTests": 0.001, "ProviderCoreTests.ModelPrefixBenchmarkLiveTests": 0.0, -"ProviderCoreTests.ModelPrefixBenchmarkMTPObservationTests": 0.002, +"ProviderCoreTests.ModelPrefixBenchmarkMTPObservationTests": 0.001, "ProviderCoreTests.ModelPrefixBenchmarkOutputTimingTests": 0.0, "ProviderCoreTests.ModelPrefixBenchmarkQuiescenceTimingTests": 0.001, -"ProviderCoreTests.ModelPrefixBenchmarkTerminalTests": 0.001, -"ProviderCoreTests.ModelRequirementLineTests": 0.001, -"ProviderCoreTests.ModelRevisionActivationTests": 0.05, -"ProviderCoreTests.ModelRevisionPreparationTests": 0.091, -"ProviderCoreTests.ModelRevisionPublicationTests": 0.07, -"ProviderCoreTests.ModelScannerArchitectureTests": 0.005, +"ProviderCoreTests.ModelPrefixBenchmarkTerminalTests": 0.002, +"ProviderCoreTests.ModelRequirementLineTests": 0.0, +"ProviderCoreTests.ModelRevisionActivationTests": 0.043, +"ProviderCoreTests.ModelRevisionPreparationTests": 0.083, +"ProviderCoreTests.ModelRevisionPublicationTests": 0.078, +"ProviderCoreTests.ModelScannerArchitectureTests": 0.006, "ProviderCoreTests.ModelScannerMemoryFilterTests": 0.004, -"ProviderCoreTests.ModelSelectionDownloadTests": 0.031, -"ProviderCoreTests.ModelSlotBookkeepingTests": 0.031, +"ProviderCoreTests.ModelSelectionDownloadTests": 0.029, +"ProviderCoreTests.ModelSlotBookkeepingTests": 0.079, "ProviderCoreTests.MultimodalErrorMappingTests": 0.0, "ProviderCoreTests.NativeBlockRetirementBridgeTests": 0.115, -"ProviderCoreTests.NativeChannelSplitterTests": 0.023, -"ProviderCoreTests.NativeCheckpointQuantizationTests": 0.093, -"ProviderCoreTests.NativeDiffusionCheckpointKeysTests": 0.003, -"ProviderCoreTests.NativeDiffusionCheckpointStoreTests": 0.865, +"ProviderCoreTests.NativeChannelSplitterTests": 0.017, +"ProviderCoreTests.NativeCheckpointQuantizationTests": 0.078, +"ProviderCoreTests.NativeDiffusionCheckpointKeysTests": 0.004, +"ProviderCoreTests.NativeDiffusionCheckpointStoreTests": 2.136, "ProviderCoreTests.NativeLocalConsumerOwnershipTests": 0.014, -"ProviderCoreTests.NativeMediaToolPreparationTests": 0.001, +"ProviderCoreTests.NativeMediaToolPreparationTests": 0.002, "ProviderCoreTests.NativeMediaToolsCapabilityTests": 0.001, "ProviderCoreTests.NativeMemoryReclamationTests": 0.0, "ProviderCoreTests.NativeMemoryRetirementWindowTests": 0.0, -"ProviderCoreTests.NativeModelToolChoiceTests": 0.002, +"ProviderCoreTests.NativeModelToolChoiceTests": 0.003, "ProviderCoreTests.NativeOutputControlRefusalTests": 0.0, -"ProviderCoreTests.NativePairMemberContractTests": 0.032, -"ProviderCoreTests.NativePairMemberControlTests": 0.178, -"ProviderCoreTests.NativePairMemberInstallTests": 0.01, -"ProviderCoreTests.NativePairMemberInvocationTests": 0.962, -"ProviderCoreTests.NativePairMemberServingTests": 2.897, -"ProviderCoreTests.NativePairMessageTests": 0.001, -"ProviderCoreTests.NativePairSessionHeartbeatTests": 0.394, -"ProviderCoreTests.NativeServeQualificationTests": 0.006, -"ProviderCoreTests.NativeServeRunLifetimeTests": 0.004, -"ProviderCoreTests.NativeToolCapabilityAdvertisementTests": 0.002, -"ProviderCoreTests.NativeToolStreamRouterTests": 0.02, +"ProviderCoreTests.NativePairMemberContractTests": 0.026, +"ProviderCoreTests.NativePairMemberControlTests": 0.163, +"ProviderCoreTests.NativePairMemberInstallTests": 0.006, +"ProviderCoreTests.NativePairMemberInvocationTests": 0.944, +"ProviderCoreTests.NativePairMemberServingTests": 2.699, +"ProviderCoreTests.NativePairMessageTests": 0.002, +"ProviderCoreTests.NativePairSessionHeartbeatTests": 0.314, +"ProviderCoreTests.NativeServeQualificationTests": 0.007, +"ProviderCoreTests.NativeServeRunLifetimeTests": 0.002, +"ProviderCoreTests.NativeToolCapabilityAdvertisementTests": 0.001, +"ProviderCoreTests.NativeToolStreamRouterTests": 0.027, "ProviderCoreTests.NativeWorkerServeQualificationTests": 0.002, "ProviderCoreTests.Nemotron35ArchitectureTests": 0.001, -"ProviderCoreTests.NemotronDemandedShortCheckpointTests": 0.029, +"ProviderCoreTests.NemotronDemandedShortCheckpointTests": 0.032, "ProviderCoreTests.NemotronMTPDeclarationTests": 0.0, -"ProviderCoreTests.NemotronPagingPrefixIntegrationTests": 15.772, -"ProviderCoreTests.NemotronStandaloneAdmissionTests": 0.01, -"ProviderCoreTests.NemotronSuperDurablePrefixCacheTests": 5.702, -"ProviderCoreTests.NemotronSuperImageDecodeTests": 1.258, -"ProviderCoreTests.NemotronSuperImageFormatHTTPTests": 7.671, -"ProviderCoreTests.NemotronSuperImageGoldenTests": 16.983, +"ProviderCoreTests.NemotronPagingPrefixIntegrationTests": 1.153, +"ProviderCoreTests.NemotronStandaloneAdmissionTests": 0.013, +"ProviderCoreTests.NemotronSuperDurablePrefixCacheTests": 7.075, +"ProviderCoreTests.NemotronSuperImageDecodeTests": 1.288, +"ProviderCoreTests.NemotronSuperImageFormatHTTPTests": 9.064, +"ProviderCoreTests.NemotronSuperImageGoldenTests": 16.856, "ProviderCoreTests.NemotronSuperImageHTTPRelayTests": 0.001, -"ProviderCoreTests.NemotronSuperImagePlanTests": 1.13, -"ProviderCoreTests.NemotronSuperJPEGContainerTests": 0.012, -"ProviderCoreTests.NemotronSuperLoadAdmissionTests": 0.002, -"ProviderCoreTests.NemotronSuperLocalBindingTests": 3.053, -"ProviderCoreTests.NemotronSuperLocalHTTPAdmissionTests": 7.535, -"ProviderCoreTests.NemotronSuperLocalHTTPTests": 3.352, -"ProviderCoreTests.NemotronSuperLocalImageBindingTests": 0.664, -"ProviderCoreTests.NemotronSuperLocalMTPBatchedTests": 5.659, -"ProviderCoreTests.NemotronSuperLocalMTPTests": 6.49, +"ProviderCoreTests.NemotronSuperImagePlanTests": 1.516, +"ProviderCoreTests.NemotronSuperJPEGContainerTests": 0.013, +"ProviderCoreTests.NemotronSuperLoadAdmissionTests": 0.001, +"ProviderCoreTests.NemotronSuperLocalBindingTests": 1.035, +"ProviderCoreTests.NemotronSuperLocalHTTPAdmissionTests": 3.767, +"ProviderCoreTests.NemotronSuperLocalHTTPTests": 5.747, +"ProviderCoreTests.NemotronSuperLocalImageBindingTests": 0.578, +"ProviderCoreTests.NemotronSuperLocalMTPBatchedTests": 5.012, +"ProviderCoreTests.NemotronSuperLocalMTPTests": 5.983, "ProviderCoreTests.NemotronSuperLocalOutputTests": 0.055, -"ProviderCoreTests.NemotronSuperLocalOwnerTests": 1.325, -"ProviderCoreTests.NemotronSuperLocalPagedTests": 2.634, -"ProviderCoreTests.NemotronSuperLocalPrefillTests": 3.447, -"ProviderCoreTests.NemotronSuperLocalPrefixCacheTests": 5.213, +"ProviderCoreTests.NemotronSuperLocalOwnerTests": 0.859, +"ProviderCoreTests.NemotronSuperLocalPagedTests": 2.575, +"ProviderCoreTests.NemotronSuperLocalPrefillTests": 1.838, +"ProviderCoreTests.NemotronSuperLocalPrefixCacheTests": 4.068, "ProviderCoreTests.NemotronSuperLongContextLiveTests": 0.0, -"ProviderCoreTests.NemotronSuperLongContextTests": 0.581, -"ProviderCoreTests.NemotronSuperManagedSlotTests": 26.678, -"ProviderCoreTests.NemotronSuperMediaChargeTests": 1.521, +"ProviderCoreTests.NemotronSuperLongContextTests": 0.201, +"ProviderCoreTests.NemotronSuperManagedSlotTests": 26.641, +"ProviderCoreTests.NemotronSuperMediaChargeTests": 1.672, "ProviderCoreTests.NemotronSuperMemoryLiveTests": 0.0, -"ProviderCoreTests.NemotronSuperOpenRouterCapabilityTests": 0.477, -"ProviderCoreTests.NemotronSuperOpenRouterVideoTests": 51.872, -"ProviderCoreTests.NemotronSuperPNGTextTests": 0.058, +"ProviderCoreTests.NemotronSuperOpenRouterCapabilityTests": 0.472, +"ProviderCoreTests.NemotronSuperOpenRouterVideoTests": 57.04, +"ProviderCoreTests.NemotronSuperPNGTextTests": 0.059, "ProviderCoreTests.NemotronSuperPagedLiveTests": 0.0, -"ProviderCoreTests.NemotronSuperPrefixCacheEvidenceTests": 1.091, +"ProviderCoreTests.NemotronSuperPrefixCacheEvidenceTests": 4.038, "ProviderCoreTests.NemotronSuperPromptContractTests": 0.433, "ProviderCoreTests.NemotronSuperPromptGoldenTests": 0.651, "ProviderCoreTests.NemotronSuperRecurrentAdmissionTests": 0.001, -"ProviderCoreTests.NemotronSuperServingPolicyTests": 0.258, -"ProviderCoreTests.NemotronSuperVideoBindingTests": 10.119, -"ProviderCoreTests.NemotronSuperVideoDecodeTests": 2.353, -"ProviderCoreTests.NemotronSuperVideoGoldenTests": 8.707, +"ProviderCoreTests.NemotronSuperServingPolicyTests": 0.259, +"ProviderCoreTests.NemotronSuperVideoBindingTests": 9.267, +"ProviderCoreTests.NemotronSuperVideoDecodeTests": 2.481, +"ProviderCoreTests.NemotronSuperVideoGoldenTests": 9.044, "ProviderCoreTests.NemotronTemplateParityLiveTests": 0.001, -"ProviderCoreTests.NetworkFrameworkCloseCodeTests": 0.012, -"ProviderCoreTests.ObservedRateDeadlineAdmissionTests": 0.009, -"ProviderCoreTests.OuterPrefixCacheReceiptTests": 0.005, +"ProviderCoreTests.ObservedRateDeadlineAdmissionTests": 0.01, +"ProviderCoreTests.OuterPrefixCacheReceiptTests": 0.004, "ProviderCoreTests.PackagedRetainedGemmaSmokeTests": 0.001, "ProviderCoreTests.PagedFootprintTelemetryTests": 0.001, -"ProviderCoreTests.PagedKernelPreflightTests": 4.99, +"ProviderCoreTests.PagedKernelPreflightTests": 4.907, "ProviderCoreTests.PagedStorageTelemetryTests": 0.001, "ProviderCoreTests.PagedTeacherForcedAgreementTests": 0.0, "ProviderCoreTests.PerformanceHeartbeatMaterialityTests": 0.0, "ProviderCoreTests.PersistentEnclaveKeyErrorTests": 0.0, -"ProviderCoreTests.PlannedProviderDisconnectTests": 2.407, +"ProviderCoreTests.PlannedProviderDisconnectTests": 2.217, "ProviderCoreTests.PrefillDeadlineProductionConfigTests": 0.005, "ProviderCoreTests.PrefillEvidenceRecoveryStateTests": 0.0, -"ProviderCoreTests.PrefillEvidenceRecoveryTests": 0.669, -"ProviderCoreTests.PrefixCacheCheckpointIdentityTests": 0.016, +"ProviderCoreTests.PrefillEvidenceRecoveryTests": 0.587, +"ProviderCoreTests.PrefixCacheCheckpointIdentityTests": 0.014, "ProviderCoreTests.PrefixCacheDiagnosisTests": 0.0, -"ProviderCoreTests.PrefixCacheEvidenceSequencerTests": 0.029, -"ProviderCoreTests.PrefixCacheLoadHashTests": 0.018, -"ProviderCoreTests.PrefixCachePolicyTests": 0.007, -"ProviderCoreTests.PrefixCacheReceiptTests": 0.064, -"ProviderCoreTests.ProcessLifecycleTests": 0.008, +"ProviderCoreTests.PrefixCacheEvidenceSequencerTests": 0.032, +"ProviderCoreTests.PrefixCacheLoadHashTests": 0.017, +"ProviderCoreTests.PrefixCachePolicyTests": 0.008, +"ProviderCoreTests.PrefixCacheReceiptTests": 0.065, +"ProviderCoreTests.ProcessLifecycleTests": 0.006, "ProviderCoreTests.ProcessMemoryNativeIntegrationTests": 0.719, "ProviderCoreTests.ProcessMemoryTelemetryTests": 0.001, -"ProviderCoreTests.ProductionModelCalibrationTests": 51.267, +"ProviderCoreTests.ProductionModelCalibrationTests": 49.866, "ProviderCoreTests.ProductionPromptParityTests": 0.0, "ProviderCoreTests.PromptDateRenderingTests": 0.003, -"ProviderCoreTests.PromptTokenCacheTests": 1.088, -"ProviderCoreTests.ProviderAuthorizationConnectionTests": 0.004, +"ProviderCoreTests.PromptTokenCacheTests": 1.05, +"ProviderCoreTests.ProviderAuthorizationConnectionTests": 0.003, "ProviderCoreTests.ProviderAuthorizationProtocolTests": 0.001, -"ProviderCoreTests.ProviderAuthorizationReadinessTests": 0.003, +"ProviderCoreTests.ProviderAuthorizationReadinessTests": 0.002, "ProviderCoreTests.ProviderAutoRestartConfigTests": 0.001, -"ProviderCoreTests.ProviderBusyWireTests": 0.002, -"ProviderCoreTests.ProviderCancelledPrefixCacheTests": 0.282, +"ProviderCoreTests.ProviderBusyWireTests": 0.001, +"ProviderCoreTests.ProviderCancelledPrefixCacheTests": 0.216, "ProviderCoreTests.ProviderCapabilityLabelsTests": 0.0, -"ProviderCoreTests.ProviderConfigParseGrowthTests": 0.007, +"ProviderCoreTests.ProviderConfigParseGrowthTests": 0.008, "ProviderCoreTests.ProviderLaunchSnapshotTests": 0.0, -"ProviderCoreTests.ProviderLifecycleTests": 2.447, -"ProviderCoreTests.ProviderLogoutTests": 0.773, -"ProviderCoreTests.ProviderLoopCalibrationTests": 3.038, -"ProviderCoreTests.ProviderLoopMTPUpgradeTests": 0.144, +"ProviderCoreTests.ProviderLifecycleTests": 2.39, +"ProviderCoreTests.ProviderLogoutTests": 0.762, +"ProviderCoreTests.ProviderLoopCalibrationTests": 2.876, +"ProviderCoreTests.ProviderLoopMTPUpgradeTests": 0.156, "ProviderCoreTests.ProviderLoopNativeMiMoLifetimeTests": 1.618, -"ProviderCoreTests.ProviderLoopPrefetchTests": 0.864, -"ProviderCoreTests.ProviderMTPFactoryTests": 0.027, -"ProviderCoreTests.ProviderModelSwitchTests": 1.689, -"ProviderCoreTests.ProviderRunMarkerTests": 0.015, -"ProviderCoreTests.ProviderRuntimeCapabilityTests": 0.006, -"ProviderCoreTests.ProviderSignalTests": 3.083, +"ProviderCoreTests.ProviderLoopPrefetchTests": 0.82, +"ProviderCoreTests.ProviderMTPFactoryTests": 0.031, +"ProviderCoreTests.ProviderModelSwitchTests": 1.737, +"ProviderCoreTests.ProviderRunMarkerTests": 0.016, +"ProviderCoreTests.ProviderRuntimeCapabilityTests": 0.005, +"ProviderCoreTests.ProviderSignalTests": 3.004, "ProviderCoreTests.ProviderStopSignalsTests": 0.0, -"ProviderCoreTests.QMVWideMetalTests": 0.996, +"ProviderCoreTests.QMVWideMetalTests": 1.172, "ProviderCoreTests.Qwen35AdjacentCheckpointLiveTests": 0.0, "ProviderCoreTests.Qwen35CBv2FixedRequestAccountingTests": 0.001, "ProviderCoreTests.Qwen35CheckpointRetentionLiveTests": 0.0, @@ -825,217 +817,215 @@ "ProviderCoreTests.Qwen38ProductionCanaryTests": 0.0, "ProviderCoreTests.Qwen4CanonicalMediaPositionsTests": 0.002, "ProviderCoreTests.Qwen4DefaultProfilePerformanceTests": 0.001, -"ProviderCoreTests.Qwen4EmbeddedMTPTests": 0.013, +"ProviderCoreTests.Qwen4EmbeddedMTPTests": 0.011, "ProviderCoreTests.Qwen4ExecutionPolicyTests": 0.0, -"ProviderCoreTests.Qwen4ExpLoadFootprintTests": 0.009, -"ProviderCoreTests.Qwen4ExpMmapFootprintTests": 0.015, -"ProviderCoreTests.Qwen4FactorySelectionTests": 0.002, +"ProviderCoreTests.Qwen4ExpLoadFootprintTests": 0.025, +"ProviderCoreTests.Qwen4ExpMmapFootprintTests": 0.01, +"ProviderCoreTests.Qwen4FactorySelectionTests": 0.003, "ProviderCoreTests.Qwen4FixedDepthPerformanceProbeTests": 0.001, "ProviderCoreTests.Qwen4LayerSubmissionSafetyProbeTests": 0.001, "ProviderCoreTests.Qwen4LayerSubmissionStateProbeTests": 0.0, -"ProviderCoreTests.Qwen4NativeMediaPrefixPositionsTests": 0.272, +"ProviderCoreTests.Qwen4NativeMediaPrefixPositionsTests": 0.348, "ProviderCoreTests.Qwen4NativeToolConstraintTests": 0.005, -"ProviderCoreTests.Qwen4OwnedVLMRoutingTests": 0.008, -"ProviderCoreTests.Qwen4PagingPrefixIntegrationTests": 18.933, +"ProviderCoreTests.Qwen4OwnedVLMRoutingTests": 0.006, +"ProviderCoreTests.Qwen4PagingPrefixIntegrationTests": 18.894, "ProviderCoreTests.Qwen4ReasoningControlTests": 0.0, -"ProviderCoreTests.Qwen4ReasoningEffortValidationTests": 0.004, -"ProviderCoreTests.Qwen4ReclaimAdmissionTests": 0.133, +"ProviderCoreTests.Qwen4ReasoningEffortValidationTests": 0.003, +"ProviderCoreTests.Qwen4ReclaimAdmissionTests": 0.126, "ProviderCoreTests.Qwen4SparseParallelProbeTests": 0.001, -"ProviderCoreTests.Qwen4StandaloneAdmissionTests": 0.027, -"ProviderCoreTests.Qwen4SupportPolicyTests": 0.01, +"ProviderCoreTests.Qwen4StandaloneAdmissionTests": 0.039, +"ProviderCoreTests.Qwen4SupportPolicyTests": 0.007, "ProviderCoreTests.Qwen4ToolChoicePromptPolicyTests": 0.002, -"ProviderCoreTests.Qwen4ToolFramingVocabularyTests": 0.002, -"ProviderCoreTests.QwenJSONAnswerConstraintTests": 4.233, -"ProviderCoreTests.QwenJSONAnswerOutputTests": 0.003, -"ProviderCoreTests.QwenJSONAnswerPolicyTests": 0.606, +"ProviderCoreTests.Qwen4ToolFramingVocabularyTests": 0.001, +"ProviderCoreTests.QwenJSONAnswerConstraintTests": 4.207, +"ProviderCoreTests.QwenJSONAnswerOutputTests": 0.006, +"ProviderCoreTests.QwenJSONAnswerPolicyTests": 0.581, "ProviderCoreTests.QwenJSONAnswerRealTokenizerTests": 0.0, -"ProviderCoreTests.QwenJSONAnswerServingTests": 0.555, +"ProviderCoreTests.QwenJSONAnswerServingTests": 0.548, "ProviderCoreTests.QwenPerImageVisionEquivalenceTests": 0.0, -"ProviderCoreTests.QwenVLMTargetExtractionTests": 2.747, +"ProviderCoreTests.QwenVLMTargetExtractionTests": 2.961, "ProviderCoreTests.ReasoningEffortLiveTests": 0.0, "ProviderCoreTests.ReasoningParserSelectionTests": 0.0, -"ProviderCoreTests.ReasoningPromptProbeTests": 0.003, +"ProviderCoreTests.ReasoningPromptProbeTests": 0.004, "ProviderCoreTests.ReleaseCoResidencyLiveTests": 0.0, -"ProviderCoreTests.RequestProfileBuilderTests": 0.046, -"ProviderCoreTests.ReserveRaisePreflightTests": 1.089, -"ProviderCoreTests.ResidentPrefixCacheEvidenceTests": 0.02, +"ProviderCoreTests.RequestProfileBuilderTests": 0.054, +"ProviderCoreTests.ReserveRaisePreflightTests": 1.11, +"ProviderCoreTests.ResidentPrefixCacheEvidenceTests": 0.021, "ProviderCoreTests.RetirementGateTests": 0.001, -"ProviderCoreTests.RuntimeConcurrencyBenchmarkTests": 0.053, -"ProviderCoreTests.RuntimeGenerationBenchmarkTests": 0.002, +"ProviderCoreTests.RuntimeConcurrencyBenchmarkTests": 0.051, +"ProviderCoreTests.RuntimeGenerationBenchmarkTests": 0.001, "ProviderCoreTests.RuntimeMetallibTemporaryDirectoryTests": 0.004, "ProviderCoreTests.SDPAPartialPrecisionTests": 1.324, -"ProviderCoreTests.SSDBlockIndexTests": 0.763, -"ProviderCoreTests.SSDBlockStoreTests": 0.063, -"ProviderCoreTests.SSDBlockStreamingTests": 0.027, -"ProviderCoreTests.SSDCacheEpochStoreRecoveryTests": 0.289, -"ProviderCoreTests.SSDCacheEpochStoreTests": 0.309, +"ProviderCoreTests.SSDBlockIndexTests": 0.0, +"ProviderCoreTests.SSDBlockStoreTests": 0.064, +"ProviderCoreTests.SSDBlockStreamingTests": 0.021, +"ProviderCoreTests.SSDCacheEpochStoreRecoveryTests": 0.288, +"ProviderCoreTests.SSDCacheEpochStoreTests": 0.281, "ProviderCoreTests.SSDCheckpointCPUAcceptanceTests": 0.314, -"ProviderCoreTests.SSDCheckpointCommitRetirementTests": 0.044, -"ProviderCoreTests.SSDCheckpointDeltaTests": 0.504, -"ProviderCoreTests.SSDCheckpointDemandAdmissionTests": 0.04, +"ProviderCoreTests.SSDCheckpointCommitRetirementTests": 0.043, +"ProviderCoreTests.SSDCheckpointDeltaTests": 0.496, +"ProviderCoreTests.SSDCheckpointDemandAdmissionTests": 0.041, "ProviderCoreTests.SSDCheckpointDemandTests": 0.011, "ProviderCoreTests.SSDCheckpointDonationHashBenchmarkTests": 0.0, "ProviderCoreTests.SSDCheckpointDonationHashTests": 0.019, "ProviderCoreTests.SSDCheckpointFileCoordinatorPathTests": 0.004, -"ProviderCoreTests.SSDCheckpointFileCoordinatorTests": 0.194, -"ProviderCoreTests.SSDCheckpointFleetWritePriorityTests": 0.113, +"ProviderCoreTests.SSDCheckpointFileCoordinatorTests": 0.01, +"ProviderCoreTests.SSDCheckpointFleetWritePriorityTests": 0.107, "ProviderCoreTests.SSDCheckpointLookupTests": 0.0, -"ProviderCoreTests.SSDCheckpointMaintenanceEpochTests": 0.058, -"ProviderCoreTests.SSDCheckpointPublicationCPUTests": 0.015, -"ProviderCoreTests.SSDCheckpointPublicationTests": 0.015, -"ProviderCoreTests.SSDCheckpointReadBudgetTests": 0.006, -"ProviderCoreTests.SSDCheckpointRecencyCoordinationTests": 0.013, -"ProviderCoreTests.SSDCheckpointRemovalRaceTests": 0.162, -"ProviderCoreTests.SSDCheckpointStageCostTests": 0.025, -"ProviderCoreTests.SSDCheckpointStageReservationTests": 0.007, -"ProviderCoreTests.SSDCheckpointWriteRecoveryTests": 0.148, -"ProviderCoreTests.SSDClosedStoreEvictionTests": 1.257, +"ProviderCoreTests.SSDCheckpointMaintenanceEpochTests": 0.068, +"ProviderCoreTests.SSDCheckpointPublicationCPUTests": 0.016, +"ProviderCoreTests.SSDCheckpointPublicationTests": 0.014, +"ProviderCoreTests.SSDCheckpointReadBudgetTests": 0.005, +"ProviderCoreTests.SSDCheckpointRecencyCoordinationTests": 0.01, +"ProviderCoreTests.SSDCheckpointRemovalRaceTests": 0.334, +"ProviderCoreTests.SSDCheckpointStageCostTests": 0.026, +"ProviderCoreTests.SSDCheckpointStageReservationTests": 0.005, +"ProviderCoreTests.SSDCheckpointWriteRecoveryTests": 0.153, "ProviderCoreTests.SSDCompleteCheckpointStageCapTests": 0.001, -"ProviderCoreTests.SSDCompleteDonationTelemetryTests": 0.033, -"ProviderCoreTests.SSDDebugCacheKeyFileTests": 0.035, -"ProviderCoreTests.SSDEpochContinuityTests": 0.061, -"ProviderCoreTests.SSDHybridCheckpointCoordinationTests": 0.123, -"ProviderCoreTests.SSDHybridCheckpointDuplicateTests": 0.16, -"ProviderCoreTests.SSDHybridCheckpointRecencyTests": 0.071, -"ProviderCoreTests.SSDHybridCheckpointStoreFactoryFailureTests": 0.02, -"ProviderCoreTests.SSDHybridCheckpointStoreTests": 0.119, -"ProviderCoreTests.SSDHybridMediaIdentityTests": 0.014, +"ProviderCoreTests.SSDCompleteDonationTelemetryTests": 0.031, +"ProviderCoreTests.SSDDebugCacheKeyFileTests": 0.037, +"ProviderCoreTests.SSDEpochContinuityTests": 0.065, +"ProviderCoreTests.SSDHybridCheckpointCoordinationTests": 0.085, +"ProviderCoreTests.SSDHybridCheckpointDuplicateTests": 0.159, +"ProviderCoreTests.SSDHybridCheckpointRecencyTests": 0.036, +"ProviderCoreTests.SSDHybridCheckpointStoreFactoryFailureTests": 0.014, +"ProviderCoreTests.SSDHybridCheckpointStoreTests": 0.114, +"ProviderCoreTests.SSDHybridMediaIdentityTests": 0.013, "ProviderCoreTests.SSDLookupKeysTests": 0.0, "ProviderCoreTests.SSDNativeCheckpointOracleTests": 1.07, -"ProviderCoreTests.SSDNativePrefixBuilderTests": 0.014, -"ProviderCoreTests.SSDNoFollowIOSpecialFileTests": 0.495, -"ProviderCoreTests.SSDOwnedEntryRetirementTests": 0.112, -"ProviderCoreTests.SSDPersistentTestKeyNamespaceTests": 0.007, -"ProviderCoreTests.SSDPrefixCacheDonationGateTests": 0.48, -"ProviderCoreTests.SSDPrefixCacheDonationOutcomeTests": 0.053, -"ProviderCoreTests.SSDPrefixCacheFactoryConstructionTests": 0.059, +"ProviderCoreTests.SSDNativePrefixBuilderTests": 0.013, +"ProviderCoreTests.SSDNoFollowIOSpecialFileTests": 0.554, +"ProviderCoreTests.SSDOwnedEntryRetirementTests": 0.014, +"ProviderCoreTests.SSDPersistentTestKeyNamespaceTests": 0.006, +"ProviderCoreTests.SSDPrefixCacheDonationGateTests": 0.472, +"ProviderCoreTests.SSDPrefixCacheDonationOutcomeTests": 0.223, +"ProviderCoreTests.SSDPrefixCacheFactoryConstructionTests": 0.067, "ProviderCoreTests.SSDPrefixCacheFactoryMaintenanceTests": 0.024, "ProviderCoreTests.SSDPrefixCacheFactoryPathTests": 0.001, -"ProviderCoreTests.SSDPrefixCacheFactoryRefusalTests": 0.003, -"ProviderCoreTests.SSDPrefixCacheLifecycleTests": 1.681, -"ProviderCoreTests.SSDPrefixCacheMetadataPlanningTests": 0.002, +"ProviderCoreTests.SSDPrefixCacheFactoryRefusalTests": 0.002, +"ProviderCoreTests.SSDPrefixCacheLifecycleTests": 1.781, +"ProviderCoreTests.SSDPrefixCacheMetadataPlanningTests": 0.001, "ProviderCoreTests.SSDPrefixCacheModeTests": 0.001, -"ProviderCoreTests.SSDPrefixCacheReadyReceiptTests": 0.21, -"ProviderCoreTests.SSDPrefixCacheReservationTests": 0.799, -"ProviderCoreTests.SSDPrefixCacheTelemetryTests": 0.004, -"ProviderCoreTests.SSDReadyWriteBarrierTests": 0.056, +"ProviderCoreTests.SSDPrefixCacheReadyReceiptTests": 0.249, +"ProviderCoreTests.SSDPrefixCacheReservationTests": 0.753, +"ProviderCoreTests.SSDPrefixCacheTelemetryTests": 0.005, +"ProviderCoreTests.SSDReadyWriteBarrierTests": 0.054, "ProviderCoreTests.SSDRootIsolationTests": 0.0, -"ProviderCoreTests.SSDSharedProcessCheckpointTests": 0.048, -"ProviderCoreTests.SSDShorterCheckpointRestoreTests": 0.832, +"ProviderCoreTests.SSDSharedProcessCheckpointTests": 0.061, +"ProviderCoreTests.SSDShorterCheckpointRestoreTests": 0.852, "ProviderCoreTests.SSDShorterNativeBlockRestoreTests": 2.004, -"ProviderCoreTests.SSDShorterRestoreClockTests": 0.047, +"ProviderCoreTests.SSDShorterRestoreClockTests": 0.051, "ProviderCoreTests.SSDTestDirectoryTests": 0.002, -"ProviderCoreTests.SSDTrackedNativeRetryTests": 0.015, -"ProviderCoreTests.SSDWholeRootMaintenanceTests": 0.283, -"ProviderCoreTests.SSDWholeRootTelemetryConcurrencyTests": 0.012, -"ProviderCoreTests.SSDWindowSidecarTests": 0.796, -"ProviderCoreTests.SSDWriteBehindLedgerChargeTests": 0.121, -"ProviderCoreTests.SSDWriteBudgetTests": 0.278, -"ProviderCoreTests.SSDWriteEnduranceTests": 1.874, -"ProviderCoreTests.ScheduleTests": 0.009, +"ProviderCoreTests.SSDTrackedNativeRetryTests": 0.012, +"ProviderCoreTests.SSDWholeRootMaintenanceTests": 0.219, +"ProviderCoreTests.SSDWholeRootTelemetryConcurrencyTests": 0.011, +"ProviderCoreTests.SSDWindowSidecarTests": 0.701, +"ProviderCoreTests.SSDWriteBudgetTests": 0.382, +"ProviderCoreTests.SSDWriteEnduranceTests": 1.959, +"ProviderCoreTests.ScheduleTests": 0.011, "ProviderCoreTests.SchedulerPrefillBenchmarkTests": 0.0, -"ProviderCoreTests.SchedulerPrefillDecisionBenchmarkTests": 0.06, +"ProviderCoreTests.SchedulerPrefillDecisionBenchmarkTests": 0.056, "ProviderCoreTests.SchedulerPrefillDecisionEvaluatorTests": 0.14, -"ProviderCoreTests.SchedulerPrefillDecisionKVProvenanceTests": 0.001, -"ProviderCoreTests.SchedulerPrefillDecisionLiveRunnerTests": 0.095, +"ProviderCoreTests.SchedulerPrefillDecisionKVProvenanceTests": 0.0, +"ProviderCoreTests.SchedulerPrefillDecisionLiveRunnerTests": 0.093, "ProviderCoreTests.SchedulerPrefillDecisionLiveTests": 0.0, -"ProviderCoreTests.SchedulerPrefillDecisionMetadataTests": 0.186, +"ProviderCoreTests.SchedulerPrefillDecisionMetadataTests": 0.104, "ProviderCoreTests.SchedulerPrefillPromptTests": 0.003, -"ProviderCoreTests.SecurityCommandRunnerTests": 0.229, +"ProviderCoreTests.SecurityCommandRunnerTests": 0.225, "ProviderCoreTests.SegmentedProductionGrantTests": 0.032, "ProviderCoreTests.SelfUpdaterInstallRootTests": 0.002, -"ProviderCoreTests.SelfUpdaterTests": 41.12, -"ProviderCoreTests.SequenceStateMachineTests": 0.0, +"ProviderCoreTests.SelfUpdaterTests": 40.446, +"ProviderCoreTests.SequenceStateMachineTests": 0.001, "ProviderCoreTests.ServeLoopAppAttestInteropTests": 0.0, -"ProviderCoreTests.ServeLoopAppAttestTests": 2.151, -"ProviderCoreTests.ServeLoopColdLoadTests": 2.788, -"ProviderCoreTests.ServeLoopConnectionTests": 6.565, -"ProviderCoreTests.ServeLoopDispatchTests": 1.483, -"ProviderCoreTests.ServiceReservationHandlerTests": 0.007, -"ProviderCoreTests.ServiceReservationInboundTests": 0.003, +"ProviderCoreTests.ServeLoopAppAttestTests": 1.873, +"ProviderCoreTests.ServeLoopColdLoadTests": 2.907, +"ProviderCoreTests.ServeLoopConnectionTests": 6.481, +"ProviderCoreTests.ServeLoopDispatchTests": 1.586, +"ProviderCoreTests.ServiceReservationHandlerTests": 0.006, +"ProviderCoreTests.ServiceReservationInboundTests": 0.002, "ProviderCoreTests.ServiceReservationLifetimeTests": 0.001, "ProviderCoreTests.ServiceReservationRequestProtocolTests": 0.0, -"ProviderCoreTests.ServingReadinessTests": 0.006, +"ProviderCoreTests.ServingReadinessTests": 0.002, "ProviderCoreTests.SignedReleaseIdentityTests": 0.003, "ProviderCoreTests.SingleProbeInlineDecisionTests": 0.001, "ProviderCoreTests.SlotSizingDriftTests": 0.002, -"ProviderCoreTests.SpecDecArtifactFunnelTests": 0.05, +"ProviderCoreTests.SpecDecArtifactFunnelTests": 0.051, "ProviderCoreTests.SpecDecHuggingFaceTests": 3.213, "ProviderCoreTests.SpecDecLoadGateTests": 0.001, -"ProviderCoreTests.SpecDecResolverTests": 5.566, +"ProviderCoreTests.SpecDecResolverTests": 5.31, "ProviderCoreTests.SpecDecSizingSnapshotTests": 0.001, -"ProviderCoreTests.SpecDecSlotTeardownTests": 0.005, -"ProviderCoreTests.StandaloneEvictionOwnershipTests": 0.004, -"ProviderCoreTests.StandaloneLifecycleControlTests": 0.806, -"ProviderCoreTests.StandaloneMTPUpgradeTests": 0.14, -"ProviderCoreTests.StandaloneServerDrainTests": 0.695, -"ProviderCoreTests.StandaloneServerModelAdmissionTests": 2.043, +"ProviderCoreTests.SpecDecSlotTeardownTests": 0.004, +"ProviderCoreTests.StandaloneEvictionOwnershipTests": 0.003, +"ProviderCoreTests.StandaloneLifecycleControlTests": 0.777, +"ProviderCoreTests.StandaloneMTPUpgradeTests": 0.145, +"ProviderCoreTests.StandaloneServerDrainTests": 0.751, +"ProviderCoreTests.StandaloneServerModelAdmissionTests": 2.034, "ProviderCoreTests.StartupPerformanceEvidenceTests": 0.004, -"ProviderCoreTests.StartupPreloadGateTests": 1.292, -"ProviderCoreTests.StartupPreloadNoEvictTests": 0.042, -"ProviderCoreTests.StartupPreloadPlanTests": 0.036, -"ProviderCoreTests.StartupPreloadPostRegistrationRetirementTests": 0.734, -"ProviderCoreTests.StartupPreloaderTests": 0.003, +"ProviderCoreTests.StartupPreloadGateTests": 1.212, +"ProviderCoreTests.StartupPreloadNoEvictTests": 0.048, +"ProviderCoreTests.StartupPreloadPlanTests": 0.019, +"ProviderCoreTests.StartupPreloadPostRegistrationRetirementTests": 0.76, +"ProviderCoreTests.StartupPreloaderTests": 0.002, "ProviderCoreTests.StartupSelfTestDecodeLiveTests": 0.0, -"ProviderCoreTests.StreamedToolCallTests": 0.034, -"ProviderCoreTests.StreamingFileDownloadDelegateTests": 0.023, -"ProviderCoreTests.StructuredForcedToolAdmissionTests": 0.044, -"ProviderCoreTests.SwiftJinjaCompatibilityTests": 0.008, -"ProviderCoreTests.SwiftJinjaLoopContextTests": 0.005, -"ProviderCoreTests.TeacherForcedBenchmarkTests": 0.004, +"ProviderCoreTests.StreamedToolCallTests": 0.033, +"ProviderCoreTests.StreamingFileDownloadDelegateTests": 0.042, +"ProviderCoreTests.StructuredForcedToolAdmissionTests": 0.046, +"ProviderCoreTests.SwiftJinjaCompatibilityTests": 0.004, +"ProviderCoreTests.SwiftJinjaLoopContextTests": 0.004, +"ProviderCoreTests.TeacherForcedBenchmarkTests": 0.005, "ProviderCoreTests.TelemetryClientTests": 0.0, -"ProviderCoreTests.TelemetryOverflowQueueTests": 0.004, +"ProviderCoreTests.TelemetryOverflowQueueTests": 0.002, "ProviderCoreTests.TelemetrySymmetryTests": 0.001, "ProviderCoreTests.ThinkStreamingLatencyTests": 0.001, -"ProviderCoreTests.ThroughputSweepDecodeTimingTests": 0.001, -"ProviderCoreTests.ThroughputSweepDecodeWarmupTests": 0.002, +"ProviderCoreTests.ThroughputSweepDecodeTimingTests": 0.002, +"ProviderCoreTests.ThroughputSweepDecodeWarmupTests": 0.001, "ProviderCoreTests.ThroughputSweepMedianTests": 0.002, -"ProviderCoreTests.ThroughputSweepNotesTests": 0.006, +"ProviderCoreTests.ThroughputSweepNotesTests": 0.004, "ProviderCoreTests.ThroughputSweepReportTests": 0.002, "ProviderCoreTests.ThroughputSweepRowAggregationTests": 0.0, "ProviderCoreTests.ThroughputSweepTilingTests": 0.0, -"ProviderCoreTests.TinyModelLoadTests": 3.176, +"ProviderCoreTests.TinyModelLoadTests": 4.015, "ProviderCoreTests.ToolCallTemplateArgumentsTests": 0.0, "ProviderCoreTests.ToolChoicePromptPolicyTests": 0.002, "ProviderCoreTests.ToolChoiceViolationErrorTests": 0.001, -"ProviderCoreTests.ToolSchemaNormalizationCorpusTests": 0.002, -"ProviderCoreTests.ToolSchemaNormalizationTests": 0.004, -"ProviderCoreTests.TransitionWatchdogSupervisionTests": 2.226, +"ProviderCoreTests.ToolSchemaNormalizationCorpusTests": 0.003, +"ProviderCoreTests.ToolSchemaNormalizationTests": 0.003, +"ProviderCoreTests.TransitionWatchdogSupervisionTests": 2.092, "ProviderCoreTests.TransitionWatchdogTests": 0.001, "ProviderCoreTests.UnauthorizedConnectionRecoveryTests": 0.001, -"ProviderCoreTests.UnauthorizedConnectionSupervisionTests": 0.061, -"ProviderCoreTests.UnevictableResidentReportTests": 0.08, -"ProviderCoreTests.UnitTests": 4.398, -"ProviderCoreTests.UnreclaimableLoadMemoryTests": 0.105, -"ProviderCoreTests.UnsupportedContentPartIngressTests": 0.003, +"ProviderCoreTests.UnauthorizedConnectionSupervisionTests": 0.067, +"ProviderCoreTests.UnevictableResidentReportTests": 0.078, +"ProviderCoreTests.UnitTests": 4.311, +"ProviderCoreTests.UnreclaimableLoadMemoryTests": 0.102, +"ProviderCoreTests.UnsupportedContentPartIngressTests": 0.004, "ProviderCoreTests.UpdateBannerTests": 0.001, "ProviderCoreTests.UpdateDrainAwarenessTests": 0.074, -"ProviderCoreTests.UpdateJitterTests": 0.003, -"ProviderCoreTests.UpdateProcessLockTests": 1.035, -"ProviderCoreTests.UpdateRecoveryStateTests": 0.002, -"ProviderCoreTests.VerifiedWeightHashStoreTests": 0.01, -"ProviderCoreTests.VisionTowerBudgetArithmeticTests": 0.001, +"ProviderCoreTests.UpdateJitterTests": 0.001, +"ProviderCoreTests.UpdateProcessLockTests": 1.037, +"ProviderCoreTests.UpdateRecoveryStateTests": 0.001, +"ProviderCoreTests.VerifiedWeightHashStoreTests": 0.024, +"ProviderCoreTests.VisionTowerBudgetArithmeticTests": 0.0, "ProviderCoreTests.VisionTowerBudgetIncidentTests": 0.001, "ProviderCoreTests.VisionTowerHeadFactorTests": 0.0, "ProviderCoreTests.WatchdogAgentPlistTests": 0.0, "ProviderCoreTests.WatchdogCrashLoopCountTests": 0.001, -"ProviderCoreTests.WatchdogCrashLoopNextStateTests": 0.005, -"ProviderCoreTests.WatchdogDecisionTests": 0.001, +"ProviderCoreTests.WatchdogCrashLoopNextStateTests": 0.003, +"ProviderCoreTests.WatchdogDecisionTests": 0.0, "ProviderCoreTests.WatchdogEffectiveDownSinceTests": 0.0, -"ProviderCoreTests.WatchdogLaunchAdapterTests": 0.172, +"ProviderCoreTests.WatchdogLaunchAdapterTests": 0.167, "ProviderCoreTests.WatchdogNextStateTests": 0.0, "ProviderCoreTests.WatchdogProbeParseTests": 0.001, -"ProviderCoreTests.WatchdogProviderIdentityTests": 0.002, +"ProviderCoreTests.WatchdogProviderIdentityTests": 0.004, "ProviderCoreTests.WatchdogRearmActionTests": 0.0, -"ProviderCoreTests.WatchdogRecoveryIntegrationTests": 11.164, -"ProviderCoreTests.WatchdogSchedulerTests": 0.042, +"ProviderCoreTests.WatchdogRecoveryIntegrationTests": 10.995, +"ProviderCoreTests.WatchdogSchedulerTests": 0.061, "ProviderCoreTests.WatchdogStateTests": 0.001, "ProviderCoreTests.WedgeMonitorTests": 0.001, -"ProviderCoreTests.WeightHashCacheEligibilityTests": 0.027, -"ProviderCoreTests.WholeMacServiceHeartbeatTests": 0.014, -"ProviderCoreTests.WholeMacServiceReservationTests": 0.044, +"ProviderCoreTests.WeightHashCacheEligibilityTests": 0.019, +"ProviderCoreTests.WholeMacServiceHeartbeatTests": 0.017, +"ProviderCoreTests.WholeMacServiceReservationTests": 0.046, "ServingQualificationTests.FlintHTTPBenchmarkTests": 0.0, -"ServingQualificationTests.ServingPromptCountArtifactTests": 0.003, +"ServingQualificationTests.ServingPromptCountArtifactTests": 0.004, "ServingQualificationTests.ServingPromptCountQualificationTests": 0.0, "ServingQualificationTests.ServingQualificationCollectorTests": 0.0, "ServingQualificationTests.ServingQualificationCompetingModelsTests": 0.0, From a7ccf0afa977d646f0fb32d1bb32f78af099ca8d Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 14:34:38 -0600 Subject: [PATCH 0254/1441] ci: keep NemotronSuperManagedSlotTests and Qwen4PagingPrefixIntegrationTests in different shards A process that runs NemotronSuperManagedSlotTests and then Qwen4PagingPrefixIntegrationTests crashes with SIGBUS (release qualification of the dev builds); each passes alone. The 3-shard PR plan put both in shard 2 with Nemotron first (run 41709742367 passed once anyway). KEPT_APART in scripts/provider-test-shards.py places such a pair on different shards in every lane. Remove the pair when the Nemotron fixture cleanup fix merges. Plans: PR CI 3 shards (Nemotron 2, Qwen4 3), release 5 shards (2 and 4). Co-Authored-By: Claude Opus 5.5 --- docs/developer/test.md | 6 +++++- scripts/provider-test-shards.py | 14 +++++++++++++- scripts/test-provider-test-shards.py | 13 +++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/docs/developer/test.md b/docs/developer/test.md index 79a3ef80ad..2abb736dce 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -130,7 +130,11 @@ native MiMo, desktop and installer gates. `Provider Unit Tests Summary` lists th the shards together executed the full list, checks that each Prompt Parity run executed every listed test of its suite, merges the shards' coverage profiles and uploads measured seconds per suite (`provider-test-shard-weights`). -When the shards drift apart, replace the weights file with that artifact. A +When the shards drift apart, replace the weights file with that artifact. +The suites in `KEPT_APART` never share a shard: a process that ran +`NemotronSuperManagedSlotTests` and then `Qwen4PagingPrefixIntegrationTests` +crashed with SIGBUS, and each passes alone. The pair stays apart until the +Nemotron fixture cleanup is fixed. A suite moves from the parallel class to the serial class when it fails or flakes in parallel; when in doubt, a suite stays serial. diff --git a/scripts/provider-test-shards.py b/scripts/provider-test-shards.py index b137fcb9e4..ba88cd97f6 100755 --- a/scripts/provider-test-shards.py +++ b/scripts/provider-test-shards.py @@ -54,6 +54,12 @@ FIRST_SHARD_EXTRA_SECONDS = 31.0 PARITY_SHARD_EXTRA_SECONDS = 65.0 LAST_SHARD_EXTRA_SECONDS = 190.0 +# Suites that must not share a serial process, in either order. A process that +# ran NemotronSuperManagedSlotTests and then Qwen4PagingPrefixIntegrationTests +# crashed with SIGBUS in release qualification; each passes alone. Remove the +# pair when the Nemotron fixture cleanup fix merges. +KEPT_APART = (("ProviderCoreTests.NemotronSuperManagedSlotTests", + "ProviderCoreTests.Qwen4PagingPrefixIntegrationTests"),) # A test identifier starts with its module and its top-level suite or function. SUITE = re.compile(r"^([^./]+)[./]([^./]+)") @@ -83,8 +89,14 @@ def assignment(shards, weights): assigned = [[] for _ in range(shards)] serial = {key: seconds for key, seconds in weights.items() if key.split(".", 1)[0] not in PARALLEL_MODULES} + partners = defaultdict(set) + for first, second in KEPT_APART: + partners[first].add(second) + partners[second].add(first) for key in sorted(serial, key=lambda key: (-serial[key], key)): - index = min(range(shards), key=lambda index: (loads[index], index)) + allowed = [index for index in range(shards) + if not partners[key] & set(assigned[index])] or list(range(shards)) + index = min(allowed, key=lambda index: (loads[index], index)) loads[index] += serial[key] assigned[index].append(key) return assigned, loads diff --git a/scripts/test-provider-test-shards.py b/scripts/test-provider-test-shards.py index 2268ec248d..13d8005475 100755 --- a/scripts/test-provider-test-shards.py +++ b/scripts/test-provider-test-shards.py @@ -107,6 +107,19 @@ def test_every_listed_test_runs_in_exactly_one_selection(self): self.assertEqual(sorted(selected), sorted(expected)) self.assertEqual(len(selected), len(set(selected))) + def test_kept_apart_suites_never_share_a_shard(self): + for first, second in shards.KEPT_APART: + # Weights that would put both on one shard: two light suites after + # two heavy ones fill the two least loaded shards in turn. + weights = {"ProviderCoreTests.A": 100.0, "ProviderCoreTests.B": 100.0, first: 1.0, second: 1.0} + for total in (2, 3, 5): + with self.subTest(pair=(first, second), shards=total): + assigned, _ = shards.assignment(total, weights) + holders = [index for index, keys in enumerate(assigned) if first in keys or second in keys] + self.assertEqual(len(holders), 2, assigned) + real, _ = shards.assignment(3, shards.load_weights()) + self.assertFalse(any(first in keys and second in keys for keys in real)) + def test_new_and_unweighted_suites_fall_into_the_last_shard(self): plans = self.plans(3) for test in ("ProviderCoreTests.BrandNew/g()", "ProviderCoreTests.freeFunction()"): From 918f3fe8a25651566512cfcacd2f0e798c784d94 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 14:54:13 -0600 Subject: [PATCH 0255/1441] test(provider): evaluate the Qwen4 paging fixture's random weights The tiny Qwen4ExpTextModel in Qwen4PagingPrefixIntegrationTests kept its random initial weights unevaluated. Its first forward runs the compiled hyper-connection decode closure, which captures those weights as constants, and MLX's compile_dfs recurses through every unevaluated input. Each random weight's graph reaches the process-global MLXRandom key, a lazy split chain that every earlier unevaluated draw in the test process lengthens. After the managed Nemotron Super slot tests (whose fixtures build random-init models and then replace the weights), the chain is deep enough that the recursion overflows the Swift Testing cooperative thread's stack. The guard page fault is EXC_BAD_ACCESS code=2, reported as signal 10, in release qualification shard 2 of dev b4800a5d5 and 70b2f6dc9. Evaluate the model after construction, as a loaded model's weights are and as the other tiny-model tests (Qwen4LayerSubmissionStateProbeTests, NemotronPagingPrefixIntegrationTests) already do. MLX eval is iterative, so evaluating the chain is safe and detaches it from the weights. Co-Authored-By: Claude Opus 5.5 --- .../Qwen4PagingPrefixIntegrationTests.swift | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Qwen4PagingPrefixIntegrationTests.swift b/provider-swift/Tests/ProviderCoreTests/Qwen4PagingPrefixIntegrationTests.swift index 4cea76ad0f..adfe191ce3 100644 --- a/provider-swift/Tests/ProviderCoreTests/Qwen4PagingPrefixIntegrationTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Qwen4PagingPrefixIntegrationTests.swift @@ -46,7 +46,14 @@ struct Qwen4PagingPrefixIntegrationTests { text.sharedExpertIntermediateSize = 32 text.moeIntermediateSize = 32 text.mropeSection = [2, 1, 1] - return Qwen4ExpTextModel(text) + // Evaluate the random weights, as a loaded model's are. The compiled + // hyper-connection trace captures the weights; unevaluated, MLX's + // recursive compile walks their graph into the process-global random + // key chain, which every earlier unevaluated draw in the test process + // lengthens, and overflows the test thread's stack (SIGBUS). + let model = Qwen4ExpTextModel(text) + eval(model) + return model } private func preparation( From 98418eacc57ba182e0f6c1f39378767217393bcc Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:42:52 -0800 Subject: [PATCH 0256/1441] test(cluster): an admission deadline ends that request, not the pair Production, 2026-11-03 23:07-23:19Z: six drops of the GLM-5.3-Flash pair in 19 minutes, and the same trigger on 2026-11-01 03:37Z (0.10.6). A request arrived with little of its first-content budget left, rank 0 answered its reservation at its next step boundary, after that admission deadline, and the leader ended the whole pair. These checks are red on origin/dev (0f99ddb18) and green with the fix that follows: - ClusterWorkerPairAdmissionDeadlineTests (scripted ranks in process): on a lane pair, a reservation answered after the request's admission deadline ends that request with a deadline outcome while the decoding lane finishes and nothing is fenced; a request ended before rank 1 was asked never fences rank 1; a closed link still ends the pair. - LinkWorkerChecks: the same deadline through both real owners and the link control channel (the follower printed the production line "fenced leader fenced: the request was cancelled before it started"), and a relayed reservation past its delivery deadline (the 23:10:25Z variant, "fenced command refused"). - PartialAdmissionTests and ProviderDeadlinePipeCheck asserted the old behaviour (pair quarantined, both ranks fenced) and now assert that only the request ends. missingProof keeps its contract with a rank that misses the pair's own admission wait. Co-Authored-By: Claude Opus 5.5 --- ...sterWorkerPairAdmissionDeadlineTests.swift | 315 ++++++++++++++++++ .../LinkWorkerPairCheck.swift | 139 ++++++++ .../ProcessChecks/PartialAdmissionTests.swift | 87 ++--- .../ProviderDeadlinePipeCheck.swift | 8 +- 4 files changed, 509 insertions(+), 40 deletions(-) create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRemoteTests/ClusterWorkerPairAdmissionDeadlineTests.swift diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRemoteTests/ClusterWorkerPairAdmissionDeadlineTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRemoteTests/ClusterWorkerPairAdmissionDeadlineTests.swift new file mode 100644 index 0000000000..402fb7f69c --- /dev/null +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRemoteTests/ClusterWorkerPairAdmissionDeadlineTests.swift @@ -0,0 +1,315 @@ +import Foundation +import XCTest +@testable import DarkbloomClusterProcess +import DarkbloomClusterProtocol + +/// One rank of a pair, scripted in this process: no worker, model or GPU. It +/// answers a reservation at once, or only when the test gives the answer (a +/// rank whose loop is inside a long step), runs a started request on rank 0 +/// one committed token per decision, `tokenNanoseconds` apart (a decode step), +/// and gives back a reservation it is told to cancel. It records every +/// reservation with its delivery deadline, every cancel and every fence. +private final class ScriptedRank: ClusterWorkerEndpoint, @unchecked Sendable { + static let identity = ClusterWorkerIdentity(membershipEpoch: UUID(), modelID: "fabricated-lanes", + artifactSHA256: String(repeating: "a", count: 64), configurationSHA256: String(repeating: "b", count: 64), + peers: [.init(id: "peer0", buildSHA256: String(repeating: "c", count: 64)), + .init(id: "peer1", buildSHA256: String(repeating: "d", count: 64))]) + static let profile = ClusterWorkerProfile(id: "fabricated-lanes", vocabularySize: 100, maximumPromptTokens: 64, + maximumOutputTokens: 128, maximumChunkTokens: 16, maximumContextTokens: 256) + static let plan = String(repeating: "e", count: 64) + let expectedIdentity = ScriptedRank.identity + let expectedProfile = ScriptedRank.profile + let executionPlanSHA256 = ScriptedRank.plan + let rank: Int + var readiness: ClusterWorkerReady? { lock.withLock { fenceReasons.isEmpty && !closed ? ready : nil } } + var localLifetimeDeadlineUptimeNanoseconds: UInt64 { UInt64.max } + var nativeCleanupObserved: Bool { lock.withLock { ended } } + private let ready: ClusterWorkerReady + private let tokenNanoseconds: UInt64 + private let lock = NSLock() + private let arrived = DispatchSemaphore(value: 0) + private var events: [ClusterWorkerEventFrame] = [] + private var sequence: UInt64 = 0 + private var handler: (@Sendable () -> Void)? + private var ended = false, closed = false, holdNext = false, closeWhenAsked = false + private var held = Set() + private var requests: [UUID: (prompt: Int, output: Int)] = [:] + private var sent: [(id: UUID, delivery: UInt64)] = [] + private var cancelled: [UUID] = [] + private var commandCount = 0 + private var fenceReasons: [String] = [] + + var reservations: [(id: UUID, delivery: UInt64)] { lock.withLock { sent } } + var cancels: [UUID] { lock.withLock { cancelled } } + var commands: Int { lock.withLock { commandCount } } + var fences: [String] { lock.withLock { fenceReasons } } + + init(rank: Int, tokenNanoseconds: UInt64 = 0) { + self.rank = rank; self.tokenNanoseconds = tokenNanoseconds + ready = ClusterWorkerReady(identity: Self.identity, rank: rank, profile: Self.profile, + executionPlanSHA256: Self.plan, requestCapacityBytes: 1 << 20) + emit(nil, .ready(ready)) + } + + /// The next reservation is answered only by `answerHeld`. + func holdNextAdmission() { lock.withLock { holdNext = true } } + func answerHeld(_ id: UUID) { + if lock.withLock({ held.remove(id) != nil }) { emit(id, .admitted(reservedBytes: 64)) } + } + /// The link to this rank closes for good when it is next asked anything. + func closeLinkWhenAsked() { lock.withLock { closeWhenAsked = true } } + + private func emit(_ requestID: UUID?, _ event: ClusterWorkerEvent) { + lock.withLock { + events.append(.init(membershipEpoch: Self.identity.membershipEpoch, sequence: sequence, + requestID: requestID, event: event)) + sequence += 1 + } + arrived.signal() + } + + private func emitToken(_ id: UUID, ordinal: Int) { + let prompt = lock.withLock { requests[id]?.prompt ?? 0 } + let token = ClusterWorkerEvent.committedToken(ordinal: ordinal, tokenID: 10 + ordinal % 50, + committedTokens: prompt + ordinal) + guard tokenNanoseconds > 0 else { return emit(id, token) } + DispatchQueue.global().asyncAfter(deadline: .now() + .nanoseconds(Int(tokenNanoseconds))) { self.emit(id, token) } + } + + func setInvalidationHandler(_ handler: @escaping @Sendable () -> Void) { + let now = lock.withLock { () -> Bool in self.handler = handler; return closed || !fenceReasons.isEmpty } + if now { DispatchQueue.global().async(execute: handler) } + } + + func sendWorkerCommand(_ command: ClusterWorkerCommand, requestID: UUID?, deadline: UInt64) throws { + let lost = lock.withLock { () -> (@Sendable () -> Void)? in + commandCount += 1 + guard closeWhenAsked && !closed else { return nil } + closed = true; return handler + } + if let lost { DispatchQueue.global().async(execute: lost) } + let admitLater = try lock.withLock { () -> Bool in + guard fenceReasons.isEmpty, !closed, !ended, deadline > DispatchTime.now().uptimeNanoseconds else { + throw ClusterWorkerOwnerError.closed + } + switch command { + case .reserve(let value): + sent.append((requestID!, deadline)) + requests[requestID!] = (value.promptTokenIDs.count, value.outputCount) + if holdNext { holdNext = false; held.insert(requestID!); return true } + case .cancel: cancelled.append(requestID!) + default: break + } + return false + } + switch command { + case .reserve where !admitLater: emit(requestID, .admitted(reservedBytes: 64)) + case .start where rank == 0: emitToken(requestID!, ordinal: 0) + case .start: emit(requestID, .finished(.length)); emit(requestID, .retired(.clean)) + case .tokenDecision(let ordinal, _): + if ordinal + 1 >= lock.withLock({ requests[requestID!]?.output ?? 0 }) { + emit(requestID, .finished(.length)); emit(requestID, .retired(.clean)) + } else { emitToken(requestID!, ordinal: ordinal + 1) } + case .cancel: emit(requestID, .retired(.cancelled)) + case .shutdown: emit(nil, .shutdownComplete); lock.withLock { ended = true } + default: break + } + } + + func receiveWorkerEvent(until deadline: UInt64, cancelled: () -> Bool) throws -> ClusterWorkerEventFrame { + while true { + if cancelled() { throw ClusterWorkerOwnerError.cancelled } + if let next = lock.withLock({ events.isEmpty ? nil : events.removeFirst() }) { return next } + if lock.withLock({ closed || !fenceReasons.isEmpty }) { throw ClusterWorkerOwnerError.closed } + let now = DispatchTime.now().uptimeNanoseconds + guard now < deadline else { throw ClusterWorkerOwnerError.deadline } + _ = arrived.wait(timeout: .init(uptimeNanoseconds: min(deadline, now + 5_000_000))) + } + } + + func requestNativeCleanup() { requestNativeCleanup(reason: "fenced without a cause") } + func requestNativeCleanup(reason: String) { + let notify = lock.withLock { () -> (@Sendable () -> Void)? in + let first = fenceReasons.isEmpty && !closed + fenceReasons.append(reason); ended = true + return first ? handler : nil + } + arrived.signal() + if let notify { DispatchQueue.global().async(execute: notify) } + } + func waitForNativeCleanup() { while !nativeCleanupObserved { Thread.sleep(forTimeInterval: 0.001) } } + func waitUntilNativeCleanup() async { while !nativeCleanupObserved { try? await Task.sleep(nanoseconds: 1_000_000) } } +} + +/// What a started request delivered to its consumer. +private final class Delivered: @unchecked Sendable { + private let lock = NSLock() + private var tokens = 0, finish: ClusterWorkerFinishReason?, failure: String? + func record(_ event: ClusterWorkerRequestEvent) { + lock.withLock { + switch event { + case .token: tokens += 1 + case .finished(let reason): finish = reason + case .failed(let text): failure = text + default: break + } + } + } + var value: (tokens: Int, finish: ClusterWorkerFinishReason?, failure: String?) { lock.withLock { (tokens, finish, failure) } } +} + +private final class Outcome: @unchecked Sendable { + private let lock = NSLock() + private var error: Error?, done = false + func finish(_ value: Error?) { lock.withLock { error = value; done = true } } + var result: (done: Bool, error: Error?) { lock.withLock { (done, error) } } +} + +/// Production, 2026-11-03 23:07–23:19Z (six drops of the GLM-5.3-Flash pair in +/// 19 minutes) and 2026-11-01 03:37Z: a request arrived with little of its +/// first-content budget left, and rank 0, busy with the pair's other lanes, +/// answered its reservation at its next step boundary, after that admission +/// deadline. The leader ended the whole pair: every lane in flight failed, rank 1 +/// (never asked) was fenced with "the request was cancelled before it started", +/// and the reservation's delivery deadline (that same budget) let rank 0's own +/// owner fence rank 0. Only that request may end. +final class ClusterWorkerPairAdmissionDeadlineTests: XCTestCase { + private func now() -> UInt64 { DispatchTime.now().uptimeNanoseconds } + private func wait(seconds: Double, until condition: () -> Bool) -> Bool { + let end = now() + UInt64(seconds * 1_000_000_000) + while !condition() && now() < end { Thread.sleep(forTimeInterval: 0.005) } + return condition() + } + private func reservation(output: Int) -> ClusterWorkerReservation { + .init(profileID: ScriptedRank.profile.id, promptTokenIDs: [1, 2, 3], stopTokenIDs: [], outputCount: output, + chunkSize: 4, deadlineUptimeNanoseconds: now() + 60_000_000_000, capacityLimitBytes: 1 << 20, + sampling: nil, prefixCache: nil) + } + private func lanePair(_ ranks: [ScriptedRank]) throws -> ClusterWorkerPair { + try ClusterWorkerPair(workers: ranks, startupDeadline: now() + 5_000_000_000, lanes: 4, lanesRetireAlone: true) + } + private func serve(_ pair: ClusterWorkerPair) throws { + let lease = try pair.reserve(requestID: UUID(), reservation: reservation(output: 3)) + let delivered = Delivered() + try lease.start { event in delivered.record(event); return true } + XCTAssertTrue(wait(seconds: 10) { lease.isRetired }, "the next request did not retire") + lease.releaseResources() + XCTAssertEqual(delivered.value.finish, .length, "the next request did not finish: \(delivered.value)") + } + private func shutdown(_ pair: ClusterWorkerPair) { + let done = DispatchSemaphore(value: 0) + Task.detached { await pair.shutdown(); done.signal() } + XCTAssertEqual(done.wait(timeout: .now() + 20), .success, "the pair did not shut down") + } + + /// (a) On a lane pair, rank 0 answers a reservation 600 ms after a request + /// arrived with 150 ms of its budget left. That request ends with a deadline + /// outcome; nothing is fenced, the pair stays valid, the lane decoding + /// meanwhile keeps running and finishes, and the pair serves the next request. + func testALaneWhoseRankAnswersAfterItsAdmissionDeadlineEndsAloneWhileTheOtherLanesFinish() throws { + let ranks = [ScriptedRank(rank: 0, tokenNanoseconds: 25_000_000), ScriptedRank(rank: 1)] + let pair = try lanePair(ranks) + let decoding = try pair.reserve(requestID: UUID(), reservation: reservation(output: 80)) + let delivered = Delivered() + try decoding.start { event in delivered.record(event); return true } + XCTAssertTrue(wait(seconds: 5) { delivered.value.tokens >= 2 }, "the first lane is not decoding") + + let late = UUID() + ranks[0].holdNextAdmission() + DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(600)) { ranks[0].answerHeld(late) } + let asked = now() + XCTAssertThrowsError(try pair.reserve(requestID: late, reservation: reservation(output: 4), + admissionDeadline: asked + 150_000_000)) { error in + XCTAssertEqual(error as? ClusterWorkerOwnerError, .deadline) + } + XCTAssertTrue(pair.admissionState.isValid && pair.readiness != nil, + "one request's admission deadline ended the pair: \(pair.lastRequestFailure ?? "no failure noted")") + XCTAssertNil(pair.lastRequestFailure) + XCTAssertEqual(ranks[0].fences, [], "rank 0 was fenced") + XCTAssertEqual(ranks[1].fences, [], "rank 1, never asked, was fenced") + XCTAssertEqual(ranks[1].reservations.map { $0.id }, [decoding.requestID], "rank 1 was asked after the deadline") + XCTAssertEqual(ranks[0].cancels, [late], "rank 0 did not give back its late admission") + // A rank's owner fences a worker whose reservation is unanswered past its + // delivery deadline: the request's budget must not be that deadline. + let delivery = try XCTUnwrap(ranks[0].reservations.first { $0.id == late }?.delivery) + XCTAssertGreaterThanOrEqual(delivery, asked + ClusterWorkerRequest.laneAdmissionWaitNanoseconds - 1_000_000_000, + "the reservation was delivered with the request's admission deadline, not the pair's admission wait") + XCTAssertFalse(decoding.isRetired, "the decoding lane did not keep running") + + XCTAssertTrue(wait(seconds: 15) { decoding.isRetired }, "the decoding lane did not retire") + decoding.releaseResources() + XCTAssertEqual(delivered.value.tokens, 80) + XCTAssertEqual(delivered.value.finish, .length) + XCTAssertNil(delivered.value.failure) + try serve(pair) + shutdown(pair) + XCTAssertTrue(ranks.allSatisfy { $0.fences.isEmpty && $0.nativeCleanupObserved }, "a rank did not end by its shutdown") + } + + /// (c) A request that ends while rank 0's answer is still on its way, before + /// rank 1 was ever asked, never fences rank 1, whatever ended it. Here the + /// pair fails for another reason (a lost peer, another lane's failure): the + /// pair's owner shuts rank 1 down, it is not fenced for a request it never + /// saw. Rank 0, which may hold the request, is fenced as before. + func testARequestEndedBeforeRankOneWasAskedNeverFencesRankOne() throws { + let ranks = [ScriptedRank(rank: 0), ScriptedRank(rank: 1)] + let pair = try lanePair(ranks) + ranks[0].holdNextAdmission() + let outcome = Outcome(), value = reservation(output: 4) + DispatchQueue.global().async { + do { _ = try pair.reserve(requestID: UUID(), reservation: value); outcome.finish(nil) } + catch { outcome.finish(error) } + } + XCTAssertTrue(wait(seconds: 5) { ranks[0].reservations.count == 1 }, "rank 0 was not asked") + Thread.sleep(forTimeInterval: 0.1) + pair.invalidate() + XCTAssertTrue(wait(seconds: 10) { outcome.result.done }, "the reservation did not end") + XCTAssertNotNil(outcome.result.error) + XCTAssertEqual(ranks[1].commands, 0, "rank 1 was asked") + XCTAssertEqual(ranks[1].fences, [], "rank 1, never asked, was fenced") + XCTAssertFalse(ranks[0].fences.isEmpty, "rank 0's pending answer was not fenced in a failed pair") + shutdown(pair) + XCTAssertTrue(ranks[1].nativeCleanupObserved && ranks[1].fences.isEmpty, "rank 1 did not end by its shutdown") + } + + /// (c) The same request ended by its caller (the pair's own shutdown) while + /// rank 0's answer is on its way fences nothing at all: rank 0 gives back + /// what it admitted, and rank 1 was never asked. + func testARequestItsCallerEndsBeforeRankOneWasAskedFencesNothing() throws { + let ranks = [ScriptedRank(rank: 0), ScriptedRank(rank: 1)] + let pair = try lanePair(ranks) + let request = UUID() + ranks[0].holdNextAdmission() + let outcome = Outcome(), value = reservation(output: 4) + DispatchQueue.global().async { + do { _ = try pair.reserve(requestID: request, reservation: value); outcome.finish(nil) } + catch { outcome.finish(error) } + } + XCTAssertTrue(wait(seconds: 5) { ranks[0].reservations.count == 1 }, "rank 0 was not asked") + DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(300)) { ranks[0].answerHeld(request) } + shutdown(pair) + XCTAssertTrue(wait(seconds: 10) { outcome.result.done }, "the reservation did not end") + XCTAssertEqual(outcome.result.error as? ClusterWorkerOwnerError, .cancelled) + XCTAssertEqual(ranks[1].reservations.count, 0, "rank 1 was asked") + XCTAssertEqual(ranks.map(\.fences), [[], []], "a rank was fenced for a request its caller ended") + XCTAssertEqual(ranks[0].cancels, [request], "rank 0 did not give back its admission") + } + + /// Regression: a peer that is really gone still ends the pair. The link to + /// rank 1 closes for good as it is asked; the request fails and the pair is + /// invalidated, as before. + func testALinkThatClosesDuringAdmissionStillEndsThePair() throws { + let ranks = [ScriptedRank(rank: 0), ScriptedRank(rank: 1)] + let pair = try lanePair(ranks) + ranks[1].closeLinkWhenAsked() + XCTAssertThrowsError(try pair.reserve(requestID: UUID(), reservation: reservation(output: 4), + admissionDeadline: now() + 10_000_000_000)) { error in + XCTAssertEqual(error as? ClusterWorkerOwnerError, .closed) + } + XCTAssertFalse(pair.admissionState.isValid) + XCTAssertNil(pair.readiness) + XCTAssertEqual(pair.lastRequestFailure?.hasSuffix("failed on the pair: admission: a rank's command stream closed"), true, + "\(pair.lastRequestFailure ?? "no failure noted")") + shutdown(pair) + } +} diff --git a/libs/darkbloom-cluster/Tests/LinkWorkerChecks/LinkWorkerPairCheck.swift b/libs/darkbloom-cluster/Tests/LinkWorkerChecks/LinkWorkerPairCheck.swift index 3667fdf8ae..62753a2aea 100644 --- a/libs/darkbloom-cluster/Tests/LinkWorkerChecks/LinkWorkerPairCheck.swift +++ b/libs/darkbloom-cluster/Tests/LinkWorkerChecks/LinkWorkerPairCheck.swift @@ -111,6 +111,46 @@ final class LinkHarness: @unchecked Sendable { func followerJournalBytes() -> UInt64 { journalBytes(followerDirectory) } } +/// The leader's side of one follower session, in this process: every wire +/// the follower sends, decoded. +final class CapturingLinkTransport: ClusterLinkWorkerTransport, @unchecked Sendable { + private let lock = NSLock() + private var sent: [ClusterLinkWorkerWire] = [] + func send(_ bytes: Data) throws { + let wire = try ClusterLinkWorkerWire.decode(bytes) + lock.withLock { sent.append(wire) } + } + /// The worker events the follower relayed. + var events: [ClusterWorkerEventFrame] { + lock.withLock { sent }.filter { $0.kind == .event }.compactMap { $0.worker.flatMap { try? ClusterWorkerCodec.decodeEvent($0) } } + } + var refusals: [ClusterLinkWorkerWire] { lock.withLock { sent }.filter { $0.kind == .commandRefused } } +} + +/// A follower server's reports, as the follower process prints them. +final class ReportLog: @unchecked Sendable { + private let lock = NSLock() + private var values: [ClusterLinkWorkerServer.Report] = [] + func add(_ report: ClusterLinkWorkerServer.Report) { lock.withLock { values.append(report) } } + var lines: [String] { + lock.withLock { values }.map { report in + switch report { + case .opened: "opened" + case .refused(let reason): "refused \(reason)" + case .fenced(_, let reason): "fenced \(reason)" + case .cleanup: "cleanup" + case .released(_, let cleanly): "released \(cleanly)" + } + } + } + var fenced: Bool { lines.contains { $0.hasPrefix("fenced") } } +} + +extension ClusterWorkerEvent { + var isReady: Bool { if case .ready = self { return true }; return false } + var isAdmission: Bool { if case .admitted = self { return true }; return false } +} + func localEndpoint(_ owner: URL, _ worker: String, _ dir: URL, behavior: String, relay: ClusterOwnerBootstrapRelay?, lifetimeNanoseconds: UInt64 = 15_000_000_000) throws -> ClusterRemoteWorkerEndpoint { try .init(transport: .init(executable: owner, arguments: [worker, dir.path, "0", behavior], environment: [:]), @@ -140,6 +180,8 @@ func shutdown(_ pair: ClusterWorkerPair, seconds: Int = 8, _ context: @autoclosu let worker = CommandLine.arguments[3] var passed = 0 try codec(); passed += 1; print("PASS codec: no host uptime crosses, a sampled reservation keeps its sampling and a routed one its route, closed fields") + try admissionDeadlineEndsThatRequestAlone(follower, owner, worker); passed += 1 + try expiredRelayedReservationIsThatRequestsRefusal(owner, worker); passed += 1 try served(follower, owner, worker, profile: "prelude"); passed += 1 try served(follower, owner, worker, profile: "mesh2"); passed += 1 try served(follower, owner, worker, profile: "none"); passed += 1 @@ -156,6 +198,103 @@ func shutdown(_ pair: ClusterWorkerPair, seconds: Int = 8, _ context: @autoclosu print("link-worker: \(passed) groups passed (two processes over loopback; not a hardware pass)") } + /// Production, 2026-11-03 23:07–23:19Z (six drops of the GLM pair) and + /// 2026-11-01 03:37Z: a request arrived with little of its first-content + /// budget left and rank 0 answered its reservation at its next step + /// boundary, after that admission deadline. The leader ended the pair: it + /// fenced rank 1, never asked ("leader fenced: the request was cancelled + /// before it started"), and rank 0's own owner fenced rank 0 when the + /// reservation's delivery deadline (the same budget) passed unanswered. + /// Through both real owners and the link, that request alone now ends: + /// rank 0 gives back its late admission, nothing is fenced, and the same + /// pair serves the next request. + static func admissionDeadlineEndsThatRequestAlone(_ follower: URL, _ owner: URL, _ worker: String) throws { + let harness = try LinkHarness(follower: follower, owner: owner, worker: worker, profile: "none", behavior: "normal") + let dir = try directory(); defer { try? FileManager.default.removeItem(at: dir) } + // Rank 0 answers each reservation 0.3 s after it is asked. + let first = try localEndpoint(owner, worker, dir, behavior: "slow-admit", relay: nil) + let second = try harness.linkEndpoint(relay: nil) + let pair = try ClusterWorkerPair(workers: [first, second], startupDeadline: now() + 10_000_000_000) + var outcome: Error? + do { + _ = try pair.reserve(requestID: UUID(), reservation: .init(profileID: fixtureProfile.id, + promptTokenIDs: [1, 2], stopTokenIDs: [], outputCount: 2, chunkSize: 1, + deadlineUptimeNanoseconds: now() + 8_000_000_000, capacityLimitBytes: 1800, sampling: nil, prefixCache: nil), + admissionDeadline: now() + 100_000_000) + } catch { outcome = error } + try require((outcome as? ClusterWorkerOwnerError) == .deadline, "The request did not end with its deadline: \(String(describing: outcome))") + // A fence on its way reaches the follower well within this. + _ = harness.sawReport("fenced", seconds: pair.readiness == nil ? 5 : 1) + try require(pair.readiness != nil && pair.admissionState.isValid, + "One request's admission deadline ended the pair: \(pair.lastRequestFailure ?? "no failure noted"); follower: \(harness.reports)") + try require(!harness.reports.contains { $0.hasPrefix("fenced") }, "The follower was fenced: \(harness.reports)") + try require(!first.nativeCleanupObserved && !second.nativeCleanupObserved, + "A rank's worker ended: rank 0 \(first.nativeCleanupObserved), rank 1 \(second.nativeCleanupObserved)") + try runRequest(pair) + try shutdown(pair, seconds: 8, "rank0 cleanup \(first.nativeCleanupObserved) rank1 cleanup \(second.nativeCleanupObserved) follower \(harness.reports)") + try require(first.nativeCleanupObserved && second.nativeCleanupObserved, "Missing cleanup proof") + try require(second.waitForOwnerReleased(deadline: now() + 10_000_000_000), "Follower's release proof missing: \(harness.reports)") + try require(first.waitForOwnerReleased(deadline: now() + 10_000_000_000), "Leader's local owner release missing") + let status = try harness.finish() + try require(status == 0 && harness.reports.contains("released true") && !harness.reports.contains(where: { $0.hasPrefix("fenced") }), + "Follower reports differ: \(harness.reports)") + print("PASS an admission deadline ends that request alone over the link: rank 0 gave back its late admission, nothing fenced, the pair served the next request") + } + + /// Production, 2026-11-03 23:10:25Z: rank 1's reservation reached the + /// follower past its delivery deadline, its own owner refused to queue it, + /// and the follower fenced its session ("command refused"), which ended + /// the pair. That request alone is now refused (`commandRefused`, + /// `deadline`): the follower's session, its real owner and worker serve on. + static func expiredRelayedReservationIsThatRequestsRefusal(_ owner: URL, _ worker: String) throws { + let transport = CapturingLinkTransport(), reports = ReportLog() + let dir = try directory(); defer { try? FileManager.default.removeItem(at: dir) } + let server = ClusterLinkWorkerServer(transport: transport, clusterID: "cpu-test", rank: 1, bootstrapProfile: nil, + admit: { open in + .init(identity: fixtureIdentity, profile: fixtureProfile) { relay in + try ClusterRemoteWorkerEndpoint(transport: .init(executable: owner, arguments: [worker, dir.path, "1", "normal"], environment: [:]), + clusterID: "cpu-test", expectedIdentity: fixtureIdentity, profile: fixtureProfile, rank: 1, + executionPlanSHA256: fixturePlan, lifetimeDeadlineUptimeNanoseconds: open.lifetimeDeadlineUptimeNanoseconds, + bootstrapRelay: relay) + } + }, report: { reports.add($0) }) + let epoch = fixtureIdentity.membershipEpoch, session = UUID() + var open = ClusterLinkWorkerWire(kind: .open, epoch: epoch, session: session, sequence: 0) + open.clusterID = "cpu-test"; open.rank = 1; open.planSHA256 = fixturePlan; open.remainingNanoseconds = 20_000_000_000 + server.deliver(try open.encoded()) + try require(wait(seconds: 10) { transport.events.contains { $0.event.isReady } }, "The follower's worker was not ready: \(reports.lines)") + func reservation() -> ClusterWorkerCommand { + .reserve(.init(profileID: fixtureProfile.id, promptTokenIDs: [1, 2], stopTokenIDs: [], outputCount: 2, chunkSize: 1, + deadlineUptimeNanoseconds: now() + 8_000_000_000, capacityLimitBytes: 900, sampling: nil, prefixCache: nil)) + } + let expired = UUID(), next = UUID() + var at = now() + // One nanosecond of delivery time left: past it before this Mac's owner can queue it. + server.deliver(try ClusterLinkWorkerWire.command(reservation(), requestID: expired, epoch: epoch, session: session, + sequence: 1, now: at, deliveryDeadline: at + 1).encoded()) + try require(wait(seconds: 5) { transport.refusals.contains { $0.requestID == expired } || reports.fenced }, + "Nothing came back for the expired reservation: \(reports.lines)") + try require(!reports.fenced, "The follower fenced its session for one request's delivery deadline: \(reports.lines)") + try require(transport.refusals.first { $0.requestID == expired }?.detail == ClusterWorkerRefusal.deadline.rawValue, + "The refusal does not name the deadline: \(transport.refusals)") + // The session serves on: the next reservation reaches the worker, which admits it and gives it back. + at = now() + server.deliver(try ClusterLinkWorkerWire.command(reservation(), requestID: next, epoch: epoch, session: session, + sequence: 2, now: at, deliveryDeadline: at + 5_000_000_000).encoded()) + try require(wait(seconds: 5) { transport.events.contains { $0.requestID == next && $0.event.isAdmission } }, + "The next reservation was not admitted: \(reports.lines)") + at = now() + server.deliver(try ClusterLinkWorkerWire.command(.cancel(.callerCancelled), requestID: next, epoch: epoch, session: session, + sequence: 3, now: at, deliveryDeadline: at + 5_000_000_000).encoded()) + try require(wait(seconds: 5) { transport.events.contains { $0.requestID == next && $0.event == .retired(.cancelled) } }, + "The next reservation was not given back: \(reports.lines)") + try require(!reports.fenced && server.busy, "The follower's session did not serve on: \(reports.lines)") + server.stop() + try require(server.waitUntilIdle(deadline: now() + 40_000_000_000), "The follower's session did not end: \(reports.lines)") + try require(reports.lines.contains("released true"), "The follower's owner did not release: \(reports.lines)") + print("PASS a relayed reservation past its delivery deadline is that request's refusal (deadline); the follower's session served on") + } + /// A fence names its cause (S24): the follower's report, and so its /// incident, carries the leader's reason; the proofs still come back over /// the live link and the leader's waits end with them. diff --git a/libs/darkbloom-cluster/Tests/ProcessChecks/PartialAdmissionTests.swift b/libs/darkbloom-cluster/Tests/ProcessChecks/PartialAdmissionTests.swift index 7fa3ce2f96..df93aabd51 100644 --- a/libs/darkbloom-cluster/Tests/ProcessChecks/PartialAdmissionTests.swift +++ b/libs/darkbloom-cluster/Tests/ProcessChecks/PartialAdmissionTests.swift @@ -12,7 +12,7 @@ private final class SubmissionEndpoint: ClusterWorkerEndpoint, @unchecked Sendab private let lock = NSLock() private let proof = DispatchGroup() private var proofGranted: Bool - private var reserves = 0, cancels = 0 + private var reserves = 0, cancels = 0, fences = 0 /// Refuses every reservation as a full command queue does /// (`ClusterWorkerOwnerError.refused(.busy)`): the rank is never asked. private let queueFull: Bool @@ -21,6 +21,7 @@ private final class SubmissionEndpoint: ClusterWorkerEndpoint, @unchecked Sendab if holdProof { proof.enter() } } var counts: (Int, Int) { lock.withLock { (reserves, cancels) } } + var fenceCount: Int { lock.withLock { fences } } var expectedIdentity: ClusterWorkerIdentity { child.expectedIdentity } var expectedProfile: ClusterWorkerProfile { child.expectedProfile } var rank: Int { child.rank } @@ -39,7 +40,7 @@ private final class SubmissionEndpoint: ClusterWorkerEndpoint, @unchecked Sendab func receiveWorkerEvent(until deadline: UInt64, cancelled: () -> Bool) throws -> ClusterWorkerEventFrame { try child.receiveWorkerEvent(until: deadline, cancelled: cancelled) } - func requestNativeCleanup() { child.requestNativeCleanup() } + func requestNativeCleanup() { lock.withLock { fences += 1 }; child.requestNativeCleanup() } func waitForNativeCleanup() { child.waitForNativeCleanup(); proof.wait() } func waitUntilNativeCleanup() async { await child.waitUntilNativeCleanup() @@ -66,37 +67,11 @@ private final class AdmissionCompletion: @unchecked Sendable { try await endpointRefusals(executable) try await cancelledBeforeStart(executable) try await servingContext(executable) - // An unanswered submitted reservation is not a refusal: the pair is - // quarantined. Real children enforce their protocol. - for (behaviors, milliseconds, reserves, cancels) in [ - (["slow-admit", "normal"], 100, [1, 0], [0, 0]) - ] { - let now = DispatchTime.now().uptimeNanoseconds, end = now + 10_000_000_000 - let endpoints = try (0..<2).map { rank -> SubmissionEndpoint in - let child = try ClusterWorkerProcess(launch: .init(executable: executable, - arguments: [String(rank), behaviors[rank]], environment: [:]), expectedIdentity: fixtureIdentity, - rank: rank, profile: fixtureProfile, executionPlanSHA256: fixturePlan, - startupDeadline: now + 3_000_000_000, initialLeaseDeadline: end) - try child.launch(); return SubmissionEndpoint(child) - } - defer { for endpoint in endpoints { endpoint.requestNativeCleanup() } } - let pair = try ClusterWorkerPair(workers: endpoints, startupDeadline: now + 3_000_000_000) - var refused = false - do { - _ = try pair.reserve(requestID: UUID(), reservation: .init(profileID: fixtureProfile.id, - promptTokenIDs: [1, 2, 3], stopTokenIDs: [], outputCount: 2, chunkSize: 2, - deadlineUptimeNanoseconds: end, capacityLimitBytes: 1800, sampling: nil, prefixCache: nil), - admissionDeadline: DispatchTime.now().uptimeNanoseconds + UInt64(milliseconds) * 1_000_000) - } catch { refused = true } - try requirePartial(refused && pair.readiness == nil, "Admission failure did not quarantine pair") - try requirePartial(endpoints.map { $0.counts.0 } == reserves, "Unexpected reservation submission") - try requirePartial(endpoints.map { $0.counts.1 } == cancels, "Cancel reached an unconfirmed or refused rank") - await pair.shutdown() - try requirePartial(endpoints.allSatisfy(\.nativeCleanupObserved), "Missing actual child cleanup") - } + try await admissionDeadline(executable) try await missingProof(executable) print("{\"passed\":true,\"groups\":8,\"actualLocalChildren\":true,\"partialAdmission\":true," - + "\"requestScopedRefusal\":true,\"endpointRefusal\":true,\"cancelBeforeStart\":true,\"servingContext\":true}") + + "\"requestScopedRefusal\":true,\"endpointRefusal\":true,\"cancelBeforeStart\":true,\"servingContext\":true," + + "\"admissionDeadline\":true}") alarm(0) } @@ -233,6 +208,37 @@ private final class AdmissionCompletion: @unchecked Sendable { try requirePartial(endpoints.allSatisfy { $0.child.termination == .exited(0) }, "A rank did not exit cleanly") } + /// Production, 2026-11-03 (six drops of a GLM pair in 19 minutes): a + /// request whose own admission deadline, its first-content budget, passes + /// while rank 0 is still answering ends alone. Rank 0 gives back its late + /// admission, rank 1 is never asked, nothing is fenced and the same pair + /// serves the next request. Before, the pair was quarantined and both + /// ranks were fenced. + static func admissionDeadline(_ executable: URL) async throws { + let end = DispatchTime.now().uptimeNanoseconds + 10_000_000_000 + let endpoints = try launch(executable, ["slow-admit", "normal"], until: end) + defer { for endpoint in endpoints { endpoint.requestNativeCleanup() } } + let pair = try ClusterWorkerPair(workers: endpoints, startupDeadline: DispatchTime.now().uptimeNanoseconds + 3_000_000_000) + var outcome: ClusterWorkerOwnerError? + do { + _ = try pair.reserve(requestID: UUID(), reservation: reservation(until: end), + admissionDeadline: DispatchTime.now().uptimeNanoseconds + 100_000_000) + } catch let error as ClusterWorkerOwnerError { outcome = error } + try requirePartial(outcome == .deadline, "The request did not end with its deadline (\(String(describing: outcome)))") + try requirePartial(pair.readiness != nil && pair.admissionState.isValid, + "One request's admission deadline quarantined the pair: \(pair.lastRequestFailure ?? "no failure noted")") + try requirePartial(endpoints.map(\.fenceCount) == [0, 0], "A rank was fenced for one request's deadline") + try requirePartial(endpoints.map { $0.counts.0 } == [1, 0], "Rank 1 was asked after the request's deadline") + try requirePartial(endpoints.map { $0.counts.1 } == [1, 0], "Rank 0's late admission was not given back") + try await serve(pair, until: end) + await pair.shutdown() + try requirePartial(endpoints.allSatisfy { $0.child.termination == .exited(0) }, "A rank did not exit cleanly") + } + + /// A rank that does not answer within the pair's own admission wait has + /// failed: the pair is quarantined, that rank is fenced, and reserve does + /// not return before its actual cleanup proof. The rank never asked holds + /// nothing of the request: it is not fenced, and the pair's shutdown ends it. static func missingProof(_ executable: URL) async throws { let now = DispatchTime.now().uptimeNanoseconds, end = now + 10_000_000_000 let endpoints = try (0..<2).map { rank -> SubmissionEndpoint in @@ -240,33 +246,36 @@ private final class AdmissionCompletion: @unchecked Sendable { arguments: [String(rank), rank == 0 ? "slow-admit" : "normal"], environment: [:]), expectedIdentity: fixtureIdentity, rank: rank, profile: fixtureProfile, executionPlanSHA256: fixturePlan, startupDeadline: now + 3_000_000_000, initialLeaseDeadline: end) - try child.launch(); return SubmissionEndpoint(child, holdProof: rank == 1) + try child.launch(); return SubmissionEndpoint(child, holdProof: rank == 0) } defer { for endpoint in endpoints { endpoint.allowCleanupProof(); endpoint.requestNativeCleanup() } } - let pair = try ClusterWorkerPair(workers: endpoints, startupDeadline: now + 3_000_000_000) + let pair = try ClusterWorkerPair(workers: endpoints, startupDeadline: now + 3_000_000_000, + timing: .init(admissionWaitNanoseconds: 100_000_000, shutdownAcknowledgementNanoseconds: 2_000_000_000)) let completion = AdmissionCompletion() DispatchQueue.global().async { do { _ = try pair.reserve(requestID: UUID(), reservation: .init(profileID: fixtureProfile.id, promptTokenIDs: [1, 2, 3], stopTokenIDs: [], outputCount: 2, chunkSize: 2, - deadlineUptimeNanoseconds: end, capacityLimitBytes: 1800, sampling: nil, prefixCache: nil), - admissionDeadline: DispatchTime.now().uptimeNanoseconds + 100_000_000) + deadlineUptimeNanoseconds: end, capacityLimitBytes: 1800, sampling: nil, prefixCache: nil)) completion.complete(refused: false) } catch { completion.complete(refused: true) } } let wait = DispatchTime.now().uptimeNanoseconds + 3_000_000_000 - while !endpoints.allSatisfy({ $0.child.nativeCleanupObserved }), DispatchTime.now().uptimeNanoseconds < wait { + while !endpoints[0].child.nativeCleanupObserved, DispatchTime.now().uptimeNanoseconds < wait { try await Task.sleep(nanoseconds: 10_000_000) } - try requirePartial(endpoints.allSatisfy({ $0.child.nativeCleanupObserved }), "Expected actual child exits") - try requirePartial(completion.result == nil && !endpoints[1].nativeCleanupObserved && pair.readiness == nil, + try requirePartial(endpoints[0].child.nativeCleanupObserved, "Expected rank 0's actual child exit") + try requirePartial(completion.result == nil && !endpoints[0].nativeCleanupObserved && pair.readiness == nil, "Missing endpoint proof allowed reserve to return/release its partial ownership") try requirePartial(endpoints.map { $0.counts.1 } == [0, 0], "Pending/never-submitted rank received cancel") - endpoints[1].allowCleanupProof() + try requirePartial(endpoints[1].counts.0 == 0 && endpoints[1].fenceCount == 0, + "The rank never asked was fenced (\(endpoints[1].fenceCount)) or asked") + endpoints[0].allowCleanupProof() while completion.result == nil, DispatchTime.now().uptimeNanoseconds < wait { try await Task.sleep(nanoseconds: 10_000_000) } try requirePartial(completion.result == true, "Actual cleanup proof did not finish failed admission") await pair.shutdown() + try requirePartial(endpoints[1].child.termination == .exited(0), "The rank never asked did not exit by its shutdown") } } diff --git a/libs/darkbloom-cluster/Tests/ProcessChecks/ProviderDeadlinePipeCheck.swift b/libs/darkbloom-cluster/Tests/ProcessChecks/ProviderDeadlinePipeCheck.swift index df4e49181a..397937c650 100644 --- a/libs/darkbloom-cluster/Tests/ProcessChecks/ProviderDeadlinePipeCheck.swift +++ b/libs/darkbloom-cluster/Tests/ProcessChecks/ProviderDeadlinePipeCheck.swift @@ -50,7 +50,13 @@ private func require(_ condition: Bool, _ message: String) throws { if !conditio throw Failure(message: "slow reserve ignored first-token admission cap") } catch ClusterWorkerOwnerError.deadline { } try require(began.duration(to: .now) < .seconds(4), "admission cleanup exceeded bound") - try require(workers.allSatisfy(\.observedExit), "reserve threw before actual fences") + // That request alone (production, 2026-11-03): rank 0 gave back its + // late admission, nothing was fenced, and the pair takes the next request. + try require(!workers.contains(where: \.observedExit) && owner.readiness() != nil, + "one request's first-token deadline ended the pair") + let next = try owner.reserve(request, identity: identity, profileID: profile.id, capacityLimit: 1800, + deadlineContext: .init(generationDeadline: ContinuousClock.now.advanced(by: .seconds(20)))) + next.cancel(); await next.waitUntilRetired(); next.releaseResources() } else { let lease = try owner.reserve(request, identity: identity, profileID: profile.id, capacityLimit: 1800, deadlineContext: context) From 9a23988084589e786ab1a27acfed8d0606cc7605 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:53:46 -0800 Subject: [PATCH 0257/1441] fix(cluster): an admission deadline ends that request, not the pair A request that arrives with little of its first-content budget left can see a busy rank answer its reservation at its next step boundary, after that admission deadline. The leader treated that as a pair failure: it invalidated the pair (every lane in flight failed with "distributed peer readiness lost"), fenced rank 1, which was never asked ("leader fenced: the request was cancelled before it started"), and its follower closed its worker. Production, 2026-11-03 23:07-23:19Z: six drops of the GLM-5.3-Flash pair in 19 minutes (and 2026-11-01 03:37Z on 0.10.6). - ClusterWorkerPair.reserve: a deadline during admission, once the request's own deadline has passed, is that request's outcome. It is cancelled with `.deadline`, so its cleanup retires alone: an answer still on its way is read and an admission given back within the lane wait, and the pair stays valid. A rank that does not give it back in time still ends the pair; every other failure keeps the catch-all. - ClusterWorkerRequest.admit: a reservation is delivered within the pair's admission wait, not with the request's admission deadline. Each rank's owner (ClusterWorkerOwnerService) fences a worker whose reservation is unanswered past its delivery deadline, so with the budget as that deadline rank 0's own owner still ended the pair (the link check shows it with the other fixes alone). The request's deadline still bounds how long reserve waits for the answers; a rank is not asked once it has passed, and a send closed only because its deadline passed is that deadline. - ClusterWorkerRequest.cleanup: a rank never asked is acknowledged, never fenced, whatever ended the request. - ClusterLinkWorkerServer: a relayed reservation that reaches the follower past its delivery deadline is that request's refusal (commandRefused, deadline), not a fence of the follower's session. No wire format changes. docs/architecture/inference.md states the rule; docs/developer/test.md names the checks; changelog fragment added. Co-Authored-By: Claude Opus 5.5 --- .../cluster-admission-deadline-per-request.md | 16 +++++++++++ docs/architecture/inference.md | 28 +++++++++++++++++++ docs/developer/test.md | 13 +++++++++ .../ClusterWorkerPair.swift | 12 ++++++++ .../ClusterWorkerRequest.swift | 23 ++++++++++++--- .../ClusterLinkWorkerEndpoint.swift | 20 +++++++++---- 6 files changed, 102 insertions(+), 10 deletions(-) create mode 100644 changelog.d/cluster-admission-deadline-per-request.md diff --git a/changelog.d/cluster-admission-deadline-per-request.md b/changelog.d/cluster-admission-deadline-per-request.md new file mode 100644 index 0000000000..d36f7cd42a --- /dev/null +++ b/changelog.d/cluster-admission-deadline-per-request.md @@ -0,0 +1,16 @@ +### A pair no longer drops all its requests when one request runs out of time before it starts + +- A two-Mac pair no longer drops all its requests when one request runs out of + time before it starts. When a request arrived with almost none of its + first-response time left and a busy Mac answered its reservation at its next + step, the leader ended the whole pair: every request in flight failed + (`distributed peer readiness lost`), the other Mac logged `session fenced: + leader fenced: the request was cancelled before it started` (or `command + refused`), and the pair re-formed about 20 seconds later. A GLM-5.3-Flash + pair under load dropped six times in 19 minutes. +- Now only that request fails, with a deadline error. The Mac that answered late + gives its reservation back, the Mac that was never asked is left alone, and + the pair keeps serving its other requests. A reservation that reaches the + other Mac too late is refused for that request alone. +- A pair still ends when a Mac or its link is really lost, or when a Mac does + not answer or give a reservation back in time. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 1fe23bc81d..2c280409bb 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -71,6 +71,34 @@ the public calls keep their synchronous queue order. Source: (`onQueueWithoutWaiting`) and `provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift`. +A pair request's admission deadline (the first-content budget left when it +arrived, `DistributedRequestDeadlineContext`) is that request's alone. It bounds +how long the pair's reservation waits for the ranks' answers, never how long a +reservation may take to reach a rank: each rank's owner fences a worker whose +reservation is unanswered past its delivery deadline +(`ClusterWorkerOwnerService`), so every reservation is delivered within the +pair's admission wait, at least `ClusterWorkerRequest.laneAdmissionWaitNanoseconds` +(30 s) with lanes. A busy rank answers at its next step boundary. When the +request's own deadline passes first, the pair throws +`ClusterWorkerOwnerError.deadline` for that request only. A rank not yet asked +is not asked; an answer still on its way is read and an admission given back +(`retired(cancelled)`) within `ClusterWorkerRequest.laneRetirementWaitNanoseconds` +(30 s); the other lanes run on. Only a rank that does not give the reservation +back in time ends the pair. A rank never asked is never fenced for a request, +whatever ended it: a failing pair's owner shuts it down. A relayed reservation +that reaches the follower past its delivery deadline is that request's refusal +(`commandRefused`, `deadline`), not a fence of the follower's session. A closed +link, a lost rank, or a rank that does not answer within the pair's admission +wait still ends the pair. Before, the deadline ended the whole pair: every lane +in flight failed and the follower logged `leader fenced: the request was +cancelled before it started`. Sources: +`libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerPair.swift` +(`reserve`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerRequest.swift` +(`admit`, `cleanup`) and +`libs/darkbloom-cluster/Sources/DarkbloomClusterRemote/ClusterLinkWorkerEndpoint.swift` +(`ClusterLinkWorkerWire.requestRefusal`). + The cluster setup liveness probe uses the same request validation as ordinary chat completions. `ClusterSetupProbeRequest` sends no family-specific thinking override, so each model’s prompt policy remains authoritative. diff --git a/docs/developer/test.md b/docs/developer/test.md index 5fb42f11ac..61a6229e26 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -2785,6 +2785,19 @@ bytes, cancellation before start, early-release refusal and idempotent release after retirement. It runs no model or MLX code; it does not replace the full provider contract or hardware suites. +A pair request whose admission deadline passes while a rank is still answering +ends alone. `ClusterWorkerPairAdmissionDeadlineTests` (in +`bash libs/darkbloom-cluster/Tests/RemoteChecks/run.sh`) drives a lane pair over +scripted ranks: rank 0 answers after the request's deadline while another lane +decodes, a request ends before rank 1 was asked, and a link closes during +admission. `bash libs/darkbloom-cluster/Tests/LinkWorkerChecks/run.sh` runs the +same deadline through both stand-in owners (the actual owner service) and the +loopback link, and relays a reservation past its delivery deadline to an +in-process follower. `PartialAdmissionTests` and `ProviderDeadlinePipeCheck` in +`bash libs/darkbloom-cluster/Tests/ProcessChecks/run.sh` run it with actual +children, the latter through the provider's own deadline and owner sources. +None of these is a hardware pass. + ### Qwen27 tensor-parallel native batch checks Run `QwenTensorParallelBatchDriverTests`, `QwenTensorParallelBatchBudgetTests` diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerPair.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerPair.swift index 0edd3b2964..b5d5af8c43 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerPair.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerPair.swift @@ -404,6 +404,18 @@ public final class ClusterWorkerPair: @unchecked Sendable { if lease.withdrewBeforeStart { lease.releaseResources(); throw ClusterWorkerOwnerError.cancelled } noteRequestFailure(lease, "admission: the request was cancelled and a rank did not give it back") invalidate(); lease.releaseResources(); throw ClusterWorkerOwnerError.cancelled + } catch ClusterWorkerOwnerError.deadline where DispatchTime.now().uptimeNanoseconds + >= min(reservation.deadlineUptimeNanoseconds, admissionDeadline ?? UInt64.max) { + // The request's own deadline passed while its ranks were asked (a + // busy rank answers at its next step boundary): this request ends, + // not the pair. Its cleanup reads an answer still on its way and + // gives back every admission within the lane wait; a rank that + // does not give it back in time ends the pair there. + lease.cancel(reason: .deadline) + lease.waitForRetirement() + if lease.withdrewBeforeStart { lease.releaseResources(); throw ClusterWorkerOwnerError.deadline } + noteRequestFailure(lease, "admission: the request's deadline passed and a rank did not give it back") + invalidate(); lease.releaseResources(); throw ClusterWorkerOwnerError.deadline } catch { // Named for the pair's incident (S24), as a started request's failure is. noteRequestFailure(lease, "admission: " + ClusterWorkerRequest.failureText(error)) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerRequest.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerRequest.swift index 68e48b668b..70c84893d1 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerRequest.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerRequest.swift @@ -53,8 +53,13 @@ public final class ClusterWorkerRequest: @unchecked Sendable { baseReservation.deadlineUptimeNanoseconds - now <= ClusterWorkerLimits.deadlineNanoseconds else { throw ClusterWorkerOwnerError.deadline } - let deadline = min(baseReservation.deadlineUptimeNanoseconds, admissionDeadline ?? UInt64.max, - now + owner.admissionWaitNanoseconds) + // A rank's owner fences a worker that has not answered a reservation + // by its delivery deadline (`ClusterWorkerOwnerService`), so the + // reservation is delivered within the pair's admission wait, as any + // command is. The request's admission deadline, often nearly spent on + // arrival, bounds only how long this request waits for the answers. + let delivery = min(baseReservation.deadlineUptimeNanoseconds, now + owner.admissionWaitNanoseconds) + let deadline = min(delivery, admissionDeadline ?? UInt64.max) guard now < deadline else { throw ClusterWorkerOwnerError.deadline } let qwenMedia = lock.withLock { self.qwenMedia } var bytes = 0 @@ -74,8 +79,15 @@ public final class ClusterWorkerRequest: @unchecked Sendable { qwenMedia: index == 0 ? qwenMedia : qwenMedia?.withoutEncodedBytes) try lock.withLock { guard cancellation == nil else { throw ClusterWorkerOwnerError.cancelled } + // Past the request's admission deadline the next rank is not asked. + guard DispatchTime.now().uptimeNanoseconds < deadline else { throw ClusterWorkerOwnerError.deadline } do { - try worker.sendWorkerCommand(.reserve(local), requestID: requestID, deadline: deadline) + try worker.sendWorkerCommand(.reserve(local), requestID: requestID, deadline: delivery) + } catch ClusterWorkerOwnerError.closed + where DispatchTime.now().uptimeNanoseconds >= deadline && worker.readiness != nil { + // A serving endpoint closes a send only once its deadline + // passed: nothing reached the rank. The request's deadline. + throw ClusterWorkerOwnerError.deadline } catch ClusterWorkerOwnerError.refused(let reason) where reason != .unavailable { // The rank's endpoint could not take this reservation now // (its command queue) or carry it: nothing reached the @@ -417,7 +429,10 @@ public final class ClusterWorkerRequest: @unchecked Sendable { // Never-submitted/refused ranks have no request to cancel. Pending // submission can race an unread refusal, so only confirmed admission // permits request cancel. All other ranks need actual native cleanup. - if alone && (submitted[index] == .none || submitted[index] == .refused) { + // A rank never asked holds nothing of the request, whatever ended + // it: nothing to give back and nothing to fence (a failing pair's + // owner shuts it down). + if submitted[index] == .none || (alone && submitted[index] == .refused) { // Never asked, or it refused: this rank holds nothing for the request. acknowledged[index] = true continue diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRemote/ClusterLinkWorkerEndpoint.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRemote/ClusterLinkWorkerEndpoint.swift index 229c05d23a..de387eb638 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRemote/ClusterLinkWorkerEndpoint.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRemote/ClusterLinkWorkerEndpoint.swift @@ -294,12 +294,16 @@ public struct ClusterLinkWorkerWire: Codable, Sendable, Equatable { /// The refusal a relayed command's failure is, when it is one request's: /// a reservation the follower's own owner could not take now (`busy`, its - /// queue) or could not encode (`profile`). Nothing reached the worker. Any - /// other failure (a malformed wire, a closed owner) fences the session. - static func requestRefusal(relaying command: ClusterWorkerCommand, failure error: Error) -> ClusterWorkerRefusal? { + /// queue), could not encode (`profile`), or that reached this Mac after its + /// delivery deadline (`deadline`: a still serving owner closes such a + /// send). Nothing reached the worker. Any other failure (a malformed wire, + /// a closed owner) fences the session. + static func requestRefusal(relaying command: ClusterWorkerCommand, failure error: Error, + deliveryExpired: Bool = false) -> ClusterWorkerRefusal? { guard case .reserve = command else { return nil } if case .refused(let reason)? = error as? ClusterWorkerOwnerError, reason != .unavailable { return reason } if error is ClusterWorkerProtocolError { return .profile } + if deliveryExpired, error as? ClusterWorkerOwnerError == .closed { return .deadline } return nil } @@ -994,13 +998,17 @@ private final class ServerSession: @unchecked Sendable { do { local = try wire.localCommand(now: now) } catch { fence(reason: "command refused"); return } do { try endpoint?.sendWorkerCommand(local.command, requestID: local.requestID, deadline: local.deliveryDeadline) - } catch let error where ClusterLinkWorkerWire.requestRefusal(relaying: local.command, failure: error) != nil { + } catch { + let expired = DispatchTime.now().uptimeNanoseconds >= local.deliveryDeadline && endpoint?.readiness != nil + guard let reason = ClusterLinkWorkerWire.requestRefusal(relaying: local.command, failure: error, + deliveryExpired: expired) else { + fence(reason: "command refused"); return + } // A reservation this Mac's owner could not take: nothing reached // the worker (no command sequence was spent), so that request // alone is refused and the session goes on. - let reason = ClusterLinkWorkerWire.requestRefusal(relaying: local.command, failure: error)! send({ $0.requestID = local.requestID; $0.detail = reason.rawValue }, kind: .commandRefused) - } catch { fence(reason: "command refused") } + } default: fence(reason: "unexpected message") } From f37f53b53f54412d381ded5c991fc94749ebe7ec Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:54:43 -0800 Subject: [PATCH 0258/1441] test(provider): cluster link isolation on three Macs after pairing Three isolated Macs captured read-only on 2026-11-03 after their cable ports paired (Mac A on en3, the M5 Max and the M3 Ultra on en6). Each route table holds macOS's host route for the port's own address on the loopback, `10.219.13.112 UHLWIi lo0`, which macOS adds once the address has carried traffic. The link checks run each table through the inspection, the summary, the guided flow and a dry run of the fix; the diagnostics checks run Mac A's through the doctor. On origin/dev every one of them reports the port as not isolated (clusterSubnetInUse), as the three Macs do; the next commit fixes that. An address in 10.219/16 on a VPN tunnel, a route into it through utun, bridge0 or another en port, and a loopback route for an address the port does not carry still block, and are checked to. Co-Authored-By: Claude Opus 5.5 --- .../ClusterLinkFindingsCheck.swift | 41 ++++++ .../ClusterLinkChecks/ClusterLinkCheck.swift | 1 + .../LinkIsolationChecks.swift | 41 ++++++ .../LinkIsolationFixtures.swift | 120 ++++++++++++++++++ 4 files changed, 203 insertions(+) diff --git a/provider-swift/Tests/ClusterDiagnosticsChecks/ClusterLinkFindingsCheck.swift b/provider-swift/Tests/ClusterDiagnosticsChecks/ClusterLinkFindingsCheck.swift index 5557b65cab..316aa1f818 100644 --- a/provider-swift/Tests/ClusterDiagnosticsChecks/ClusterLinkFindingsCheck.swift +++ b/provider-swift/Tests/ClusterDiagnosticsChecks/ClusterLinkFindingsCheck.swift @@ -157,5 +157,46 @@ extension ClusterDiagnosticsCheck { ("localLinkDevice.rdma_en7", .passed), ("localLinkIsolation.rdma_en7", .passed)], "an exposed port serving does not use") try require(try detail(sharing, "localLinkIsolation.rdma_en6").contains("Darkbloom does not change Internet Sharing") && detail(sharing, "localLinkIsolation.rdma_en6").contains("“Thunderbolt 2” (en6)"), "the owner's step for Internet Sharing") + + // Mac A after pairing, through the inspection itself: macOS reaches the + // port's own address through lo0, which is not the subnet used elsewhere. + let paired = report(ClusterLinkReadinessProbe.inspect(run: pairedMacA, readingIsolation: true), configuredDevice: "rdma_en3") + try requireChecks(paired, [("localLink", .passed), ("localLinkDevice.rdma_en3", .passed), ("localLinkIsolation.rdma_en3", .passed)], + "Mac A after pairing") + try require(try detail(paired, "localLinkIsolation.rdma_en3").hasPrefix("Isolated: Thunderbolt port en3 has its own network service"), + "Mac A after pairing: the doctor says isolated") + } + + /// Mac A after pairing (2026-11-03): its cable port's address and cluster + /// subnet routes as captured, MAC addresses replaced; the other readings as + /// Darkbloom leaves an isolated port. + private static func pairedMacA(_ command: ClusterLinkToolCommand) -> ClusterLinkToolOutcome { + let device = "hca_id:\trdma_en3\n\ttransport:\t\t\tThunderbolt (100)\n\t\tport:\t1\n\t\t\tstate:\t\t\tPORT_ACTIVE (4)\n" + switch command { + case .rdmaControlStatus: return .output("enabled\n") + case .rdmaDeviceList: return .output(device) + case .rdmaDeviceDetail: return .output(device + "\t\t\tGID[ 2]:\t\t::ffff:10.219.13.112\n") + case .interfaceList: + return .output("lo0: flags=8049 mtu 16384\n\tinet 127.0.0.1 netmask 0xff000000\n" + + "en3: flags=8863 mtu 1500\n" + + "\tinet 10.219.13.112 netmask 0xffff0000 broadcast 10.219.255.255\n\tstatus: active\n") + case .hardwarePorts: return .output("Hardware Port: Thunderbolt 3\nDevice: en3\n") + case .networkServiceOrder: + return .output("An asterisk (*) denotes that a network service is disabled.\n(1) Darkbloom Cluster Link (en3)\n" + + "(Hardware Port: Thunderbolt 3, Device: en3)\n") + case .networkServiceInfo: + return .output("Manual Configuration\nIP address: 10.219.13.112\nSubnet mask: 255.255.0.0\nRouter: (null)\nIPv6: Link Local\n") + case .bridgePreferences: return .output("{}\n") + case .routeTable: + return .output("Routing tables\n\nInternet:\nDestination Gateway Flags Netif Expire\n" + + "default 192.0.2.1 UGScg en1\n" + + "10.219/16 link#19 UCS en3 !\n" + + "10.219.13.112/32 link#19 UCS en3 !\n" + + "10.219.13.112 2:0:5e:0:53:3 UHLWIi lo0\n" + + "10.219.165.133 2:0:5e:0:53:33 UHLWIi en3 1150\n" + + "10.219.255.255 ff:ff:ff:ff:ff:ff UHLWbI en3 !\n") + case .dnsConfiguration: return .output("DNS configuration\n") + default: return .unavailable + } } } diff --git a/provider-swift/Tests/ClusterLinkChecks/ClusterLinkCheck.swift b/provider-swift/Tests/ClusterLinkChecks/ClusterLinkCheck.swift index 53d3cf39a5..613826a5b3 100644 --- a/provider-swift/Tests/ClusterLinkChecks/ClusterLinkCheck.swift +++ b/provider-swift/Tests/ClusterLinkChecks/ClusterLinkCheck.swift @@ -56,6 +56,7 @@ import Darwin ("isolation command set", isolationCommandSet), ("isolation Mac A findings", isolationMacAFindings), ("isolation Mac B findings", isolationMacBFindings), + ("isolation after pairing", isolationPairedMacs), ("isolation plans", isolationPlans), ("isolation fix outcomes", isolationFixOutcomes), ("isolation remove outcomes", isolationRemoveOutcomes), diff --git a/provider-swift/Tests/ClusterLinkChecks/LinkIsolationChecks.swift b/provider-swift/Tests/ClusterLinkChecks/LinkIsolationChecks.swift index a08ce9ad47..b9e6bdc349 100644 --- a/provider-swift/Tests/ClusterLinkChecks/LinkIsolationChecks.swift +++ b/provider-swift/Tests/ClusterLinkChecks/LinkIsolationChecks.swift @@ -223,6 +223,47 @@ extension ClusterLinkCheck { "a hostile service name on the port blocks it") } + /// Three isolated Macs after pairing: macOS's loopback route to the port's + /// own address is not the cluster subnet used elsewhere, and everything + /// that is still blocks. + static func isolationPairedMacs() { + for mac in IsolationFixtures.pairedMacs { + let world = FakeIsolationWorld(mac.tools()) + let report = world.report() + let port = report.devices.first { $0.device == mac.device } + expectEqual(port?.verdict, .ready, "\(mac.name): ready") + expectEqual(port?.isolation?.findings, [], "\(mac.name): isolated with its own address routed through lo0") + expect(report.summaryLines.contains(" \(mac.device) (\(mac.port)): ready · port active · own IPv4 address · " + + "IPv4-mapped GID published · isolated: own network service, fixed address, no bridge, router or DNS"), + "\(mac.name): the probe says isolated: \(report.summaryLines)") + expectEqual(report.guidance, nil, "\(mac.name): nothing to do") + expect(compactJSON(report).contains("\"isolation\":{\"findings\":[],\"isolated\":true}"), "\(mac.name): JSON says isolated") + expectEqual(world.fix(dryRun: true).outcome, .alreadyReady, "\(mac.name): a dry run of the fix is not refused") + var flow = ClusterLinkSetupFlow(mayPrompt: true) + let step = flow.observed(report) + expectEqual(step.action, .finish(exitCode: 0), "\(mac.name): the guided flow is done") + expect(step.lines.contains { $0.hasPrefix("Isolated: Thunderbolt port \(mac.port) has its own network service") }, + "\(mac.name): and says so: \(step.lines)") + + func findings(routes: [String] = [], interfaces: String = "") -> [ClusterLinkIsolationFinding]? { + FakeIsolationWorld(mac.tools(extraRoutes: routes, extraInterfaces: interfaces)).report() + .devices.first { $0.device == mac.device }?.isolation?.findings + } + let vpn = IsolationFixtures.tunnel("utun4", address: "10.219.77.1") + expectEqual(findings(interfaces: vpn), [.clusterSubnetInUse], "\(mac.name): a VPN address in the cluster subnet") + expectEqual(findings(routes: ["10.219.77.1 2:0:5e:0:53:99 UHLWIi lo0 "], interfaces: vpn), + [.clusterSubnetInUse], "\(mac.name): the VPN address and its loopback route") + for route in ["10.219/16 link#40 UCS utun4 ", + "10.219.77/24 link#13 UCS bridge0 !", + "10.219.77.7 2:0:5e:0:53:99 UHLWIi en9 1200", + "\(mac.address) \(mac.address) UH utun4 "] { + expectEqual(findings(routes: [route]), [.clusterSubnetInUse], "\(mac.name): a route elsewhere: \(route)") + } + expectEqual(findings(routes: ["10.219.77.77 2:0:5e:0:53:99 UHLWIi lo0 "]), + [.clusterSubnetInUse], "\(mac.name): a loopback route for an address the port does not carry") + } + } + static func isolationPlans() { let addressA = IsolationFixtures.macAAddress.dottedDecimal let planA = ClusterLinkIsolationPlan(interface: "en7", address: IsolationFixtures.macAAddress, hardwarePort: "Thunderbolt 6", diff --git a/provider-swift/Tests/ClusterLinkChecks/LinkIsolationFixtures.swift b/provider-swift/Tests/ClusterLinkChecks/LinkIsolationFixtures.swift index 62e8fa6902..ed69fcc2c2 100644 --- a/provider-swift/Tests/ClusterLinkChecks/LinkIsolationFixtures.swift +++ b/provider-swift/Tests/ClusterLinkChecks/LinkIsolationFixtures.swift @@ -405,6 +405,126 @@ enum IsolationFixtures { tools.isolation.routes = .output(macBIsolatedRoutes(address: address.dottedDecimal)) return tools } + + // MARK: three isolated Macs after pairing + + /// An isolated Mac captured read-only on 2026-11-03 after its port paired + /// and carried traffic. `routes` are the captured `netstat -rn -f inet` + /// rows for the default routes, the cluster subnet and the loopback, and + /// the port carries its captured cluster address; MAC addresses, the + /// Wi-Fi gateway and its address are placeholders. The rest of each Mac + /// is what Darkbloom leaves on an isolated port. + struct PairedMac { + let name: String + let port: String + let address: String + let hardwarePort: String + let wifi: String + let devices: [String] + let otherPorts: [String] + let bridgeMembers: [String] + let routes: [String] + let serviceOrder: String + + var device: String { ClusterLinkName.device(ofInterface: port) } + + func tools(extraRoutes: [String] = [], extraInterfaces: String = "") -> FakeLinkTools { + var tools = FakeLinkTools( + deviceList: .output(devices.map { LinkFixtures.deviceBlock($0, active: $0 == device) }.joined()), + interfaces: .output(LinkFixtures.loopback + IsolationFixtures.port(wifi, active: true, addresses: [LinkFixtures.wifiIPv4]) + + otherPorts.map { IsolationFixtures.port($0, active: false, addresses: []) }.joined() + + IsolationFixtures.port(port, active: true, addresses: [address]) + + (bridgeMembers.isEmpty ? "" : LinkFixtures.bridge(members: bridgeMembers)) + extraInterfaces), + details: [device: .output(LinkFixtures.detailWithMappedGID(device))]) + let bridges = bridgeMembers.isEmpty ? IsolationFixtures.emptyBridgePreferences + : "{\"bridge0\":{\"Interfaces\":[\(bridgeMembers.map { "\"\($0)\"" }.joined(separator: ","))]}}\n" + tools.isolation = FakeIsolationTools(hardwarePorts: .output("Hardware Port: \(hardwarePort)\nDevice: \(port)\n"), + serviceOrder: .output(serviceOrder), + serviceInfo: [ClusterLinkServiceName.cluster(interface: port): .output(IsolationFixtures.manualServiceInfo(address: address))], + bridgePreferences: .output(bridges), routes: .output(IsolationFixtures.routeTable(routes + extraRoutes)), + dns: .output("DNS configuration\n\n" + IsolationFixtures.resolver(1, servers: ["192.0.2.1"], interface: wifi, scoped: false))) + return tools + } + } + + /// `ifconfig` of a VPN tunnel with one IPv4 address. + static func tunnel(_ name: String, address: String) -> String { + "\(name): flags=8051 mtu 1380\n\tinet \(address) --> \(address) netmask 0xffffffff\n" + + "\tnd6 options=201\n" + } + + /// Mac A, port en3, paired with 10.219.165.133. macOS reaches its own + /// address through `lo0`, as it does the Wi-Fi address. + static let pairedMacA = PairedMac(name: "Mac A", port: "en3", address: "10.219.13.112", hardwarePort: "Thunderbolt 3", + wifi: "en1", devices: ["rdma_en2", "rdma_en13", "rdma_en3", "rdma_en4", "rdma_en5", "rdma_en6"], + otherPorts: ["en2", "en13", "en4", "en5", "en6"], bridgeMembers: ["en2", "en13", "en5", "en6"], + routes: [ + "default 192.0.2.1 UGScg en1 ", + "default link#38 UCSIg utun8 ", + "10.219/16 link#19 UCS en3 !", + "10.219.13.112/32 link#19 UCS en3 !", + "10.219.13.112 2:0:5e:0:53:3 UHLWIi lo0 ", + "10.219.165.133 2:0:5e:0:53:33 UHLWIi en3 1150", + "10.219.255.255 ff:ff:ff:ff:ff:ff UHLWbI en3 !", + "127 127.0.0.1 UCS lo0 ", + "127.0.0.1 127.0.0.1 UH lo0 ", + "\(LinkFixtures.wifiIPv4) 2:0:5e:0:53:1 UHLWI lo0 ", + ], + serviceOrder: serviceOrderHeader + service(1, "Ethernet", port: "Ethernet", device: "en0") + + service(2, "USB 10/100/1000 LAN", port: "USB 10/100/1000 LAN", device: "en14") + + service(3, "Thunderbolt Bridge", port: "Thunderbolt Bridge", device: "bridge0") + + service(4, "Wi-Fi", port: "Wi-Fi", device: "en1") + + service(5, "Darkbloom Cluster Link (en4)", port: "Thunderbolt 4", device: "en4") + + service(6, "Darkbloom Cluster Link (en3)", port: "Thunderbolt 3", device: "en3") + + service(7, "Tailscale", port: "io.tailscale.ipn.macsys", device: "")) + + /// The M5 Max, port en6, paired with the M3 Ultra. Darkbloom's services + /// on en1 and en2 are left from earlier cables; those ports are down. + static let pairedM5Max = PairedMac(name: "M5 Max", port: "en6", address: "10.219.129.164", hardwarePort: "Thunderbolt 2", + wifi: "en0", devices: ["rdma_en1", "rdma_en6", "rdma_en2"], otherPorts: ["en1", "en2"], bridgeMembers: [], + routes: [ + "default 192.0.2.1 UGScg en0 ", + "default link#40 UCSIg utun15 ", + "10.219/16 link#11 UCS en6 !", + "10.219.21.80 2:0:5e:0:53:26 UHLWIi en6 1128", + "10.219.129.164/32 link#11 UCS en6 !", + "10.219.129.164 2:0:5e:0:53:16 UHLWI lo0 ", + "10.219.255.255 ff:ff:ff:ff:ff:ff UHLWbI en6 !", + "127 127.0.0.1 UCS lo0 ", + "127.0.0.1 127.0.0.1 UH lo0 ", + ], + serviceOrder: serviceOrderHeader + service(1, "Dell D3100 USB3.0 Dock", port: "Dell D3100 USB3.0 Dock", device: "en8") + + service(2, "USB 10/100/1000 LAN", port: "USB 10/100/1000 LAN", device: "en10") + + service(3, "Thunderbolt Bridge", port: "Thunderbolt Bridge", device: "bridge0") + + service(4, "Thunderbolt Bridge 2", port: "Thunderbolt Bridge", device: "bridge0") + + service(5, "Wi-Fi", port: "Wi-Fi", device: "en0") + + service(6, "Darkbloom Cluster Link (en2)", port: "Thunderbolt 3", device: "en2") + + service(7, "Darkbloom Cluster Link (en1)", port: "Thunderbolt 1", device: "en1") + + service(8, "Darkbloom Cluster Link (en6)", port: "Thunderbolt 2", device: "en6") + + service(9, "iPhone USB", port: "iPhone USB", device: "en9") + + service(10, "Tailscale 2", port: "io.tailscale.ipn.macsys", device: "")) + + /// The M3 Ultra, port en6, paired with the M5 Max: only its route table + /// was captured, so its hardware port and services are assumed. + static let pairedM3Ultra = PairedMac(name: "M3 Ultra", port: "en6", address: "10.219.21.80", hardwarePort: "Thunderbolt 5", + wifi: "en1", devices: ["rdma_en2", "rdma_en3", "rdma_en4", "rdma_en5", "rdma_en7", "rdma_en6"], + otherPorts: ["en2", "en3", "en4", "en5", "en7"], bridgeMembers: [], + routes: [ + "default 192.0.2.1 UGScg en1 ", + "default link#29 UCSIg utun2 ", + "10.219/16 link#21 UCS en6 !", + "10.219.21.80/32 link#21 UCS en6 !", + "10.219.21.80 2:0:5e:0:53:26 UHLWIi lo0 ", + "10.219.129.164 2:0:5e:0:53:16 UHLWIi en6 1186", + "10.219.255.255 ff:ff:ff:ff:ff:ff UHLWbI en6 !", + "127 127.0.0.1 UCS lo0 ", + "127.0.0.1 127.0.0.1 UH lo0 ", + ], + serviceOrder: serviceOrderHeader + service(1, "Wi-Fi", port: "Wi-Fi", device: "en1") + + service(2, "Thunderbolt Bridge", port: "Thunderbolt Bridge", device: "bridge0") + + service(3, "Darkbloom Cluster Link (en6)", port: "Thunderbolt 5", device: "en6")) + + static let pairedMacs = [pairedMacA, pairedM5Max, pairedM3Ultra] } /// A scripted Mac for link setup v2: the first version's world with the From b7cff6ef78db3e23cfa72813535f12e752aafb6d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:56:48 -0800 Subject: [PATCH 0259/1441] Offer Pair again in darkbloom cluster for a pairing it cannot use On 2026-11-03 both Macs of our pair held a pairing made with the other app's Secure Enclave key: `darkbloom cluster` showed its usual menu while every start of the part ended "This Mac's Secure Enclave key is not the one it paired with; pair again", and recovery took the hidden `cluster pair --status --json` and `--forget` on both Macs. A Mac that still holds a pairing its other Mac no longer has says "Nothing to do here" (member) or offers no way out (leader), while that other Mac waits at 2/4 Pair. - `OnboardingLive.resume` reports `keyChanged` when the pairing's local pin is not this Mac's current key, read without creating or repairing a key (`ClusterPairingProvider.existingPin`). - A resumed Mac asks the other Mac once over the cable (`otherMacAnswers`); when it is silent, the member offers Try again, Pair again or Quit and the leader adds Pair again to its list. - Pair again runs `ClusterUnpairing` (the steps `cluster pair --forget` takes, now shared with that command, whose output is unchanged), then the ordinary pairing. Checks fail first on 0f99ddb18 (44 failures, only in the new checks). Co-Authored-By: Claude Opus 5.5 --- .../Onboarding/ClusterOnboardingFlow.swift | 113 +++++++++- .../Onboarding/ClusterOnboardingLive.swift | 41 +++- .../Pairing/ClusterPairingCommandLine.swift | 11 +- .../Pairing/ClusterPairingProvider.swift | 13 ++ .../Pairing/ClusterUnpairing.swift | 43 ++++ .../darkbloom/ClusterPairCommand.swift | 40 ++-- .../OnboardingChecks.swift | 208 +++++++++++++++++- .../ClusterOnboardingPeerLabelTests.swift | 33 ++- 8 files changed, 454 insertions(+), 48 deletions(-) create mode 100644 provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterUnpairing.swift diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift index be3c516b16..5b449d5468 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift @@ -158,12 +158,39 @@ public struct ClusterOnboardingResume: Sendable, Equatable { /// The cable is on a port Darkbloom has not set up ("Thunderbolt 1 (en1)"): the Macs cannot reach each other /// there until it is. Nil when the active port is set up, or nothing could be read. public var unsetCablePort: String? + /// The saved pairing cannot be used, as this Mac alone can tell (its Secure Enclave key changed); nil when it can, + /// or nothing could be read. + public var pairingProblem: ClusterOnboardingPairingProblem? public init(role: ClusterOnboardingRole? = nil, peerName: String? = nil, serving: Bool = false, modelName: String? = nil) { self.role = role; self.peerName = peerName; self.serving = serving; self.modelName = modelName } } +/// Why a saved pairing cannot be used, said in one sentence on the Mac that holds it, which then offers to pair again +/// (2026-11-03: a pairing made with the other app's Secure Enclave key looped "pair again" in the part's log while +/// `darkbloom cluster` showed its usual menu; recovering took the hidden `cluster pair --forget` on both Macs). +public enum ClusterOnboardingPairingProblem: Sendable, Equatable { + /// This Mac's Secure Enclave key is not the one it paired with: Darkbloom was reinstalled, or this Mac moved between + /// the Darkbloom and DevNet apps (each keeps its own key). The roster names the old key, so the coordinator refuses + /// the pair's registration. + case keyChanged + /// The other Mac does not answer over the cable with this pairing: it is off, asleep or unplugged, or it no longer + /// holds the pairing (reinstalled, unpaired, or another Mac is on the cable). + case otherMacSilent + + public var line: String { + switch self { + case .keyChanged: + return "This Mac's Secure Enclave key changed after it paired (Darkbloom was reinstalled, or this Mac moved between " + + "the Darkbloom and DevNet apps), so the Macs must pair again to serve through Darkbloom." + case .otherMacSilent: + return "The other Mac doesn't answer over the cable: if it is on and connected, it no longer has this pairing " + + "(reinstalled, unpaired or replaced), so pair again." + } + } +} + /// How the screens name the two Macs of a pair: "this Mac" for the Mac the screen is on and "the other Mac" for the /// other one, which the lines that identify it also call by its hardware name ("the other Mac (Apple M5 Ultra, /// 256 GB)"). Two Macs of one kind share that name, so the name alone never says which Mac is meant (2026-10-25: both @@ -698,6 +725,11 @@ public struct ClusterOnboardingOperations: Sendable { /// This Mac's name as System Settings shows it, said on its own screen beside the part it plays (two identical /// Macs read the same hardware); nil when unknown. public var thisMacName: @Sendable () -> String? + /// The other Mac answers over the cable with the saved pairing (one short request). + public var otherMacAnswers: @Sendable () -> Bool + /// Forgets this Mac's saved pairing as `darkbloom cluster pair --forget` does (a leader tells its member first), so + /// the Macs can pair again; its lines say what was done. + public var unpair: @Sendable () -> Result<[String], ClusterOnboardingFailure> public init(resume: @escaping @Sendable () -> ClusterOnboardingResume, checkLink: @escaping @Sendable (@escaping @Sendable (String) -> Void) -> ClusterOnboardingLinkResult, @@ -728,7 +760,10 @@ public struct ClusterOnboardingOperations: Sendable { runAsAdministrator: @escaping @Sendable (String) -> Bool = { _ in false }, serviceOutlivesWindow: @escaping @Sendable () -> Bool = { true }, remote: @escaping @Sendable () -> Bool = { false }, - thisMacName: @escaping @Sendable () -> String? = { nil }) { + thisMacName: @escaping @Sendable () -> String? = { nil }, + otherMacAnswers: @escaping @Sendable () -> Bool = { true }, + unpair: @escaping @Sendable () -> Result<[String], ClusterOnboardingFailure> + = { .failure(.init("This build cannot pair again from here.")) }) { self.resume = resume; self.checkLink = checkLink; self.pair = pair; self.answerCode = answerCode self.ensureService = ensureService; self.reachMembers = reachMembers; self.planModels = planModels self.adopt = adopt; self.serve = serve; self.waitReady = waitReady; self.testRequest = testRequest @@ -737,6 +772,7 @@ public struct ClusterOnboardingOperations: Sendable { self.developerNotice = developerNotice; self.setScope = setScope; self.register = register self.localNetwork = localNetwork; self.commandApp = commandApp; self.runAsAdministrator = runAsAdministrator self.serviceOutlivesWindow = serviceOutlivesWindow; self.remote = remote; self.thisMacName = thisMacName + self.otherMacAnswers = otherMacAnswers; self.unpair = unpair } } @@ -918,14 +954,51 @@ public enum ClusterOnboardingDriver { switch resume.role { case .member: console.banner(title, followerSubtitle(named: named)) + if let problem = resume.pairingProblem { return offerPairAgain(problem, operations, console, request: request) } return member(resume, operations, console, request: request) case .leader: console.banner(title, leaderSubtitle(named: named)) + if let problem = resume.pairingProblem { return offerPairAgain(problem, operations, console, request: request) } return leader(resume, operations, console, justPaired: false, request: request) case nil: return onboard(operations, console, request: request) } } + /// The item that unpairs this Mac and pairs the two Macs again, code on both screens (`pairAgain`). + public static let pairAgainItem = "Pair again" + /// Said once this Mac unpaired: the other Mac still holds the old pairing until it pairs again too (it offers the + /// same item, unless it unpaired already). + public static let otherMacPairAgainLine = "On the other Mac, choose Pair again too if it asks." + + /// The saved pairing cannot be used: why, in one sentence, then Pair again or Quit (which changes nothing). + static func offerPairAgain(_ problem: ClusterOnboardingPairingProblem, _ operations: ClusterOnboardingOperations, + _ console: ClusterOnboardingConsole, request: ClusterOnboardingRequest) -> Int32 { + console.say(" " + problem.line) + console.say("") + guard console.choose([pairAgainItem, "Quit"], selected: 0) == 0 else { return 0 } + return pairAgain(operations, console, request: request) + } + + /// Unpairs this Mac, then pairs as a Mac with no pairing does: the cable, the code on both screens and, on the Mac + /// that leads, the model. + static func pairAgain(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, + request: ClusterOnboardingRequest) -> Int32 { + switch busy(console, "Unpairing this Mac", operations.unpair) { + case .success(let lines): + for line in lines { console.say(" " + line) } + case .failure(let failure): + for line in failure.lines { console.say(line) } + return 1 + } + console.say(" " + otherMacPairAgainLine) + return onboard(operations, console, request: request, opening: false) + } + + /// Whether the other Mac answers over the cable with the saved pairing, asked with a live line. + static func otherMacAnswers(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> Bool { + busy(console, "Asking the other Mac over the cable", operations.otherMacAnswers) + } + /// The setup's opening (the name alone), and the opening on a Mac that is already in a cluster (`darkbloom /// cluster` run again): the same mark, with the part this Mac plays. `named`: this Mac's own name beside "This /// Mac" (`thisMac`). @@ -1080,10 +1153,11 @@ public enum ClusterOnboardingDriver { } } - /// No pairing yet: checks, then find a waiting leader or become one. + /// No pairing yet: checks, then find a waiting leader or become one. `opening`: the setup's name first (a Mac that + /// just unpaired to pair again said it already). static func onboard(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, - request: ClusterOnboardingRequest = .init()) -> Int32 { - console.banner(title, "") + request: ClusterOnboardingRequest = .init(), opening: Bool = true) -> Int32 { + if opening { console.banner(title, "") } console.heading("1/4 Connect") console.say(" " + approvalsLine(remote: operations.remote())) var link = checkLink(operations, console) @@ -1183,6 +1257,18 @@ public enum ClusterOnboardingDriver { static func member(_ resume: ClusterOnboardingResume, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, request: ClusterOnboardingRequest = .init()) -> Int32 { guard startService(operations, console) else { return 1 } + // The cluster is managed on the other Mac, so it must answer: while it does not, why, and the way on from here + // (2026-11-03: a member whose other Mac no longer held the pairing said "Nothing to do here" while that Mac + // waited at Pair). A cable on a port that is not set up is said below instead. + while resume.unsetCablePort == nil, !otherMacAnswers(operations, console) { + console.say(" " + ClusterOnboardingPairingProblem.otherMacSilent.line) + console.say("") + switch console.choose(["Try again", pairAgainItem, "Quit"], selected: 0) { + case 0?: continue + case 1?: return pairAgain(operations, console, request: request) + default: return 0 + } + } for line in operations.status() { console.say(" " + line) } if let port = resume.unsetCablePort { // The cable moved to a port that was never set up: the one thing that is this Mac's to do. @@ -1205,23 +1291,27 @@ public enum ClusterOnboardingDriver { _ console: ClusterOnboardingConsole, justPaired: Bool, request: ClusterOnboardingRequest = .init()) -> Int32 { guard startService(operations, console) else { return 1 } if justPaired { guard allowLocalNetwork(.service, operations, console) else { return 1 } } + // A pairing kept from earlier whose other Mac does not answer over the cable (a cable on a port that is not set + // up has its own item): the menu says so and offers to pair again. + let silent = !justPaired && resume.unsetCablePort == nil && !otherMacAnswers(operations, console) // Serving, or stopped after a model was chosen: the menu. Only a leader that never chose a model goes straight - // to the choice. - if !justPaired, resume.serving || resume.modelName != nil { - return menu(resume, operations, console, request: request) + // to the choice (which first waits for the other Mac to answer). + if !justPaired, resume.serving || resume.modelName != nil || silent { + return menu(resume, operations, console, request: request, otherMacSilent: silent) } return chooseAndServe(operations, console, scope: request.scope ?? resume.scope, saveScope: request.scope != nil, model: request.model, privateImage: request.privateImageQualification) } /// One thing the leader's menu does. - enum MenuItem { case fixPort, test, model, scope, stop, verify, quit } + enum MenuItem { case fixPort, test, model, scope, stop, verify, pairAgain, quit } /// The status, then one choice from a list. `darkbloom cluster local` comes here asking for local-only serving: a /// cluster that is not serving (or asked for a model by name) goes to the choice and starts that way; a serving - /// cluster switches and serves again. + /// cluster switches and serves again. `otherMacSilent`: the other Mac does not answer over the cable, said under + /// the status, with Pair again before Quit. static func menu(_ resume: ClusterOnboardingResume, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, - request: ClusterOnboardingRequest = .init()) -> Int32 { + request: ClusterOnboardingRequest = .init(), otherMacSilent: Bool = false) -> Int32 { if let wanted = request.scope { if request.model != nil || !resume.serving { return chooseAndServe(operations, console, scope: wanted, saveScope: true, model: request.model, @@ -1236,11 +1326,13 @@ public enum ClusterOnboardingDriver { console.say(unsetPortLine(port)) items.append((.fixPort, fixPortItem)) } + if otherMacSilent { console.say(" " + ClusterOnboardingPairingProblem.otherMacSilent.line) } if resume.serving { items.append((.test, "Test")) } items.append((.model, resume.serving ? "Change model" : "Choose a model")) items.append((.scope, resume.scope.isLocalOnly ? "Serve through Darkbloom" : "Serve locally")) if resume.serving { items.append((.stop, "Stop")) } items.append((.verify, "Check memory is freed")) + if otherMacSilent { items.append((.pairAgain, pairAgainItem)) } items.append((.quit, "Quit")) console.say("") guard let index = console.choose(items.map(\.1), selected: 0) else { return 0 } @@ -1270,6 +1362,7 @@ public enum ClusterOnboardingDriver { return 1 } case .fixPort: return fixPort(operations, console) + case .pairAgain: return pairAgain(operations, console, request: request) } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift index 85f48bda79..5fb630974f 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift @@ -57,7 +57,9 @@ extension ClusterOnboardingOperations { runAsAdministrator: { ClusterLocalNetworkAccess.runLinkScriptWithSudo($0, paths: paths) }, serviceOutlivesWindow: { live.serviceOutlivesWindow() }, remote: { ClusterLocalNetworkAccess.overSSH() }, - thisMacName: { ClusterLocalNetworkAccess.computerName() }) + thisMacName: { ClusterLocalNetworkAccess.computerName() }, + otherMacAnswers: { live.otherMacAnswers() }, + unpair: { live.unpair() }) } } @@ -76,6 +78,8 @@ final class OnboardingLive: @unchecked Sendable { private var peerReportAt: Date? private var partsStoppedAt: Date? private let readPairing: @Sendable () throws -> ClusterSetupLinkExchange.Pairing? + /// This Mac's pin as a pairing made now would store it (nil: no key could be read). + private let currentPin: @Sendable () -> String? /// What adopting a listed choice needs: its folder, plan key, model id, the members that hold it alone, its /// deployment line and plan. typealias ChoiceKey = (folder: String, key: String, title: String, alone: [String], deployment: String?, plan: ClusterSetupPlanSummary?) @@ -106,9 +110,10 @@ final class OnboardingLive: @unchecked Sendable { static func sentence(_ text: String) -> String { ClusterOnboardingMacName.sentence(text) } init(context: LiveContext, store: ClusterSetupStore, settings: ClusterOnboardingOperations.LiveSettings, - readPairing: @escaping @Sendable () throws -> ClusterSetupLinkExchange.Pairing? = { try ClusterSetupLinkExchange.pairing() }) { + readPairing: @escaping @Sendable () throws -> ClusterSetupLinkExchange.Pairing? = { try ClusterSetupLinkExchange.pairing() }, + currentPin: @escaping @Sendable () -> String? = { ClusterPairingProvider.existingPin() }) { self.context = context; self.store = store; self.settings = settings - self.readPairing = readPairing + self.readPairing = readPairing; self.currentPin = currentPin } var leadership: ClusterOnboardingLeadership? { (try? store.readRecord())?.leadership } @@ -135,11 +140,15 @@ final class OnboardingLive: @unchecked Sendable { func resume() -> ClusterOnboardingResume { guard let leadership, let role = ClusterOnboardingRole(rawValue: leadership.role), let pairing = try? readPairing(), pairing.peerPin == leadership.peerPin else { return .init() } + // A pairing made with another Secure Enclave key (the other app's, or the one before a reinstall) cannot + // register: its roster names that key (2026-11-03). Said only when this Mac's key could be read. + let problem: ClusterOnboardingPairingProblem? = currentPin().flatMap { $0 == pairing.localPin ? nil : .keyChanged } // After onboarding the role is the derived control leadership, not who drove the screens. let record = try? store.readRecord() guard let claim = record?.control?.claim(localID: pairing.localMemberID, peerID: pairing.peerMemberID) else { var resume = ClusterOnboardingResume(role: role, peerName: peerName, serving: leadership.serving, modelName: leadership.modelName) resume.scope = leadership.scope + resume.pairingProblem = problem return resume } let leads = claim.leaderID == pairing.localMemberID @@ -151,9 +160,35 @@ final class OnboardingLive: @unchecked Sendable { resume.leaderReason = claim.reason resume.term = claim.term resume.localLine = ClusterService.published()?.control?.line + resume.pairingProblem = problem return resume } + /// One status request over the cable, which only a Mac holding this pairing's link key can answer. + func otherMacAnswers() -> Bool { + (try? command(.init(op: .status), seconds: Self.answerSeconds)) != nil + } + + static let answerSeconds: Double = 8 + + /// Pair again: this Mac's saved pairing removed as `darkbloom cluster pair --forget` removes it. + func unpair() -> Result<[String], ClusterOnboardingFailure> { + let pairing: ClusterSetupLinkExchange.Pairing? + do { pairing = try readPairing() } catch { + return .failure(.init("This Mac's pairing could not be read: \(ClusterConsoleText.bounded(String(describing: error), maximum: 200))")) + } + guard let pairing else { return .success([]) } + let wizard = settings.service.wizard + do { + let outcome = try ClusterUnpairing.run(peerPin: pairing.peerPin, executable: wizard.darkbloomExecutable, + providerConfiguration: wizard.providerConfiguration) + return .success(["\(ClusterOnboardingDriver.done) Unpaired this Mac."] + + (outcome.serviceProblem.map { ["Its cluster service is still running: \(ClusterConsoleText.bounded($0, maximum: 200))"] } ?? [])) + } catch { + return .failure(.init("This Mac could not unpair: \(ClusterConsoleText.bounded(String(describing: error), maximum: 200))")) + } + } + // MARK: - Where a command runs (the derived control leader) /// The control leader's name as this Mac knows it. diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterPairingCommandLine.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterPairingCommandLine.swift index da3598ab37..eaec17d08d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterPairingCommandLine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterPairingCommandLine.swift @@ -119,12 +119,9 @@ public enum ClusterPairCommandLine { return lines.joined(separator: "\n") } - /// `--forget PIN`: the lines to print. - public static func forget(pin: String, store: ClusterPairingStore = .default()) throws -> String { - do { - let record = try store.forget(peerPin: pin) - return "Unpaired from \(record.peerPin.prefix(16))… (\(record.peerName)); its pin and link key were removed.\n" - + "A setup whose roster names it no longer starts here until the two Macs pair again." - } catch { throw Failure(description: "\(error)") } + /// `--forget PIN`: the lines to print for the pairing it removed (`ClusterUnpairing`). + public static func forgotten(_ record: ClusterPairingRecord) -> String { + "Unpaired from \(record.peerPin.prefix(16))… (\(record.peerName)); its pin and link key were removed.\n" + + "A setup whose roster names it no longer starts here until the two Macs pair again." } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterPairingProvider.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterPairingProvider.swift index 88bfacfec5..aecf5ab026 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterPairingProvider.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterPairingProvider.swift @@ -52,6 +52,19 @@ public enum ClusterPairingProvider { return try SignerIdentity(chosen.signer) } + /// The pin a pairing made now would store for this Mac, read without creating, deleting or repairing a key (as + /// `identity()` may); nil when no key can be read. + public static func existingPin() -> String? { + #if DEBUG + if let path = ProcessInfo.processInfo.environment["DARKBLOOM_DEBUG_SE_KEY_FILE"], path.hasPrefix("/"), + SecureEnclaveIdentity.isAvailable, let key = try? SecureEnclaveIdentity.debugLoadExisting(at: path) { + return (try? SignerIdentity(key)).map { ClusterPairingPin.of(identityKey: $0.identityPublicKey) } + } + #endif + guard PersistentEnclaveKey.isAvailable, let key = try? PersistentEnclaveKey.loadExisting() else { return nil } + return (try? SignerIdentity(key)).map { ClusterPairingPin.of(identityKey: $0.identityPublicKey) } + } + /// "Apple M3 Ultra, 256 GB": what the other Mac shows. Never a host name. public static func displayName(chipName: String) -> String { let gigabytes = ProcessInfo.processInfo.physicalMemory / (1 << 30) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterUnpairing.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterUnpairing.swift new file mode 100644 index 0000000000..5394628b5d --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterUnpairing.swift @@ -0,0 +1,43 @@ +import DarkbloomClusterSecurity +import Foundation + +/// Unpairing this Mac from the Mac with `peerPin`, as `darkbloom cluster pair --forget` and the onboarding's Pair +/// again both do it, in this order: a leader tells its member first, while the pairing still keys the link (the member +/// reclaims the pair's prefix records and stops its part); then the pairing is removed (the trust anchor, then the link +/// key); with no pairing left, this Mac's cluster service no longer starts at login; then this Mac's pair prefix records +/// are reclaimed (a live rank's are kept). +public enum ClusterUnpairing { + public struct Outcome: Sendable { + /// The member's answer when this Mac led it (`ClusterService.tellMemberOfUnpair`), else nil. + public var memberLine: String? + public var removed: ClusterPairingRecord + /// The cluster service was stopped and no longer starts at login. + public var serviceRemoved = false + /// Why the service could not be removed from login, when it could not. + public var serviceProblem: String? + /// The pair prefix records reclaimed here; nil when the provider configuration names no prefix tier. + public var reclaim: ClusterPrefixSSDReclaim.Report? + } + + /// The pairing was not removed; `memberLine` is what the member said before (a leader tells it first). + public struct Failure: Error, CustomStringConvertible { + public var memberLine: String? + public var description: String + } + + public static func run(peerPin: String, executable: URL, providerConfiguration: URL?) throws -> Outcome { + let store = ClusterPairingStore.default() + let memberLine = ClusterService.tellMemberOfUnpair(peerPin: peerPin) + let removed: ClusterPairingRecord + do { removed = try store.forget(peerPin: peerPin) } catch { throw Failure(memberLine: memberLine, description: "\(error)") } + var outcome = Outcome(memberLine: memberLine, removed: removed) + if ClusterService.holdsNoPairing(store: store) { + do { outcome.serviceRemoved = !(try ClusterService.removeFromLogin(executable: executable)).isEmpty } + catch { outcome.serviceProblem = "\(error)" } + } + if let providerConfiguration, let settings = try? ClusterPrefixCacheSettings.resolved(providerConfiguration: providerConfiguration) { + outcome.reclaim = ClusterPrefixSSDReclaim.reclaim(root: settings.root) + } + return outcome + } +} diff --git a/provider-swift/Sources/darkbloom/ClusterPairCommand.swift b/provider-swift/Sources/darkbloom/ClusterPairCommand.swift index 6d16e37a64..033ba16a1e 100644 --- a/provider-swift/Sources/darkbloom/ClusterPairCommand.swift +++ b/provider-swift/Sources/darkbloom/ClusterPairCommand.swift @@ -58,29 +58,25 @@ extension Cluster { do { if status { print(try ClusterPairCommandLine.status(json: json)); return } if let forget { - // The leader tells its member first, while the pairing still keys the link: - // the member reclaims the pair's prefix-tier records (its single-Mac cache stays). - if let line = ClusterService.tellMemberOfUnpair(peerPin: forget) { print(line) } - print(try ClusterPairCommandLine.forget(pin: forget)) - // Unpaired: this Mac's cluster service has nobody to answer, so it no - // longer starts at login (`darkbloom cluster` pairs and installs it again). - if ClusterService.holdsNoPairing() { - do { - if !(try ClusterService.removeFromLogin(executable: URL(fileURLWithPath: Start.currentExecutablePath()))).isEmpty { - print("This Mac's cluster service is stopped and no longer starts at login.") - } - } catch { printError("note: this Mac's cluster service could not be removed from login: \(error)") } + // The steps `darkbloom cluster`'s Pair again takes too (`ClusterUnpairing`): the leader tells its + // member first, unpaired the service no longer starts at login, and the pair's prefix records are + // reclaimed here (the peer reclaims its own when it unpairs; a live rank's plan is left alone). + let outcome: ClusterUnpairing.Outcome + do { + outcome = try ClusterUnpairing.run(peerPin: forget, executable: URL(fileURLWithPath: Start.currentExecutablePath()), + providerConfiguration: try? ConfigManager.defaultConfigPath()) + } catch let failure as ClusterUnpairing.Failure { + if let line = failure.memberLine { print(line) } + throw ValidationError(failure.description) } - // No rank of this Mac will open the pair's prefix records - // again: reclaim them here (the peer reclaims its own when - // it unpairs; a live rank's plan is left alone). - if let settings = try? ClusterPrefixCacheSettings.resolved(providerConfiguration: ConfigManager.defaultConfigPath()) { - let report = ClusterPrefixSSDReclaim.reclaim(root: settings.root) - if report.removedPlans > 0 || report.keptLive > 0 || !report.problems.isEmpty { - print("Cluster prefix tier: removed \(report.removedPlans) plan\(report.removedPlans == 1 ? "" : "s")" - + (report.keptLive > 0 ? ", \(report.keptLive) in use by a running rank (kept)" : "") - + (report.problems.isEmpty ? "" : "; " + report.problems.joined(separator: "; ")) + ".") - } + if let line = outcome.memberLine { print(line) } + print(ClusterPairCommandLine.forgotten(outcome.removed)) + if outcome.serviceRemoved { print("This Mac's cluster service is stopped and no longer starts at login.") } + if let problem = outcome.serviceProblem { printError("note: this Mac's cluster service could not be removed from login: \(problem)") } + if let report = outcome.reclaim, report.removedPlans > 0 || report.keptLive > 0 || !report.problems.isEmpty { + print("Cluster prefix tier: removed \(report.removedPlans) plan\(report.removedPlans == 1 ? "" : "s")" + + (report.keptLive > 0 ? ", \(report.keptLive) in use by a running rank (kept)" : "") + + (report.problems.isEmpty ? "" : "; " + report.problems.joined(separator: "; ")) + ".") } return } diff --git a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift index 593642885a..8245c9923c 100644 --- a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift +++ b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift @@ -102,6 +102,14 @@ import Darwin eachMacNamesItselfBesideItsPart() modelOnTheOtherMacIsCopiedNotDownloaded() modelThatDoesNotFitSaysSoOnce() + // Already paired Macs whose pairing cannot be used (2026-11-03): failing first on 0f99ddb18. + keyChangedLeaderPairsAgain() + keyChangedMemberPairsAgain() + keyChangedQuitChangesNothing() + memberWhoseLeaderIsSilentPairsAgain() + leaderWhoseMemberIsSilentOffersPairAgain() + answeringOtherMacKeepsTheScreens() + failedUnpairStopsBeforePairing() print("onboarding checks: \(passed) passed, \(failures.count) failed") for failure in failures { print("FAIL " + failure) } exit(failures.isEmpty ? 0 : 1) @@ -413,8 +421,16 @@ import Darwin var calls = [String]() var answers = [Bool]() var adopted: Int? + /// How often the other Mac was asked whether it answers (kept apart, so the flows' call lists stay as they were). + var probes = 0 func note(_ call: String) { lock.lock(); calls.append(call); lock.unlock() } var all: [String] { lock.lock(); defer { lock.unlock() }; return calls } + /// The next scripted answer of the other Mac (the last one repeats; none scripted: it answers). + func probe(_ answers: [Bool]) -> Bool { + lock.lock(); defer { lock.unlock() } + probes += 1 + return answers.isEmpty ? true : answers[min(probes, answers.count) - 1] + } } static func operations(_ recorder: Recorder, resume: ClusterOnboardingResume = .init(), linkReady: Bool = true, @@ -439,6 +455,9 @@ import Darwin remote: Bool = false, commandApp: String = "Terminal", thisMacName: String? = nil, + otherMacAnswers: [Bool] = [], + statusLines: [String]? = nil, + unpairResult: Result<[String], ClusterOnboardingFailure> = .success(["\u{2713} Unpaired this Mac."]), reachFailures: Int = 0, readyResult: Result = .success(.init(servedBy: "this Mac", port: 8000, deployment: "Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers", @@ -510,9 +529,9 @@ import Darwin }, testRequest: { recorder.note("testRequest"); return testResult }, // Rank 0, which serves the API, is the Mac that leads: this Mac on the leader, the other Mac on a member. - status: { recorder.note("status"); return resume.role == .member + status: { recorder.note("status"); return statusLines ?? (resume.role == .member ? ["Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 on the other Mac (earning through Darkbloom)."] - : ["Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom)."] }, + : ["Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom)."]) }, stop: { recorder.note("stop"); return .success(["Stopping both Macs. Run `darkbloom cluster` to serve again."]) }, provision: { index, download, progress in recorder.note("provision \(index) \(download ? "download" : "copy")") @@ -539,7 +558,9 @@ import Darwin runAsAdministrator: { script in recorder.note("runAsAdministrator"); return sudoSucceeds && script == linkScript }, serviceOutlivesWindow: { outlivesWindow }, remote: { remote }, - thisMacName: { thisMacName }) + thisMacName: { thisMacName }, + otherMacAnswers: { recorder.probe(otherMacAnswers) }, + unpair: { recorder.note("unpair"); return unpairResult }) } static func privateMiMoSelectionRefusesBeforeAnyActionOnMemberOrUnpairedMac() { @@ -2171,4 +2192,185 @@ import Darwin run.type("1") expect(run.finish() == 0, "fit: the model that fits is served") } + + // MARK: - Already paired Macs whose pairing cannot be used (2026-11-03) + + /// The leader's status as Mac A's screen showed it on 2026-11-03 21:26Z, while its pairing was the production app's + /// and its part looped "This Mac's Secure Enclave key is not the one it paired with; pair again". + static let stoppedLocalStatus = ["Stopped; last model EigenLabs/Qwen3.8-27B-4bit-mtp.", + "When it starts: Local only, on this Mac only (127.0.0.1); API key: `darkbloom local`."] + + /// S1: the pairing was made with another Secure Enclave key (the other app's, or the one before a reinstall). The + /// leader's screen says so in one sentence and offers Pair again, which unpairs this Mac and runs the ordinary + /// pairing, code on both screens, then the model choice; the usual menu (which served nothing) is not shown. + static func keyChangedLeaderPairsAgain() { + let recorder = Recorder() + var resume = ClusterOnboardingResume(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, + modelName: "EigenLabs/Qwen3.8-27B-4bit-mtp") + resume.scope = .localOnly(bind: "127.0.0.1") + resume.pairingProblem = .keyChanged + let run = TerminalRun(operations(recorder, resume: resume, pairEvents: leaderEvents, + pairResult: .paired(role: .leader, peerName: "Apple M5 Ultra, 256 GB"), statusLines: stoppedLocalStatus)) + expect(run.waitFor(prompt(2)), "key changed (leader): a list") + let asked = run.text + expect(asked.contains("This Mac leads\n " + ClusterOnboardingPairingProblem.keyChanged.line + "\n\n 1) " + + ClusterOnboardingDriver.pairAgainItem + "\n 2) Quit\n"), "key changed (leader): why, then Pair again or Quit: \(asked)") + expect(!asked.contains("Choose a model") && !asked.contains("Check memory is freed"), "key changed (leader): not the usual menu") + run.type("\r") + expect(run.waitFor(codeQuestion), "key changed (leader): the ordinary pairing follows") + run.type("y") + expect(run.waitFor(prompt(2), count: 3), "key changed (leader): then the model list") + run.type("\r") + expect(run.finish() == 0, "key changed (leader): served") + let text = run.text + for line in [" \u{2713} Unpaired this Mac.\n " + ClusterOnboardingDriver.otherMacPairAgainLine + "\n", + "\n1/4 Connect\n", " Run `darkbloom cluster` on the other Mac.\n", " \u{2713} Paired. This Mac leads.\n"] { + expect(text.contains(line), "key changed (leader): \(line)") + } + expect(text.components(separatedBy: ClusterOnboardingDriver.title).count == 2, "key changed (leader): one opening") + expect(recorder.all == ["unpair", "checkLink", "pair", "answer y", "ensureService", "reachMembers", "planModels", "recheckFit 0", + "adopt 0", "serve", "waitReady", "testRequest", "register"], "key changed (leader): unpair, then pair and serve: \(recorder.all)") + transcript("leader-key-changed-pairs-again", text, keys: run.keys) + } + + /// S1 on the Mac that follows: the same sentence and Pair again instead of "Nothing to do here"; it then joins the + /// other Mac's pairing as a Mac with no pairing does. + static func keyChangedMemberPairsAgain() { + let recorder = Recorder() + var resume = memberResume() + resume.pairingProblem = .keyChanged + let run = TerminalRun(operations(recorder, resume: resume, pairEvents: memberEvents, + pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"))) + expect(run.waitFor(prompt(2)), "key changed (member): a list") + expect(run.text.contains("This Mac follows the other Mac\n " + ClusterOnboardingPairingProblem.keyChanged.line + "\n"), + "key changed (member): why, under the opening: \(run.text)") + run.type("\r") + expect(run.waitFor(codeQuestion), "key changed (member): the ordinary pairing follows") + run.type("y") + expect(run.finish() == 0, "key changed (member): joined") + let text = run.text + expect(!text.contains(ClusterOnboardingDriver.memberNothingLine), "key changed (member): never Nothing to do here") + expect(text.contains(" \u{2713} Paired. The other Mac leads.\n") + && text.hasSuffix(ClusterOnboardingDriver.joinedLine + " " + ClusterOnboardingDriver.closeWindowLine + "\n"), + "key changed (member): joined, and where to continue: \(text)") + expect(recorder.all == ["unpair", "checkLink", "pair", "answer y", "ensureService"], "key changed (member): \(recorder.all)") + transcript("member-key-changed-pairs-again", text, keys: run.keys) + } + + /// Quit leaves everything as it was: nothing unpaired, no service started. + static func keyChangedQuitChangesNothing() { + let recorder = Recorder() + var resume = ClusterOnboardingResume(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: true, modelName: "Qwen3.8-27B-4bit-mtp") + resume.pairingProblem = .keyChanged + let run = TerminalRun(operations(recorder, resume: resume, pairEvents: [], pairResult: .failed([]))) + expect(run.waitFor(prompt(2)), "key changed, quit: the list") + run.type("2") + expect(run.finish() == 0, "key changed, quit: exit 0") + expect(recorder.all.isEmpty, "key changed, quit: nothing ran: \(recorder.all)") + } + + /// S2 on the Mac that follows: the leader does not answer over the cable with this pairing (2026-11-03: one Mac + /// of a pair showed its opening and "Nothing to do here" while the other waited at Pair). The member says why and + /// offers Try again, Pair again or Quit; Pair again unpairs it and joins the waiting Mac; Try again asks again. + static func memberWhoseLeaderIsSilentPairsAgain() { + let recorder = Recorder() + let run = TerminalRun(operations(recorder, resume: memberResume(), pairEvents: memberEvents, + pairResult: .paired(role: .member, peerName: "Apple M5 Ultra, 256 GB"), otherMacAnswers: [false])) + expect(run.waitFor(prompt(3)), "silent leader: a list") + let asked = run.text + expect(asked.contains("This Mac follows the other Mac\n " + ClusterOnboardingPairingProblem.otherMacSilent.line + "\n\n 1) Try again\n 2) " + + ClusterOnboardingDriver.pairAgainItem + "\n 3) Quit\n"), "silent leader: why, then the three choices: \(asked)") + run.type("2") + expect(run.waitFor(codeQuestion), "silent leader: the ordinary pairing follows") + run.type("y") + expect(run.finish() == 0, "silent leader: joined") + let text = run.text + expect(!text.contains(ClusterOnboardingDriver.memberNothingLine), "silent leader: never Nothing to do here") + expect(text.contains(" \u{2713} Paired. The other Mac leads.\n"), "silent leader: paired again") + expect(recorder.all == ["ensureService", "unpair", "checkLink", "pair", "answer y", "ensureService"], "silent leader: \(recorder.all)") + transcript("member-silent-leader-pairs-again", text, keys: run.keys) + + // The leader was only asleep: Try again asks once more, then the screen is the member's usual one. + let again = Recorder() + let woke = TerminalRun(operations(again, resume: memberResume(), pairEvents: [], pairResult: .failed([]), otherMacAnswers: [false, true])) + expect(woke.waitFor(prompt(3)), "silent leader, try again: the list") + woke.type("1") + expect(woke.finish() == 0, "silent leader, try again: ends by itself") + expect(woke.text.hasSuffix(ClusterOnboardingDriver.memberNothingLine + "\n"), "silent leader, try again: the usual screen: \(woke.text)") + expect(again.all == ["ensureService", "status"] && again.probes == 2, "silent leader, try again: asked twice, nothing unpaired: \(again.all)") + } + + /// S2 on the Mac that leads: its other Mac does not answer over the cable. Its menu says why and adds Pair again + /// (before Quit), also for a leader that never chose a model (which otherwise goes straight to the list and waits + /// two minutes for the other Mac). + static func leaderWhoseMemberIsSilentOffersPairAgain() { + let recorder = Recorder() + var stopped = ClusterOnboardingResume(role: .leader, peerName: "Apple M5 Ultra, 256 GB", serving: false, modelName: "EigenLabs/Qwen3.8-27B-4bit-mtp") + stopped.scope = .localOnly(bind: "127.0.0.1") + let run = TerminalRun(operations(recorder, resume: stopped, pairEvents: leaderEvents, pairResult: .paired(role: .leader, peerName: "Apple M5 Max, 128 GB"), + otherMacAnswers: [false], statusLines: stoppedLocalStatus)) + expect(run.waitFor(prompt(5)), "silent member: the menu") + let menu = run.text + expect(menu.contains(" " + stoppedLocalStatus[1] + "\n " + ClusterOnboardingPairingProblem.otherMacSilent.line + "\n\n 1) Choose a model\n" + + " 2) Serve through Darkbloom\n 3) Check memory is freed\n 4) " + ClusterOnboardingDriver.pairAgainItem + "\n 5) Quit\n"), + "silent member: the status, why, and Pair again before Quit: \(menu)") + run.type("4") + expect(run.waitFor(codeQuestion), "silent member: the ordinary pairing follows") + run.type("y") + expect(run.waitFor(prompt(2), count: 2), "silent member: then the model list") + run.type("\r") + expect(run.finish() == 0, "silent member: served") + expect(Array(recorder.all.prefix(4)) == ["ensureService", "status", "unpair", "checkLink"], "silent member: unpaired, then paired: \(recorder.all)") + expect(recorder.probes == 1, "silent member: asked once (never right after pairing)") + transcript("leader-silent-member-pairs-again", run.text, keys: run.keys) + + // A leader that never chose a model: the menu too, not two minutes of "Reading both Macs". + let unchosen = Recorder() + let fresh = TerminalRun(operations(unchosen, resume: .init(role: .leader, peerName: "Apple M5 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), otherMacAnswers: [false])) + expect(fresh.waitFor(prompt(5)), "silent member, no model yet: the menu") + expect(fresh.text.contains(" 4) " + ClusterOnboardingDriver.pairAgainItem + "\n 5) Quit\n"), "silent member, no model yet: Pair again: \(fresh.text)") + fresh.type("5") + expect(fresh.finish() == 0, "silent member, no model yet: quit") + expect(!unchosen.all.contains("reachMembers") && !unchosen.all.contains("unpair"), "silent member, no model yet: nothing read or unpaired: \(unchosen.all)") + } + + /// A pair whose other Mac answers keeps its screens as they were: the member's status and "Nothing to do here", the + /// leader's menu without Pair again; each asks the other Mac once, and a cable on a port that is not set up is the + /// one thing said (the other Mac cannot answer there, which is no reason to pair again). + static func answeringOtherMacKeepsTheScreens() { + let member = Recorder() + let followed = TerminalRun(operations(member, resume: memberResume(), pairEvents: [], pairResult: .failed([]))) + expect(followed.finish() == 0 && followed.text.hasSuffix(ClusterOnboardingDriver.memberNothingLine + "\n"), "answers (member): as before") + expect(member.probes == 1 && !followed.text.contains(ClusterOnboardingDriver.pairAgainItem), "answers (member): asked once, no Pair again") + let leader = Recorder() + let led = TerminalRun(operations(leader, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB", serving: true, + modelName: "Qwen3.8-27B-4bit-mtp"), pairEvents: [], pairResult: .failed([]))) + expect(led.waitFor(prompt(6)), "answers (leader): the usual menu") + expect(!led.text.contains(ClusterOnboardingDriver.pairAgainItem) && leader.probes == 1, "answers (leader): no Pair again, asked once") + led.type("6") + _ = led.finish() + var moved = memberResume() + moved.unsetCablePort = "Thunderbolt 1 (en1)" + let port = Recorder() + let cable = TerminalRun(operations(port, resume: moved, pairEvents: [], pairResult: .failed([]), otherMacAnswers: [false])) + expect(cable.waitFor(prompt(2)), "unset port: its list") + expect(!cable.text.contains(ClusterOnboardingDriver.pairAgainItem) && port.probes == 0, "unset port: no Pair again, nothing asked: \(cable.text)") + cable.type("2") + _ = cable.finish() + } + + /// An unpairing that fails says why and starts no pairing. + static func failedUnpairStopsBeforePairing() { + let recorder = Recorder() + var resume = memberResume() + resume.pairingProblem = .keyChanged + let run = TerminalRun(operations(recorder, resume: resume, pairEvents: [], pairResult: .failed([]), + unpairResult: .failure(.init("The pairing store could not be written.")))) + expect(run.waitFor(prompt(2)), "failed unpair: the list") + run.type("\r") + expect(run.finish() == 1, "failed unpair: exit 1") + expect(run.text.contains("The pairing store could not be written.\n"), "failed unpair: why") + expect(recorder.all == ["unpair"], "failed unpair: no pairing: \(recorder.all)") + } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOnboardingPeerLabelTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOnboardingPeerLabelTests.swift index a9ada2c1d9..28c2c7d0ad 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOnboardingPeerLabelTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOnboardingPeerLabelTests.swift @@ -43,6 +43,30 @@ struct ClusterOnboardingPeerLabelTests { #expect(try fixture.store.readRecord().leadership?.peerPin == Fixture.peerPin) } + /// 2026-11-03: the pairing was the production app's and this Mac signed with the DevNet app's key; `darkbloom cluster` + /// showed the usual menu while every start failed "pair again". The resume says so; the part this Mac plays stays. + @Test func aPairingMadeWithAnotherKeyIsSaidSo() throws { + let fixture = try Fixture() + defer { fixture.remove() } + let changed = fixture.live(peerPin: Fixture.peerPin, currentPin: String(repeating: "d", count: 64)).resume() + #expect(changed.pairingProblem == .keyChanged) + #expect(changed.role == .leader && changed.modelName == "saved-model") + #expect(fixture.live(peerPin: Fixture.peerPin).resume().pairingProblem == nil, "the key it paired with") + #expect(fixture.live(peerPin: Fixture.peerPin, currentPin: nil).resume().pairingProblem == nil, "no key read: nothing claimed") + #expect(fixture.live(peerPin: String(repeating: "c", count: 64), currentPin: String(repeating: "d", count: 64)).resume() + == ClusterOnboardingResume(), "a pairing the record does not name resumes nothing, as before") + } + + /// Pair again on a Mac that holds no pairing removes nothing and goes on to pair. + @Test func unpairWithoutAPairingChangesNothing() throws { + let fixture = try Fixture() + defer { fixture.remove() } + let live = OnboardingLive(context: fixture.context, store: fixture.store, settings: fixture.settings, readPairing: { nil }, + currentPin: { nil }) + #expect(try live.unpair().get().isEmpty) + #expect(try fixture.store.readRecord().leadership?.peerPin == Fixture.peerPin) + } + @Test func peerDisplaySanitizesControlCharactersAndUsesRemoteMemory() throws { let fixture = try Fixture() defer { fixture.remove() } @@ -165,15 +189,18 @@ struct ClusterOnboardingPeerLabelTests { _ = try store.updateRecord { $0.leadership = leadership } } - func live(peerPin: String) -> OnboardingLive { + /// `currentPin`: this Mac's key as the live lookup would read it (the pairing's own by default; never the keychain). + func live(peerPin: String, currentPin: String? = Self.localPin) -> OnboardingLive { let pairing = Self.pairing(peerPin: peerPin) - return OnboardingLive(context: context, store: store, settings: settings, readPairing: { pairing }) + return OnboardingLive(context: context, store: store, settings: settings, readPairing: { pairing }, currentPin: { currentPin }) } + static let localPin = String(repeating: "a", count: 64) + func remove() { try? FileManager.default.removeItem(at: home) } private static func pairing(peerPin: String) -> ClusterSetupLinkExchange.Pairing { - .init(localPin: String(repeating: "a", count: 64), peerPin: peerPin, clusterID: "fixture", + .init(localPin: localPin, peerPin: peerPin, clusterID: "fixture", linkEpoch: "fixture", edgeID: "fixture", secretFile: "/not-read", secret: Data(repeating: 0, count: 32)) } } From 9f9ddf1eda5790fbccd6c3e88aa9bba31cc07504 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:56:48 -0800 Subject: [PATCH 0260/1441] Document Pair again for moving apps, reinstalling and re-pairing The two-Mac guide gains "Pairing again" (moving between the Darkbloom and DevNet apps, reinstalling, a reset or replaced Mac) and the 2/4 Pair symptom; the CLI reference, troubleshooting and the inference architecture page say what `darkbloom cluster` checks and offers. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-pair-again.md | 15 +++++++++ docs/architecture/inference.md | 25 +++++++++++++++ docs/provider/cli-reference.md | 2 +- docs/provider/troubleshooting.md | 9 +++++- docs/provider/two-mac-cluster.md | 52 ++++++++++++++++++++++++++++--- 5 files changed, 96 insertions(+), 7 deletions(-) create mode 100644 changelog.d/cluster-pair-again.md diff --git a/changelog.d/cluster-pair-again.md b/changelog.d/cluster-pair-again.md new file mode 100644 index 0000000000..45e1b0163e --- /dev/null +++ b/changelog.d/cluster-pair-again.md @@ -0,0 +1,15 @@ +### `darkbloom cluster` offers Pair again for a pairing it cannot use + +- A Mac whose saved pairing was made with another Secure Enclave key (after + moving between the Darkbloom and DevNet apps, or after the installer made a + new key) now says so when `darkbloom cluster` opens and offers **Pair again**, + instead of its usual menu while every start of its part failed with "pair + again". +- When the other Mac does not answer over the cable, the Mac that follows offers + **Try again**, **Pair again** and **Quit** instead of "Nothing to do here", + and the leader adds **Pair again** to its list. This ends the case where one + Mac waited at "2/4 Pair" while the other, still holding an earlier pairing, + showed its status and ended. +- **Pair again** unpairs this Mac exactly as `darkbloom cluster pair --forget` + does, then runs the ordinary pairing with the code on both screens; the + other Mac offers the same item when it still holds the old pairing. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 1fe23bc81d..b157ac2f6d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3719,6 +3719,31 @@ Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/C `provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupLinkExchange.swift` (`ClusterSetupLinkExchange.Responder`). +## A saved pairing the onboarding cannot use + +`darkbloom cluster` resumes a paired Mac only when the pairing it would use can +serve. Two facts end that (`ClusterOnboardingPairingProblem`): + +| Case | How it is found | What the screen offers | +|---|---|---| +| `keyChanged` | `OnboardingLive.resume` compares the pairing's local pin with this Mac's current key, read without creating, deleting or repairing one (`ClusterPairingProvider.existingPin`); no key read claims nothing. A roster names the key that paired, so the member start refuses another (`ProviderLoop.nativePairRosterNamesAnotherKey`) | **Pair again**, **Quit** (instead of the leader's list or the member's status) | +| `otherMacSilent` | One status request over the cable (`OnboardingLive.otherMacAnswers`, `answerSeconds` = `8`), which only a Mac holding this pairing's edge secret answers. Not asked right after pairing, nor when the cable is on a port that is not set up | Member: **Try again**, **Pair again**, **Quit**; leader: **Pair again** before **Quit** in its list | + +**Pair again** runs `ClusterUnpairing.run`, the steps of `darkbloom cluster pair +--forget` (a leader tells its member, the pairing store forgets the peer pin, the +service leaves login with no pairing left, the pair prefix records are +reclaimed), then the ordinary pairing ceremony, which stores a new record set +for the current key (`ClusterPairingStore.commit`). Nothing on the other Mac is +changed beyond what `--forget` already does: it offers the same item while it +holds the old pairing. + +Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift` +(`ClusterOnboardingDriver.pairAgain`, `member`, `menu`), +`provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift` +(`OnboardingLive.resume`, `otherMacAnswers`, `unpair`) and +`provider-swift/Sources/ProviderCore/Inference/Distributed/Pairing/ClusterUnpairing.swift` +(`ClusterUnpairing`). + ## GLM tool-stream completion GLM tool output uses the SDK GLM parser to validate the complete tool suffix at diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 5ecb5a7811..0ffa7798bb 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -161,7 +161,7 @@ Subcommands declared by `Darkbloom.configuration.subcommands`: | `doctor` | Diagnostics (see [troubleshooting](./troubleshooting.md#doctor-checks)) | ✓ | `DoctorCommand.swift` (`Doctor`) | | `models` | `list`, `catalog`, `download`, `remove` | ✓ | `ModelsCommand.swift` (`Models`) | | `local` | Print the direct-mode endpoint and API key | | `LocalCommand.swift` (`Local`) | -| `cluster` | Set up two Macs to serve one model together ([guided setup](./two-mac-cluster.md)); `cluster local` serves without a coordinator | ✓ | `ClusterCommand.swift` (`Cluster`) | +| `cluster` | Set up two Macs to serve one model together ([guided setup](./two-mac-cluster.md)); `cluster local` serves without a coordinator. Run again on a paired Mac, it offers **Pair again** when the saved pairing was made with another Secure Enclave key or the other Mac does not answer over the cable, taking the steps of `cluster pair --forget` (`ClusterUnpairing`), then pairing ([pairing again](./two-mac-cluster.md#pairing-again)) | ✓ | `ClusterCommand.swift` (`Cluster`) | | `login` | Link the machine to an account (RFC 8628 device code) | ✓ | `LoginCommand.swift` (`Login`) | | `logout` | Stop the provider, revoke its current saved token, then remove the local credential | ✓ | `LogoutCommand.swift` (`Logout`) | | `benchmark` | Inference benchmarks and harnesses | ✓ | `BenchmarkCommand.swift` (`Benchmark`) | diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index 8f1ffde203..0356140611 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -1,6 +1,6 @@ # Provider troubleshooting -> Last updated: 2026-11-02 +> Last updated: 2026-11-03 Symptom → check → fix for the `darkbloom` provider: installer exits, `doctor` check names, service lifecycle, coordinator connection, updates, models and the @@ -161,6 +161,13 @@ The check cadence (`autoUpdateInitialDelay`, `autoUpdateInterval`), the restart (`provider-swift/Sources/ProviderCore/ProviderLoop+AutoUpdate.swift`) are tabulated in [`cli-reference.md`](./cli-reference.md#runtime-constants). +## Two-Mac pairs + +| Symptom | Cause | Fix | +|---|---|---| +| The part log (`~/.darkbloom/cluster-setup/rank.log`) repeats `This Mac cannot register the saved roster: This Mac's Secure Enclave key is not the one it paired with; pair again.` | The pairing was made with another Secure Enclave key: the Mac moved between the Darkbloom and DevNet apps, or the official installer made a new key | Run `darkbloom cluster` on each Mac and choose **Pair again** ([pairing again](./two-mac-cluster.md#pairing-again)) | +| One Mac waits at "2/4 Pair"; the other shows its status and ends, or says "The other Mac doesn't answer over the cable" | The second Mac still holds an earlier pairing, so it never joins the waiting Mac | On the second Mac run `darkbloom cluster` and choose **Pair again** | + ## Models and memory | Symptom | Cause | Fix | diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index b890bccc16..8218cd0a05 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -119,7 +119,10 @@ memory is freed** and **Quit**, with **Set up the cable port** first when the cable moved to a port not set up yet. On the other Mac it shows the status and "Nothing to do here: manage it on the other Mac (`darkbloom cluster`).": its part runs by itself, and setting up such a port is the only choice it offers -([below](#when-something-is-in-the-way)). +([below](#when-something-is-in-the-way)). Either Mac first asks the other over +the cable; when it does not answer, or when the saved pairing was made with +another Secure Enclave key, the screen says so and offers **Pair again** +([pairing again](#pairing-again)). The planner picks tensor parallel or pipeline for your Macs by itself. Phase split is off. A model whose artifact ships a speculative (MTP) head can also @@ -791,7 +794,12 @@ drained for an update yet: its update waits while it serves (the log says and **Cancel**, since the other Mac's Darkbloom prompt may still be waiting for Allow. If you denied the Local Network prompt there, allow Darkbloom in System Settings → Privacy & Security → Local Network, then - run `darkbloom cluster` again. + run `darkbloom cluster` again. When `darkbloom cluster` is run again and the + other Mac does not answer, it offers **Pair again** ([pairing again](#pairing-again)). +- **One Mac waits at "2/4 Pair" while the other shows its status and ends**: + the second Mac still holds an earlier pairing, so it never joins. Run + `darkbloom cluster` on it and choose **Pair again** + ([pairing again](#pairing-again)). - **A model is not offered**: the list leaves out every model that is not approved for clusters or that these Macs cannot serve, with no reason beside it. A model named on the command line says why ("… is not approved for @@ -809,13 +817,47 @@ drained for an update yet: its update waits while it serves (the log says your home folder (no keys, addresses or names in it; nothing is written if any would remain). +## Pairing again + +Pair the Macs again after either Mac moves between the Darkbloom and DevNet apps, +after the official installer reinstalls Darkbloom ("Secure Enclave ✓ (P-256 key +generated)"), or when one Mac was reset or replaced. Each app keeps its own +Secure Enclave key, and the pair's roster names the keys the Macs paired with, +so a pairing made with another key cannot register: every start of its part ends +with "This Mac's Secure Enclave key is not the one it paired with; pair again." + +1. Run `darkbloom cluster` on either Mac. It says why its pairing cannot be used + and offers **Pair again**: + - "This Mac's Secure Enclave key changed after it paired (…), so the Macs + must pair again to serve through Darkbloom." (this Mac's key is not the one + its pairing names; offered with **Quit**); + - "The other Mac doesn't answer over the cable: if it is on and connected, it + no longer has this pairing (reinstalled, unpaired or replaced), so pair + again." (offered with **Try again** and **Quit**; on the leader, in its list + before **Quit**). +2. Choose **Pair again**. This Mac unpairs as `darkbloom cluster pair --forget` + does ([undo](#undo)), says "✓ Unpaired this Mac.", then runs the ordinary + setup and waits at "2/4 Pair". +3. Run `darkbloom cluster` on the other Mac. If it offers **Pair again** too, + choose it; a Mac with no pairing goes straight to Pair. +4. Answer **Yes** on each Mac when both show the same code. The Mac that waited + leads and chooses the model again. + +**Quit** changes nothing. Asking the other Mac is one status request over the +cable (`OnboardingLive.otherMacAnswers`); the key check reads this Mac's key +without creating one (`ClusterPairingProvider.existingPin`). Both are in +`provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift` +(`ClusterOnboardingPairingProblem`) and the driver's `pairAgain`. + ## Undo `darkbloom cluster link --remove` on each Mac restores the cable port's earlier network settings (one approval). `darkbloom cluster pair --forget ` removes -a pairing. Run on the leader, it first tells the other Mac over the cable, which -removes the pair's prompt-cache records (its own single-Mac cache stays) and -stops its part; each Mac also removes its own pair records when it unpairs. +a pairing; **Pair again** in `darkbloom cluster` takes the same steps +(`ClusterUnpairing`). Run on the leader, it first tells the other Mac over the +cable, which removes the pair's prompt-cache records (its own single-Mac cache +stays) and stops its part; each Mac also removes its own pair records when it +unpairs. `darkbloom cluster stop` stops a Mac's cluster service and keeps it from starting at login. On the leader it stops the pair first. When the other Mac is gone for good, `darkbloom cluster stop --local-only` stops only this one. From 8f912a0e483e168eea12accda7958113be1bc548 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:58:30 -0800 Subject: [PATCH 0261/1441] fix(provider): a paired Mac's own loopback route leaves its cable port isolated Once a cable port's own address has carried traffic, which pairing does, macOS reaches it through the loopback with a cloned host route (`10.219.13.112 UHLWIi lo0`). The isolation check counted that route as the cluster subnet used on another interface, so every paired Mac said "not isolated: the cluster subnet 10.219/16 is already used on this Mac", `cluster doctor` failed localLinkIsolation., and `cluster link --fix` (also --dry-run) refused with isolationRefused. Seen on three Macs on 0.10.7 and on an end user's Mac (rdma_en1); the M3 Ultra was isolated before it paired and not after. The route reader now counts a loopback host route to an address that an interface carries in `ifconfig -a` on that interface (ClusterLinkNetworkFacts.clusterSubnetRouteInterfaces), and the readiness probe hands the inspection the listing it already read (ClusterLinkIsolationInspection.machine(run:interfaceListing:)). Only interface names leave the reader, and status is unchanged. An address in 10.219/16 on another interface, a route into it through utun, bridge or another en port, and a loopback route to an address that no interface carries still block. The repair paths read only services and bridges from that reading and pass no listing. Checks: ClusterLinkChecks 2502 expectations in 46 groups (21 failed on origin/dev, all on the three captured tables); ClusterDiagnosticsChecks passes with Mac A's table through the doctor (failed on origin/dev). docs-impact, docs-check and changelog-check pass. Co-Authored-By: Claude Opus 5.5 --- .../cluster-link-own-address-loopback.md | 4 ++++ docs/architecture/inference.md | 24 +++++++++++++++++++ docs/reference/configuration.md | 4 ++-- .../Link/ClusterLinkIsolationInspection.swift | 7 ++++-- .../Link/ClusterLinkNetworkFacts.swift | 24 ++++++++++++++----- .../Link/ClusterLinkReadinessProbe.swift | 2 +- .../LinkIsolationChecks.swift | 20 +++++++++++++--- .../LinkIsolationFixtures.swift | 21 +++++++++------- .../Tests/ClusterLinkChecks/README.md | 6 +++++ 9 files changed, 90 insertions(+), 22 deletions(-) create mode 100644 changelog.d/cluster-link-own-address-loopback.md diff --git a/changelog.d/cluster-link-own-address-loopback.md b/changelog.d/cluster-link-own-address-loopback.md new file mode 100644 index 0000000000..e8ba53f4c3 --- /dev/null +++ b/changelog.d/cluster-link-own-address-loopback.md @@ -0,0 +1,4 @@ +### A paired Mac's cable port is no longer called not isolated + +- `darkbloom cluster doctor` no longer reports a paired Mac's cable port as not isolated because of its own address. Once the port has carried traffic, macOS reaches the port's own address through the loopback (`lo0`), and that route was taken for the cluster subnet `10.219/16` being used elsewhere on the Mac: `darkbloom cluster link` said "not isolated: the cluster subnet 10.219/16 is already used on this Mac", the doctor failed `localLinkIsolation.`, and `darkbloom cluster link --fix` (also with `--dry-run`) refused with `isolationRefused`. +- Another interface or VPN with an address in `10.219/16`, a route into it through any other interface, and a loopback route to an address the port does not carry still stop the isolation, as before. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 1fe23bc81d..df0847165a 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3719,6 +3719,30 @@ Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/C `provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupLinkExchange.swift` (`ClusterSetupLinkExchange.Responder`). +## A paired cable port's own address + +`darkbloom cluster link`, `darkbloom cluster doctor` and the guided setup judge +whether the cable port is isolated +([findings](../reference/configuration.md#link-setup-v2-isolating-the-cluster-port)). +`clusterSubnetInUse` blocks the isolation when another interface or route +already uses the cluster subnet `10.219/16`. Once the port's own address has +carried traffic, which pairing does, macOS reaches that address through the +loopback with a cloned host route (`10.219.13.112 UHLWIi lo0`). That +route is how the Mac reaches the port's address, not a second use of the +subnet: the route reader counts a loopback host route to an address that an +interface carries on that interface +(`ClusterLinkNetworkFacts.clusterSubnetRouteInterfaces`), reading the +`ifconfig -a` text the readiness probe already took +(`ClusterLinkIsolationInspection.machine(run:interfaceListing:)`). Only interface +names leave the reader. Another interface's address in the subnet, a route into +it through any other interface, and a loopback route to an address that no +interface carries still block. + +Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkNetworkFacts.swift` +(`ClusterLinkNetworkFacts.clusterSubnetRouteInterfaces`) and +`provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkIsolationInspection.swift` +(`ClusterLinkIsolationInspection.status`). + ## GLM tool-stream completion GLM tool output uses the SDK GLM parser to validate the complete tool suffix at diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index bee14f2780..57fecb7dd0 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1,6 +1,6 @@ # Configuration reference -> Last updated: 2026-11-02 +> Last updated: 2026-11-03 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. @@ -1400,7 +1400,7 @@ the port serving would use when not, `notObserved` for another active port. | `portAddressMissing` | no `inet` on `P` | own service with a fixed address | | `clusterServiceMissing`, `clusterServiceMisconfigured` | `/usr/sbin/networksetup -listnetworkserviceorder` and `-getinfo` (manual, recorded address, `255.255.0.0`, no router, IPv6 not `Automatic`) | the service is made, or made afresh | | `otherServiceOnPort` | another enabled service on `P` | switched off | -| `clusterSubnetInUse` | another interface's address or route in `10.219/16` | blocks | +| `clusterSubnetInUse` | another interface's address in `10.219/16` (`ifconfig -a`), or a route into it through another interface (`netstat -rn -f inet`). A loopback (`lo0`) host route to an address an interface carries counts on that interface, so macOS's route to `P`'s own address does not count | blocks | | `serviceNameUnsafe` | a service or hardware port name outside letters, digits, spaces and `( ) - . _` | blocks | | `hardwarePortUnknown` | `networksetup -listallhardwareports` lists no port for `P` | blocks | | `stateUnreadable` | a reading failed | blocks | diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkIsolationInspection.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkIsolationInspection.swift index 0fbd50633a..53aa632229 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkIsolationInspection.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkIsolationInspection.swift @@ -20,7 +20,10 @@ enum ClusterLinkIsolationInspection { /// Nil when one reading timed out, overflowed, or printed text of the /// wrong shape. A tool that exits non-zero where that means "none" (no /// Internet Sharing file, no bridge key) is an empty answer, not a failure. - static func machine(run: ClusterLinkToolRunner) -> Machine? { + /// The cluster subnet's routes are read against `interfaceListing`, the + /// `ifconfig -a` text of the same inspection; without it, a loopback route + /// to an address of this Mac's own counts on the loopback. + static func machine(run: ClusterLinkToolRunner, interfaceListing: String = "") -> Machine? { /// A reading that must succeed. func required(_ command: ClusterLinkToolCommand) -> String? { guard case .output(let text) = run(command) else { return nil } @@ -42,7 +45,7 @@ enum ClusterLinkIsolationInspection { let devices = optional(.internetSharingDevices, empty: [], ClusterLinkNetworkFacts.sharingDevices), let routes = required(.routeTable), let defaults = ClusterLinkNetworkFacts.defaultRouteInterfaces(routes), - let subnetRoutes = ClusterLinkNetworkFacts.clusterSubnetRouteInterfaces(routes), + let subnetRoutes = ClusterLinkNetworkFacts.clusterSubnetRouteInterfaces(routes, interfaceListing: interfaceListing), let resolvers = required(.dnsConfiguration).flatMap(ClusterLinkNetworkFacts.dnsInterfaces) else { return nil } return Machine(hardwarePorts: ClusterLinkNetworkFacts.hardwarePorts(ports), services: services, preferenceBridges: bridges, sharingEnabled: enabled, sharingDevices: devices, diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkNetworkFacts.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkNetworkFacts.swift index 0ca42baf8b..8164c76cf7 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkNetworkFacts.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkNetworkFacts.swift @@ -142,9 +142,11 @@ enum ClusterLinkNetworkFacts { } /// `netstat -rn -f inet`: the interface of every route whose destination - /// matches `destination`, in listed order. Nil when the text is not a + /// matches `destination`, in listed order, as `countedOn` names it from + /// the destination and the route's interface. Nil when the text is not a /// route table. - static func routeInterfaces(_ text: String, where destination: (Substring) -> Bool) -> [String]? { + static func routeInterfaces(_ text: String, where destination: (Substring) -> Bool, + countedOn: (_ destination: Substring, _ interface: String) -> String = { $1 }) -> [String]? { var inTable = false, interfaces = [String]() for line in text.split(whereSeparator: \.isNewline) { let words = line.split(whereSeparator: \.isWhitespace) @@ -154,7 +156,7 @@ enum ClusterLinkNetworkFacts { } guard inTable, words.count >= 4, destination(words[0]) else { continue } let interface = String(words[3]) - if ClusterLinkName.isInterface(interface) { interfaces.append(interface) } + if ClusterLinkName.isInterface(interface) { interfaces.append(countedOn(words[0], interface)) } } return inTable ? interfaces : nil } @@ -164,11 +166,21 @@ enum ClusterLinkNetworkFacts { routeInterfaces(text) { $0 == "default" } } - /// The interfaces that carry a route into the cluster subnet. - static func clusterSubnetRouteInterfaces(_ text: String) -> [String]? { - routeInterfaces(text) { ClusterLinkClusterAddress.inSubnet($0) } + /// The interfaces that carry a route into the cluster subnet. Once an + /// address of this Mac's own has carried traffic, macOS reaches it through + /// the loopback (`10.219.4.7 UHLWIi lo0`), so a loopback route to + /// an address that an interface in `interfaceListing` (`ifconfig -a`) + /// carries counts on that interface. + static func clusterSubnetRouteInterfaces(_ text: String, interfaceListing: String) -> [String]? { + let listed = ClusterNetworkInterfaces.parse(interfaceListing)?.interfaces.map(\.name) ?? [] + return routeInterfaces(text, where: { ClusterLinkClusterAddress.inSubnet($0) }) { destination, interface in + guard interface == loopback else { return interface } + return listed.first { lists(String(destination), on: $0, inListing: interfaceListing) } ?? interface + } } + private static let loopback = "lo0" + /// `scutil --dns`: the interfaces through which a resolver with at least /// one name server is reached, scoped or not. Nil when the text is not a /// DNS configuration. diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkReadinessProbe.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkReadinessProbe.swift index 128ceb6b8a..3702625c43 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkReadinessProbe.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkReadinessProbe.swift @@ -51,7 +51,7 @@ public enum ClusterLinkReadinessProbe { do { var (devices, listing) = try inspectDevices(run: run, recorded: recorded) if readingIsolation, devices.contains(where: \.portActive) { - let machine = ClusterLinkIsolationInspection.machine(run: run) + let machine = ClusterLinkIsolationInspection.machine(run: run, interfaceListing: listing) for index in devices.indices where devices[index].portActive { guard let interface = devices[index].interface else { continue } devices[index].isolation = ClusterLinkIsolationInspection.status(interface: interface, diff --git a/provider-swift/Tests/ClusterLinkChecks/LinkIsolationChecks.swift b/provider-swift/Tests/ClusterLinkChecks/LinkIsolationChecks.swift index b9e6bdc349..92df6a39b7 100644 --- a/provider-swift/Tests/ClusterLinkChecks/LinkIsolationChecks.swift +++ b/provider-swift/Tests/ClusterLinkChecks/LinkIsolationChecks.swift @@ -44,9 +44,23 @@ extension ClusterLinkCheck { expectEqual(Facts.defaultRouteInterfaces(IsolationFixtures.macBRoutes), ["en0", "bridge0", "utun2"], "Mac B: none via en6") expectEqual(Facts.defaultRouteInterfaces(IsolationFixtures.macAIsolatedRoutes(address: "10.219.1.2")), ["en1", "utun4"], "isolated Mac A: no default route via the cable") - expectEqual(Facts.clusterSubnetRouteInterfaces(IsolationFixtures.macAIsolatedRoutes(address: "10.219.1.2")), ["en7", "en7"], - "the cluster subnet routes through the port") - expectEqual(Facts.clusterSubnetRouteInterfaces(IsolationFixtures.macARoutes), [], "no cluster subnet before") + expectEqual(Facts.clusterSubnetRouteInterfaces(IsolationFixtures.macAIsolatedRoutes(address: "10.219.1.2"), + interfaceListing: IsolationFixtures.macAInterfaces(en7: ["10.219.1.2"])), ["en7", "en7"], "the cluster subnet routes through the port") + expectEqual(Facts.clusterSubnetRouteInterfaces(IsolationFixtures.macARoutes, + interfaceListing: IsolationFixtures.macAInterfaces(en7: [IsolationFixtures.macALeaseIPv4])), [], "no cluster subnet before") + // macOS reaches an address of its own through lo0: the route counts on + // the interface that carries the address, and only there. + let paired = IsolationFixtures.pairedMacA, pairedRoutes = IsolationFixtures.routeTable(paired.routes) + expectEqual(Facts.clusterSubnetRouteInterfaces(pairedRoutes, interfaceListing: paired.interfaceListing), + ["en3", "en3", "en3", "en3", "en3"], "paired Mac A: its own address through lo0 counts on en3") + expectEqual(Facts.clusterSubnetRouteInterfaces(pairedRoutes, interfaceListing: ""), ["en3", "en3", "lo0", "en3", "en3"], + "without a listing it counts on the loopback") + let tunnelRoute = "10.219.77.1 2:0:5e:0:53:99 UHLWIi lo0 " + expectEqual(Facts.clusterSubnetRouteInterfaces(IsolationFixtures.routeTable(paired.routes + [tunnelRoute]), + interfaceListing: paired.interfaceListing + IsolationFixtures.tunnel("utun4", address: "10.219.77.1"))?.last, "utun4", + "another interface's own address counts on that interface") + expectEqual(Facts.clusterSubnetRouteInterfaces(IsolationFixtures.routeTable(paired.routes + [tunnelRoute]), + interfaceListing: paired.interfaceListing)?.last, "lo0", "an address no interface carries stays on the loopback") expectEqual(Facts.defaultRouteInterfaces("default 192.0.2.1 UGScg en1\n"), nil, "rows without the header are not a table") expectEqual(Facts.dnsInterfaces(IsolationFixtures.macADNS()), ["en1", "en7", "utun4"], "Mac A: a resolver through en7") diff --git a/provider-swift/Tests/ClusterLinkChecks/LinkIsolationFixtures.swift b/provider-swift/Tests/ClusterLinkChecks/LinkIsolationFixtures.swift index ed69fcc2c2..16a0f0ddf1 100644 --- a/provider-swift/Tests/ClusterLinkChecks/LinkIsolationFixtures.swift +++ b/provider-swift/Tests/ClusterLinkChecks/LinkIsolationFixtures.swift @@ -410,10 +410,11 @@ enum IsolationFixtures { /// An isolated Mac captured read-only on 2026-11-03 after its port paired /// and carried traffic. `routes` are the captured `netstat -rn -f inet` - /// rows for the default routes, the cluster subnet and the loopback, and - /// the port carries its captured cluster address; MAC addresses, the - /// Wi-Fi gateway and its address are placeholders. The rest of each Mac - /// is what Darkbloom leaves on an isolated port. + /// rows for the default routes, the cluster subnet and the loopback, the + /// port carries its captured cluster address and the service order is the + /// captured one where there is one; MAC addresses, the Wi-Fi gateway and + /// its address are placeholders. The rest of each Mac is what Darkbloom + /// leaves on an isolated port. struct PairedMac { let name: String let port: String @@ -428,13 +429,17 @@ enum IsolationFixtures { var device: String { ClusterLinkName.device(ofInterface: port) } + var interfaceListing: String { + LinkFixtures.loopback + IsolationFixtures.port(wifi, active: true, addresses: [LinkFixtures.wifiIPv4]) + + otherPorts.map { IsolationFixtures.port($0, active: false, addresses: []) }.joined() + + IsolationFixtures.port(port, active: true, addresses: [address]) + + (bridgeMembers.isEmpty ? "" : LinkFixtures.bridge(members: bridgeMembers)) + } + func tools(extraRoutes: [String] = [], extraInterfaces: String = "") -> FakeLinkTools { var tools = FakeLinkTools( deviceList: .output(devices.map { LinkFixtures.deviceBlock($0, active: $0 == device) }.joined()), - interfaces: .output(LinkFixtures.loopback + IsolationFixtures.port(wifi, active: true, addresses: [LinkFixtures.wifiIPv4]) - + otherPorts.map { IsolationFixtures.port($0, active: false, addresses: []) }.joined() - + IsolationFixtures.port(port, active: true, addresses: [address]) - + (bridgeMembers.isEmpty ? "" : LinkFixtures.bridge(members: bridgeMembers)) + extraInterfaces), + interfaces: .output(interfaceListing + extraInterfaces), details: [device: .output(LinkFixtures.detailWithMappedGID(device))]) let bridges = bridgeMembers.isEmpty ? IsolationFixtures.emptyBridgePreferences : "{\"bridge0\":{\"Interfaces\":[\(bridgeMembers.map { "\"\($0)\"" }.joined(separator: ","))]}}\n" diff --git a/provider-swift/Tests/ClusterLinkChecks/README.md b/provider-swift/Tests/ClusterLinkChecks/README.md index 8bd8678a3a..0a311bc08d 100644 --- a/provider-swift/Tests/ClusterLinkChecks/README.md +++ b/provider-swift/Tests/ClusterLinkChecks/README.md @@ -83,6 +83,12 @@ Checks cover: part-way, applied without effect, unreadable record, a service without a record); the record file on real files; the guided flow's v2 transcripts; and the bounded wait before a rank starts, over a fake clock. +- Three isolated Macs after pairing, from route tables captured read-only on + 2026-11-03 (MAC addresses and the Wi-Fi gateway replaced): macOS's loopback + route to the port's own address leaves the port isolated in the report, the + summary, the guided flow and a dry run of the fix, while a VPN address in the + cluster subnet, a route into it through utun, bridge0 or another port, and a + loopback route to an address the port does not carry still block. Fixture addresses are documentation placeholders or derived from made-up machine values. No RDMA or network tool, `launchctl`, `plutil`, `osascript` or From b225931426167698f8a463a1aa13baae8325641d Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:05:29 -0800 Subject: [PATCH 0262/1441] refactor(provider): keep route destinations inside the link network facts reader ClusterLinkNetworkFacts.routeInterfaces(_:where:countedOn:) passed each route's destination, an address, to a caller's closure and returned whatever that closure made of it. A private row reader, routes(_:), now keeps destinations inside ClusterLinkNetworkFacts. defaultRouteInterfaces and clusterSubnetRouteInterfaces filter its rows and return interface names only. The loopback rule now lives entirely in clusterSubnetRouteInterfaces, and the defaulted countedOn closure is gone. The rows, their order and the nil for text that is not a route table are unchanged. ClusterLinkIsolationInspection.machine(run:interfaceListing:) keeps its empty default. Without the listing a loopback route stays on the loopback, so status can only be stricter (clusterSubnetInUse); it never passes a port that is not isolated. The doc comment now says so, and says that the repair leaves the listing out because it reads only services and bridges. Making the listing required would touch the repair paths, and --remove would still need an explicit empty listing or one more ifconfig -a. The fixture MAC addresses move to the EUI-48 documentation block (0:0:5e:0:53:xx, RFC 9542). The gateway column is not read, so no assertion changes. One test-local name, tunnelRoute, becomes loopbackRoute, because the route goes through lo0. The README notes that the cluster addresses are as captured and that the Wi-Fi address was replaced. The architecture section now says that any loopback route to an address the port does not carry still blocks, including utun4's. The changelog fragment is one operator sentence. Checks: ClusterLinkChecks (2502 expectations in 46 groups) and ClusterDiagnosticsChecks pass, as do docs-check, docs-impact-check BASE=origin/dev, changelog-check and git diff --check. Co-Authored-By: Claude Opus 5.5 --- .../cluster-link-own-address-loopback.md | 5 ++-- docs/architecture/inference.md | 4 +-- .../Link/ClusterLinkIsolationInspection.swift | 8 +++-- .../Link/ClusterLinkNetworkFacts.swift | 30 +++++++++---------- .../ClusterLinkFindingsCheck.swift | 4 +-- .../LinkIsolationChecks.swift | 12 ++++---- .../LinkIsolationFixtures.swift | 14 ++++----- .../Tests/ClusterLinkChecks/README.md | 14 +++++---- 8 files changed, 46 insertions(+), 45 deletions(-) diff --git a/changelog.d/cluster-link-own-address-loopback.md b/changelog.d/cluster-link-own-address-loopback.md index e8ba53f4c3..3e984ae184 100644 --- a/changelog.d/cluster-link-own-address-loopback.md +++ b/changelog.d/cluster-link-own-address-loopback.md @@ -1,4 +1,3 @@ -### A paired Mac's cable port is no longer called not isolated +### A paired Mac's cable port is no longer reported as not isolated -- `darkbloom cluster doctor` no longer reports a paired Mac's cable port as not isolated because of its own address. Once the port has carried traffic, macOS reaches the port's own address through the loopback (`lo0`), and that route was taken for the cluster subnet `10.219/16` being used elsewhere on the Mac: `darkbloom cluster link` said "not isolated: the cluster subnet 10.219/16 is already used on this Mac", the doctor failed `localLinkIsolation.`, and `darkbloom cluster link --fix` (also with `--dry-run`) refused with `isolationRefused`. -- Another interface or VPN with an address in `10.219/16`, a route into it through any other interface, and a loopback route to an address the port does not carry still stop the isolation, as before. +- `darkbloom cluster link` and `darkbloom cluster doctor` no longer report a paired Mac's cable port as not isolated ("the cluster subnet 10.219/16 is already used on this Mac") because macOS routes the port's own address through the loopback. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index df0847165a..ff035ecbbc 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3735,8 +3735,8 @@ interface carries on that interface `ifconfig -a` text the readiness probe already took (`ClusterLinkIsolationInspection.machine(run:interfaceListing:)`). Only interface names leave the reader. Another interface's address in the subnet, a route into -it through any other interface, and a loopback route to an address that no -interface carries still block. +it through any other interface, and a loopback route to an address the port +does not carry still block. Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkNetworkFacts.swift` (`ClusterLinkNetworkFacts.clusterSubnetRouteInterfaces`) and diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkIsolationInspection.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkIsolationInspection.swift index 53aa632229..9c96294002 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkIsolationInspection.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkIsolationInspection.swift @@ -20,9 +20,11 @@ enum ClusterLinkIsolationInspection { /// Nil when one reading timed out, overflowed, or printed text of the /// wrong shape. A tool that exits non-zero where that means "none" (no /// Internet Sharing file, no bridge key) is an empty answer, not a failure. - /// The cluster subnet's routes are read against `interfaceListing`, the - /// `ifconfig -a` text of the same inspection; without it, a loopback route - /// to an address of this Mac's own counts on the loopback. + /// `interfaceListing` is the `ifconfig -a` text `status` judges with: a + /// loopback route to one of this Mac's own addresses counts on the + /// interface that carries it. Without it that route stays on the loopback, + /// which `status` takes for `clusterSubnetInUse`; the repair, which reads + /// only services and bridges, leaves it out. static func machine(run: ClusterLinkToolRunner, interfaceListing: String = "") -> Machine? { /// A reading that must succeed. func required(_ command: ClusterLinkToolCommand) -> String? { diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkNetworkFacts.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkNetworkFacts.swift index 8164c76cf7..d9fc15786c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkNetworkFacts.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Diagnostics/Link/ClusterLinkNetworkFacts.swift @@ -141,41 +141,39 @@ enum ClusterLinkNetworkFacts { return names.filter(ClusterLinkName.isInterface) } - /// `netstat -rn -f inet`: the interface of every route whose destination - /// matches `destination`, in listed order, as `countedOn` names it from - /// the destination and the route's interface. Nil when the text is not a - /// route table. - static func routeInterfaces(_ text: String, where destination: (Substring) -> Bool, - countedOn: (_ destination: Substring, _ interface: String) -> String = { $1 }) -> [String]? { - var inTable = false, interfaces = [String]() + /// `netstat -rn -f inet`: the destination and interface of every route + /// through an interface with a valid name, in listed order. Nil when the + /// text is not a route table. + private static func routes(_ text: String) -> [(destination: Substring, interface: String)]? { + var inTable = false, routes = [(destination: Substring, interface: String)]() for line in text.split(whereSeparator: \.isNewline) { let words = line.split(whereSeparator: \.isWhitespace) if words.first == "Destination", words.dropFirst().first == "Gateway" { inTable = true continue } - guard inTable, words.count >= 4, destination(words[0]) else { continue } + guard inTable, words.count >= 4 else { continue } let interface = String(words[3]) - if ClusterLinkName.isInterface(interface) { interfaces.append(countedOn(words[0], interface)) } + if ClusterLinkName.isInterface(interface) { routes.append((words[0], interface)) } } - return inTable ? interfaces : nil + return inTable ? routes : nil } /// The interfaces that carry a default route. static func defaultRouteInterfaces(_ text: String) -> [String]? { - routeInterfaces(text) { $0 == "default" } + routes(text)?.filter { $0.destination == "default" }.map(\.interface) } - /// The interfaces that carry a route into the cluster subnet. Once an - /// address of this Mac's own has carried traffic, macOS reaches it through + /// The interfaces that carry a route into the cluster subnet. Once one of + /// this Mac's own addresses has carried traffic, macOS reaches it through /// the loopback (`10.219.4.7 UHLWIi lo0`), so a loopback route to /// an address that an interface in `interfaceListing` (`ifconfig -a`) /// carries counts on that interface. static func clusterSubnetRouteInterfaces(_ text: String, interfaceListing: String) -> [String]? { let listed = ClusterNetworkInterfaces.parse(interfaceListing)?.interfaces.map(\.name) ?? [] - return routeInterfaces(text, where: { ClusterLinkClusterAddress.inSubnet($0) }) { destination, interface in - guard interface == loopback else { return interface } - return listed.first { lists(String(destination), on: $0, inListing: interfaceListing) } ?? interface + return routes(text)?.filter { ClusterLinkClusterAddress.inSubnet($0.destination) }.map { route in + guard route.interface == loopback else { return route.interface } + return listed.first { lists(String(route.destination), on: $0, inListing: interfaceListing) } ?? route.interface } } diff --git a/provider-swift/Tests/ClusterDiagnosticsChecks/ClusterLinkFindingsCheck.swift b/provider-swift/Tests/ClusterDiagnosticsChecks/ClusterLinkFindingsCheck.swift index 316aa1f818..95684b3082 100644 --- a/provider-swift/Tests/ClusterDiagnosticsChecks/ClusterLinkFindingsCheck.swift +++ b/provider-swift/Tests/ClusterDiagnosticsChecks/ClusterLinkFindingsCheck.swift @@ -192,8 +192,8 @@ extension ClusterDiagnosticsCheck { + "default 192.0.2.1 UGScg en1\n" + "10.219/16 link#19 UCS en3 !\n" + "10.219.13.112/32 link#19 UCS en3 !\n" - + "10.219.13.112 2:0:5e:0:53:3 UHLWIi lo0\n" - + "10.219.165.133 2:0:5e:0:53:33 UHLWIi en3 1150\n" + + "10.219.13.112 0:0:5e:0:53:3 UHLWIi lo0\n" + + "10.219.165.133 0:0:5e:0:53:33 UHLWIi en3 1150\n" + "10.219.255.255 ff:ff:ff:ff:ff:ff UHLWbI en3 !\n") case .dnsConfiguration: return .output("DNS configuration\n") default: return .unavailable diff --git a/provider-swift/Tests/ClusterLinkChecks/LinkIsolationChecks.swift b/provider-swift/Tests/ClusterLinkChecks/LinkIsolationChecks.swift index 92df6a39b7..f2f3cc428d 100644 --- a/provider-swift/Tests/ClusterLinkChecks/LinkIsolationChecks.swift +++ b/provider-swift/Tests/ClusterLinkChecks/LinkIsolationChecks.swift @@ -55,11 +55,11 @@ extension ClusterLinkCheck { ["en3", "en3", "en3", "en3", "en3"], "paired Mac A: its own address through lo0 counts on en3") expectEqual(Facts.clusterSubnetRouteInterfaces(pairedRoutes, interfaceListing: ""), ["en3", "en3", "lo0", "en3", "en3"], "without a listing it counts on the loopback") - let tunnelRoute = "10.219.77.1 2:0:5e:0:53:99 UHLWIi lo0 " - expectEqual(Facts.clusterSubnetRouteInterfaces(IsolationFixtures.routeTable(paired.routes + [tunnelRoute]), + let loopbackRoute = "10.219.77.1 0:0:5e:0:53:99 UHLWIi lo0 " + expectEqual(Facts.clusterSubnetRouteInterfaces(IsolationFixtures.routeTable(paired.routes + [loopbackRoute]), interfaceListing: paired.interfaceListing + IsolationFixtures.tunnel("utun4", address: "10.219.77.1"))?.last, "utun4", "another interface's own address counts on that interface") - expectEqual(Facts.clusterSubnetRouteInterfaces(IsolationFixtures.routeTable(paired.routes + [tunnelRoute]), + expectEqual(Facts.clusterSubnetRouteInterfaces(IsolationFixtures.routeTable(paired.routes + [loopbackRoute]), interfaceListing: paired.interfaceListing)?.last, "lo0", "an address no interface carries stays on the loopback") expectEqual(Facts.defaultRouteInterfaces("default 192.0.2.1 UGScg en1\n"), nil, "rows without the header are not a table") @@ -265,15 +265,15 @@ extension ClusterLinkCheck { } let vpn = IsolationFixtures.tunnel("utun4", address: "10.219.77.1") expectEqual(findings(interfaces: vpn), [.clusterSubnetInUse], "\(mac.name): a VPN address in the cluster subnet") - expectEqual(findings(routes: ["10.219.77.1 2:0:5e:0:53:99 UHLWIi lo0 "], interfaces: vpn), + expectEqual(findings(routes: ["10.219.77.1 0:0:5e:0:53:99 UHLWIi lo0 "], interfaces: vpn), [.clusterSubnetInUse], "\(mac.name): the VPN address and its loopback route") for route in ["10.219/16 link#40 UCS utun4 ", "10.219.77/24 link#13 UCS bridge0 !", - "10.219.77.7 2:0:5e:0:53:99 UHLWIi en9 1200", + "10.219.77.7 0:0:5e:0:53:99 UHLWIi en9 1200", "\(mac.address) \(mac.address) UH utun4 "] { expectEqual(findings(routes: [route]), [.clusterSubnetInUse], "\(mac.name): a route elsewhere: \(route)") } - expectEqual(findings(routes: ["10.219.77.77 2:0:5e:0:53:99 UHLWIi lo0 "]), + expectEqual(findings(routes: ["10.219.77.77 0:0:5e:0:53:99 UHLWIi lo0 "]), [.clusterSubnetInUse], "\(mac.name): a loopback route for an address the port does not carry") } } diff --git a/provider-swift/Tests/ClusterLinkChecks/LinkIsolationFixtures.swift b/provider-swift/Tests/ClusterLinkChecks/LinkIsolationFixtures.swift index 16a0f0ddf1..97376c44a3 100644 --- a/provider-swift/Tests/ClusterLinkChecks/LinkIsolationFixtures.swift +++ b/provider-swift/Tests/ClusterLinkChecks/LinkIsolationFixtures.swift @@ -468,12 +468,12 @@ enum IsolationFixtures { "default link#38 UCSIg utun8 ", "10.219/16 link#19 UCS en3 !", "10.219.13.112/32 link#19 UCS en3 !", - "10.219.13.112 2:0:5e:0:53:3 UHLWIi lo0 ", - "10.219.165.133 2:0:5e:0:53:33 UHLWIi en3 1150", + "10.219.13.112 0:0:5e:0:53:3 UHLWIi lo0 ", + "10.219.165.133 0:0:5e:0:53:33 UHLWIi en3 1150", "10.219.255.255 ff:ff:ff:ff:ff:ff UHLWbI en3 !", "127 127.0.0.1 UCS lo0 ", "127.0.0.1 127.0.0.1 UH lo0 ", - "\(LinkFixtures.wifiIPv4) 2:0:5e:0:53:1 UHLWI lo0 ", + "\(LinkFixtures.wifiIPv4) 0:0:5e:0:53:1 UHLWI lo0 ", ], serviceOrder: serviceOrderHeader + service(1, "Ethernet", port: "Ethernet", device: "en0") + service(2, "USB 10/100/1000 LAN", port: "USB 10/100/1000 LAN", device: "en14") @@ -491,9 +491,9 @@ enum IsolationFixtures { "default 192.0.2.1 UGScg en0 ", "default link#40 UCSIg utun15 ", "10.219/16 link#11 UCS en6 !", - "10.219.21.80 2:0:5e:0:53:26 UHLWIi en6 1128", + "10.219.21.80 0:0:5e:0:53:26 UHLWIi en6 1128", "10.219.129.164/32 link#11 UCS en6 !", - "10.219.129.164 2:0:5e:0:53:16 UHLWI lo0 ", + "10.219.129.164 0:0:5e:0:53:16 UHLWI lo0 ", "10.219.255.255 ff:ff:ff:ff:ff:ff UHLWbI en6 !", "127 127.0.0.1 UCS lo0 ", "127.0.0.1 127.0.0.1 UH lo0 ", @@ -519,8 +519,8 @@ enum IsolationFixtures { "default link#29 UCSIg utun2 ", "10.219/16 link#21 UCS en6 !", "10.219.21.80/32 link#21 UCS en6 !", - "10.219.21.80 2:0:5e:0:53:26 UHLWIi lo0 ", - "10.219.129.164 2:0:5e:0:53:16 UHLWIi en6 1186", + "10.219.21.80 0:0:5e:0:53:26 UHLWIi lo0 ", + "10.219.129.164 0:0:5e:0:53:16 UHLWIi en6 1186", "10.219.255.255 ff:ff:ff:ff:ff:ff UHLWbI en6 !", "127 127.0.0.1 UCS lo0 ", "127.0.0.1 127.0.0.1 UH lo0 ", diff --git a/provider-swift/Tests/ClusterLinkChecks/README.md b/provider-swift/Tests/ClusterLinkChecks/README.md index 0a311bc08d..b4475edeea 100644 --- a/provider-swift/Tests/ClusterLinkChecks/README.md +++ b/provider-swift/Tests/ClusterLinkChecks/README.md @@ -84,14 +84,16 @@ Checks cover: record); the record file on real files; the guided flow's v2 transcripts; and the bounded wait before a rank starts, over a fake clock. - Three isolated Macs after pairing, from route tables captured read-only on - 2026-11-03 (MAC addresses and the Wi-Fi gateway replaced): macOS's loopback - route to the port's own address leaves the port isolated in the report, the - summary, the guided flow and a dry run of the fix, while a VPN address in the - cluster subnet, a route into it through utun, bridge0 or another port, and a - loopback route to an address the port does not carry still block. + 2026-11-03 (cluster addresses as captured; MAC addresses, the Wi-Fi gateway + and the Wi-Fi address replaced): macOS's loopback route to the port's own + address leaves the port isolated in the report, the summary, the guided flow + and a dry run of the fix, while a VPN address in the cluster subnet, a route + into it through utun, bridge0 or another port, and a loopback route to an + address the port does not carry still block. Fixture addresses are documentation placeholders or derived from made-up -machine values. No RDMA or network tool, `launchctl`, `plutil`, `osascript` or +machine values, apart from the cluster addresses captured after pairing. +No RDMA or network tool, `launchctl`, `plutil`, `osascript` or approval prompt is started, no setting is read or changed, and no peer is contacted. How a report appears among the doctor's checks is covered by `ClusterDiagnosticsChecks`; From 5a604f83be84abde32b2093351b051568d0bd656 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:06:58 -0800 Subject: [PATCH 0263/1441] fix(cluster): say Serving and Done only once the pair is loaded On 2026-11-03 the owner's M3 Ultra + M5 Max and an end user's 2x M4 Max both printed "Serving" and "Done" while nothing was loaded: a pair offered for pairing counted as tested, and register() discarded awaitReady's result. The driver now waits for a pair offered for pairing to serve (operation pairServing: rank 0's pair slot published, both ranks loaded, first request answered) before it says Serving or Done; a start that does not serve, the restart after the registration included, says why in one line and stays open with Retry, Change model, Serve locally only and Diagnostics; q exits 1. A Mac without a Darkbloom login is named before the Start step starts anything, with darkbloom login or local-only serving offered. Onboarding checks (a)-(d) fail first (30 failures on the driver as on origin/dev) and pass after (765 passed, 0 failed). Co-Authored-By: Claude Opus 5.5 --- .../Onboarding/ClusterOnboardingFlow.swift | 229 +++++++++++++++--- .../ClusterOnboardingPairServing.swift | 116 +++++++++ .../OnboardingChecks.swift | 207 +++++++++++++++- .../Tests/ClusterOnboardingChecks/run.sh | 2 +- 4 files changed, 511 insertions(+), 43 deletions(-) create mode 100644 provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingPairServing.swift diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift index be3c516b16..b34ece60ad 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift @@ -577,6 +577,13 @@ public struct ClusterOnboardingReady: Codable, Sendable, Equatable { return servesHere ? notice : notice.replacingOccurrences(of: "this Mac's API", with: "that Mac's API") } + /// A pair offered for pairing once the coordinator paired both Macs, both loaded the model and it answered its first + /// request: "Serving Qwen3.8 27B (pipeline) through Darkbloom on both Macs". Registered alone is not serving. + public func pairServingLine(model: String) -> String { + let name = ClusterOnboardingDeployment.shownMarker(split).map { "\(model) (\($0))" } ?? model + return "Serving \(name) through Darkbloom on both Macs" + } + /// How the line of a pair registered with the coordinator as a cluster member starts (`ClusterLocalServing`). public static let registeredNotice = "Registered with the coordinator as a cluster member" @@ -698,6 +705,15 @@ public struct ClusterOnboardingOperations: Sendable { /// This Mac's name as System Settings shows it, said on its own screen beside the part it plays (two identical /// Macs read the same hardware); nil when unknown. public var thisMacName: @Sendable () -> String? + /// A pair offered for pairing (both members registered): waits, bounded, until the coordinator committed it and + /// both Macs loaded their share and the pair answered its first request; its line is that request's time ("in + /// 0.84 s"). A failure's first line says why it does not serve, in plain words (`ClusterOnboardingNotServing`). + public var pairServing: @Sendable (_ progress: @escaping @Sendable (String) -> Void) -> Result<[String], ClusterOnboardingFailure> + /// The Macs of the cluster without a Darkbloom login, as this screen names them ("this Mac", "the other Mac + /// (…)"): the coordinator pairs only logged-in Macs. Empty when every Mac is logged in, or it cannot be told. + public var missingLogins: @Sendable () -> [String] + /// Runs `darkbloom login` in this terminal (the person approves it in the browser); true when it ended logged in. + public var login: @Sendable () -> Bool public init(resume: @escaping @Sendable () -> ClusterOnboardingResume, checkLink: @escaping @Sendable (@escaping @Sendable (String) -> Void) -> ClusterOnboardingLinkResult, @@ -728,7 +744,11 @@ public struct ClusterOnboardingOperations: Sendable { runAsAdministrator: @escaping @Sendable (String) -> Bool = { _ in false }, serviceOutlivesWindow: @escaping @Sendable () -> Bool = { true }, remote: @escaping @Sendable () -> Bool = { false }, - thisMacName: @escaping @Sendable () -> String? = { nil }) { + thisMacName: @escaping @Sendable () -> String? = { nil }, + pairServing: @escaping @Sendable (@escaping @Sendable (String) -> Void) -> Result<[String], ClusterOnboardingFailure> + = { _ in .failure(.init("This build cannot tell whether the coordinator formed the pair.")) }, + missingLogins: @escaping @Sendable () -> [String] = { [] }, + login: @escaping @Sendable () -> Bool = { false }) { self.resume = resume; self.checkLink = checkLink; self.pair = pair; self.answerCode = answerCode self.ensureService = ensureService; self.reachMembers = reachMembers; self.planModels = planModels self.adopt = adopt; self.serve = serve; self.waitReady = waitReady; self.testRequest = testRequest @@ -737,6 +757,7 @@ public struct ClusterOnboardingOperations: Sendable { self.developerNotice = developerNotice; self.setScope = setScope; self.register = register self.localNetwork = localNetwork; self.commandApp = commandApp; self.runAsAdministrator = runAsAdministrator self.serviceOutlivesWindow = serviceOutlivesWindow; self.remote = remote; self.thisMacName = thisMacName + self.pairServing = pairServing; self.missingLogins = missingLogins; self.login = login } } @@ -1430,6 +1451,13 @@ public enum ClusterOnboardingDriver { } } } + // Serving through Darkbloom needs both Macs logged in: said before anything starts (2026-11-03: neither Mac of the + // owner's second pair had a login, and both screens said Done while the coordinator never paired them). + guard let startScope = checkLogins(scope: scope, operations, console) else { + console.say("Nothing changed.") + return 0 + } + let savesScope = saveScope || startScope != scope console.heading("4/4 Start") // Memory moves while the person reads: the fit is checked again right before anything starts. if let remedy = operations.recheckFit(chosen!) { @@ -1445,8 +1473,8 @@ public enum ClusterOnboardingDriver { return 1 } // After the adopt (which stopped a running model first), so the scope never restarts the old model. - if saveScope { - switch operations.setScope(scope) { + if savesScope { + switch operations.setScope(startScope) { case .success: break case .failure(let failure): for line in failure.lines { console.say(" " + line) } @@ -1459,21 +1487,147 @@ public enum ClusterOnboardingDriver { for line in failure.lines { console.say(" " + line) } return 1 } - guard let ready = awaitReady(title: choice.title, operations, console) else { return 1 } - console.say(" \(done) " + ready.summary(model: choice.title) + servesWords(scope: scope, ready: ready)) - // A pair offered for pairing has no local API to test: its requests come through Darkbloom. - if ready.offered != nil { console.say(ClusterOnboardingReady.offeredTestLine) } - let tested = ready.offered != nil || test(operations, console) - if tested, ready.offered == nil, !scope.isLocalOnly { register(title: choice.title, operations, console) } - console.say("") - guard tested else { - console.say("Setup saved, but the test failed. Run `darkbloom cluster` to test again.") - return 1 + return finishStart(title: choice.title, scope: startScope, operations, console) + } + + /// Serving through Darkbloom needs every Mac logged in: the coordinator pairs only Macs logged in to one account. + /// Names the Macs without a login before anything starts, and offers `darkbloom login` here (the other Mac's own + /// login is asked for) or serving locally only. The scope to start with; nil when the person cancelled. + static func checkLogins(scope: ClusterServingScope, _ operations: ClusterOnboardingOperations, + _ console: ClusterOnboardingConsole) -> ClusterServingScope? { + guard !scope.isLocalOnly else { return scope } + while true { + let missing = operations.missingLogins() + guard !missing.isEmpty else { return scope } + console.say(" " + ClusterOnboardingNotServing.notLoggedIn(missing) + ".") + let here = missing.contains(ClusterOnboardingMacName.this) + if !here { console.say(" Run `darkbloom login` on the other Mac, then Check again.") } + switch console.choose([here ? "Log in on this Mac" : "Check again", "Serve locally only", "Cancel"], selected: 0) { + case 0: + if here, !console.suspended({ operations.login() }) { console.say(" This Mac is still not logged in.") } + case 1: return .localOnly(bind: ClusterServingScope.localOnlyDefaultBind) + default: return nil + } + } + } + + /// How a start ended up: serving (the lines that say so), its test failed, or not serving (why, first). + enum StartOutcome { case served([String]), testFailed, notServing([String]) } + + /// After the start. Serving and Done are said only once the model is loaded on both Macs and a request answered + /// (2026-11-03: a pair offered for pairing said both while nothing was loaded). A pair that does not serve says why + /// and stays open with the choices; leaving it never claims success. + static func finishStart(title: String, scope: ClusterServingScope, _ operations: ClusterOnboardingOperations, + _ console: ClusterOnboardingConsole) -> Int32 { + var scope = scope + var mayRegister = true + while true { + switch startOutcome(title: title, scope: scope, mayRegister: &mayRegister, operations, console) { + case .served(let lines): + for line in lines { console.say(" " + line) } + console.say("") + if let restart = operations.afterRestart() { console.say(restart) } + console.say("Done. " + (operations.serviceOutlivesWindow() ? "You can close both windows." : "Keep both windows open.")) + console.say(againLine) + return 0 + case .testFailed: + console.say("") + console.say("Setup saved, but the test failed. Run `darkbloom cluster` to test again.") + return 1 + case .notServing(let lines): + switch notServing(lines, operations, console) { + case .retry: continue + case .changeModel: return chooseAndServe(operations, console, scope: scope) + case .localOnly: + let local = ClusterServingScope.localOnly(bind: ClusterServingScope.localOnlyDefaultBind) + switch busy(console, "Switching to local only", { operations.setScope(local) }) { + case .success(let said): + for line in said { console.say(" " + line) } + scope = local + case .failure(let failure): + for line in failure.lines { console.say(" " + line) } + } + case .leave: + console.say(notServingLastLine) + return 1 + } + } + } + } + + /// The last line when the person leaves a pair that does not serve. + public static let notServingLastLine = "Not serving yet. Both Macs keep trying by themselves; run `darkbloom cluster` to check." + + /// Waits for the started parts; a pair offered for pairing then for the coordinator to pair both Macs and load the + /// model there (registered is not serving); a pair on the leader's API is tested, then registered with the + /// coordinator when it serves a cluster approval (once per start: both parts then start again and are awaited). + static func startOutcome(title: String, scope: ClusterServingScope, mayRegister: inout Bool, + _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> StartOutcome { + let ready: ClusterOnboardingReady + switch waitForParts(title: title, operations, console) { + case .success(let value): ready = value + case .failure(let failure): return .notServing(failure.lines) + } + if ready.offered != nil { + switch awaitPairServing(title: title, operations, console) { + case .success(let test): + return .served(["\(done) Test response" + (test.map { " " + $0 } ?? ""), "\(done) " + ready.pairServingLine(model: title)]) + case .failure(let failure): return .notServing(failure.lines) + } + } + guard test(operations, console) else { return .testFailed } + if mayRegister, !scope.isLocalOnly { + mayRegister = false + if register(operations, console) { return startOutcome(title: title, scope: scope, mayRegister: &mayRegister, operations, console) } + } + return .served(["\(done) " + ready.summary(model: title) + servesWords(scope: scope, ready: ready)]) + } + + enum NotServingChoice { case retry, changeModel, localOnly, leave } + + public static let notServingItems = ["Retry", "Change model", "Serve locally only", "Diagnostics"] + + /// Why the pair does not serve in one plain line (details under it), what to do, then the choices. Diagnostics + /// saves the file and asks again; q leaves. + static func notServing(_ lines: [String], _ operations: ClusterOnboardingOperations, + _ console: ClusterOnboardingConsole) -> NotServingChoice { + let first = lines.first ?? "the cluster did not report ready" + let reason = first.hasSuffix(".") ? String(first.dropLast()) : first + console.say("Not serving yet: \(reason).") + for line in lines.dropFirst() { console.say(" " + line) } + if let remedy = ClusterOnboardingNotServing.remedy(forReason: reason) { console.say(" " + remedy) } + while true { + switch console.choose(notServingItems, selected: 0) { + case 0: return .retry + case 1: return .changeModel + case 2: return .localOnly + case 3: + switch busy(console, "Saving diagnostics", operations.saveDiagnostics) { + case .success(let said): for line in said { console.say(" " + line) } + case .failure(let failure): for line in failure.lines { console.say(" " + line) } + } + default: return .leave + } + } + } + + /// A pair offered for pairing: waits for the coordinator to pair both Macs and both to load the model, its progress + /// live; the pair's first request's time ("in 0.84 s"), or why it does not serve. + static func awaitPairServing(title: String, _ operations: ClusterOnboardingOperations, + _ console: ClusterOnboardingConsole) -> Result { + let progress = ClusterOnboardingMailbox() + let finished = ClusterOnboardingMailbox>() + Thread.detachNewThread { finished.post(operations.pairServing { progress.post($0) }) } + var latest: String? + while true { + if let line = progress.take().last { latest = line } + if let value = finished.take().first { + console.settle() + return value.map { $0.first.flatMap { $0.isEmpty ? nil : $0 } } + } + console.working("Serving \(title) through Darkbloom" + (latest.map { " (\($0))" } ?? "")) + _ = console.key(milliseconds: 120) } - if let restart = operations.afterRestart() { console.say(restart) } - console.say("Done. " + (operations.serviceOutlivesWindow() ? "You can close both windows." : "Keep both windows open.")) - console.say(againLine) - return 0 } /// The leader's last line: `darkbloom cluster` again manages the cluster (its menu tests, changes the model, stops). @@ -1488,48 +1642,51 @@ public enum ClusterOnboardingDriver { return " (earning through Darkbloom)" } - /// After the Test stage: registers the pair with the coordinator when it serves a cluster approval for this pair, - /// then waits until both Macs serve again. Nothing is said, and nothing stopped, when the coordinator serves none. - /// A registration that stopped the parts and was then refused also waits: both parts start again as before. - static func register(title: String, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) { + /// After the Test stage: registers the pair with the coordinator when it serves a cluster approval for this pair. + /// True when both parts start again (as cluster members, or as before after a refusal), which the caller awaits as + /// after the start; false, with nothing said or stopped, when the coordinator serves none. + static func register(_ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> Bool { let lines: [String] switch operations.register() { case .success(let said): lines = said case .failure(let failure): lines = failure.lines } - guard !lines.isEmpty else { return } + guard !lines.isEmpty else { return false } for line in lines { console.say(" " + line) } console.say(lines.first?.hasPrefix(ClusterOnboardingReady.registeredNotice) == true ? "Starting both Macs' parts again as cluster members…" : "Starting both Macs' parts again…") - _ = awaitReady(title: title, operations, console) + return true } /// Waits for the started cluster with its progress (the caller says where it serves); nil (with the last errors /// and the diagnostics offer) when it did not become ready. static func awaitReady(title: String, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) -> ClusterOnboardingReady? { + switch waitForParts(title: title, operations, console) { + case .success(let where_): + return where_ + case .failure(let failure): + for line in failure.lines { console.say(line) } + offerDiagnostics(operations, console) + console.say("Both Macs keep trying. Run `darkbloom cluster` to check.") + return nil + } + } + + /// Waits for the started cluster's parts with their progress as the live line. + static func waitForParts(title: String, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) + -> Result { let progress = ClusterOnboardingMailbox() let finished = ClusterOnboardingMailbox>() Thread.detachNewThread { finished.post(operations.waitReady { progress.post($0) }) } - var ready: Result? // The parts' progress ("1 of 2 parts ready") is the live line only: the screen keeps the result. var latest: String? - while ready == nil { + while true { if let line = progress.take().last { latest = line } - if let value = finished.take().first { ready = value; break } + if let value = finished.take().first { console.settle(); return value } console.working("Loading \(title) on both Macs" + (latest.map { " (\($0))" } ?? "")) _ = console.key(milliseconds: 120) } - console.settle() - switch ready! { - case .success(let where_): - return where_ - case .failure(let failure): - for line in failure.lines { console.say(line) } - offerDiagnostics(operations, console) - console.say("Both Macs keep trying. Run `darkbloom cluster` to check.") - return nil - } } /// One choice to save a diagnostics file (redacted) after a start that did not finish. diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingPairServing.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingPairServing.swift new file mode 100644 index 0000000000..4d266d6b03 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingPairServing.swift @@ -0,0 +1,116 @@ +import Foundation + +// A pair the coordinator forms (a setup saved with a cluster approval, "offered for pairing") serves only once the +// coordinator committed it and both Macs loaded their share: both members being registered is not serving. On +// 2026-11-03 both screens said "Serving" and "Done" while nothing was loaded (the coordinator refused the pair because +// its rank 0 had no App Attest trust). Pure (Foundation only): the onboarding checks compile it with plain swiftc. + +/// How a coordinator-paired part reports its pair's progress in its log (its stderr, the cluster service's +/// `rank.log`): one line per change, the latest one telling where the CURRENT run stands. +public enum ClusterOnboardingPairReport { + public static let logPrefix = "Pair: " + + /// The coordinator committed a start: both Macs load their share of the model. + public static let startingLine = logPrefix + "starting" + + /// Both ranks loaded and the pair answered its own first request (the warm-up, `ProviderLoop+ClusterPairWarmup`); + /// requests from the coordinator reach it now. + public static func servingLine(warmupSeconds: Double?) -> String { + logPrefix + "serving" + (warmupSeconds.map { " (first request in \(String(format: "%.2f", $0)) s)" } ?? "") + } + + /// The committed start ended or never formed. `guidance` is the incident's guidance code (`ClusterGuidance`, such as + /// `memory_gate_refused`), or a few fixed words. + public static func stoppedLine(_ guidance: String) -> String { logPrefix + "stopped (" + guidance + ")" } + + public enum State: Sendable, Equatable { + case starting + /// The first request's time ("in 0.84 s") when the warm-up ran. + case serving(test: String?) + /// Why, as the part wrote it (a guidance code or a few fixed words). + case stopped(String) + } + + /// The latest pair line in `log`, nil when there is none. + public static func latest(inLog log: String) -> State? { + guard let line = log.split(whereSeparator: \.isNewline).last(where: { $0.hasPrefix(logPrefix) }) else { return nil } + return state(String(line.dropFirst(logPrefix.count))) + } + + /// The state a pair line's text (after the prefix) says; nil for text no build writes. + public static func state(_ text: String) -> State? { + let text = text.trimmingCharacters(in: .whitespaces) + if text == "starting" { return .starting } + if text.hasPrefix("serving") { + guard let open = text.range(of: "(first request in "), let close = text.range(of: ")", range: open.upperBound.. String { + switch state { + case .starting: return String(startingLine.dropFirst(logPrefix.count)) + case .serving(let test): + return String(servingLine(warmupSeconds: nil).dropFirst(logPrefix.count)) + (test.map { " (first request \($0))" } ?? "") + case .stopped(let why): return String(stoppedLine(why).dropFirst(logPrefix.count)) + } + } +} + +/// Why a pair the coordinator forms does not serve, in one plain line for the screens, with what to do. The words come +/// from what the two Macs know: their Darkbloom login, the coordinator's trust status for each member (App Attest), +/// the guidance of the incident a failed start recorded, and a coordinator refusal reason when one reaches them. +public enum ClusterOnboardingNotServing { + /// `mac` as the screen names it ("this Mac", "the other Mac (Apple M3 Ultra, 256 GB)"). + public static func notLoggedIn(_ macs: [String]) -> String { + "\(ClusterOnboardingMacName.sentence(joined(macs))) \(macs.count == 1 ? "isn't" : "aren't") logged in to Darkbloom, " + + "so the coordinator won't pair \(macs.count == 1 ? "it" : "them")" + } + + public static func notVerified(_ mac: String) -> String { + "Darkbloom hasn't verified \(mac) for private serving yet (App Attest)" + } + + public static func lacksMemory(_ mac: String) -> String { "\(ClusterOnboardingMacName.sentence(mac)) lacks free memory for its share" } + + /// The plain words for a reason one of the Macs knows: a coordinator refusal word (`liveness:trust_floor`, + /// `private_text`, `serves_model`, …) or an incident's guidance code (`memory_gate_refused`, …), about `mac`. + public static func words(reason: String, mac: String) -> String { + let reason = reason.lowercased() + let trust = ["trust_floor", "private_text", "app_attest", "no_trust_evidence", "runtime_unverified", "challenge_stale", + "attestation", "untrusted", "private_only"] + if trust.contains(where: reason.contains) { return notVerified(mac) } + if reason.contains("memory_gate") || reason.contains("free_memory") || reason.contains("no_headroom") { return lacksMemory(mac) } + if reason.contains("serves_model") || reason.contains("not_serving_model") { + return "The coordinator doesn't let \(mac) serve this model in a pair" + } + if reason.contains("offline") || reason.contains("heartbeat") || reason.contains("not_logged_in") { + return "\(ClusterOnboardingMacName.sentence(mac)) isn't connected to Darkbloom" + } + if reason.contains("idle:") || reason.contains("busy") { return "\(ClusterOnboardingMacName.sentence(mac)) is busy with other work" } + if reason.contains("release") || reason.contains("build_hash") { return "The two Macs run different Darkbloom builds" } + if reason.contains("clock") { return "The clock of \(mac) is off; turn on Set time automatically there" } + let shown = reason.count <= 80 && ClusterOnboardingDeployment.shownPlainly(reason) ? reason : "no reason given" + return "The coordinator didn't accept the pair (\(shown))" + } + + /// What to do next, said under the reason (the choices follow it). + public static func remedy(forReason line: String) -> String? { + if line.contains("logged in to Darkbloom") { return "Run `darkbloom login` on each Mac named, then Retry; or serve locally only." } + if line.contains("(App Attest)") { + return "Keep both Macs logged in and running Darkbloom; it is verified within minutes. Retry then, or serve locally only." + } + if line.contains("lacks free memory") { return "Quit apps on that Mac, then Retry; or change the model." } + return nil + } + + static func joined(_ macs: [String]) -> String { + macs.count <= 1 ? (macs.first ?? ClusterOnboardingMacName.other) : macs.dropLast().joined(separator: ", ") + " and " + macs.last! + } +} diff --git a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift index 593642885a..d707c33fc9 100644 --- a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift +++ b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift @@ -102,6 +102,12 @@ import Darwin eachMacNamesItselfBesideItsPart() modelOnTheOtherMacIsCopiedNotDownloaded() modelThatDoesNotFitSaysSoOnce() + // 2026-11-03, the owner's second pair and an end user's: "Serving" and "Done" while nothing was loaded. + offeredPairThatTheCoordinatorRefusesSaysWhy() + failedRestartAfterTheRegistrationIsNotDone() + missingLoginIsSaidBeforeTheStart() + offeredPairServesOnceLoaded() + pairReportsAndReasonsInPlainWords() print("onboarding checks: \(passed) passed, \(failures.count) failed") for failure in failures { print("FAIL " + failure) } exit(failures.isEmpty ? 0 : 1) @@ -442,9 +448,20 @@ import Darwin reachFailures: Int = 0, readyResult: Result = .success(.init(servedBy: "this Mac", port: 8000, deployment: "Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers", - split: "pipeline"))) -> ClusterOnboardingOperations { + split: "pipeline")), + readyResults: [Result]? = nil, + pairServingResults: [Result<[String], ClusterOnboardingFailure>] = [.failure(.init("not asked in this check"))], + missingLogins: [String] = [], + loginSucceeds: Bool = true) -> ClusterOnboardingOperations { let answered = DispatchSemaphore(value: 0) let chosenPort = Recorder() + // The n-th wait for the parts answers `readyResults[n]` (the last one again after it), else `readyResult`. + @Sendable func ready(_ call: Int) -> Result { + guard let readyResults, !readyResults.isEmpty else { return readyResult } + return readyResults[min(call, readyResults.count - 1)] + } + let loggedOut = Recorder() + for mac in missingLogins { loggedOut.note(mac) } return ClusterOnboardingOperations( resume: { resume }, checkLink: { say in @@ -505,8 +522,9 @@ import Darwin adopt: { index in recorder.note("adopt \(index)"); return .success(["Saved this Mac's setup.", "Sent the setup to the other Mac over the cable; its cluster service applied it."]) }, serve: { recorder.note("serve"); return .success(["Started the other Mac's part over the cable (its cluster service runs it); this Mac's service runs its own."]) }, waitReady: { progress in + let call = recorder.all.filter { $0 == "waitReady" }.count recorder.note("waitReady"); progress("1 of 2 parts ready"); usleep(50_000); progress("2 of 2 parts ready") - return readyResult + return ready(call) }, testRequest: { recorder.note("testRequest"); return testResult }, // Rank 0, which serves the API, is the Mac that leads: this Mac on the leader, the other Mac on a member. @@ -539,7 +557,21 @@ import Darwin runAsAdministrator: { script in recorder.note("runAsAdministrator"); return sudoSucceeds && script == linkScript }, serviceOutlivesWindow: { outlivesWindow }, remote: { remote }, - thisMacName: { thisMacName }) + thisMacName: { thisMacName }, + pairServing: { progress in + let call = recorder.all.filter { $0 == "pairServing" }.count + recorder.note("pairServing") + progress("waiting for the coordinator to pair both Macs"); usleep(30_000) + progress("the coordinator paired them: loading the model on both Macs"); usleep(30_000) + return pairServingResults[min(call, pairServingResults.count - 1)] + }, + missingLogins: { loggedOut.all }, + login: { + recorder.note("login") + guard loginSucceeds else { return false } + loggedOut.lock.withLock { loggedOut.calls.removeAll { $0 == ClusterOnboardingMacName.this } } + return true + }) } static func privateMiMoSelectionRefusesBeforeAnyActionOnMemberOrUnpairedMac() { @@ -758,7 +790,8 @@ import Darwin _ = run.finish() let text = run.text expect(text.contains(restart), "\(label): the restart line: \(text)") - expect(Array(recorder.all.suffix(3)) == ["testRequest", "register", "waitReady"], + // The restarted parts are awaited and tested again: the serving line is about the parts that run now. + expect(Array(recorder.all.suffix(4)) == ["testRequest", "register", "waitReady", "testRequest"], "\(label): the parts are awaited after the registration: \(recorder.all)") let done = text.range(of: "Done.")?.lowerBound, restarted = text.range(of: restart)?.lowerBound expect(done != nil && restarted != nil && restarted! < done!, "\(label): Done comes after the parts serve again") @@ -1275,9 +1308,14 @@ import Darwin readyResult: .failure(.init(["The cluster did not report ready within 15 minutes.", "The other Mac (Apple M3 Ultra, 256 GB): its part ended: out of memory.", "This Mac: loading layers 16-31."])))) expect(run.waitFor(prompt(2)), "timeout: choice"); run.type("\r") - expect(run.waitFor(" 1) Save diagnostics for Darkbloom\n 2) Skip\n"), "timeout: one choice for diagnostics") - run.type("1") + // A start that did not finish stays open with the choices; Diagnostics is one of them. + expect(run.waitFor(notServingChoices), "timeout: the choices, diagnostics among them: \(run.text)") + run.type("4") + expect(run.waitFor(notServingChoices, count: 2), "timeout: the choices again after the file") + run.type("q") expect(run.finish() == 1, "timeout: exit 1") + expect(run.text.contains("Not serving yet: The cluster did not report ready within 15 minutes.\n"), "timeout: why, first") + expect(!run.text.contains("Done."), "timeout: never Done") expect(run.text.contains("The other Mac (Apple M3 Ultra, 256 GB): its part ended: out of memory."), "timeout: each Mac's last error on screen") expect(run.text.contains("Saved a diagnostics file"), "timeout: the file is saved") expect(!run.text.contains("rank.log"), "timeout: no log path") @@ -2171,4 +2209,161 @@ import Darwin run.type("1") expect(run.finish() == 0, "fit: the model that fits is served") } + + // MARK: - A pair the coordinator forms serves only once loaded (2026-11-03) + + /// Both Macs' members registered with the coordinator: offered for pairing, nothing loaded yet. + static let offeredReady = ClusterOnboardingReady(servedBy: "this Mac", port: 0, + deployment: "Serving Qwen3.8-27B-4bit-mtp across both Macs: pipeline, this Mac 32 layers / the other Mac 32 layers", + offered: ClusterOnboardingReady.registeredNotice + ": approval release/0.10.7/EigenLabs/Qwen3.8-27B-4bit-mtp/s1, until 2027-02-01T22:53:02Z", + split: "pipeline") + + static let registeredLine = ClusterOnboardingReady.registeredNotice + + ": approval release/0.10.7/EigenLabs/Qwen3.8-27B-4bit-mtp/s1, until 2027-02-01T22:53:02Z." + + /// The coordinator's refusal of the owner's pair (`liveness:private_text` on rank 0), as the screen words it. + static let notVerified = ClusterOnboardingNotServing.notVerified("the other Mac (Apple M3 Ultra, 256 GB)") + + static let notServingChoices = " 1) Retry\n 2) Change model\n 3) Serve locally only\n 4) Diagnostics\n" + + /// (a) 2026-11-03, the owner's M3 Ultra + M5 Max and an end user's 2x M4 Max: a pair offered for pairing said + /// "Serving" and "Done" while the coordinator refused it and nothing was loaded. Now the screen says why, in one + /// line, and stays open with the choices; leaving it never claims success. + static func offeredPairThatTheCoordinatorRefusesSaysWhy() { + let recorder = Recorder() + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), readyResult: .success(offeredReady), pairServingResults: [.failure(.init(notVerified))])) + expect(run.waitFor(prompt(2)), "refused: the list"); run.type("\r") + expect(run.waitFor(notServingChoices), "refused: the choices: \(run.text)") + let shown = run.text + expect(shown.contains("Not serving yet: " + notVerified + ".\n"), "refused: why, in one line: \(shown)") + expect(!shown.contains("\u{2713} Serving") && !shown.contains("Done.") && !shown.contains(ClusterOnboardingReady.offeredTestLine), + "refused: no Serving, no Done, no test claimed: \(shown)") + run.type("4") + expect(run.waitFor("Saved a diagnostics file"), "refused: Diagnostics saves the file") + expect(run.waitFor(notServingChoices, count: 2), "refused: the choices again after the file") + run.type("q") + let code = run.finish() + expect(code == 1, "refused: leaving is not success, got \(String(describing: code))") + let text = run.text + expect(!text.contains("\u{2713} Serving") && !text.contains("Done."), "refused: never Serving or Done: \(text)") + expect(text.hasSuffix("Not serving yet. Both Macs keep trying by themselves; run `darkbloom cluster` to check.\n"), + "refused: the last line says it does not serve: \(text)") + expect(recorder.all.contains("pairServing") && !recorder.all.contains("testRequest"), + "refused: the pair's own serving is awaited (no local API to test): \(recorder.all)") + transcript("offered-pair-refused", text, keys: run.keys) + + // Retry, once the coordinator paired them meanwhile: served, then Done. + let retried = Recorder() + let again = TerminalRun(operations(retried, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), readyResult: .success(offeredReady), + pairServingResults: [.failure(.init(notVerified)), .success(["in 0.84 s"])])) + expect(again.waitFor(prompt(2)), "retry: the list"); again.type("\r") + expect(again.waitFor(notServingChoices), "retry: the choices"); again.type("1") + expect(again.finish() == 0, "retry: served") + expect(again.text.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp (pipeline) through Darkbloom on both Macs\n") + && again.text.contains("Done."), "retry: Serving and Done only after the pair served: \(again.text)") + expect(retried.all.filter { $0 == "pairServing" }.count == 2, "retry: waited again: \(retried.all)") + } + + /// (b) The registration after the Test stage restarts both parts as cluster members; a restart that does not + /// come back is said with its reason and the choices, and the screen never says Done. + static func failedRestartAfterTheRegistrationIsNotDone() { + let recorder = Recorder() + let ended = "A part keeps ending the same way: rank 0 on the other Mac ended (exit 1); it starts again by itself." + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), registerResult: .success([registeredLine]), + readyResults: [.success(.init(servedBy: "this Mac", port: 8000, split: "pipeline")), .failure(.init([ended]))])) + expect(run.waitFor(prompt(2)), "restart: the list"); run.type("\r") + expect(run.waitFor("Starting both Macs' parts again as cluster members…"), "restart: the restart line") + _ = run.waitFor(notServingChoices, seconds: 5) + run.type("q") + let code = run.finish() + let text = run.text + expect(code == 1, "restart: a failed restart is not success, got \(String(describing: code))") + expect(!text.contains("Done."), "restart: never Done: \(text)") + expect(text.contains("Not serving yet: " + ended + "\n"), "restart: why: \(text)") + expect(text.contains(notServingChoices), "restart: the choices: \(text)") + expect(Array(recorder.all.prefix { $0 != "register" }.suffix(2)) == ["waitReady", "testRequest"] + && recorder.all.filter { $0 == "waitReady" }.count == 2, "restart: tested, registered, then the parts awaited: \(recorder.all)") + transcript("restart-after-registration-fails", text, keys: run.keys) + } + + /// (c) Serving through Darkbloom needs both Macs logged in: a Mac without a login is named before the Start step + /// starts anything, with `darkbloom login` or local-only serving offered. + static func missingLoginIsSaidBeforeTheStart() { + let both = [ClusterOnboardingMacName.this, ClusterOnboardingMacName.other(named: "Apple M3 Ultra, 256 GB")] + let recorder = Recorder() + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), missingLogins: both)) + expect(run.waitFor(prompt(2)), "login: the list"); run.type("\r") + expect(run.waitFor(" 1) Log in on this Mac\n 2) Serve locally only\n 3) Cancel\n"), "login: the choices: \(run.text)") + let shown = run.text + let said = shown.range(of: ClusterOnboardingNotServing.notLoggedIn(both) + ".") + expect(said != nil, "login: which Macs, in one line: \(shown)") + let start = shown.range(of: "4/4 Start") + expect(said != nil && (start == nil || said!.lowerBound < start!.lowerBound), "login: before the Start step: \(shown)") + expect(!recorder.all.contains { $0.hasPrefix("adopt") || $0 == "serve" }, "login: nothing started yet: \(recorder.all)") + run.type("3") + expect(run.finish() == 0, "login: cancel") + expect(run.text.hasSuffix("Nothing changed.\n"), "login: nothing changed: \(run.text)") + + // Log in here: the other Mac still has none, so its own `darkbloom login` is asked for; then local only. + let switched = Recorder() + let local = TerminalRun(operations(switched, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), readyResult: .success(localReady), missingLogins: both)) + expect(local.waitFor(prompt(2)), "login, local: the list"); local.type("\r") + expect(local.waitFor(" 1) Log in on this Mac\n"), "login, local: the choices"); local.type("1") + expect(local.waitFor("Run `darkbloom login` on the other Mac, then Check again.\n"), "login, local: the other Mac's turn: \(local.text)") + expect(local.waitFor(" 1) Check again\n 2) Serve locally only\n 3) Cancel\n"), "login, local: check again") + local.type("2") + expect(local.finish() == 0, "login, local: served locally") + expect(switched.all.contains("login") && switched.all.contains("setScope local 0.0.0.0"), + "login, local: logged in here, then local only saved: \(switched.all)") + let setScope = switched.all.firstIndex(of: "setScope local 0.0.0.0"), serve = switched.all.firstIndex(of: "serve") + expect(setScope != nil && serve != nil && setScope! < serve!, "login, local: saved before the start: \(switched.all)") + expect(local.text.contains("(local only)\n") && local.text.contains("Done."), "login, local: serving locally: \(local.text)") + expect(!switched.all.contains("register"), "login, local: no registration with a coordinator: \(switched.all)") + } + + /// (d) Offered for pairing, then the coordinator committed the pair, both Macs loaded it and it answered its first + /// request: Serving and Done, as before, now said only then. + static func offeredPairServesOnceLoaded() { + let recorder = Recorder() + let run = TerminalRun(operations(recorder, resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), readyResult: .success(offeredReady), pairServingResults: [.success(["in 0.84 s"])])) + expect(run.waitFor(prompt(2)), "served: the list"); run.type("\r") + let code = run.finish() + expect(code == 0, "served: exit 0, got \(String(describing: code))") + let text = run.text + expect(text.contains(" \u{2713} Test response in 0.84 s\n"), "served: the pair's first request: \(text)") + expect(text.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp (pipeline) through Darkbloom on both Macs\n"), "served: the line: \(text)") + expect(text.hasSuffix("Done. You can close both windows.\n" + ClusterOnboardingDriver.againLine + "\n"), "served: Done: \(text)") + expect(Array(recorder.all.suffix(3)) == ["serve", "waitReady", "pairServing"], "served: loaded before it is said: \(recorder.all)") + transcript("offered-pair-served", text, keys: run.keys) + } + + /// The pair's progress lines a coordinator-paired part writes, and the plain words of the reasons the Macs know. + static func pairReportsAndReasonsInPlainWords() { + typealias R = ClusterOnboardingPairReport + let log = "darkbloom 0.10.7 (registered cluster member; solo inference disabled)\n" + offeredLogLine + "\n" + + R.startingLine + "\n" + R.servingLine(warmupSeconds: 0.8412) + "\n" + expect(R.latest(inLog: log) == .serving(test: "in 0.84 s"), "report: serving with the first request's time") + expect(R.latest(inLog: log + R.stoppedLine("memory_gate_refused") + "\n") == .stopped("memory_gate_refused"), "report: stopped") + expect(R.latest(inLog: "no pair line\n") == nil, "report: none") + expect(R.state("serving") == .serving(test: nil) && R.state("starting") == .starting && R.state("other") == nil, "report: states") + expect(R.state(R.text(.serving(test: "in 0.84 s"))) == .serving(test: "in 0.84 s"), "report: the status's text reads back") + typealias N = ClusterOnboardingNotServing + let other = "the other Mac (Apple M3 Ultra, 256 GB)" + for reason in ["liveness:trust_floor", "member rank 0 provider p: liveness:private_text", "app_attest_required (app_attest:lease)"] { + expect(N.words(reason: reason, mac: other) == "Darkbloom hasn't verified the other Mac (Apple M3 Ultra, 256 GB) for private serving yet (App Attest)", + "words: \(reason)") + } + expect(N.words(reason: "memory_gate_refused", mac: other) == "The other Mac (Apple M3 Ultra, 256 GB) lacks free memory for its share", "words: memory") + expect(N.words(reason: "x\u{1B}[2J", mac: other) == "The coordinator didn't accept the pair (no reason given)", "words: never control characters") + expect(N.notLoggedIn(["this Mac"]) == "This Mac isn't logged in to Darkbloom, so the coordinator won't pair it", "words: one Mac") + expect(N.remedy(forReason: notVerified)?.contains("Retry") == true && N.remedy(forReason: "anything") == nil, "remedy") + } + + static let offeredLogLine = "Notice: " + ClusterOnboardingReady.registeredNotice + " with an installed cluster approval" } diff --git a/provider-swift/Tests/ClusterOnboardingChecks/run.sh b/provider-swift/Tests/ClusterOnboardingChecks/run.sh index f902c2e3ce..8dbede8ea1 100755 --- a/provider-swift/Tests/ClusterOnboardingChecks/run.sh +++ b/provider-swift/Tests/ClusterOnboardingChecks/run.sh @@ -10,6 +10,6 @@ task_build="$(mktemp -d "$task_provider/.cluster-onboarding.XXXXXXXX")" trap 'rm -rf "$task_build"' EXIT xcrun swiftc -swift-version 6 -warnings-as-errors -parse-as-library -target "$(uname -m)-apple-macos14.0" \ "$task_sources/ClusterOnboardingFlow.swift" "$task_sources/ClusterOnboardingTerminal.swift" \ - "$task_sources/ClusterOnboardingBrand.swift" \ + "$task_sources/ClusterOnboardingBrand.swift" "$task_sources/ClusterOnboardingPairServing.swift" \ "$task_provider/Tests/ClusterOnboardingChecks/OnboardingChecks.swift" -o "$task_build/onboarding-checks" "$task_build/onboarding-checks" From 9743729ec0a063b51c919ecb0c1f70a21003726a Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:07:04 -0800 Subject: [PATCH 0264/1441] fix(cluster): report the pair's real progress and why it does not serve Rank 0's coordinator-paired part writes its pair's progress to its log (Pair: starting / serving (first request in N s) / stopped ()), from serveCommittedStart and the pair slot's publication and retirement. Each cluster service publishes the latest line, the member's App Attest authorization from the coordinator's trust status, and whether the Mac has a Darkbloom login (ClusterServiceStatus.Child.pair, Child.appAttest, loggedIn; all optional, nil from an older build). OnboardingLive.pairServing waits up to 15 minutes for rank 0 to serve; a missing login ends it at once, App Attest, memory or a stopped start after 90 s. The status line of a registered pair says Serving only while it serves, else " is not serving yet: ." with what to do. missingLogins and login back the login check before the Start step. Docs: two-mac-cluster, troubleshooting, architecture/inference; changelog. Co-Authored-By: Claude Opus 5.5 --- ...ter-start-says-serving-only-when-loaded.md | 7 ++ docs/architecture/inference.md | 20 ++++- docs/provider/troubleshooting.md | 15 +++- docs/provider/two-mac-cluster.md | 42 ++++++++-- .../Installed/ClusterServiceWire.swift | 10 +++ .../Onboarding/ClusterOnboardingLive.swift | 82 ++++++++++++++++++- .../Onboarding/ClusterService.swift | 23 ++++++ .../ProviderLoop+ClusterPairServing.swift | 22 +++-- .../ProviderLoop+ClusterPairSlot.swift | 4 + 9 files changed, 203 insertions(+), 22 deletions(-) create mode 100644 changelog.d/cluster-start-says-serving-only-when-loaded.md diff --git a/changelog.d/cluster-start-says-serving-only-when-loaded.md b/changelog.d/cluster-start-says-serving-only-when-loaded.md new file mode 100644 index 0000000000..4264097851 --- /dev/null +++ b/changelog.d/cluster-start-says-serving-only-when-loaded.md @@ -0,0 +1,7 @@ +### `darkbloom cluster` says Serving and Done only once the model is loaded + +- A pair registered with the coordinator as a cluster member is no longer called serving: `darkbloom cluster` now waits (at most 15 minutes, its progress on the live line) until the coordinator paired both Macs, both loaded the model and the pair answered its first request, then says `✓ Serving () through Darkbloom on both Macs` and Done. Before, both Macs said Serving and Done while nothing was loaded, as when the coordinator refused a pair without App Attest trust. +- A start that does not come to serve, including the parts' restart after the registration, now says why in one line (a Mac without a Darkbloom login, a Mac Darkbloom has not verified for private serving yet (App Attest), a Mac without free memory for its share, a part that keeps ending) and stays open with **Retry**, **Change model**, **Serve locally only** and **Diagnostics**. Leaving with q says the pair does not serve yet and exits 1; it never says Done. +- Before the Start step starts anything for serving through Darkbloom, a Mac without a Darkbloom login is named, with **Log in on this Mac** (or **Check again** after `darkbloom login` on the other Mac) and **Serve locally only**. +- The cluster's status line for such a pair says `Serving () through Darkbloom on both Macs.` only while it serves, else ` is not serving yet: .` with what to do. +- The leader's last lines now give the test response first, then what serves. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 1fe23bc81d..578d638884 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-11-03 +> Last updated: 2026-11-04 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -255,9 +255,21 @@ the test response succeeds, the control leader registers the pair with the coordinator when the coordinator serves a cluster approval for this pair (`ClusterOnboardingDriver.register`, control operation `register`). Both parts then run as coordinator-paired members -(`ClusterService.Settings.memberArguments`), which have no local API, and the -ready screen shows the registered line (`ClusterOnboardingReady.offered`, -`OnboardingLive.offeredReadiness`). How the approval is fetched, matched, +(`ClusterService.Settings.memberArguments`), which have no local API. Both +members registered (`ClusterOnboardingReady.offered`, +`OnboardingLive.offeredReadiness`) is not serving: the driver then waits +(`ClusterOnboardingDriver.awaitPairServing`, operation `pairServing`) until the +plan's rank 0 part reports its pair slot published, which needs both ranks +loaded and the warm-up request answered. That part writes its pair's progress +to its log (`ClusterOnboardingPairReport`, written by +`ProviderLoop.reportPair`); its cluster service publishes the latest line with +the member's App Attest authorization and this Mac's Darkbloom login +(`ClusterServiceStatus.Child.pair`, `Child.appAttest`, `loggedIn`). A start that +does not serve, the restart after the registration included, ends on its reason +(`ClusterOnboardingNotServing`, `OnboardingLive.pairLook`) and the driver's +choices (`ClusterOnboardingDriver.finishStart`); it never says Done. A Mac +without a login is named before the Start step (`ClusterOnboardingDriver.checkLogins`). +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 diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index 8f1ffde203..a154a27519 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -1,6 +1,6 @@ # Provider troubleshooting -> Last updated: 2026-11-02 +> Last updated: 2026-11-04 Symptom → check → fix for the `darkbloom` provider: installer exits, `doctor` check names, service lifecycle, coordinator connection, updates, models and the @@ -242,6 +242,19 @@ SSD caching remains enabled by default with no resident retention; use `DARKBLOOM_PREFIX_CACHE=0` to disable local reuse independently ([prefix-cache defaults](../architecture/prefix-cache.md#invariants)). +## A two-Mac cluster says "Not serving yet" + +`darkbloom cluster` says Serving only once both Macs loaded the model and a +request answered. Otherwise its line names why +([two-Mac cluster](two-mac-cluster.md#the-steps-once)): + +| Line | What to do | +|---|---| +| `… isn't logged in to Darkbloom, so the coordinator won't pair it` | `darkbloom login` on the Mac named, then **Retry**; or **Serve locally only**. | +| `Darkbloom hasn't verified for private serving yet (App Attest)` | Keep both Macs logged in and Darkbloom running; the coordinator pairs only members with a current App Attest authorization. **Retry** after a few minutes, or **Serve locally only**. | +| ` lacks free memory for its share` | Quit apps on that Mac, then **Retry**; or **Change model**. | +| `A part keeps ending the same way: …` | **Diagnostics** saves a redacted file in the home folder to send with a report. | + ## Missing base reward `doctor` billing is local usage reporting, not a coordinator diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index b890bccc16..1ceb09d4c4 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-11-03 +> Last updated: 2026-11-04 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 @@ -88,11 +88,27 @@ Mac chooses the model. You can close this window."; started with `darkbloom cluster local`, "Done here: run `darkbloom cluster local` on the other Mac."). A signed Darkbloom.app's login agent keeps serving; without one, as for a development build, the line ends "Keep this window open." and the Mac -serves only while the window stays open. The leader ends with what serves and -how ("✓ Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning -through Darkbloom)", or "(local only)"), the test ("✓ Test response in 0.61 s"), -whether the windows can close ("Done. You can close both windows.") and, last, -"Run `darkbloom cluster` again to manage it." +serves only while the window stays open. The leader ends with the test ("✓ Test +response in 0.61 s"), then what serves and how ("✓ Serving Qwen3.8-27B-4bit-mtp +(pipeline) at http://localhost:8000 (earning through Darkbloom)", or "(local +only)"), whether the windows can close ("Done. You can close both windows.") +and, last, "Run `darkbloom cluster` again to manage it." It says Serving and +Done only once both Macs loaded the model and a request answered. + +Serving through Darkbloom needs both Macs logged in (`darkbloom login`): the +coordinator pairs only logged-in Macs. Before the Start step starts anything, +the leader names each Mac without a login ("This Mac and the other Mac (…) +aren't logged in to Darkbloom, so the coordinator won't pair them.") and offers +**Log in on this Mac** (or **Check again** after `darkbloom login` on the other +Mac), **Serve locally only** or **Cancel**. + +A start that does not come to serve says why in one line ("Not serving yet: +Darkbloom hasn't verified the other Mac (…) for private serving yet (App +Attest).", "… lacks free memory for its share", "A part keeps ending the same +way: …"), what to do, and stays open with **Retry**, **Change model**, **Serve +locally only** and **Diagnostics** (a redacted file in the home folder). q +leaves with "Not serving yet. Both Macs keep trying by themselves; run +`darkbloom cluster` to check." and exit status 1, never Done. On a color terminal with a UTF-8 locale and at least 40 columns, setup opens with the Darkbloom mark, which blooms in pixel by pixel. Each step's heading @@ -241,10 +257,17 @@ once; one planned with the one-chunk lookahead takes one at a time ``` Registered with the coordinator as a cluster member: approval , until . + Starting both Macs' parts again as cluster members… ``` - There is no local API in this mode. `darkbloom cluster` status says it after - the model: `Serving : Registered with the coordinator as a cluster member: approval , until .` + Registered is not serving: the coordinator still has to pair both Macs, and + both then load their share. The leader waits for that (at most 15 minutes, + its progress on the live line) and says `✓ Serving () through + Darkbloom on both Macs` only once the plan's rank 0 reports that both ranks + loaded the model and the pair answered its first request (the warm-up). A + reason the Macs know ends the wait sooner (a missing login at once, others + after 90 s), with the choices [above](#the-steps-once). There is no local API + in this mode. An approval ends at its `not_after`, which the operator sets; one derived from a release ends 90 days after that release registered @@ -275,7 +298,8 @@ What `darkbloom cluster` status says in each mode: | Mode | Status line | |---|---| -| Registered | `Serving : Registered with the coordinator as a cluster member: approval , until .` | +| Registered, paired and loaded | `Serving () through Darkbloom on both Macs.` | +| Registered, not serving yet | ` is not serving yet: .`, then what to do (a missing login, App Attest, memory) | | Coordinator gave no answer for the grace | The serving line, then `The coordinator has not answered for 10 minutes: the pair serves on the leader's local API until it answers again, then it is offered again with approval .` | | Approval no longer listed | The serving line, then `The coordinator no longer lists cluster approval : the pair serves on the leader's local API until it lists a matching one again.` | | Parts kept ending | The serving line, then `The coordinator-paired parts ended 3 times in a row right after starting with cluster approval : the pair serves on the leader's local API for 60 minutes, then it is offered again with it, or sooner with a later one the coordinator lists.` | diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterServiceWire.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterServiceWire.swift index 152bd16dbb..09047c83ce 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterServiceWire.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterServiceWire.swift @@ -28,6 +28,13 @@ public struct ClusterServiceStatus: Codable, Sendable, Equatable { /// the service's selected setup, it changes only after restart or an /// acknowledged same-listener handoff. Used to fence automatic replans. public var configurationSHA256: String? = nil + /// While a coordinator-paired part runs: its pair's latest progress line without its prefix + /// (`ClusterOnboardingPairReport.text`: "starting", "serving …", "stopped (…)"); nil before any, for any other + /// part, and from an older build. + public var pair: String? = nil + /// While a coordinator-paired part runs: whether the coordinator's latest trust status for it carries a current + /// App Attest serving authorization, which pair membership requires; nil when it has sent none yet. + public var appAttest: Bool? = nil } public struct Session: Codable, Sendable, Equatable { public var observed: Bool @@ -75,6 +82,9 @@ public struct ClusterServiceStatus: Codable, Sendable, Equatable { /// This Mac's part in the pair's coordinated update, as its cluster service supervisor writes it. Nil from an /// older build, which cannot coordinate one. public var pairUpdate: ClusterPairUpdateProgress? = nil + /// This Mac has a Darkbloom login (`darkbloom login`): the coordinator pairs only logged-in Macs. Nil from an + /// older build, which the leader never reads as "not logged in". + public var loggedIn: Bool? = nil public struct Control: Codable, Sendable, Equatable { public var leaderID: String public var leaderName: String diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift index 85f48bda79..7214d0cde8 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift @@ -57,7 +57,10 @@ extension ClusterOnboardingOperations { runAsAdministrator: { ClusterLocalNetworkAccess.runLinkScriptWithSudo($0, paths: paths) }, serviceOutlivesWindow: { live.serviceOutlivesWindow() }, remote: { ClusterLocalNetworkAccess.overSSH() }, - thisMacName: { ClusterLocalNetworkAccess.computerName() }) + thisMacName: { ClusterLocalNetworkAccess.computerName() }, + pairServing: { progress in live.pairServing(progress) }, + missingLogins: { live.missingLogins() }, + login: { live.login() }) } } @@ -1499,6 +1502,70 @@ final class OnboardingLive: @unchecked Sendable { return (nil, line) } + /// How long the setup waits for the coordinator to pair both Macs and both to load the model (MiMo's load takes + /// minutes); a reason the Macs know ends it sooner. + static let pairServingSeconds: Double = 900 + /// A reason other than a missing login holds this long before the wait ends on it: a new key's App Attest + /// authorization lands about a minute after its registration, and the coordinator retries a start that failed. + static let pairReasonSettleSeconds: Double = 90 + + /// A pair offered for pairing: waits until the coordinator paired both Macs, both loaded the model and the pair + /// answered its first request (rank 0's part says so), or a reason the Macs know held (`pairLook`). + func pairServing(_ progress: @escaping @Sendable (String) -> Void) -> Result<[String], ClusterOnboardingFailure> { + let started = Date() + var said: String?, last: String? + while Date().timeIntervalSince(started) < Self.pairServingSeconds { + let look = pairLook() + if look.serving { return .success([look.test ?? ""]) } + if let reason = look.reason { + last = reason + let settle = reason.contains("logged in to Darkbloom") ? 0 : Self.pairReasonSettleSeconds + if Date().timeIntervalSince(started) >= settle { return .failure(.init(reason)) } + } + if look.progress != said { progress(look.progress); said = look.progress } + sleep(2) + } + return .failure(.init(last ?? "The coordinator has not paired both Macs within 15 minutes")) + } + + /// One look at a pair offered for pairing, from both Macs' reports: whether it serves (rank 0's part runs the pair's + /// slot and says so, with its first request's time), what it is doing, and why it does not serve when the Macs know + /// (a Mac without a Darkbloom login, which the coordinator never pairs; a member the coordinator's trust status gives + /// no App Attest authorization, which pair membership requires; a committed start that stopped). + func pairLook() -> (serving: Bool, test: String?, progress: String, reason: String?) { + let own = ClusterService.published() + let peer = try? JSONDecoder().decode(ClusterServiceStatus.self, from: command(.init(op: .status), seconds: 10)) + let localRankZero = context.savedConfiguration().configuration?.localRank == 0 + let rankZero = (localRankZero ? own : peer)?.child.pair.flatMap(ClusterOnboardingPairReport.state) + if case .serving(let test)? = rankZero { return (true, test, "serving", nil) } + let progress = rankZero == .starting ? "the coordinator paired both Macs: loading the model on both" + : "waiting for the coordinator to pair both Macs" + let missing = (AuthTokenStore.load() == nil ? [here] : []) + (peer?.loggedIn == false ? [there] : []) + if !missing.isEmpty { return (false, nil, progress, ClusterOnboardingNotServing.notLoggedIn(missing)) } + if own?.child.appAttest == false { return (false, nil, progress, ClusterOnboardingNotServing.notVerified(here)) } + if peer?.child.appAttest == false { return (false, nil, progress, ClusterOnboardingNotServing.notVerified(there)) } + if case .stopped(let why)? = rankZero { + return (false, nil, progress, ClusterOnboardingNotServing.words(reason: why, mac: "one of the Macs")) + } + return (false, nil, progress, nil) + } + + /// The Macs without a Darkbloom login, as this screen names them (the other Mac's own status says; an older build + /// that does not is not counted). + func missingLogins() -> [String] { + let peer = try? JSONDecoder().decode(ClusterServiceStatus.self, from: command(.init(op: .status), seconds: 10)) + return (AuthTokenStore.load() == nil ? [here] : []) + (peer?.loggedIn == false ? [there] : []) + } + + /// `darkbloom login` in this terminal (the console is suspended): true when this Mac is logged in afterwards. + func login() -> Bool { + let process = Process() + process.executableURL = settings.service.wizard.darkbloomExecutable + process.arguments = ["login"] + do { try process.run(); process.waitUntilExit() } catch { return false } + return AuthTokenStore.load() != nil + } + func testRequest() -> Result<[String], ClusterOnboardingFailure> { routed(.init(op: .test), seconds: 240, acting: false, local: { localTestRequest() }) { $0.lines } } @@ -1567,7 +1634,18 @@ final class OnboardingLive: @unchecked Sendable { if let scope = leadership?.scope, scope.isLocalOnly { lines.append("When it starts: " + scope.line + ".") } } else if let offered = offeredLine() { let ready = offeredReadiness(offered, own: ClusterService.published()?.child) - lines.append((ready.ready?.summary(model: model) ?? "\(model): \(ready.line)") + ".") + if let registered = ready.ready { + // Registered is not serving: the pair serves once the coordinator paired both Macs and both loaded it. + let look = pairLook() + if look.serving { + lines.append(registered.pairServingLine(model: model) + ".") + } else { + lines.append("\(model) is not serving yet: " + (look.reason ?? look.progress) + ".") + if let remedy = look.reason.flatMap(ClusterOnboardingNotServing.remedy(forReason:)) { lines.append(remedy) } + } + } else { + lines.append("\(model): \(ready.line).") + } } else if let session = now.session, session.observed { if session.ready { let ready = ready(now, port: session.port ?? 0) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index 3e9f62004c..f9397e4714 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -999,6 +999,11 @@ public final class ClusterService: @unchecked Sendable { control: controlStatusLocked(model: record?.leadership?.modelName), servicePID: getpid()) value.updating = updatingLine value.localOnly = record?.leadership.map { $0.scope.isLocalOnly } + value.loggedIn = AuthTokenStore.load() != nil + if child?.isRunning == true, childIsMember { + value.child.pair = Self.pairReport(in: serviceFiles.rankLog, from: childLogOffset).map(ClusterOnboardingPairReport.text) + value.child.appAttest = Self.memberAppAttest(pid: child?.processIdentifier) + } value.memberQuickEnds = memberQuickEnds value.approvalID = configuration?.nativeMember?.clusterApproval?.id ?? "" value.pairUpdate = ClusterPairUpdate.readProgress(from: ClusterServiceAgent.updateProgressPath(serviceDirectory: store.paths.directory)) @@ -1230,6 +1235,24 @@ public final class ClusterService: @unchecked Sendable { return ClusterConsoleText.plain(ClusterConsoleText.bounded(String(line.dropFirst(6)).trimmingCharacters(in: .whitespaces), maximum: 240)) } + /// The latest pair line (`ClusterOnboardingPairReport`) the running coordinator-paired part wrote in `log` since + /// `offset`, where it began writing: a line an earlier part wrote is never this part's. + static func pairReport(in log: URL, from offset: UInt64) -> ClusterOnboardingPairReport.State? { + guard let handle = FileHandle(forReadingAtPath: log.path) else { return nil } + defer { try? handle.close() } + let size = (try? handle.seekToEnd()) ?? 0 + let window: UInt64 = size > 16_384 ? size - 16_384 : 0 + try? handle.seek(toOffset: offset <= size ? max(offset, window) : window) + return ClusterOnboardingPairReport.latest(inLog: String(decoding: handle.readDataToEndOfFile(), as: UTF8.self)) + } + + /// Whether the coordinator's latest trust status for the running coordinator-paired part (`pid`, the process that + /// wrote the daemon state) carries a current App Attest serving authorization; nil when it has sent none yet. + static func memberAppAttest(pid: Int32?, state: DaemonState? = DaemonStateFile.read(), now: Double = Date().timeIntervalSince1970) -> Bool? { + guard let pid, let state, state.pid == pid, let trust = state.trust else { return nil } + return trust.authorization?.hasCurrentAppAttestAuthorization(now: now) ?? false + } + /// `ClusterLocalServing.notice` when this Mac's running part (rank 0) said it serves on its local API only. public static func servingNotice() -> String? { (try? paths().rankLog).flatMap { servingNotice(in: $0) } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift index f46e6bc827..44b3d5e1c5 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift @@ -143,11 +143,13 @@ extension ProviderLoop: NativePairMemberServingHost { } guard clusterPairServingEpoch == nil else { throw ClusterPairSlotError.notServing("a committed start is already served") } clusterPairServingEpoch = epoch + Self.reportPair(ClusterOnboardingPairReport.startingLine) let owner: any DistributedResidentExecutionOwner do { owner = try await Task.detached { try context.makeOwner(start) }.value } catch { // S24: a pair that could not form is a launch failure with a reason. - recordClusterPairIncident(.activationLaunchFailed, error: error, context: context, start: start) + let guidance = recordClusterPairIncident(.activationLaunchFailed, error: error, context: context, start: start) + Self.reportPair(ClusterOnboardingPairReport.stoppedLine(guidance ?? "the pair did not form")) endClusterPairServing(epoch); throw error } // A stop that arrived while the pair formed wins: nothing publishes, @@ -198,16 +200,24 @@ extension ProviderLoop: NativePairMemberServingHost { } /// One incident about a committed start this leader serves (S24), with - /// the session endpoint's owner diagnostics when it has them. + /// the session endpoint's owner diagnostics when it has them. Returns the + /// incident's guidance code (`memory_gate_refused`, …) when one was recorded. + @discardableResult func recordClusterPairIncident(_ stateCode: ClusterIncidentStateCode, error: Error, - context: ClusterPairServingContext, start: NativePairMemberServingStart) { - guard let base = context.observabilityFacts else { return } + context: ClusterPairServingContext, start: NativePairMemberServingStart) -> String? { + guard let base = context.observabilityFacts else { return nil } let diagnostics = (start.endpoint as? ClusterRemoteWorkerEndpoint).map { [DistributedSessionFacts.tail($0.diagnosticTail)] } ?? [] let facts = DistributedSessionFacts(clusterID: base.clusterID, memberID: base.memberID, modelID: base.modelID, mode: base.mode, cut: base.cut, membershipEpoch: start.membershipEpoch.uuidString.lowercased(), diagnostics: diagnostics, terminations: [], peerHosts: base.peerHosts, peerUsers: base.peerUsers, ranks: base.ranks) - ClusterObservability.current().recordFailure(stateCode, source: "member", - error: String(describing: error), facts: facts) + return ClusterObservability.current().recordFailure(stateCode, source: "member", + error: String(describing: error), facts: facts)?.guidanceCode + } + + /// One line of the pair's progress in this coordinator-paired part's log (its stderr, the cluster service's + /// `rank.log`), which the onboarding and the status read: registered is not serving. + static func reportPair(_ line: String) { + FileHandle.standardError.write(Data((line + "\n").utf8)) } /// Clears the served epoch, once, for this epoch only. diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift index 75ffa88bee..e6665413ff 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift @@ -235,6 +235,8 @@ extension ProviderLoop { startClusterPairCapacityRefresh() await refreshClusterPairCapacity() logger.info("Cluster pair slot published (\(handle.id.uuidString.prefix(8)))") + // Both ranks loaded and, with the canary on, the pair answered its first request: it serves now. + Self.reportPair(ClusterOnboardingPairReport.servingLine(warmupSeconds: clusterPairWarmup.flatMap { $0.succeeded ? $0.seconds : nil })) if let client = coordinatorClient { await client.sendEventHeartbeat() } return id } @@ -272,6 +274,8 @@ extension ProviderLoop { } modelsUnloading.insert(modelID) logger.info("Cluster pair slot retiring (\(handle.id.uuidString.prefix(8))): \(reason)") + // Fixed words only: a warm-up failure's detail is the engine's own text. + Self.reportPair(ClusterOnboardingPairReport.stoppedLine(reason.hasPrefix("warmup canary failed") ? "its first request failed" : reason)) if reason == Self.readinessLostReason { // S24: serving ended without being asked to. A planned stop // retires the slot first with its own reason and records nothing. From eef2995aaf743667833ce961025964fa478a7ea8 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:09:50 -0800 Subject: [PATCH 0265/1441] refactor(cluster): tighten the admission-deadline comments, docs and changelog Behavior-preserving cleanup of the admission-deadline fix (the required refactor pass). No source logic, wire format or test assertion changes. - ClusterWorkerRequest.admit: drop the claim that every command is delivered within the pair's admission wait (start and token decisions use the request's generation deadline, cancels the cleanup wait). Say why a send a still-serving endpoint closed is a deadline, not a lost rank. - ClusterWorkerRequest.cleanup: state the never-asked rule once, at its branch, instead of in three overlapping comments. - LinkWorkerPairCheck: one local helper relays each leader command in the expired-reservation check, instead of three hand-built wires. - ClusterWorkerPairAdmissionDeadlineTests: drop the task-list labels (a) and (c) from the doc comments. - docs/architecture/inference.md: fold "a rank not yet asked is not asked" and "only a rank that does not give the reservation back in time ends the pair" into the sentences they belong to, with the same facts; restamped. - changelog: the heading and one plain sentence for pair owners. Co-Authored-By: Claude Opus 5.5 --- .../cluster-admission-deadline-per-request.md | 15 +----------- docs/architecture/inference.md | 24 +++++++++---------- .../ClusterWorkerRequest.swift | 15 ++++++------ ...sterWorkerPairAdmissionDeadlineTests.swift | 6 ++--- .../LinkWorkerPairCheck.swift | 18 +++++++------- 5 files changed, 32 insertions(+), 46 deletions(-) diff --git a/changelog.d/cluster-admission-deadline-per-request.md b/changelog.d/cluster-admission-deadline-per-request.md index d36f7cd42a..2d99b302a5 100644 --- a/changelog.d/cluster-admission-deadline-per-request.md +++ b/changelog.d/cluster-admission-deadline-per-request.md @@ -1,16 +1,3 @@ ### A pair no longer drops all its requests when one request runs out of time before it starts -- A two-Mac pair no longer drops all its requests when one request runs out of - time before it starts. When a request arrived with almost none of its - first-response time left and a busy Mac answered its reservation at its next - step, the leader ended the whole pair: every request in flight failed - (`distributed peer readiness lost`), the other Mac logged `session fenced: - leader fenced: the request was cancelled before it started` (or `command - refused`), and the pair re-formed about 20 seconds later. A GLM-5.3-Flash - pair under load dropped six times in 19 minutes. -- Now only that request fails, with a deadline error. The Mac that answered late - gives its reservation back, the Mac that was never asked is left alone, and - the pair keeps serving its other requests. A reservation that reaches the - other Mac too late is refused for that request alone. -- A pair still ends when a Mac or its link is really lost, or when a Mac does - not answer or give a reservation back in time. +- Only that request now fails, with a deadline error, and the pair keeps serving. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 2c280409bb..682e6377fd 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-11-03 +> Last updated: 2026-11-04 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -80,18 +80,18 @@ reservation is unanswered past its delivery deadline pair's admission wait, at least `ClusterWorkerRequest.laneAdmissionWaitNanoseconds` (30 s) with lanes. A busy rank answers at its next step boundary. When the request's own deadline passes first, the pair throws -`ClusterWorkerOwnerError.deadline` for that request only. A rank not yet asked -is not asked; an answer still on its way is read and an admission given back +`ClusterWorkerOwnerError.deadline` for that request only: no further rank is +asked, an answer still on its way is read, every admission is given back (`retired(cancelled)`) within `ClusterWorkerRequest.laneRetirementWaitNanoseconds` -(30 s); the other lanes run on. Only a rank that does not give the reservation -back in time ends the pair. A rank never asked is never fenced for a request, -whatever ended it: a failing pair's owner shuts it down. A relayed reservation -that reaches the follower past its delivery deadline is that request's refusal -(`commandRefused`, `deadline`), not a fence of the follower's session. A closed -link, a lost rank, or a rank that does not answer within the pair's admission -wait still ends the pair. Before, the deadline ended the whole pair: every lane -in flight failed and the follower logged `leader fenced: the request was -cancelled before it started`. Sources: +(30 s), and the other lanes run on. A rank never asked is never fenced for a +request, whatever ended it: a failing pair's owner shuts it down. A relayed +reservation that reaches the follower past its delivery deadline is that +request's refusal (`commandRefused`, `deadline`), not a fence of the follower's +session. A closed link, a lost rank, a rank that does not answer within the +pair's admission wait, or one that does not give a reservation back in time +still ends the pair. Before, the deadline ended the whole pair: every lane in +flight failed and the follower logged `leader fenced: the request was cancelled +before it started`. Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerPair.swift` (`reserve`), `libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerRequest.swift` diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerRequest.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerRequest.swift index 70c84893d1..9039cf3c96 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerRequest.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProcess/ClusterWorkerRequest.swift @@ -55,9 +55,9 @@ public final class ClusterWorkerRequest: @unchecked Sendable { } // A rank's owner fences a worker that has not answered a reservation // by its delivery deadline (`ClusterWorkerOwnerService`), so the - // reservation is delivered within the pair's admission wait, as any - // command is. The request's admission deadline, often nearly spent on - // arrival, bounds only how long this request waits for the answers. + // reservation is delivered within the pair's admission wait. The + // request's admission deadline, often nearly spent on arrival, bounds + // only how long this request waits for the answers. let delivery = min(baseReservation.deadlineUptimeNanoseconds, now + owner.admissionWaitNanoseconds) let deadline = min(delivery, admissionDeadline ?? UInt64.max) guard now < deadline else { throw ClusterWorkerOwnerError.deadline } @@ -85,8 +85,8 @@ public final class ClusterWorkerRequest: @unchecked Sendable { try worker.sendWorkerCommand(.reserve(local), requestID: requestID, deadline: delivery) } catch ClusterWorkerOwnerError.closed where DispatchTime.now().uptimeNanoseconds >= deadline && worker.readiness != nil { - // A serving endpoint closes a send only once its deadline - // passed: nothing reached the rank. The request's deadline. + // A still-serving endpoint closes a send only once its + // deadline passed: nothing reached the rank, no rank is lost. throw ClusterWorkerOwnerError.deadline } catch ClusterWorkerOwnerError.refused(let reason) where reason != .unavailable { // The rank's endpoint could not take this reservation now @@ -429,11 +429,10 @@ public final class ClusterWorkerRequest: @unchecked Sendable { // Never-submitted/refused ranks have no request to cancel. Pending // submission can race an unread refusal, so only confirmed admission // permits request cancel. All other ranks need actual native cleanup. - // A rank never asked holds nothing of the request, whatever ended - // it: nothing to give back and nothing to fence (a failing pair's - // owner shuts it down). if submitted[index] == .none || (alone && submitted[index] == .refused) { // Never asked, or it refused: this rank holds nothing for the request. + // One never asked is not fenced whatever ended the request: a + // failing pair's owner shuts it down. acknowledged[index] = true continue } diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRemoteTests/ClusterWorkerPairAdmissionDeadlineTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRemoteTests/ClusterWorkerPairAdmissionDeadlineTests.swift index 402fb7f69c..6fa0a90475 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRemoteTests/ClusterWorkerPairAdmissionDeadlineTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRemoteTests/ClusterWorkerPairAdmissionDeadlineTests.swift @@ -202,7 +202,7 @@ final class ClusterWorkerPairAdmissionDeadlineTests: XCTestCase { XCTAssertEqual(done.wait(timeout: .now() + 20), .success, "the pair did not shut down") } - /// (a) On a lane pair, rank 0 answers a reservation 600 ms after a request + /// On a lane pair, rank 0 answers a reservation 600 ms after a request /// arrived with 150 ms of its budget left. That request ends with a deadline /// outcome; nothing is fenced, the pair stays valid, the lane decoding /// meanwhile keeps running and finishes, and the pair serves the next request. @@ -246,7 +246,7 @@ final class ClusterWorkerPairAdmissionDeadlineTests: XCTestCase { XCTAssertTrue(ranks.allSatisfy { $0.fences.isEmpty && $0.nativeCleanupObserved }, "a rank did not end by its shutdown") } - /// (c) A request that ends while rank 0's answer is still on its way, before + /// A request that ends while rank 0's answer is still on its way, before /// rank 1 was ever asked, never fences rank 1, whatever ended it. Here the /// pair fails for another reason (a lost peer, another lane's failure): the /// pair's owner shuts rank 1 down, it is not fenced for a request it never @@ -272,7 +272,7 @@ final class ClusterWorkerPairAdmissionDeadlineTests: XCTestCase { XCTAssertTrue(ranks[1].nativeCleanupObserved && ranks[1].fences.isEmpty, "rank 1 did not end by its shutdown") } - /// (c) The same request ended by its caller (the pair's own shutdown) while + /// The same request ended by its caller (the pair's own shutdown) while /// rank 0's answer is on its way fences nothing at all: rank 0 gives back /// what it admitted, and rank 1 was never asked. func testARequestItsCallerEndsBeforeRankOneWasAskedFencesNothing() throws { diff --git a/libs/darkbloom-cluster/Tests/LinkWorkerChecks/LinkWorkerPairCheck.swift b/libs/darkbloom-cluster/Tests/LinkWorkerChecks/LinkWorkerPairCheck.swift index 62753a2aea..a74264667f 100644 --- a/libs/darkbloom-cluster/Tests/LinkWorkerChecks/LinkWorkerPairCheck.swift +++ b/libs/darkbloom-cluster/Tests/LinkWorkerChecks/LinkWorkerPairCheck.swift @@ -267,25 +267,25 @@ func shutdown(_ pair: ClusterWorkerPair, seconds: Int = 8, _ context: @autoclosu .reserve(.init(profileID: fixtureProfile.id, promptTokenIDs: [1, 2], stopTokenIDs: [], outputCount: 2, chunkSize: 1, deadlineUptimeNanoseconds: now() + 8_000_000_000, capacityLimitBytes: 900, sampling: nil, prefixCache: nil)) } + // The leader's next command on this session, with `deliveryNanoseconds` to reach the worker. + func relay(_ command: ClusterWorkerCommand, for requestID: UUID, sequence: UInt64, deliveryNanoseconds: UInt64) throws { + let at = now() + server.deliver(try ClusterLinkWorkerWire.command(command, requestID: requestID, epoch: epoch, session: session, + sequence: sequence, now: at, deliveryDeadline: at + deliveryNanoseconds).encoded()) + } let expired = UUID(), next = UUID() - var at = now() // One nanosecond of delivery time left: past it before this Mac's owner can queue it. - server.deliver(try ClusterLinkWorkerWire.command(reservation(), requestID: expired, epoch: epoch, session: session, - sequence: 1, now: at, deliveryDeadline: at + 1).encoded()) + try relay(reservation(), for: expired, sequence: 1, deliveryNanoseconds: 1) try require(wait(seconds: 5) { transport.refusals.contains { $0.requestID == expired } || reports.fenced }, "Nothing came back for the expired reservation: \(reports.lines)") try require(!reports.fenced, "The follower fenced its session for one request's delivery deadline: \(reports.lines)") try require(transport.refusals.first { $0.requestID == expired }?.detail == ClusterWorkerRefusal.deadline.rawValue, "The refusal does not name the deadline: \(transport.refusals)") // The session serves on: the next reservation reaches the worker, which admits it and gives it back. - at = now() - server.deliver(try ClusterLinkWorkerWire.command(reservation(), requestID: next, epoch: epoch, session: session, - sequence: 2, now: at, deliveryDeadline: at + 5_000_000_000).encoded()) + try relay(reservation(), for: next, sequence: 2, deliveryNanoseconds: 5_000_000_000) try require(wait(seconds: 5) { transport.events.contains { $0.requestID == next && $0.event.isAdmission } }, "The next reservation was not admitted: \(reports.lines)") - at = now() - server.deliver(try ClusterLinkWorkerWire.command(.cancel(.callerCancelled), requestID: next, epoch: epoch, session: session, - sequence: 3, now: at, deliveryDeadline: at + 5_000_000_000).encoded()) + try relay(.cancel(.callerCancelled), for: next, sequence: 3, deliveryNanoseconds: 5_000_000_000) try require(wait(seconds: 5) { transport.events.contains { $0.requestID == next && $0.event == .retired(.cancelled) } }, "The next reservation was not given back: \(reports.lines)") try require(!reports.fenced && server.busy, "The follower's session did not serve on: \(reports.lines)") From ca0347271e2bb71e1b46d43615e26e46b33d41de Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:14:56 -0800 Subject: [PATCH 0266/1441] Test that an attestation already with Apple survives a disconnect or a stop Apple attests a key once. When the exchange running attestKey is cancelled by a connection end or a planned stop, the provider drops Apple's answer, retires the key and refuses a replacement for an hour (production, 2026-11-03: a pair leader answered busy for the whole hour, so the coordinator refused its MiMo, Qwen 3.8 and Gemma pairs). - CancelledAttestationTests: a connection end 0.2 s into a one-second Apple call keeps the proof for the next connection; a prepare that arrives meanwhile waits for it and Apple is asked once; a call cut off by a process exit is still retired; an Apple timeout is still retired. - ProviderLifecycleTests: the lifecycle drain (SIGTERM, darkbloom stop, a cluster part stop) waits for Apple's answer before it completes. These fail on origin/dev. Co-Authored-By: Claude Opus 5.5 --- .../CancelledAttestationTests.swift | 223 ++++++++++++++++++ .../Service/ProviderLifecycleTests.swift | 93 +++++++- 2 files changed, 315 insertions(+), 1 deletion(-) create mode 100644 provider-swift/Tests/ProviderAppAttestTests/CancelledAttestationTests.swift diff --git a/provider-swift/Tests/ProviderAppAttestTests/CancelledAttestationTests.swift b/provider-swift/Tests/ProviderAppAttestTests/CancelledAttestationTests.swift new file mode 100644 index 0000000000..38a48d9fea --- /dev/null +++ b/provider-swift/Tests/ProviderAppAttestTests/CancelledAttestationTests.swift @@ -0,0 +1,223 @@ +import Foundation +import XCTest +@testable import ProviderAppAttest + +private final class AttestationKeys: ShadowKeyStorage, @unchecked Sendable { + private let lock = NSLock() + private var values: [String: ShadowKeyRecord] = [:] + func load(scope: String) -> ShadowKeyRecord? { lock.withLock { values[scope] } } + func save(_ record: ShadowKeyRecord, scope: String) { lock.withLock { values[scope] = record } } +} + +/// Apple's side of the calls. Keys and assertions answer at once; each +/// attestation answers `delay` seconds after it starts, or, with no delay, +/// only when the test answers it. +private final class AttestingApple: AppAttestCallbacks, @unchecked Sendable { + private let lock = NSLock() + private let delay: Double? + private var started: [(keyID: String, hash: Data)] = [] + private var waiting: [@Sendable (Result) -> Void] = [] + private var answered = 0 + private var generated = 0 + + init(answeringAttestationsAfter delay: Double?) { self.delay = delay } + + func generateKey(_ complete: @escaping @Sendable (Result) -> Void) { + let count = lock.withLock { generated += 1; return generated } + complete(.success(Data(repeating: UInt8(count), count: 32).base64EncodedString())) + } + + func attestKey(_ id: String, hash: Data, complete: @escaping @Sendable (Result) -> Void) { + lock.withLock { started.append((id, hash)) } + let answer: @Sendable (Result) -> Void = { [self] result in + lock.withLock { answered += 1 } + complete(result) + } + guard let delay else { lock.withLock { waiting.append(answer) }; return } + DispatchQueue.global().asyncAfter(deadline: .now() + delay) { answer(.success(Data("attestation-\(id)".utf8))) } + } + + func generateAssertion(_ id: String, hash: Data, complete: @escaping @Sendable (Result) -> Void) { + complete(.success(Data("assertion".utf8))) + } + + /// Answers every attestation still waiting, as a late Apple callback would. + func answerWaitingAttestations(_ result: Result) { + let answers = lock.withLock { () -> [@Sendable (Result) -> Void] in + defer { waiting = [] } + return waiting + } + for answer in answers { answer(result) } + } + + var attestations: [(keyID: String, hash: Data)] { lock.withLock { started } } + var answers: Int { lock.withLock { answered } } + var generatedKeys: Int { lock.withLock { generated } } +} + +/// Availability passes; key calls go through the real Apple adapter and its +/// callback deadline. +private actor AvailableApple: AppAttestService { + private let apple: AppleAppAttestService + init(_ callbacks: AttestingApple, deadline: Double) { + apple = AppleAppAttestService(callbacks: callbacks, operationTimeout: deadline) + } + func checkAvailability(environment: String) {} + func generateKey() async throws -> String { try await apple.generateKey() } + func attestKey(_ id: String, hash: Data) async throws -> Data { try await apple.attestKey(id, hash: hash) } + func generateAssertion(_ id: String, hash: Data) async throws -> Data { try await apple.generateAssertion(id, hash: hash) } + func operationHeldSince() async -> Date? { await apple.operationHeldSince() } +} + +/// Apple attests a key once. An exchange cancelled by a connection end must not +/// throw away an answer Apple is already producing: the key would be retired, +/// and its replacement would wait out the one-hour generation rule. +final class CancelledAttestationTests: XCTestCase { + private let scope = "test:production:account:" + String(repeating: "a", count: 64) + private let endpoint = Data(repeating: 7, count: 32).base64EncodedString() + private let status = AppAttestStatus(osVersion: "27.2.0", osBuild: "test", appVersion: "0.10.7", chip: "test", + binaryHash: String(repeating: "b", count: 64)) + + private func request(_ action: String, session: UInt8 = 3, key: String? = nil) -> AppAttestShadowPayload { + var p = AppAttestShadowPayload(action: action, session: Data(repeating: session, count: 32).base64EncodedString()) + p.protocolVersion = 3; p.accountScope = String(repeating: "a", count: 64); p.environment = "production"; p.keyID = key + if action != "prepare" { p.challenge = Data(repeating: 4, count: 32).base64EncodedString() } + return p + } + + private func client(_ apple: AttestingApple, _ storage: AttestationKeys, deadline: Double = 25) -> AppAttestShadowClient { + AppAttestShadowClient(scope: "test", service: AvailableApple(apple, deadline: deadline), storage: storage) + } + + private func waitUntil(seconds: Double = 5, _ condition: () -> Bool) async throws { + let deadline = Date(timeIntervalSinceNow: seconds) + while !condition() { + guard Date() < deadline else { return XCTFail("not reached within \(seconds) s") } + try await Task.sleep(nanoseconds: 2_000_000) + } + } + + /// Starts `attest` for `key` the way the serve loop does: in a task that a + /// connection end cancels. Returns once Apple has the call. + private func startAttestation(_ client: AppAttestShadowClient, _ apple: AttestingApple, + key: String) async throws -> (request: AppAttestShadowPayload, exchange: Task) { + let attest = request("attest", key: key) + let publicKey = endpoint, status = self.status + let exchange = Task { await client.respond(to: attest, publicKey: publicKey, status: status) } + try await waitUntil { apple.attestations.count == 1 } + return (attest, exchange) + } + + func testConnectionEndKeepsApplesAttestationForTheNextConnection() async throws { + let storage = AttestationKeys(), apple = AttestingApple(answeringAttestationsAfter: 1) + let client = client(apple, storage) + let ready = await client.respond(to: request("prepare"), publicKey: endpoint) + let key = try XCTUnwrap(ready.keyID) + let (attest, exchange) = try await startAttestation(client, apple, key: key) + try await Task.sleep(nanoseconds: 200_000_000) + exchange.cancel() + _ = await exchange.value + try await waitUntil { apple.answers == 1 } + + let stored = try XCTUnwrap(storage.load(scope: scope)) + XCTAssertEqual(stored.keyID, key, "Apple answered, so the key is not retired") + XCTAssertTrue(stored.attested) + XCTAssertEqual(stored.pendingProof, Data("attestation-\(key)".utf8).base64EncodedString()) + XCTAssertEqual(stored.pendingEnrollment, attest.session) + XCTAssertEqual(stored.pendingStatus, status) + XCTAssertNil(stored.attestationStartedAt) + XCTAssertNil(stored.retryEnrollment) + + // The next connection: a new session, and a newer status than the one Apple attested. + let next = await client.respond(to: request("prepare", session: 4), publicKey: endpoint) + XCTAssertEqual(next.result, "ok") + XCTAssertEqual(next.keyID, key) + var newer = status; newer.appVersion = "0.10.8" + let replay = await client.respond(to: request("attest", session: 4, key: key), publicKey: endpoint, status: newer) + XCTAssertEqual(replay.result, "ok") + XCTAssertEqual(replay.proof, stored.pendingProof) + // The proof stays bound to the transcript Apple attested. + XCTAssertEqual(replay.enrollmentSession, attest.session) + XCTAssertEqual(replay.status, status) + var signed = attest; signed.status = status + XCTAssertEqual(apple.attestations.map { $0.hash }, [signed.clientHash(publicKey: endpoint)]) + XCTAssertEqual(apple.attestations.map { $0.keyID }, [key]) + XCTAssertEqual(apple.generatedKeys, 1) + } + + func testAttestationCutOffByAProcessExitIsStillRetired() async throws { + let storage = AttestationKeys(), unanswered = AttestingApple(answeringAttestationsAfter: nil) + let exiting = client(unanswered, storage) + let ready = await exiting.respond(to: request("prepare"), publicKey: endpoint) + let key = try XCTUnwrap(ready.keyID) + let (_, abandoned) = try await startAttestation(exiting, unanswered, key: key) + XCTAssertNotNil(storage.load(scope: scope)?.attestationStartedAt) + XCTAssertNil(storage.load(scope: scope)?.pendingProof) + + // A new process (fresh client, same Keychain) cannot learn what Apple answered. + let apple = AttestingApple(answeringAttestationsAfter: 0) + let restarted = client(apple, storage) + let next = await restarted.respond(to: request("prepare", session: 4), publicKey: endpoint) + XCTAssertEqual(next.result, "busy") + let retired = try XCTUnwrap(storage.load(scope: scope)) + XCTAssertEqual(retired.keyID, "") + XCTAssertEqual(apple.generatedKeys, 0, "the replacement waits out the hour") + XCTAssertTrue(apple.attestations.isEmpty) + let local = await restarted.currentLocalStatus() + XCTAssertEqual(local?.key?.recordPresent, false) + XCTAssertEqual(try XCTUnwrap(local?.key?.generationBlockedUntil), + retired.createdAt.addingTimeInterval(KeyGenerationBudget.window).timeIntervalSince1970, accuracy: 0.001) + + // The exited process's call ended with it; release this stand-in. + unanswered.answerWaitingAttestations(.failure(ShadowFailure.appleError)) + _ = await abandoned.value + XCTAssertEqual(storage.load(scope: scope)?.keyID, "") + } + + func testAppleTimeoutStillRetiresTheKey() async throws { + for cancelled in [false, true] { + let storage = AttestationKeys(), apple = AttestingApple(answeringAttestationsAfter: nil) + let client = client(apple, storage, deadline: 0.3) + let ready = await client.respond(to: request("prepare"), publicKey: endpoint) + let key = try XCTUnwrap(ready.keyID) + let (_, exchange) = try await startAttestation(client, apple, key: key) + if cancelled { exchange.cancel() } + let reply = await exchange.value + if !cancelled { XCTAssertEqual(reply.result, "operation_timeout") } + try await waitUntil { storage.load(scope: scope)?.keyID == "" } + XCTAssertNil(storage.load(scope: scope)?.pendingProof, "cancelled: \(cancelled)") + + let next = await client.respond(to: request("prepare", session: 4), publicKey: endpoint) + XCTAssertEqual(next.result, "busy", "the one-hour replacement rule, cancelled: \(cancelled)") + XCTAssertEqual(apple.generatedKeys, 1) + // A late answer after the deadline is not taken. + apple.answerWaitingAttestations(.success(Data("late".utf8))) + try await Task.sleep(nanoseconds: 50_000_000) + XCTAssertEqual(storage.load(scope: scope)?.keyID, "", "cancelled: \(cancelled)") + XCTAssertNil(storage.load(scope: scope)?.pendingProof) + XCTAssertEqual(apple.attestations.count, 1) + } + } + + func testNextConnectionWaitsForTheOutstandingAttestationInsteadOfAskingAppleAgain() async throws { + let storage = AttestationKeys(), apple = AttestingApple(answeringAttestationsAfter: 1) + let client = client(apple, storage) + let ready = await client.respond(to: request("prepare"), publicKey: endpoint) + let key = try XCTUnwrap(ready.keyID) + let (attest, exchange) = try await startAttestation(client, apple, key: key) + try await Task.sleep(nanoseconds: 200_000_000) + exchange.cancel() + + // The next connection's prepare arrives while Apple is still attesting. + let next = await client.respond(to: request("prepare", session: 4), publicKey: endpoint) + XCTAssertEqual(apple.answers, 1, "the prepare waited for Apple's answer") + XCTAssertEqual(next.result, "ok") + XCTAssertEqual(next.keyID, key) + let replay = await client.respond(to: request("attest", session: 4, key: key), publicKey: endpoint, status: status) + XCTAssertEqual(replay.result, "ok") + XCTAssertEqual(replay.enrollmentSession, attest.session) + XCTAssertEqual(apple.attestations.count, 1, "one attestKey for the key") + XCTAssertEqual(apple.generatedKeys, 1) + _ = await exchange.value + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift index d3f2675676..445da59397 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderLifecycleTests.swift @@ -1,6 +1,6 @@ import Foundation import Testing -import ProviderAppAttest +@testable import ProviderAppAttest @testable import ProviderCore private func lifecycleHardware() -> HardwareInfo { @@ -48,6 +48,15 @@ private extension ProviderLoop { appAttestShadowClient = AppAttestShadowClient(scope: loopConfig.coordinatorURL, service: IdleAppAttestService(), storage: EmptyShadowKeys()) } + /// Starts `attest` as `handleAppAttestShadow` does, so a stop cancels it + /// through `cancelAppAttestShadow`. + func beginAppAttestation(_ client: AppAttestShadowClient, key: String) { + appAttestShadowClient = client + let request = lifecycleShadowRequest("attest", key: key) + appAttestShadowTask = Task.detached { + _ = await client.respond(to: request, publicKey: lifecycleEndpoint, status: lifecycleShadowStatus) + } + } func holdLifecycleRequests(_ ids: Set) { acceptedLifecycleRequests.formUnion(ids) } func completeLifecycleRequest(_ id: String) { acceptedLifecycleRequests.remove(id) } func installCancellableLifecycleRequest(_ id: String) { @@ -103,6 +112,31 @@ struct ProviderLifecycleTests { #expect(await loop.drainAndShutdown(timeoutSeconds: 1)) } + /// SIGTERM, `darkbloom stop` and the cluster service's part stop all drain + /// here. Apple already has the attestation: the stop lets it answer, so the + /// next process sends the proof instead of retiring the key for an hour. + @Test(.timeLimit(.minutes(1))) + func shutdownWaitsForAnAttestationAppleIsAnswering() async throws { + let (loop, root) = try await lifecycleLoop() + defer { try? FileManager.default.removeItem(at: root) } + let apple = SlowAttestingApple(answerAfter: 1) + let keys = LifecycleShadowKeys() + let client = AppAttestShadowClient(scope: "test", service: AvailableAttestingApple(apple), storage: keys) + let ready = await client.respond(to: lifecycleShadowRequest("prepare"), publicKey: lifecycleEndpoint) + let key = try #require(ready.keyID) + await loop.beginAppAttestation(client, key: key) + #expect(await waitFor { apple.attestationsStarted == 1 }) + let identity = try #require(ProcessIdentity.current()) + let stop = await loop.drainForLifecycle(request: .init(target: identity, timeoutSeconds: 3)) + #expect(stop.outcome == .drained) + #expect(apple.attestationsAnswered == 1, "the stop waited for Apple's answer") + let stored = try #require(keys.load(scope: lifecycleKeyScope)) + #expect(stored.keyID == key) + #expect(stored.pendingProof == Data("attestation-\(key)".utf8).base64EncodedString()) + #expect(stored.attestationStartedAt == nil) + #expect(await loop.drainAndShutdown(timeoutSeconds: 1)) + } + @Test func failedWorkerRetirementCannotAcknowledgeForcedShutdown() async throws { let (loop, root) = try await lifecycleLoop() defer { try? FileManager.default.removeItem(at: root) } @@ -339,6 +373,63 @@ private struct EmptyShadowKeys: ShadowKeyStorage { func save(_ record: ShadowKeyRecord, scope: String) {} } +private let lifecycleEndpoint = Data(repeating: 7, count: 32).base64EncodedString() +private let lifecycleKeyScope = "test:production:account:" + String(repeating: "a", count: 64) +private let lifecycleShadowStatus = AppAttestStatus(osVersion: "27.2.0", osBuild: "test", appVersion: "0.10.7", + chip: "test", binaryHash: String(repeating: "b", count: 64)) + +private func lifecycleShadowRequest(_ action: String, key: String? = nil) -> AppAttestShadowPayload { + var request = AppAttestShadowPayload(action: action, session: Data(repeating: 3, count: 32).base64EncodedString()) + request.protocolVersion = 3 + request.accountScope = String(repeating: "a", count: 64) + request.environment = "production" + request.keyID = key + if action != "prepare" { request.challenge = Data(repeating: 4, count: 32).base64EncodedString() } + return request +} + +private final class LifecycleShadowKeys: ShadowKeyStorage, @unchecked Sendable { + private let lock = NSLock() + private var records: [String: ShadowKeyRecord] = [:] + func load(scope: String) -> ShadowKeyRecord? { lock.withLock { records[scope] } } + func save(_ record: ShadowKeyRecord, scope: String) { lock.withLock { records[scope] = record } } +} + +/// Apple's side: keys at once, each attestation `answerAfter` seconds after it starts. +private final class SlowAttestingApple: AppAttestCallbacks, @unchecked Sendable { + private let lock = NSLock() + private let answerAfter: Double + private var started = 0 + private var answered = 0 + init(answerAfter: Double) { self.answerAfter = answerAfter } + func generateKey(_ complete: @escaping @Sendable (Result) -> Void) { + complete(.success(Data(repeating: 1, count: 32).base64EncodedString())) + } + func attestKey(_ id: String, hash: Data, complete: @escaping @Sendable (Result) -> Void) { + lock.withLock { started += 1 } + DispatchQueue.global().asyncAfter(deadline: .now() + answerAfter) { [self] in + lock.withLock { answered += 1 } + complete(.success(Data("attestation-\(id)".utf8))) + } + } + func generateAssertion(_ id: String, hash: Data, complete: @escaping @Sendable (Result) -> Void) { + complete(.success(Data("assertion".utf8))) + } + var attestationsStarted: Int { lock.withLock { started } } + var attestationsAnswered: Int { lock.withLock { answered } } +} + +/// Availability passes; key calls go through the real Apple adapter. +private actor AvailableAttestingApple: AppAttestService { + private let apple: AppleAppAttestService + init(_ callbacks: SlowAttestingApple) { apple = AppleAppAttestService(callbacks: callbacks, operationTimeout: 25) } + func checkAvailability(environment: String) {} + func generateKey() async throws -> String { try await apple.generateKey() } + func attestKey(_ id: String, hash: Data) async throws -> Data { try await apple.attestKey(id, hash: hash) } + func generateAssertion(_ id: String, hash: Data) async throws -> Data { try await apple.generateAssertion(id, hash: hash) } + func operationHeldSince() async -> Date? { await apple.operationHeldSince() } +} + private func waitFor(_ condition: () async -> Bool) async -> Bool { for _ in 0..<500 { if await condition() { return true } From 4ba74aedf5b761c04921cb5e2dbb87c419ca063b Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:19:22 -0800 Subject: [PATCH 0267/1441] fix(cluster): end the setup with an unmistakable outcome and show progress MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From the owner's call with an end user (2x M3 Ultra and 2x M4 Max on 0.10.7): the setup "just ends", step 4 gave no sense of time, and a failure gave no reason. The Start step now opens with "Loading takes a few minutes for a large model; both Macs show progress here." and, on a color terminal, the waits draw one live row per Mac with the time since loading began (no bar or percent: no load fraction is reported). The setup ends with its outcome as a block between two rules: "✓ Serving through Darkbloom on both Macs ()" or "✓ Serving on this Mac's local API only", with the API and test response under it, or "✗ Not serving: ." with the next step before the choices. The other Mac's window says where to look and shows the same block from the cluster's status. A Mac Apple has not verified yet is named with when Darkbloom retries by itself, and to restart neither Mac. Onboarding checks (e)-(h) fail first (15 failures on the previous driver) and pass after (796 passed, 0 failed). Co-Authored-By: Claude Opus 5.5 --- .../Onboarding/ClusterOnboardingFlow.swift | 113 +++++++++--- .../ClusterOnboardingPairServing.swift | 49 ++++- .../ClusterOnboardingTerminal.swift | 53 ++++-- .../OnboardingChecks.swift | 174 +++++++++++++++--- 4 files changed, 319 insertions(+), 70 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift index b34ece60ad..490fc397b4 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift @@ -578,15 +578,30 @@ public struct ClusterOnboardingReady: Codable, Sendable, Equatable { } /// A pair offered for pairing once the coordinator paired both Macs, both loaded the model and it answered its first - /// request: "Serving Qwen3.8 27B (pipeline) through Darkbloom on both Macs". Registered alone is not serving. + /// request: "Serving Qwen3.8 27B through Darkbloom on both Macs (pipeline)". Registered alone is not serving. public func pairServingLine(model: String) -> String { - let name = ClusterOnboardingDeployment.shownMarker(split).map { "\(model) (\($0))" } ?? model - return "Serving \(name) through Darkbloom on both Macs" + "Serving \(model) through Darkbloom on both Macs" + (ClusterOnboardingDeployment.shownMarker(split).map { " (\($0))" } ?? "") + } + + /// The outcome block once the pair serves and a request answered (`test`: "in 0.61 s"): through Darkbloom on both + /// Macs, or on the serving Mac's local API only (asked for, or a coordinator without cluster support). + public func outcome(model: String, scope: ClusterServingScope, test: String?) -> (title: String, lines: [String]) { + let tested = "Test response" + (test.map { " " + $0 } ?? "") + if offered != nil { return (pairServingLine(model: model), [Self.offeredAPILine, tested]) } + guard scope.isLocalOnly || notice.map({ !$0.hasPrefix(Self.registeredNotice) }) == true else { + return (pairServingLine(model: model), [apiLine, tested]) + } + let mode = ClusterOnboardingDeployment.shownMarker(split).map { " (\($0))" } ?? "" + let whose = servesHere ? "this Mac's" : servedBy + "'s" + return ("Serving \(model) on \(whose) local API only\(mode)", [apiLine] + (scope.isLocalOnly ? [] : noticeLine.map { [$0] } ?? []) + [tested]) } /// How the line of a pair registered with the coordinator as a cluster member starts (`ClusterLocalServing`). public static let registeredNotice = "Registered with the coordinator as a cluster member" + /// Where a pair offered for pairing takes requests, in the outcome block. + public static let offeredAPILine = "No local API: requests reach the pair through Darkbloom" + /// Said instead of the test request when the pair is offered for pairing (and the answer of `t` then). public static let offeredTestLine = "This pair has no local API while it is offered for pairing: requests from your own account reach it through Darkbloom." @@ -873,6 +888,10 @@ public protocol ClusterOnboardingConsole: AnyObject { /// Work that is still running, said again while it runs; the next said /// line replaces it. A transcript shows nothing extra. func working(_ text: String) + /// Live work of several rows (one per Mac), replaced as `working` is. + func workingRows(_ rows: [String]) + /// The setup's outcome as its own block (`ClusterOnboardingDriver.resultRule` above and below). + func result(_ succeeded: Bool, _ title: String, _ lines: [String]) /// The work said by `working` finished. func settle() /// A copy's or download's live report (`ClusterOnboardingProgress.live`): redrawn in place where `working` @@ -892,6 +911,19 @@ public protocol ClusterOnboardingConsole: AnyObject { } public extension ClusterOnboardingConsole { + /// The setup's outcome as its own block: a blank line, a rule, ✓ or ✗ with what serves (or why nothing does), + /// its details, a rule. + func result(_ succeeded: Bool, _ title: String, _ lines: [String]) { + say("") + say(ClusterOnboardingDriver.resultRule) + say((succeeded ? ClusterOnboardingDriver.done : ClusterOnboardingDriver.failed) + " " + title) + for line in lines { say(" " + line) } + say(ClusterOnboardingDriver.resultRule) + } + + /// Live work of several rows (one per Mac); a console with one live row shows the first. + func workingRows(_ rows: [String]) { working(rows.first ?? "") } + /// Scrollable sections also work in transcripts and non-terminal consoles. func heading(_ title: String) { say(""); say(title) } func banner(_ title: String, _ subtitle: String) { heading(title); if !subtitle.isEmpty { say(subtitle) } } @@ -968,6 +1000,8 @@ public enum ClusterOnboardingDriver { /// A step that is done, at the start of its line. public static let done = "\u{2713}" + /// An outcome that is not what was asked for, at the start of its block's line. + public static let failed = "\u{2717}" /// What to answer, for the program macOS names. `remote` (over SSH): the prompt is on this Mac's own screen, not in /// this terminal. @@ -996,7 +1030,7 @@ public enum ClusterOnboardingDriver { /// The Mac that joined ends its onboarding once paired; the last thing it says (the one thing to do next), with /// whether its window may close. - public static let joinedLine = "Done here: the other Mac chooses the model." + public static let joinedLine = "Done here: the other Mac chooses the model, and its screen shows whether the cluster serves." /// The same, for a Mac that joined when it was asked for `darkbloom cluster local`. public static let joinedLocalContinueLine = "Done here: run `darkbloom cluster local` on the other Mac." @@ -1204,7 +1238,8 @@ public enum ClusterOnboardingDriver { static func member(_ resume: ClusterOnboardingResume, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, request: ClusterOnboardingRequest = .init()) -> Int32 { guard startService(operations, console) else { return 1 } - for line in operations.status() { console.say(" " + line) } + let status = operations.status() + if !showOutcome(status, console) { for line in status { console.say(" " + line) } } if let port = resume.unsetCablePort { // The cable moved to a port that was never set up: the one thing that is this Mac's to do. console.say("") @@ -1221,6 +1256,20 @@ public enum ClusterOnboardingDriver { return 0 } + /// The cluster's status as the outcome block on the other Mac, when its first line tells it: "Serving …" (✓) or + /// " is not serving yet: ." (✗); false (nothing said) for any other status. + static func showOutcome(_ status: [String], _ console: ClusterOnboardingConsole) -> Bool { + guard let first = status.first else { return false } + let line = first.hasSuffix(".") ? String(first.dropLast()) : first + if line.hasPrefix("Serving ") { + console.result(true, line, Array(status.dropFirst())) + return true + } + guard let marker = line.range(of: " is not serving yet: ") else { return false } + console.result(false, "Not serving: " + line[marker.upperBound...] + ".", Array(status.dropFirst())) + return true + } + /// The leader: the model and options, the sync, the start, serving. static func leader(_ resume: ClusterOnboardingResume, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole, justPaired: Bool, request: ClusterOnboardingRequest = .init()) -> Int32 { @@ -1459,6 +1508,7 @@ public enum ClusterOnboardingDriver { } let savesScope = saveScope || startScope != scope console.heading("4/4 Start") + console.say(" " + startNotice) // Memory moves while the person reads: the fit is checked again right before anything starts. if let remedy = operations.recheckFit(chosen!) { console.say("\(choice.title) doesn't fit in free memory now: \(remedy)") @@ -1511,8 +1561,8 @@ public enum ClusterOnboardingDriver { } } - /// How a start ended up: serving (the lines that say so), its test failed, or not serving (why, first). - enum StartOutcome { case served([String]), testFailed, notServing([String]) } + /// How a start ended up: serving (the outcome block's title and lines), its test failed, or not serving (why, first). + enum StartOutcome { case served(title: String, lines: [String]), testFailed, notServing([String]) } /// After the start. Serving and Done are said only once the model is loaded on both Macs and a request answered /// (2026-11-03: a pair offered for pairing said both while nothing was loaded). A pair that does not serve says why @@ -1523,9 +1573,9 @@ public enum ClusterOnboardingDriver { var mayRegister = true while true { switch startOutcome(title: title, scope: scope, mayRegister: &mayRegister, operations, console) { - case .served(let lines): - for line in lines { console.say(" " + line) } - console.say("") + case .served(let served, let lines): + // 2026-11-03 call: "it should show whether it is success or not VERY clearly". + console.result(true, served, lines) if let restart = operations.afterRestart() { console.say(restart) } console.say("Done. " + (operations.serviceOutlivesWindow() ? "You can close both windows." : "Keep both windows open.")) console.say(againLine) @@ -1558,6 +1608,12 @@ public enum ClusterOnboardingDriver { /// The last line when the person leaves a pair that does not serve. public static let notServingLastLine = "Not serving yet. Both Macs keep trying by themselves; run `darkbloom cluster` to check." + /// Said as the Start step begins (2026-11-03 call: no sense of how long it takes). + public static let startNotice = "Loading takes a few minutes for a large model; both Macs show progress here." + + /// The rule above and below the outcome block. + public static let resultRule = String(repeating: "\u{2500}", count: 48) + /// Waits for the started parts; a pair offered for pairing then for the coordinator to pair both Macs and load the /// model there (registered is not serving); a pair on the leader's API is tested, then registered with the /// coordinator when it serves a cluster approval (once per start: both parts then start again and are awaited). @@ -1568,19 +1624,27 @@ public enum ClusterOnboardingDriver { case .success(let value): ready = value case .failure(let failure): return .notServing(failure.lines) } + let tested: String? if ready.offered != nil { switch awaitPairServing(title: title, operations, console) { - case .success(let test): - return .served(["\(done) Test response" + (test.map { " " + $0 } ?? ""), "\(done) " + ready.pairServingLine(model: title)]) + case .success(let test): tested = test case .failure(let failure): return .notServing(failure.lines) } + } else { + // The test's time is said in the outcome block; only a failure is said here. + switch busy(console, "Sending a test request", operations.testRequest) { + case .success(let lines): tested = lines.first.flatMap { $0.isEmpty ? nil : $0 } + case .failure(let failure): + for line in failure.lines { console.say(" " + line) } + return .testFailed + } + if mayRegister, !scope.isLocalOnly { + mayRegister = false + if register(operations, console) { return startOutcome(title: title, scope: scope, mayRegister: &mayRegister, operations, console) } + } } - guard test(operations, console) else { return .testFailed } - if mayRegister, !scope.isLocalOnly { - mayRegister = false - if register(operations, console) { return startOutcome(title: title, scope: scope, mayRegister: &mayRegister, operations, console) } - } - return .served(["\(done) " + ready.summary(model: title) + servesWords(scope: scope, ready: ready)]) + let outcome = ready.outcome(model: title, scope: scope, test: tested) + return .served(title: outcome.title, lines: outcome.lines) } enum NotServingChoice { case retry, changeModel, localOnly, leave } @@ -1593,9 +1657,8 @@ public enum ClusterOnboardingDriver { _ console: ClusterOnboardingConsole) -> NotServingChoice { let first = lines.first ?? "the cluster did not report ready" let reason = first.hasSuffix(".") ? String(first.dropLast()) : first - console.say("Not serving yet: \(reason).") - for line in lines.dropFirst() { console.say(" " + line) } - if let remedy = ClusterOnboardingNotServing.remedy(forReason: reason) { console.say(" " + remedy) } + console.result(false, "Not serving: \(reason).", + Array(lines.dropFirst()) + (ClusterOnboardingNotServing.remedy(forReason: reason).map { [$0] } ?? [])) while true { switch console.choose(notServingItems, selected: 0) { case 0: return .retry @@ -1619,13 +1682,14 @@ public enum ClusterOnboardingDriver { let finished = ClusterOnboardingMailbox>() Thread.detachNewThread { finished.post(operations.pairServing { progress.post($0) }) } var latest: String? + var clock = ClusterOnboardingLoadRows(started: Date()) while true { if let line = progress.take().last { latest = line } if let value = finished.take().first { console.settle() return value.map { $0.first.flatMap { $0.isEmpty ? nil : $0 } } } - console.working("Serving \(title) through Darkbloom" + (latest.map { " (\($0))" } ?? "")) + console.workingRows(clock.rows("Serving \(title) through Darkbloom", report: latest, now: Date())) _ = console.key(milliseconds: 120) } } @@ -1679,12 +1743,13 @@ public enum ClusterOnboardingDriver { let progress = ClusterOnboardingMailbox() let finished = ClusterOnboardingMailbox>() Thread.detachNewThread { finished.post(operations.waitReady { progress.post($0) }) } - // The parts' progress ("1 of 2 parts ready") is the live line only: the screen keeps the result. + // The parts' progress ("1 of 2 parts ready", then a row per Mac) is live only: the screen keeps the result. var latest: String? + var clock = ClusterOnboardingLoadRows(started: Date()) while true { if let line = progress.take().last { latest = line } if let value = finished.take().first { console.settle(); return value } - console.working("Loading \(title) on both Macs" + (latest.map { " (\($0))" } ?? "")) + console.workingRows(clock.rows("Loading \(title) on both Macs", report: latest, now: Date())) _ = console.key(milliseconds: 120) } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingPairServing.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingPairServing.swift index 4d266d6b03..6d5d19e472 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingPairServing.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingPairServing.swift @@ -63,6 +63,33 @@ public enum ClusterOnboardingPairReport { } } +/// The live rows while the parts load: the first row is the wait itself, then one row per Mac ("This Mac: loading +/// its share"), each with the time since the wait began; a Mac's time stops when it is first seen ready. A progress +/// report carries the Mac rows after its first line, one per line. No bar or percent: no real fraction is reported. +public struct ClusterOnboardingLoadRows: Sendable { + public let started: Date + private var readyAt: [String: Date] = [:] + + public init(started: Date) { self.started = started } + + public mutating func rows(_ title: String, report: String?, now: Date) -> [String] { + let parts = report?.components(separatedBy: "\n").filter { !$0.isEmpty } ?? [] + let head = (parts.first.map { "\(title) (\($0))" } ?? title) + " \u{00B7} " + Self.elapsed(now.timeIntervalSince(started)) + return [head] + parts.dropFirst().map { row in + let mac = row.components(separatedBy: ": ").first ?? row + if row.hasSuffix(": ready"), readyAt[mac] == nil { readyAt[mac] = now } + let end = row.hasSuffix(": ready") ? readyAt[mac] ?? now : now + return row + " \u{00B7} " + Self.elapsed(end.timeIntervalSince(started)) + } + } + + /// "48 s", "1 min 15 s". + static func elapsed(_ seconds: Double) -> String { + let whole = max(0, Int(seconds.rounded(.down))) + return whole < 60 ? "\(whole) s" : "\(whole / 60) min \(whole % 60) s" + } +} + /// Why a pair the coordinator forms does not serve, in one plain line for the screens, with what to do. The words come /// from what the two Macs know: their Darkbloom login, the coordinator's trust status for each member (App Attest), /// the guidance of the incident a failed start recorded, and a coordinator refusal reason when one reaches them. @@ -73,8 +100,22 @@ public enum ClusterOnboardingNotServing { + "so the coordinator won't pair \(macs.count == 1 ? "it" : "them")" } - public static func notVerified(_ mac: String) -> String { - "Darkbloom hasn't verified \(mac) for private serving yet (App Attest)" + /// The coordinator pairs only members Apple has verified (App Attest). `retryAt`: when this Mac's local + /// key-generation safeguard lets Darkbloom try again, said in local time; unknown, "within minutes". A restart + /// meanwhile cut an attestation once (an end user's M4 pair, 2026-11-03), so the line asks to leave both Macs alone. + public static func notVerified(_ mac: String, retryAt: Date? = nil, timeZone: TimeZone = .current) -> String { + let when = retryAt.map { "at about " + clock($0, timeZone: timeZone) } ?? "within minutes" + return "\(ClusterOnboardingMacName.sentence(mac)) isn't verified by Apple yet; Darkbloom retries by itself \(when). " + + "Don't restart either Mac until then" + } + + /// "00:34": hours and minutes in `timeZone`. + static func clock(_ date: Date, timeZone: TimeZone) -> String { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = timeZone + formatter.dateFormat = "HH:mm" + return formatter.string(from: date) } public static func lacksMemory(_ mac: String) -> String { "\(ClusterOnboardingMacName.sentence(mac)) lacks free memory for its share" } @@ -103,9 +144,7 @@ public enum ClusterOnboardingNotServing { /// What to do next, said under the reason (the choices follow it). public static func remedy(forReason line: String) -> String? { if line.contains("logged in to Darkbloom") { return "Run `darkbloom login` on each Mac named, then Retry; or serve locally only." } - if line.contains("(App Attest)") { - return "Keep both Macs logged in and running Darkbloom; it is verified within minutes. Retry then, or serve locally only." - } + if line.contains("isn't verified by Apple yet") { return "Then choose Retry, or serve locally only now." } if line.contains("lacks free memory") { return "Quit apps on that Mac, then Retry; or change the model." } return nil } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingTerminal.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingTerminal.swift index e661e55a61..e703f25c2e 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingTerminal.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingTerminal.swift @@ -27,8 +27,8 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { /// The window's width in columns when the setup started (0 when unknown). private let columns: Int private let brand: String - /// The live work line on screen, if any; the next said line replaces it. - private var working: String? + /// The live work rows on screen (one, or one per Mac while the parts load), if any; the next said line replaces them. + private var working: [String]? private var drawnFrame = -1 private let echoesInput: Bool private var saved = termios() @@ -92,11 +92,26 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { public func say(_ line: String) { guard let live = working else { write(line + "\n"); return } - // The said line takes the live line's row; the live line moves below it. - write("\r\u{1B}[K" + line + "\n") + // The said line takes the live rows' place; the live rows move below it. + write(Self.up(live.count) + "\r\u{1B}[J" + line + "\n") + working = nil drawWorking(live, force: true) } + /// From the last live row back to the first. + private static func up(_ rows: Int) -> String { rows > 1 ? "\u{1B}[\(rows - 1)A" : "" } + + /// The outcome block: the rules dim, the outcome bold, green for ✓ and red for ✗ (the mark carries it too). + public func result(_ succeeded: Bool, _ title: String, _ lines: [String]) { + let rule = usesColor ? "\u{1B}[2m" + ClusterOnboardingDriver.resultRule + "\u{1B}[0m" : ClusterOnboardingDriver.resultRule + let mark = succeeded ? ClusterOnboardingDriver.done : ClusterOnboardingDriver.failed + say("") + say(rule) + say(usesColor ? "\u{1B}[1;\(succeeded ? "32" : "31")m\(mark) \(title)\u{1B}[0m" : "\(mark) \(title)") + for line in lines { say(" " + line) } + say(rule) + } + /// The setup's opening: the mark beside its name where the terminal can /// draw it (blooming when it animates), else the plain heading lines. public func banner(_ title: String, _ subtitle: String) { @@ -124,16 +139,19 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { /// Live work under the last said line: a turning petal and what runs. /// Plain transcripts show nothing extra. - public func working(_ text: String) { - guard decorates else { return } - drawWorking(text, force: text != working) + public func working(_ text: String) { workingRows([text]) } + + /// Live rows, one per row of the window (the first with the turning petal); plain transcripts show nothing extra. + public func workingRows(_ rows: [String]) { + guard decorates, !rows.isEmpty else { return } + drawWorking(rows, force: rows != working) } - /// Clears the live work line, leaving the cursor where it was. + /// Clears the live work rows, leaving the cursor at the start of the first. public func settle() { - guard working != nil else { return } + guard let live = working else { return } working = nil; drawnFrame = -1 - write("\r\u{1B}[K") + write(Self.up(live.count) + "\r\u{1B}[J") } /// A copy's or download's report: the live line, laid out for its room, where @@ -144,7 +162,7 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { let now = DispatchTime.now().uptimeNanoseconds let due = now &- progressDrawn >= 125_000_000 if due { progressDrawn = now } - drawWorking(text(liveRoom), force: due) + drawWorking([text(liveRoom)], force: due) } /// When the progress line was last redrawn (uptime, nanoseconds). @@ -155,15 +173,20 @@ public final class ClusterOnboardingTerminal: ClusterOnboardingConsole { /// Room: the indent, petal and space, the ellipsis and the last column. private var liveRoom: Int { max(1, columns - 6) } - private func drawWorking(_ text: String, force: Bool) { + private func drawWorking(_ rows: [String], force: Bool) { let now = DispatchTime.now().uptimeNanoseconds let frame = animates ? Int((now / 125_000_000) % 4) : 0 - working = text + let shownRows = working?.count ?? 0 + working = rows guard force || frame != drawnFrame else { return } drawnFrame = frame let petal = animates ? ClusterOnboardingBrand.spin(now) : ClusterOnboardingBrand.spinner[0] - let shown = text.count > liveRoom ? String(text.prefix(liveRoom)) : text - write("\r\u{1B}[K \u{1B}[\(brand)m\(petal)\u{1B}[0m \u{1B}[2m\(shown)\u{2026}\u{1B}[0m") + // Each row fits one row of the window: the climb back to the first row counts rows, never wrapped lines. + func fit(_ text: String) -> String { text.count > liveRoom ? String(text.prefix(liveRoom)) : text } + let drawn = rows.enumerated().map { index, text in + index == 0 ? " \u{1B}[\(brand)m\(petal)\u{1B}[0m \u{1B}[2m\(fit(text))\u{2026}\u{1B}[0m" : " \u{1B}[2m\(fit(text))\u{1B}[0m" + } + write(Self.up(shownRows) + "\r\u{1B}[J" + drawn.joined(separator: "\n")) } static func supportsColor(inputIsTerminal: Bool, outputIsTerminal: Bool, diff --git a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift index d707c33fc9..2509aa8460 100644 --- a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift +++ b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift @@ -108,6 +108,11 @@ import Darwin missingLoginIsSaidBeforeTheStart() offeredPairServesOnceLoaded() pairReportsAndReasonsInPlainWords() + // The end user's call (Dylan, 2026-11-03): a clear outcome, a sense of time, the reason with its time. + startSaysItTakesAWhileAndShowsEachMac() + theOutcomeIsItsOwnBlock() + appleVerificationSaysWhenItRetries() + memberSeesTheOutcomeOrWhereToLook() print("onboarding checks: \(passed) passed, \(failures.count) failed") for failure in failures { print("FAIL " + failure) } exit(failures.isEmpty ? 0 : 1) @@ -182,8 +187,8 @@ import Darwin expect(screen.contains(" \u{25B8} Yes") && screen.contains(" \u{25B8} Qwen3.8-27B-4bit-mtp · 16.3 GB · pipeline"), "colour: each choice folds to the chosen line") expect(run.text.contains("\u{1B}[3A\r\u{1B}[J"), "colour: the list is erased in place once chosen") - expect(screen.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom)"), - "colour: the serving line reads plainly") + expect(screen.contains("\u{2713} Serving Qwen3.8-27B-4bit-mtp through Darkbloom on both Macs (pipeline)"), + "colour: the outcome reads plainly") for live in ["Checking the cable", "Reading both Macs over the cable", "Planning each model for both Macs", "Loading Qwen3.8-27B-4bit-mtp on both Macs", "Sending a test request"] { expect(!screen.contains { $0.contains(live + "\u{2026}") }, "colour: the live line \(live) is replaced, never left behind") @@ -452,7 +457,10 @@ import Darwin readyResults: [Result]? = nil, pairServingResults: [Result<[String], ClusterOnboardingFailure>] = [.failure(.init("not asked in this check"))], missingLogins: [String] = [], - loginSucceeds: Bool = true) -> ClusterOnboardingOperations { + loginSucceeds: Bool = true, + readyReports: [String] = ["1 of 2 parts ready", "2 of 2 parts ready"], + readyReportPause: useconds_t = 50_000, + statusLines: [String]? = nil) -> ClusterOnboardingOperations { let answered = DispatchSemaphore(value: 0) let chosenPort = Recorder() // The n-th wait for the parts answers `readyResults[n]` (the last one again after it), else `readyResult`. @@ -523,12 +531,13 @@ import Darwin serve: { recorder.note("serve"); return .success(["Started the other Mac's part over the cable (its cluster service runs it); this Mac's service runs its own."]) }, waitReady: { progress in let call = recorder.all.filter { $0 == "waitReady" }.count - recorder.note("waitReady"); progress("1 of 2 parts ready"); usleep(50_000); progress("2 of 2 parts ready") + recorder.note("waitReady") + for report in readyReports { progress(report); usleep(readyReportPause) } return ready(call) }, testRequest: { recorder.note("testRequest"); return testResult }, // Rank 0, which serves the API, is the Mac that leads: this Mac on the leader, the other Mac on a member. - status: { recorder.note("status"); return resume.role == .member + status: { recorder.note("status"); if let statusLines { return statusLines }; return resume.role == .member ? ["Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 on the other Mac (earning through Darkbloom)."] : ["Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom)."] }, stop: { recorder.note("stop"); return .success(["Stopping both Macs. Run `darkbloom cluster` to serve again."]) }, @@ -744,8 +753,10 @@ import Darwin " " + ClusterOnboardingPairing.otherMacAnswerLine, " \u{2713} Paired. This Mac leads.", " \(prompt(2))Qwen3.8-27B-4bit-mtp", - " \u{2713} Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom)", - " \u{2713} Test response in 0.61 s", + "\u{2713} Serving Qwen3.8-27B-4bit-mtp through Darkbloom on both Macs (pipeline)", + " API at http://localhost:8000 on this Mac", + " Test response in 0.61 s", + " " + ClusterOnboardingDriver.startNotice, ] { expect(text.contains(line + "\n"), "leader: \(line)") } @@ -759,7 +770,8 @@ import Darwin let positions = stages.compactMap { text.range(of: $0)?.lowerBound } expect(positions.count == stages.count && positions == positions.sorted(), "setup stages stay in order") expect(!text.contains("\u{1B}"), "NO_COLOR transcript has no terminal escapes") - expect(visible(text).filter { !$0.isEmpty }.count <= 21, "leader: a short screen: \(visible(text).filter { !$0.isEmpty }.count) lines") + // The 2026-11-03 call asked for the Start step's notice and an unmistakable outcome block: four lines more. + expect(visible(text).filter { !$0.isEmpty }.count <= 25, "leader: a short screen: \(visible(text).filter { !$0.isEmpty }.count) lines") // 2026-11-03 (owner, from the customer's review): "less is better". The setup's screen keeps to a word budget. expect(words(text) <= leaderWordBudget, "leader: at most \(leaderWordBudget) words, got \(words(text))") expect(run.keys == 2, "leader: two keys (y, enter), got \(run.keys)") @@ -946,8 +958,8 @@ import Darwin let text = run.text expect(text.contains("This Mac follows the other Mac\n"), "member again: who leads, in the opening") expect(!text.contains("derived") && !text.contains("term ") && !text.contains("rank 0"), "member again: no leadership jargon") - expect(text.contains(" Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 on the other Mac (earning through Darkbloom).\n"), - "member again: the status, with how it is split") + expect(text.contains("\u{2713} Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 on the other Mac (earning through Darkbloom)\n"), + "member again: the status as the outcome, with how it is split") expect(text.hasSuffix(ClusterOnboardingDriver.memberNothingLine + "\n"), "member again: where to manage the cluster, last: \(text)") expect(!text.contains("Change model") && !text.contains("Choose 1-"), "member again: no menu") expect(recorder.all == ["ensureService", "status"], "member again: its service and the status only: \(recorder.all)") @@ -1314,7 +1326,7 @@ import Darwin expect(run.waitFor(notServingChoices, count: 2), "timeout: the choices again after the file") run.type("q") expect(run.finish() == 1, "timeout: exit 1") - expect(run.text.contains("Not serving yet: The cluster did not report ready within 15 minutes.\n"), "timeout: why, first") + expect(run.text.contains("\u{2717} Not serving: The cluster did not report ready within 15 minutes.\n"), "timeout: why, first") expect(!run.text.contains("Done."), "timeout: never Done") expect(run.text.contains("The other Mac (Apple M3 Ultra, 256 GB): its part ended: out of memory."), "timeout: each Mac's last error on screen") expect(run.text.contains("Saved a diagnostics file"), "timeout: the file is saved") @@ -1477,8 +1489,8 @@ import Darwin run.type("\r") expect(run.finish() == 0, "local from scratch: exit 0") let text = run.text - expect(text.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp at http://localhost:8000 and on the network (local only)\n"), - "local from scratch: one serving line, the network and local only on it: \(text)") + expect(text.contains("\u{2713} Serving Qwen3.8-27B-4bit-mtp on this Mac's local API only\n " + localReady.apiLine + "\n"), + "local from scratch: the outcome, the network and local only on it: \(text)") expect(recorder.all == ["checkLink", "pair", "answer y", "ensureService", "reachMembers", "planModels", "recheckFit 0", "adopt 0", "setScope local 0.0.0.0", "serve", "waitReady", "testRequest"], "local from scratch: scope saved after the adopt, before the start: \(recorder.all)") expect(run.keys == 2, "local from scratch: the same two keys (y, enter), got \(run.keys)") @@ -1659,7 +1671,7 @@ import Darwin for line in [ " \u{2713} Paired. This Mac leads.", " 1) Z.ai: GLM-5.3-Flash · 181.8 GB", - " \u{2713} Serving Z.ai: GLM-5.3-Flash at http://localhost:8000 (local only)", + "\u{2713} Serving Z.ai: GLM-5.3-Flash on this Mac's local API only", ] { expect(text.contains(line + "\n"), "identical: \(line)") } @@ -1864,8 +1876,10 @@ import Darwin /// The from-scratch screens' word budgets (2026-11-03: about 70% fewer words than the 2026-11-02 screens, 293 and /// 148): a line that grows them back fails here. - static let leaderWordBudget = 100 - static let memberWordBudget = 60 + /// 2026-11-03 call (Dylan): the Start step's notice and an unmistakable outcome block on the leader, and where the + /// other Mac's window shows the outcome; both budgets grew by that much. + static let leaderWordBudget = 125 + static let memberWordBudget = 70 static let codeQuestion = ClusterOnboardingPairing.codeQuestion @@ -1958,15 +1972,15 @@ import Darwin expect(run.finish() == 0, "serves: exit 0") let text = run.text expect(!text.contains("public traffic in pipeline mode"), "serves: no public-traffic line at the choice: \(text)") - expect(text.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom)\n"), - "serves: through Darkbloom, on the serving line: \(text)") + expect(text.contains("\u{2713} Serving Qwen3.8-27B-4bit-mtp through Darkbloom on both Macs (pipeline)\n"), + "serves: through Darkbloom, in the outcome: \(text)") let local = TerminalRun(operations(Recorder(), resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], pairResult: .failed([]), choices: qualified, readyResult: .success(localReady)), request: localRequest) expect(local.waitFor(prompt(1)), "serves locally: the list"); local.type("\r") expect(local.finish() == 0, "serves locally: exit 0") expect(!local.text.contains("public traffic in pipeline mode") && !local.text.contains("earning"), "serves locally: no public-traffic line, no earning: \(local.text)") - expect(local.text.contains("(local only)\n"), "serves locally: said on the serving line: \(local.text)") + expect(local.text.contains("local API only\n"), "serves locally: said in the outcome: \(local.text)") } /// The list's keys on a colour UTF-8 terminal. @@ -2236,7 +2250,7 @@ import Darwin expect(run.waitFor(prompt(2)), "refused: the list"); run.type("\r") expect(run.waitFor(notServingChoices), "refused: the choices: \(run.text)") let shown = run.text - expect(shown.contains("Not serving yet: " + notVerified + ".\n"), "refused: why, in one line: \(shown)") + expect(shown.contains("\u{2717} Not serving: " + notVerified + ".\n"), "refused: why, in one line: \(shown)") expect(!shown.contains("\u{2713} Serving") && !shown.contains("Done.") && !shown.contains(ClusterOnboardingReady.offeredTestLine), "refused: no Serving, no Done, no test claimed: \(shown)") run.type("4") @@ -2261,7 +2275,7 @@ import Darwin expect(again.waitFor(prompt(2)), "retry: the list"); again.type("\r") expect(again.waitFor(notServingChoices), "retry: the choices"); again.type("1") expect(again.finish() == 0, "retry: served") - expect(again.text.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp (pipeline) through Darkbloom on both Macs\n") + expect(again.text.contains("\u{2713} Serving Qwen3.8-27B-4bit-mtp through Darkbloom on both Macs (pipeline)\n") && again.text.contains("Done."), "retry: Serving and Done only after the pair served: \(again.text)") expect(retried.all.filter { $0 == "pairServing" }.count == 2, "retry: waited again: \(retried.all)") } @@ -2282,7 +2296,7 @@ import Darwin let text = run.text expect(code == 1, "restart: a failed restart is not success, got \(String(describing: code))") expect(!text.contains("Done."), "restart: never Done: \(text)") - expect(text.contains("Not serving yet: " + ended + "\n"), "restart: why: \(text)") + expect(text.contains("\u{2717} Not serving: " + ended + "\n"), "restart: why: \(text)") expect(text.contains(notServingChoices), "restart: the choices: \(text)") expect(Array(recorder.all.prefix { $0 != "register" }.suffix(2)) == ["waitReady", "testRequest"] && recorder.all.filter { $0 == "waitReady" }.count == 2, "restart: tested, registered, then the parts awaited: \(recorder.all)") @@ -2322,7 +2336,7 @@ import Darwin "login, local: logged in here, then local only saved: \(switched.all)") let setScope = switched.all.firstIndex(of: "setScope local 0.0.0.0"), serve = switched.all.firstIndex(of: "serve") expect(setScope != nil && serve != nil && setScope! < serve!, "login, local: saved before the start: \(switched.all)") - expect(local.text.contains("(local only)\n") && local.text.contains("Done."), "login, local: serving locally: \(local.text)") + expect(local.text.contains("local API only\n") && local.text.contains("Done."), "login, local: serving locally: \(local.text)") expect(!switched.all.contains("register"), "login, local: no registration with a coordinator: \(switched.all)") } @@ -2336,8 +2350,8 @@ import Darwin let code = run.finish() expect(code == 0, "served: exit 0, got \(String(describing: code))") let text = run.text - expect(text.contains(" \u{2713} Test response in 0.84 s\n"), "served: the pair's first request: \(text)") - expect(text.contains(" \u{2713} Serving Qwen3.8-27B-4bit-mtp (pipeline) through Darkbloom on both Macs\n"), "served: the line: \(text)") + expect(text.contains(" Test response in 0.84 s\n"), "served: the pair's first request: \(text)") + expect(text.contains("\u{2713} Serving Qwen3.8-27B-4bit-mtp through Darkbloom on both Macs (pipeline)\n"), "served: the line: \(text)") expect(text.hasSuffix("Done. You can close both windows.\n" + ClusterOnboardingDriver.againLine + "\n"), "served: Done: \(text)") expect(Array(recorder.all.suffix(3)) == ["serve", "waitReady", "pairServing"], "served: loaded before it is said: \(recorder.all)") transcript("offered-pair-served", text, keys: run.keys) @@ -2356,7 +2370,7 @@ import Darwin typealias N = ClusterOnboardingNotServing let other = "the other Mac (Apple M3 Ultra, 256 GB)" for reason in ["liveness:trust_floor", "member rank 0 provider p: liveness:private_text", "app_attest_required (app_attest:lease)"] { - expect(N.words(reason: reason, mac: other) == "Darkbloom hasn't verified the other Mac (Apple M3 Ultra, 256 GB) for private serving yet (App Attest)", + expect(N.words(reason: reason, mac: other) == N.notVerified(other), "words: \(reason)") } expect(N.words(reason: "memory_gate_refused", mac: other) == "The other Mac (Apple M3 Ultra, 256 GB) lacks free memory for its share", "words: memory") @@ -2366,4 +2380,112 @@ import Darwin } static let offeredLogLine = "Notice: " + ClusterOnboardingReady.registeredNotice + " with an installed cluster approval" + + // MARK: - The end user's call (Dylan, 2026-11-03): a clear outcome, a sense of time, the reason with its time + + /// The outcome block as a plain transcript shows it. + static func block(_ mark: String, _ title: String, _ lines: [String]) -> String { + "\n" + ClusterOnboardingDriver.resultRule + "\n" + mark + " " + title + "\n" + lines.map { " " + $0 + "\n" }.joined() + + ClusterOnboardingDriver.resultRule + "\n" + } + + static let colourTerminal = ["TERM": "xterm-256color", "LANG": "en_US.UTF-8", "DARKBLOOM_NO_ANIMATION": "1"] + + /// Dylan's M4 pair: the leader's App Attest key was cut 0.7 s into Apple's attestation, and its key-generation + /// safeguard cleared at about 00:34 UTC. + static let appleRetry = ISO8601DateFormatter().date(from: "2026-11-04T00:34:00Z")! + static let notVerifiedTimed = ClusterOnboardingNotServing.notVerified("the other Mac (Apple M4 Max, 128 GB)", retryAt: appleRetry, + timeZone: TimeZone(identifier: "UTC")!) + + /// (e) Step 4 says it takes a while, then shows one live row per Mac with the time since loading began. + static func startSaysItTakesAWhileAndShowsEachMac() { + let run = TerminalRun(operations(Recorder(), resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]))) + expect(run.waitFor(prompt(2)), "notice: the list"); run.type("\r") + expect(run.finish() == 0, "notice: served") + expect(run.text.contains("4/4 Start\n " + ClusterOnboardingDriver.startNotice + "\n"), "notice: under the Start heading: \(run.text)") + + let live = TerminalRun(operations(Recorder(), resume: .init(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), pairEvents: [], + pairResult: .failed([]), readyReports: ["1 of 2 parts ready\nThis Mac: ready\nThe other Mac (Apple M3 Ultra, 256 GB): loading its share"], + readyReportPause: 900_000), environment: colourTerminal) + expect(live.waitFor(arrowHint), "rows: the list"); live.type("\r") + expect(live.waitFor("The other Mac (Apple M3 Ultra, 256 GB): loading its share \u{00B7} "), "rows: the other Mac's row with its time") + expect(live.text.contains("This Mac: ready \u{00B7} "), "rows: this Mac's row with its time") + _ = live.finish() + let rowsShown = live.text.components(separatedBy: "\n").filter { $0.contains("loading its share") || $0.contains("This Mac: ready") } + expect(!rowsShown.isEmpty && !rowsShown.contains { $0.contains("%") || $0.contains("\u{2588}") }, "rows: no bar or percent without a real fraction") + + var clock = ClusterOnboardingLoadRows(started: Date(timeIntervalSince1970: 0)) + let first = clock.rows("Loading m on both Macs", report: "1 of 2 parts ready\nThis Mac: ready\nThe other Mac: loading its share", + now: Date(timeIntervalSince1970: 48)) + expect(first == ["Loading m on both Macs (1 of 2 parts ready) \u{00B7} 48 s", "This Mac: ready \u{00B7} 48 s", + "The other Mac: loading its share \u{00B7} 48 s"], "clock: \(first)") + let later = clock.rows("Loading m on both Macs", report: "2 of 2 parts ready\nThis Mac: ready\nThe other Mac: ready", + now: Date(timeIntervalSince1970: 75)) + expect(later == ["Loading m on both Macs (2 of 2 parts ready) \u{00B7} 1 min 15 s", "This Mac: ready \u{00B7} 48 s", + "The other Mac: ready \u{00B7} 1 min 15 s"], "clock: a Mac's time stops once it is ready: \(later)") + } + + /// (f) The outcome is its own block: ✓ with what serves and how it was checked, or ✗ with why and the next step. + static func theOutcomeIsItsOwnBlock() { + let leader = ClusterOnboardingResume(role: .leader, peerName: "Apple M3 Ultra, 256 GB") + let run = TerminalRun(operations(Recorder(), resume: leader, pairEvents: [], pairResult: .failed([]))) + expect(run.waitFor(prompt(2)), "block: the list"); run.type("\r") + expect(run.finish() == 0, "block: served") + expect(run.text.contains(block("\u{2713}", "Serving Qwen3.8-27B-4bit-mtp through Darkbloom on both Macs (pipeline)", + ["API at http://localhost:8000 on this Mac", "Test response in 0.61 s"]) + "Done. You can close both windows.\n"), + "block: through Darkbloom, then Done: \(run.text)") + transcript("outcome-through-darkbloom", run.text, keys: run.keys) + + let local = TerminalRun(operations(Recorder(), resume: leader, pairEvents: [], pairResult: .failed([]), + readyResult: .success(localReady)), request: localRequest) + expect(local.waitFor(prompt(2)), "block, local: the list"); local.type("\r") + expect(local.finish() == 0, "block, local: served") + expect(local.text.contains(block("\u{2713}", "Serving Qwen3.8-27B-4bit-mtp on this Mac's local API only", + [localReady.apiLine, "Test response in 0.61 s"])), "block, local: \(local.text)") + transcript("outcome-local-only", local.text, keys: local.keys) + + let offered = TerminalRun(operations(Recorder(), resume: leader, pairEvents: [], pairResult: .failed([]), + readyResult: .success(offeredReady), pairServingResults: [.success(["in 0.84 s"])])) + expect(offered.waitFor(prompt(2)), "block, offered: the list"); offered.type("\r") + expect(offered.finish() == 0, "block, offered: served") + expect(offered.text.contains(block("\u{2713}", "Serving Qwen3.8-27B-4bit-mtp through Darkbloom on both Macs (pipeline)", + [ClusterOnboardingReady.offeredAPILine, "Test response in 0.84 s"])), "block, offered: \(offered.text)") + + let refused = TerminalRun(operations(Recorder(), resume: leader, pairEvents: [], pairResult: .failed([]), + readyResult: .success(offeredReady), pairServingResults: [.failure(.init(notVerifiedTimed))])) + expect(refused.waitFor(prompt(2)), "block, refused: the list"); refused.type("\r") + expect(refused.waitFor(notServingChoices), "block, refused: the choices"); refused.type("q") + expect(refused.finish() == 1, "block, refused: exit 1") + expect(refused.text.contains(block("\u{2717}", "Not serving: " + notVerifiedTimed + ".", + [ClusterOnboardingNotServing.remedy(forReason: notVerifiedTimed) ?? "-"]) + notServingChoices), "block, refused: \(refused.text)") + transcript("outcome-not-serving-app-attest", refused.text, keys: refused.keys) + } + + /// (g) Not verified by Apple yet: when Darkbloom retries by itself (the local key-generation safeguard), and to + /// leave both Macs alone until then; "within minutes" when the time is unknown. + static func appleVerificationSaysWhenItRetries() { + expect(notVerifiedTimed == "The other Mac (Apple M4 Max, 128 GB) isn't verified by Apple yet; Darkbloom retries by itself at about 00:34. " + + "Don't restart either Mac until then", "apple: with the time: \(notVerifiedTimed)") + expect(ClusterOnboardingNotServing.notVerified("this Mac") == "This Mac isn't verified by Apple yet; Darkbloom retries by itself within minutes. " + + "Don't restart either Mac until then", "apple: without a time") + expect(ClusterOnboardingNotServing.words(reason: "liveness:private_text", mac: "this Mac") == ClusterOnboardingNotServing.notVerified("this Mac"), + "apple: the coordinator's words map to the same line") + } + + /// (h) The other Mac's window: where to see the outcome once it joined, and the outcome itself when it can know it. + static func memberSeesTheOutcomeOrWhereToLook() { + expect(ClusterOnboardingDriver.joinedLine.contains("its screen shows whether the cluster serves"), "member: where to look: \(ClusterOnboardingDriver.joinedLine)") + let serving = TerminalRun(operations(Recorder(), resume: .init(role: .member, peerName: "Apple M5 Ultra, 256 GB", serving: true), + pairEvents: [], pairResult: .failed([]), statusLines: ["Serving Qwen3.8-27B-4bit-mtp (pipeline) through Darkbloom on both Macs."])) + expect(serving.finish() == 0, "member: served") + expect(serving.text.contains(block("\u{2713}", "Serving Qwen3.8-27B-4bit-mtp (pipeline) through Darkbloom on both Macs", [])), + "member: the outcome block: \(serving.text)") + let notServing = TerminalRun(operations(Recorder(), resume: .init(role: .member, peerName: "Apple M5 Ultra, 256 GB", serving: true), + pairEvents: [], pairResult: .failed([]), statusLines: ["Qwen3.8-27B-4bit-mtp is not serving yet: " + notVerifiedTimed + ".", + ClusterOnboardingNotServing.remedy(forReason: notVerifiedTimed) ?? "-"])) + _ = notServing.finish() + expect(notServing.text.contains(block("\u{2717}", "Not serving: " + notVerifiedTimed + ".", + [ClusterOnboardingNotServing.remedy(forReason: notVerifiedTimed) ?? "-"])), "member: the not-serving block: \(notServing.text)") + } } From 99baeaf0b6ed403fdb5421e8a9d756043a005482 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:19:22 -0800 Subject: [PATCH 0268/1441] fix(cluster): say when Apple verification retries, and each Mac's load row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each Mac's cluster service now also passes the end of its member's local App Attest key-generation safeguard (ClusterServiceStatus.Child .appAttestRetryAt, read only from the daemon state's AppAttestKeyState .generationBlockedUntil; nil when nothing blocks it or from an older build). The not-verified reason names that time in local time ("… retries by itself at about 00:34. Don't restart either Mac until then."), or "within minutes". An end user's M4 pair was refused this way for an hour after the setup's own restart cut its leader's attestation (production telemetry, 2026-11-03). pairLook's progress carries one row per Mac (registering, registered, loading its share once rank 0's part reports the committed start); the status line keeps only the wait's first line. Docs: two-mac-cluster (Start notice, live rows, outcome block, the reason's time), troubleshooting, architecture/inference; changelog. Co-Authored-By: Claude Opus 5.5 --- ...ter-start-says-serving-only-when-loaded.md | 4 +- docs/architecture/inference.md | 7 ++- docs/provider/troubleshooting.md | 2 +- docs/provider/two-mac-cluster.md | 51 +++++++++++++------ .../Installed/ClusterServiceWire.swift | 3 ++ .../Onboarding/ClusterOnboardingLive.swift | 22 ++++++-- .../Onboarding/ClusterService.swift | 11 +++- 7 files changed, 75 insertions(+), 25 deletions(-) diff --git a/changelog.d/cluster-start-says-serving-only-when-loaded.md b/changelog.d/cluster-start-says-serving-only-when-loaded.md index 4264097851..64cdd186df 100644 --- a/changelog.d/cluster-start-says-serving-only-when-loaded.md +++ b/changelog.d/cluster-start-says-serving-only-when-loaded.md @@ -4,4 +4,6 @@ - A start that does not come to serve, including the parts' restart after the registration, now says why in one line (a Mac without a Darkbloom login, a Mac Darkbloom has not verified for private serving yet (App Attest), a Mac without free memory for its share, a part that keeps ending) and stays open with **Retry**, **Change model**, **Serve locally only** and **Diagnostics**. Leaving with q says the pair does not serve yet and exits 1; it never says Done. - Before the Start step starts anything for serving through Darkbloom, a Mac without a Darkbloom login is named, with **Log in on this Mac** (or **Check again** after `darkbloom login` on the other Mac) and **Serve locally only**. - The cluster's status line for such a pair says `Serving () through Darkbloom on both Macs.` only while it serves, else ` is not serving yet: .` with what to do. -- The leader's last lines now give the test response first, then what serves. +- The Start step now says loading takes a few minutes for a large model, and on a color terminal shows the wait and one live row per Mac with the time since loading began (no bar or percent: no load fraction is reported). +- The setup now ends with its outcome as its own block between two rules: `✓ Serving through Darkbloom on both Macs ()` or `✓ Serving on this Mac's local API only`, with the API and the test response under it, or `✗ Not serving: .` with the next step. `darkbloom cluster` on the other Mac shows the same block once the cluster has an outcome; the line that ends its setup says the leader's screen shows it. +- A Mac Apple has not verified yet is named with when Darkbloom retries by itself, from that Mac's local App Attest key-generation safeguard ("… retries by itself at about 00:34. Don't restart either Mac until then."), or "within minutes" when that is unknown. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 578d638884..880bcfa91d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -268,7 +268,12 @@ the member's App Attest authorization and this Mac's Darkbloom login does not serve, the restart after the registration included, ends on its reason (`ClusterOnboardingNotServing`, `OnboardingLive.pairLook`) and the driver's choices (`ClusterOnboardingDriver.finishStart`); it never says Done. A Mac -without a login is named before the Start step (`ClusterOnboardingDriver.checkLogins`). +without a login is named before the Start step (`ClusterOnboardingDriver.checkLogins`). The +Start step opens with `ClusterOnboardingDriver.startNotice`; the waits draw one live row per Mac +(`ClusterOnboardingLoadRows`, `ClusterOnboardingConsole.workingRows`), and the setup ends with the +outcome block (`ClusterOnboardingConsole.result`, `ClusterOnboardingReady.outcome`). A member's +missing App Attest names its local key-generation safeguard's end (`ClusterServiceStatus.Child.appAttestRetryAt`, +read from the daemon state's `AppAttestKeyState.generationBlockedUntil`). How the approval is fetched, matched, checked on each Mac and saved: [coordinator-paired member](../reference/configuration.md#coordinator-paired-member). diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index a154a27519..179cf80658 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -251,7 +251,7 @@ request answered. Otherwise its line names why | Line | What to do | |---|---| | `… isn't logged in to Darkbloom, so the coordinator won't pair it` | `darkbloom login` on the Mac named, then **Retry**; or **Serve locally only**. | -| `Darkbloom hasn't verified for private serving yet (App Attest)` | Keep both Macs logged in and Darkbloom running; the coordinator pairs only members with a current App Attest authorization. **Retry** after a few minutes, or **Serve locally only**. | +| ` isn't verified by Apple yet; Darkbloom retries by itself at about