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`). diff --git a/libs/darkbloom-cluster/Tests/PreludeChecks/main.swift b/libs/darkbloom-cluster/Tests/PreludeChecks/main.swift index 79d3edd8cd..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) } } @@ -66,7 +69,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 +315,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..1badee5499 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,12 @@ 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 errno == EWOULDBLOCK || errno == EINTR, + 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 +208,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..f4c1c7e1b6 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift @@ -198,12 +198,20 @@ public struct ClusterSetupStore: Sendable { return value } - /// Applies `change` to the record as it is on disk now and writes the result. + /// 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. + public static let recordLockWaitSeconds: Double = 2 + + /// 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) { current in + try ClusterConfigurationFiles.update(paths.record, maximum: ClusterSetupRecord.maximumBytes, + 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 89ee9edf28..92f9669193 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRecoveryTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServiceRecoveryTests.swift @@ -348,6 +348,40 @@ 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) + 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)") + 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) } + 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) }