diff --git a/changelog.d/cluster-leader-local-api-beside-darkbloom.md b/changelog.d/cluster-leader-local-api-beside-darkbloom.md
new file mode 100644
index 0000000000..393ac91b52
--- /dev/null
+++ b/changelog.d/cluster-leader-local-api-beside-darkbloom.md
@@ -0,0 +1,7 @@
+### A pair's leader can take its owner's local requests beside Darkbloom
+
+- The member that hosts a pair's slot can now run the local OpenAI-compatible API while the pair serves through Darkbloom. Local and Darkbloom requests share the pair's one engine and its lanes: no second process or engine, and no extra copy of the stream. No command starts it yet: `darkbloom start --cluster-member` still refuses `--local-endpoint`, and `darkbloom cluster` keeps serving a pair through Darkbloom with no local API.
+- Only that member runs it, and always with a key. Any other member still refuses a local API.
+- While the pair isn't serving (it is forming, re-forming or stopped), a local request gets 503, as `darkbloom cluster local` answers, instead of a 500. A model the pair doesn't serve gets 404.
+- When every lane is busy, a local request waits its turn in a bounded queue, as on `darkbloom cluster local` (`DARKBLOOM_CLUSTER_QUEUE_WAITING`, default 64): 429 when the queue is full, 503 when it waited too long. A waiting request is woken when a lane frees and is never polled; Darkbloom requests never wait for it.
+- A local request that arrives while the pair runs its first test request waits until the pair opens, and gets 503 if the pair stops instead.
diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md
index d2c6189761..6076ad7334 100644
--- a/docs/architecture/inference.md
+++ b/docs/architecture/inference.md
@@ -1,6 +1,6 @@
# Provider inference engine
-> Last updated: 2026-11-06
+> Last updated: 2026-11-07
How a chat-completion request is served inside the `darkbloom` provider
process: one in-process engine (`mlx-swift-lm`
@@ -7522,6 +7522,66 @@ candidate choice),
`provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledFiles.swift`,
`provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledNativeStart.swift`.
+## The pair's leader takes local requests beside Darkbloom
+
+The member that hosts a pair's slot (`ProviderLoop.hostsClusterPairSlot`, the
+serving host role a rank-0 installation gives through
+`installClusterPairServing`) can serve that slot on its unified local API while
+the pair serves through Darkbloom
+([direct mode](../provider/direct-mode.md#a-pairs-leader-beside-darkbloom)).
+Local requests reach the slot's one bridge, the one Darkbloom requests reach, so
+both share the pair's lanes (`ClusterPairSlotOwner.concurrentRequests`), its
+capacity report and its admission. Nothing is loaded, no session forms and no
+device lock is taken
+(`provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairLocal.swift`).
+
+```mermaid
+flowchart LR
+ L["Local request"] --> S{"Slot live?"}
+ S -- "no" --> N["503"]
+ S -- "yes" --> F{"Admission open,
a lane free,
nobody waiting?"}
+ F -- "yes" --> B["The slot's bridge"]
+ F -- "no" --> Q["FIFO queue
(parked)"]
+ Q -- "woken" --> F
+ Q -- "full / ceiling / retired" --> E["429 / 503"]
+ D["Darkbloom request"] --> B
+```
+
+1. Only the slot's host runs a local API, and only with a key; any other member
+ refuses one at startup (`ProviderLoop.prepareClusterMemberControl`,
+ `admitsClusterPairLocalAPI`).
+2. A local request takes a lane only while fewer requests hold the pair's lanes
+ than it has: local ones granted here (`ClusterPairLocalLanes.lanesHeld`) and
+ Darkbloom ones accepted (`requestToModel`), with the engine's own count
+ below the lanes too, read without waiting for its queue
+ (`grantClusterPairLaneIfFree`, `EngineV2Bridge.capacitySnapshot`). The drain
+ check and the reservation (`localReservations`) have no suspension between
+ them, so a drain counts every granted local request.
+3. Waiters are parked continuations (`ClusterPairLocalLanes.park`), never
+ polled. A released local lane (`releaseClusterPairLane`), each Darkbloom
+ request's end and the periodic capacity refresh (`refreshClusterPairCapacity`
+ calls `wakeClusterPairLocalWaiters`), admission opening, a drain beginning
+ (`beginServingDrain`) and retirement wake them; cancellation and the
+ queue's ceiling refuse them. A reset connection cancels its request at
+ once; a connection closed normally is seen only at the request's first
+ write, after its turn (`LocalHTTPConnectionCancellationRegistry`), as on
+ `cluster local`.
+4. Local admission opens only once the warmup canary passed
+ (`clusterPairAdmissionOpenSlotID`, set in `publishClusterPairSlot`) and
+ closes when retirement starts (`retireClusterPairSlot`).
+5. A Darkbloom request never waits for this queue; its path through the pair
+ is unchanged.
+6. The owner-pause hook `noteClusterPairLocalUse` brackets each local request
+ once: from when it starts waiting for a lane, or takes one, until it leaves
+ without one or its lane is released.
+7. Nothing keys on two ranks: the host is a serving role, not a rank, and the
+ pair engine takes any identity of two or more distinct peers
+ (`DistributedResidentIdentity.validate`). That check is only the shape of
+ the roster the provider expects: a repeated peer is still refused, and an
+ impostor still is too, because the engine serves only an owner whose
+ readiness equals that identity, peer for peer (`DistributedCBv2Engine`).
+ Every roster formed today is still two distinct peers.
+
## Cluster pair capability honesty
A pair advertises what its placed mode serves, not what the artifact's
diff --git a/docs/provider/direct-mode.md b/docs/provider/direct-mode.md
index aa06da80c9..b1561b6734 100644
--- a/docs/provider/direct-mode.md
+++ b/docs/provider/direct-mode.md
@@ -1,6 +1,6 @@
# Direct mode: a local OpenAI-compatible endpoint
-> Last updated: 2026-11-06
+> Last updated: 2026-11-07
Run the provider's inference engine as an OpenAI-compatible HTTP server on your
own Mac, either standalone (`darkbloom start --local`, no coordinator, no
@@ -335,6 +335,43 @@ If a short burst drains before planning finishes, the host may retain the metada
The replacement must preserve the exact model and request limits and must fit both Macs. If a wider mode cannot start, a fresh previous-mode session may be restored after the failed replacement releases. Missing release proof stops the transition; it is never treated as free memory. The HTTP API gains no mode-selection parameter or credential change from this mechanism.
+### A pair's leader beside Darkbloom
+
+The member that hosts a pair's slot while the pair serves through Darkbloom
+(the coordinator-paired part on the plan's rank 0 Mac) can run this local API
+too. It serves the published slot through the slot's own bridge and lanes, so
+local and Darkbloom requests share one engine: no second process, engine or
+copy of the stream (`provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairLocal.swift`,
+`acquireClusterPairForLocal`). No command starts it yet:
+`darkbloom start --cluster-member` still refuses `--local-endpoint`, and
+`darkbloom cluster` serves a pair through Darkbloom with
+[no local API](./two-mac-cluster.md).
+
+| Case | Answer | Source |
+|---|---|---|
+| A member that does not host the slot, or a local API without a key | The member refuses to start (`ClusterMemberControlError.incompatibleConfiguration`), as before | `ProviderLoop.prepareClusterMemberControl`, `admitsClusterPairLocalAPI` |
+| The pair is not serving (forming, re-forming, retired) | HTTP `503`, as `darkbloom cluster local` answers (`DistributedRequestQueue.unavailableMessage`) | `ProviderLoop.clusterPairNotServing` |
+| A model the pair does not serve | HTTP `404` | `acquireClusterPairForLocal` |
+| Every lane busy | Waits in arrival order with at most `DARKBLOOM_CLUSTER_QUEUE_WAITING` (default `64`) others; `429` when the queue is full; `503` after waiting longer than `requestTimeout * ((waiting + lanes) / lanes)` (`DistributedRequestQueue.Limits.waitCeiling`); a cancelled request or a reset connection leaves the queue at once, a connection closed normally only at its turn (below) | `ClusterPairLocalLanes` |
+| The pair's warm-up request is running | Waits until admission opens; `503` if the slot retires instead | `ProviderLoop.publishClusterPairSlot` |
+| A stop or an update drain | Waiting requests get `429` at once, as new ones do; running ones finish before the slot retires | `ProviderLoop.beginServingDrain` |
+| A lost rank | Waiting requests get `503`; running ones end with their terminal | `ProviderLoop.retireClusterPairSlot` |
+
+A waiting request costs nothing: it is parked, not polled, until a local
+request releases a lane, a Darkbloom request ends (the capacity refresh that
+follows it), admission opens, a drain begins or the slot retires. A request
+that finds a lane free and nobody waiting takes it at once. Darkbloom requests
+never wait for this queue, and their path through the pair is unchanged.
+
+A client that closes its connection normally while it waits, as curl and
+URLSession do when they give up, keeps its place in the queue until its turn,
+then reaches the pair, the same as on `darkbloom cluster local`. Only a
+cancelled request or a reset connection frees the place at once. The close is
+noticed at the request's first write, which ends the request and frees its
+lane: that bounds the waste to its turn, up to its first write. A stream
+writes as its answer starts; an answer sent whole is written when it is done
+(`provider-swift/Sources/ProviderCore/Server/LocalHTTPConnectionCancellation.swift`).
+
### Speed records of cluster requests
A cluster endpoint records how fast each request ran that computed its whole
diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/DistributedResidentExecution.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/DistributedResidentExecution.swift
index 5480172bce..41598b5de7 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Distributed/DistributedResidentExecution.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/DistributedResidentExecution.swift
@@ -2,7 +2,7 @@ import Foundation
import DarkbloomClusterProtocol
import MLXLMCommon
-/// Experimental identity reported by an owner after both peer loads finish.
+/// Experimental identity reported by an owner after every peer's load finished.
/// These are backend assertions, not remote attestation or hardware qualification.
public struct DistributedResidentIdentity: Sendable, Equatable {
public struct Peer: Sendable, Equatable {
@@ -38,11 +38,20 @@ public struct DistributedResidentIdentity: Sendable, Equatable {
(48...57).contains($0) || (97...102).contains($0)
}
}
+ // Two ranks or more, each named once: nothing here keys on a pair of two.
+ // This checks only the shape of the roster the provider expects, never a
+ // peer's claim. A repeated peer is refused at any size (for two, the same
+ // test as `peers[0].id != peers[1].id`); an impostor or any other roster
+ // is refused because the engine serves only an owner whose readiness
+ // equals this identity, peer for peer, and the owner checks it again on
+ // every reservation. Every roster formed today is still two distinct
+ // peers (`ClusterConfiguration`, `NativePairMemberInstallation`, each
+ // worker's readiness in `ClusterWorkerValidation`).
guard !modelID.isEmpty, modelID.utf8.count <= 512,
digest(artifactSHA256), digest(configurationSHA256),
- peers.count == 2, peers[0].id != peers[1].id,
+ peers.count >= 2, Set(peers.map(\.id)).count == peers.count,
peers.allSatisfy({ !$0.id.isEmpty && $0.id.utf8.count <= 128 && digest($0.buildSHA256) })
- else { throw DistributedEngineError.invalidConfiguration("invalid two-peer identity") }
+ else { throw DistributedEngineError.invalidConfiguration("invalid peer identity") }
}
}
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterMember.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterMember.swift
index 1bf663f810..d523b4b2c4 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterMember.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterMember.swift
@@ -5,8 +5,10 @@ extension ProviderLoop {
/// Called before any solo subsystem can start. No model, GPU probe, cache
/// maintenance, update/relaunch, capacity monitor or device lease is started.
+ /// Only the member that hosts its pair's slot may run a local API
+ /// (`ProviderLoop+ClusterPairLocal`).
internal func prepareClusterMemberControl() throws {
- guard loopConfig.localEndpoint == nil, modelSlots.isEmpty,
+ guard loopConfig.localEndpoint.map({ admitsClusterPairLocalAPI($0) }) ?? true, modelSlots.isEmpty,
modelsLoading.isEmpty, preloadTasks.isEmpty else {
throw ClusterMemberControlError.incompatibleConfiguration
}
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairLocal.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairLocal.swift
new file mode 100644
index 0000000000..3e6ab787b5
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairLocal.swift
@@ -0,0 +1,293 @@
+import Foundation
+
+// The pair's leader takes the owner's local requests beside Darkbloom.
+//
+// The leader member's unified local endpoint (`ProviderLoop+LocalEndpoint`)
+// serves the published pair slot: local and Darkbloom requests share its one
+// bridge and its lanes. No process, copy or buffer is added. What holds:
+//
+// - Only the member that hosts the slot runs a local API, and only with a key
+// (`admitsClusterPairLocalAPI`). Every other member refuses one before
+// `run()` binds anything.
+// - A local request that finds every lane busy waits in arrival order,
+// bounded as `cluster local`'s queue is (`DistributedRequestQueue`): 429 when
+// the queue is full, 503 past its ceiling. Nobody overtakes a waiter.
+// - A waiter costs nothing: it is parked until something that can free a lane
+// or refuse it wakes it (a local request released one, the capacity refresh
+// that follows every Darkbloom request's end, admission opening after the
+// warmup canary, a drain, the slot retiring), its request is cancelled (a
+// reset connection cancels it; one closed normally is seen only at the
+// request's first write, after its turn, as on `cluster local`) or its
+// ceiling passes. Nothing polls.
+// - Darkbloom requests never enter this queue, and their path through the slot
+// is unchanged. Their side only calls `wakeClusterPairLocalWaiters`, which
+// does nothing while nobody waits.
+
+/// The owner's use of the pair through this Mac's local API began or ended.
+enum ClusterPairLocalUse { case began, ended }
+
+/// The leader's local requests on its pair's lanes: those waiting, oldest
+/// first, and the lanes the others hold, per published slot. Owned by the
+/// loop actor; every method is synchronous. The queue is bounded
+/// (`enqueue`) and first in, first out: only the request `isNext` may take a
+/// free lane.
+struct ClusterPairLocalLanes {
+ /// Fixed when the loop is made (`DARKBLOOM_CLUSTER_QUEUE_WAITING`).
+ let limits: DistributedRequestQueue.Limits
+ private var waiting: [UUID] = []
+ private var parked: [UUID: CheckedContinuation] = [:]
+ /// Woken while checking rather than parked: it checks again first.
+ private var woken: Set = []
+ /// Refused while checking rather than parked: it throws instead of parking.
+ private var refusals: [UUID: any Error] = [:]
+ /// Each lane a local request holds, and the slot it was taken on.
+ private var grants: [UUID: UUID] = [:]
+ /// Local requests waiting for a lane or holding one: the owner's use.
+ private(set) var inUse = 0
+
+ init(limits: DistributedRequestQueue.Limits) { self.limits = limits }
+
+ var waitingCount: Int { waiting.count }
+ private func isFirst(_ ticket: UUID) -> Bool { waiting.first == ticket }
+ func lanesHeld(on slot: UUID) -> Int { grants.values.reduce(0) { $1 == slot ? $0 + 1 : $0 } }
+
+ /// Whether a request may take a free lane now: the first waiter, or one
+ /// not queued (nil) while nobody waits, so it never overtakes a waiter.
+ func isNext(_ ticket: UUID?) -> Bool {
+ guard let ticket else { return waiting.isEmpty }
+ return isFirst(ticket)
+ }
+
+ /// A place at the back of the queue, or 429 when it is full.
+ mutating func enqueue() throws -> UUID {
+ guard waiting.count < limits.maximumWaiting else {
+ throw MultiModelBatchSchedulerEngineError.queueFull(DistributedRequestQueue.fullMessage)
+ }
+ let ticket = UUID()
+ waiting.append(ticket)
+ return ticket
+ }
+
+ /// Parks a waiter until it is woken or refused; one that was either
+ /// since its last check resumes at once.
+ mutating func park(_ ticket: UUID, _ continuation: CheckedContinuation) {
+ if let refusal = refusals.removeValue(forKey: ticket) {
+ continuation.resume(throwing: refusal)
+ } else if woken.remove(ticket) != nil {
+ continuation.resume()
+ } else {
+ parked[ticket] = continuation
+ }
+ }
+
+ /// A lane may be free: the first waiter checks.
+ mutating func wakeFirst() {
+ if let first = waiting.first { wake(first) }
+ }
+
+ /// Waiters may be refused (the slot retires, the provider drains): each checks.
+ mutating func wakeAll() {
+ for ticket in waiting { wake(ticket) }
+ }
+
+ private mutating func wake(_ ticket: UUID) {
+ if let continuation = parked.removeValue(forKey: ticket) { continuation.resume() } else { woken.insert(ticket) }
+ }
+
+ /// Refuses one waiter: its ceiling passed, or its request was cancelled.
+ mutating func refuse(_ ticket: UUID, _ error: any Error) {
+ guard waiting.contains(ticket) else { return }
+ if let continuation = parked.removeValue(forKey: ticket) {
+ continuation.resume(throwing: error)
+ } else {
+ refusals[ticket] = error
+ }
+ }
+
+ /// The waiter left, with a lane or without: if it was first, the next checks.
+ mutating func leave(_ ticket: UUID) {
+ let wasFirst = isFirst(ticket)
+ waiting.removeAll { $0 == ticket }
+ woken.remove(ticket)
+ refusals.removeValue(forKey: ticket)
+ if wasFirst { wakeFirst() }
+ }
+
+ mutating func grant(on slot: UUID) -> UUID {
+ let grant = UUID()
+ grants[grant] = slot
+ return grant
+ }
+
+ mutating func release(_ grant: UUID) { grants.removeValue(forKey: grant) }
+
+ mutating func note(_ use: ClusterPairLocalUse) {
+ inUse = use == .began ? inUse + 1 : max(0, inUse - 1)
+ }
+}
+
+extension ProviderLoop {
+ /// Whether this member hosts its pair's slot: the serving host role only
+ /// a rank-0 installation gives (`installClusterPairServing`, before
+ /// `run()`), whatever the number of ranks.
+ var hostsClusterPairSlot: Bool { clusterPairServing != nil }
+
+ /// A member runs a local API only where its pair's slot is, and always
+ /// with a key, as `cluster local` does. `prepareClusterMemberControl` asks
+ /// first thing in `run()`, before the endpoint binds: any other member
+ /// refuses to start with one.
+ func admitsClusterPairLocalAPI(_ endpoint: LocalInferenceHTTPConfig) -> Bool {
+ hostsClusterPairSlot && !(endpoint.authToken ?? "").isEmpty
+ }
+
+ /// The owner-pause hook (me first): the owner's use of the pair begins
+ /// when a local request starts waiting for a lane, or takes one at once,
+ /// before it can wait behind Darkbloom work, and ends exactly once: when
+ /// it leaves without a lane, or when its lane is released.
+ func noteClusterPairLocalUse(_ use: ClusterPairLocalUse) {
+ clusterPairLocalLanes.note(use)
+ }
+
+ /// The pair's refusal while it does not serve (forming, re-forming,
+ /// retired): 503, as `cluster local` answers, so a client retries later
+ /// or goes elsewhere.
+ static var clusterPairNotServing: MultiModelBatchSchedulerEngineError {
+ .requestRejected(DistributedRequestQueue.unavailableMessage)
+ }
+
+ /// A local request on the leader: 404 for a model this member does not
+ /// serve, the drain's refusal as on a single Mac, 503 while the pair does
+ /// not serve, otherwise one of the pair's lanes (`takeClusterPairLane`).
+ /// The owner's use begins once the request is past those refusals.
+ func acquireClusterPairForLocal(_ modelID: String) async throws -> MultiModelBatchSchedulerEngine.AcquiredModel {
+ guard advertisedModels[modelID] != nil else { throw MultiModelBatchSchedulerEngineError.modelNotLoaded(modelID) }
+ try throwIfRefusingNewLocalWork(modelId: modelID)
+ guard let handle = clusterPairSlot, handle.modelID == modelID, clusterPairSlotServes(modelID) else {
+ throw Self.clusterPairNotServing
+ }
+ noteClusterPairLocalUse(.began)
+ do {
+ return try await takeClusterPairLane(handle)
+ } catch {
+ noteClusterPairLocalUse(.ended)
+ throw error
+ }
+ }
+
+ /// The request's lane: taken at once when one is free and nobody waits,
+ /// otherwise in its place in the queue, until its ceiling. Every wake
+ /// checks the slot, the drain and the lanes again before parking again.
+ private func takeClusterPairLane(_ handle: ClusterPairSlotHandle) async throws
+ -> MultiModelBatchSchedulerEngine.AcquiredModel {
+ if let acquired = try await grantClusterPairLaneIfFree(handle, ticket: nil) { return acquired }
+ let ticket = try clusterPairLocalLanes.enqueue()
+ let ceiling = clusterPairLocalLanes.limits.waitCeiling(requestTimeout: handle.requestTimeout, lanes: handle.lanes)
+ let expiry = Task { [weak self] in
+ do { try await Task.sleep(for: ceiling) } catch { return }
+ await self?.refuseClusterPairWaiter(ticket,
+ MultiModelBatchSchedulerEngineError.requestRejected(DistributedRequestQueue.waitedTooLongMessage))
+ }
+ defer {
+ expiry.cancel()
+ clusterPairLocalLanes.leave(ticket)
+ }
+ while true {
+ try Task.checkCancellation()
+ guard clusterPairSlotStillServes(handle) else { throw Self.clusterPairNotServing }
+ try throwIfRefusingNewLocalWork(modelId: handle.modelID)
+ if let acquired = try await grantClusterPairLaneIfFree(handle, ticket: ticket) { return acquired }
+ try await parkClusterPairWaiter(ticket)
+ }
+ }
+
+ /// Parks a waiter until it is woken (it then checks again) or refused (its
+ /// ceiling passed, or its request was cancelled).
+ private func parkClusterPairWaiter(_ ticket: UUID) async throws {
+ try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in
+ clusterPairLocalLanes.park(ticket, continuation)
+ }
+ } onCancel: {
+ Task { await self.refuseClusterPairWaiter(ticket, CancellationError()) }
+ }
+ }
+
+ /// A lane for this request when it is next and a lane is free, nil
+ /// otherwise. Free means both counts are below the pair's lanes: this
+ /// Mac's (`clusterPairLaneFreeHere`) and the engine's own. Every check is
+ /// made again after the engine's answer, and from there to the reservation
+ /// nothing suspends, so a drain or retirement either refuses this request
+ /// or counts it (`hasInflightWork`).
+ private func grantClusterPairLaneIfFree(_ handle: ClusterPairSlotHandle, ticket: UUID?) async throws
+ -> MultiModelBatchSchedulerEngine.AcquiredModel? {
+ guard clusterPairLocalLanes.isNext(ticket), clusterPairLaneFreeHere(handle),
+ let bridge = modelSlots[handle.modelID]?.engineV2 else { return nil }
+ // The engine's own count, read without waiting for its queue: a
+ // request that ended here may still be retiring there.
+ let engine = await bridge.capacitySnapshot()
+ guard engine.activeRequests + engine.waitingRequests < handle.lanes,
+ clusterPairLocalLanes.isNext(ticket), clusterPairLaneFreeHere(handle),
+ let slot = modelSlots[handle.modelID] else { return nil }
+ try throwIfRefusingNewLocalWork(modelId: handle.modelID)
+ let grant = clusterPairLocalLanes.grant(on: handle.id)
+ localReservations.reserve(handle.modelID)
+ modelSlots[handle.modelID]?.lastInferenceAt = .now
+ let release: @Sendable (String) async -> Void = { [weak self] model in
+ await self?.releaseClusterPairLane(grant, model: model)
+ }
+ // The pair's tokenizer and bridge, as `cluster local` hands them out: no
+ // container and no vision gate (the ranks hold the model).
+ return .init(tokenizer: slot.tokenizer,
+ releaseToken: OneShotRelease(release: release, modelId: handle.modelID),
+ modelType: slot.modelType, container: nil, isVLM: false, engineV2Bridge: slot.engineV2, visionGate: nil,
+ queueExitedAt: ticket == nil ? nil : .now)
+ }
+
+ /// Whether `handle` is still the published slot and serves now: a request
+ /// bound to it on arrival gets 503 once it does not.
+ private func clusterPairSlotStillServes(_ handle: ClusterPairSlotHandle) -> Bool {
+ clusterPairSlot === handle && clusterPairSlotServes(handle.modelID)
+ }
+
+ /// The slot still serves, its admission opened, and fewer requests hold
+ /// its lanes than it has: local ones taken here and the Darkbloom ones
+ /// this member accepted.
+ private func clusterPairLaneFreeHere(_ handle: ClusterPairSlotHandle) -> Bool {
+ guard clusterPairAdmissionOpenSlotID == handle.id, clusterPairSlotStillServes(handle) else { return false }
+ let darkbloom = requestToModel.reduce(0) { held, entry in
+ entry.value == handle.modelID && !entry.key.hasPrefix(Self.engineV2RecoveryPinPrefix) ? held + 1 : held
+ }
+ return clusterPairLocalLanes.lanesHeld(on: handle.id) + darkbloom < handle.lanes
+ }
+
+ /// The pair's own release, kept apart from a single Mac's
+ /// (`releaseLocalReservation`): here the owner's use ends, once, and the
+ /// first waiter checks the lane just freed.
+ private func releaseClusterPairLane(_ grant: UUID, model: String) {
+ clusterPairLocalLanes.release(grant)
+ localReservations.release(model)
+ modelSlots[model]?.lastInferenceAt = .now
+ noteClusterPairLocalUse(.ended)
+ clusterPairLocalLanes.wakeFirst()
+ }
+
+ private func refuseClusterPairWaiter(_ ticket: UUID, _ error: any Error) {
+ clusterPairLocalLanes.refuse(ticket, error)
+ }
+
+ /// Something that can free a lane or refuse the waiters happened: the
+ /// first waiter checks, or every waiter when they are to be refused.
+ /// The Darkbloom side calls this too (each request's end through
+ /// `refreshClusterPairCapacity`, and `beginServingDrain` on every Mac):
+ /// while nobody waits it is one count check, so their path costs nothing
+ /// more.
+ func wakeClusterPairLocalWaiters() {
+ guard clusterPairLocalLanes.waitingCount > 0 else { return }
+ let serving = clusterPairSlot.map { clusterPairSlotServes($0.modelID) } ?? false
+ if !serving || isDraining || isShuttingDown {
+ clusterPairLocalLanes.wakeAll()
+ } else {
+ clusterPairLocalLanes.wakeFirst()
+ }
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift
index 1ff740ecb6..c4ae2b5611 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairSlot.swift
@@ -64,13 +64,19 @@ final class ClusterPairSlotHandle: @unchecked Sendable {
let tokenizer: TokenizerHandle
let sizing: SlotSizingSnapshot
let owner: ClusterPairSlotOwner
+ /// The profile's request lifetime, the unit of a queued local request's
+ /// ceiling (`DistributedRequestQueue.Limits.waitCeiling`).
+ let requestTimeout: Duration
let publishedAt = ContinuousClock.now
init(modelID: String, membershipEpoch: UUID, tokenizer: TokenizerHandle, sizing: SlotSizingSnapshot,
- owner: ClusterPairSlotOwner) {
+ owner: ClusterPairSlotOwner, requestTimeout: Duration) {
self.modelID = modelID; self.membershipEpoch = membershipEpoch; self.tokenizer = tokenizer
- self.sizing = sizing; self.owner = owner
+ self.sizing = sizing; self.owner = owner; self.requestTimeout = requestTimeout
}
+
+ /// The pair's batch lanes, which its engine admits at once.
+ var lanes: Int { max(1, owner.concurrentRequests) }
}
/// The execution owner as the slot's engine sees it, with one addition: the
@@ -206,7 +212,7 @@ extension ProviderLoop {
defaultMaxTokens: min(profile.maxOutputTokens, Self.schedulerDefaultMaxTokens))
let handle = ClusterPairSlotHandle(modelID: specification.publicModelID,
membershipEpoch: specification.expectedIdentity.membershipEpoch,
- tokenizer: specification.tokenizer, sizing: sizing, owner: owner)
+ tokenizer: specification.tokenizer, sizing: sizing, owner: owner, requestTimeout: profile.requestTimeout)
// No suspension since the checks above: publication is atomic on
// this actor with them.
try requireClusterPairPublication(specification.publicModelID)
@@ -237,7 +243,11 @@ extension ProviderLoop {
return id
}
}
+ // Admission opens, the coordinator's and the local API's alike: a
+ // local request made during the canary has waited for this.
+ clusterPairAdmissionOpenSlotID = handle.id
refreshClusterMemberAdmission()
+ wakeClusterPairLocalWaiters()
syncWarmModelState()
startClusterPairCapacityRefresh()
await refreshClusterPairCapacity()
@@ -280,6 +290,10 @@ extension ProviderLoop {
return false
}
modelsUnloading.insert(modelID)
+ // Local admission closes with the slot: its waiters hear 503 now; its
+ // local requests in flight drain below with the Darkbloom ones.
+ clusterPairAdmissionOpenSlotID = nil
+ wakeClusterPairLocalWaiters()
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))
@@ -348,6 +362,9 @@ extension ProviderLoop {
state.inferenceActive = summary.activeRequests > 0
scheduleEventHeartbeatIfMaterial()
writeDaemonState()
+ // Each Darkbloom request's end comes through here (`updateAggregateCapacity`),
+ // as does the periodic refresh: a lane may be free for a local waiter.
+ wakeClusterPairLocalWaiters()
}
/// A member runs no solo capacity monitor; while a pair slot is
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Lifecycle.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Lifecycle.swift
index 7ec03e4282..e9392d4e3c 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop+Lifecycle.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Lifecycle.swift
@@ -14,6 +14,8 @@ extension ProviderLoop {
}
localResponseTracker.setAccepting(false)
state.refusingNewWork = true
+ // A pair leader's waiting local requests hear the drain now.
+ wakeClusterPairLocalWaiters()
}
internal var lifecycleRemaining: Int {
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+LocalEndpoint.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+LocalEndpoint.swift
index bb527bb5de..7ef3a7aa44 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop+LocalEndpoint.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop+LocalEndpoint.swift
@@ -6,6 +6,7 @@
import CryptoKit
import Foundation
+import NIOCore
import MLX
import MLXLLM
import MLXLMCommon
@@ -57,8 +58,11 @@ extension ProviderLoop {
// could answer). If the bind fails, runService throws below and this
// never runs, so no stale/foreign discovery record is written.
responseTracker: localResponseTracker,
- onServerRunning: { [weak self] _ in
- await self?.onLocalEndpointBound(cfg)
+ onServerRunning: { [weak self] channel in
+ // The port actually bound: the configured one, or the one the
+ // system chose for port 0.
+ let bound = channel.localAddress?.port.flatMap { UInt16(exactly: $0) }
+ await self?.onLocalEndpointBound(cfg, port: bound ?? cfg.port)
},
modelTypeProvider: { [weak self] modelId in
await self?.localModelTypeForAudioAdmission(modelId)
@@ -96,11 +100,12 @@ extension ProviderLoop {
/// listening. Publishes the discovery record so `darkbloom local` /
/// local-first clients find the unified endpoint — only now that the bind is
/// CONFIRMED to be ours.
- private func onLocalEndpointBound(_ cfg: LocalInferenceHTTPConfig) {
- logger.info("Local OpenAI endpoint listening on \(cfg.host):\(cfg.port) (unified mode)")
+ private func onLocalEndpointBound(_ cfg: LocalInferenceHTTPConfig, port: UInt16) {
+ let mode = isClusterMember ? "the pair's leader, beside Darkbloom" : "unified mode"
+ logger.info("Local OpenAI endpoint listening on \(cfg.host):\(port) (\(mode))")
try? LocalEndpoint.writeInfo(LocalEndpoint.Info(
host: cfg.host,
- port: cfg.port,
+ port: port,
apiKey: cfg.authToken ?? "",
version: ProviderCore.version,
pid: ProcessInfo.processInfo.processIdentifier,
@@ -128,6 +133,8 @@ extension ProviderLoop {
throw MultiModelBatchSchedulerEngineError.requestRejected(
"\(modelId) is served only through chat completions")
}
+ // A pair's leader loads nothing: it serves its pair slot's lanes.
+ if isClusterMember { return try await acquireClusterPairForLocal(modelId) }
// Fast-path drain/shutdown reject; an authoritative re-check follows the
// `await` below, right before the reservation is taken (see comment there).
try throwIfRefusingNewLocalWork(modelId: modelId)
diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift
index 53c426f0ec..910f79d5bc 100644
--- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift
+++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift
@@ -773,6 +773,11 @@ public actor ProviderLoop {
/// 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?
+ /// The pair slot whose admission opened, once its warmup canary passed:
+ /// the leader's local requests wait for it (`ProviderLoop+ClusterPairLocal`).
+ internal var clusterPairAdmissionOpenSlotID: UUID?
+ /// The leader's local requests on its pair's lanes: waiting, or holding one.
+ internal var clusterPairLocalLanes = ClusterPairLocalLanes(limits: .fromEnvironment())
/// Rate cap + trailing-edge coalescing for event-triggered heartbeats
/// (routing v2, Phase 1). Driven from `updateAggregateCapacity()` — the
diff --git a/provider-swift/Sources/ProviderCore/Server/Distributed/DistributedLocalServer+HTTP.swift b/provider-swift/Sources/ProviderCore/Server/Distributed/DistributedLocalServer+HTTP.swift
index ebf1d03d55..1f145cc55f 100644
--- a/provider-swift/Sources/ProviderCore/Server/Distributed/DistributedLocalServer+HTTP.swift
+++ b/provider-swift/Sources/ProviderCore/Server/Distributed/DistributedLocalServer+HTTP.swift
@@ -54,7 +54,7 @@ extension DistributedLocalServer {
// The pipeline takes as many acquisitions as the pair has lanes; further
// requests wait in arrival order, in a bounded queue (`DistributedRequestQueue`).
guard acceptsPendingRequests else {
- throw MultiModelBatchSchedulerEngineError.requestRejected("Distributed session is unavailable")
+ throw MultiModelBatchSchedulerEngineError.requestRejected(DistributedRequestQueue.unavailableMessage)
}
if let response = DistributedHTTPResponseScope.current {
guard responses.owns(response), !response.unavailableBeforeAdmission else {
@@ -64,7 +64,7 @@ extension DistributedLocalServer {
let (target, id, queued) = try await waitForTurn()
guard let entry = target.entry else {
release(id, generation: target)
- throw MultiModelBatchSchedulerEngineError.requestRejected("Distributed session is unavailable")
+ throw MultiModelBatchSchedulerEngineError.requestRejected(DistributedRequestQueue.unavailableMessage)
}
return .init(tokenizer: entry.tokenizer,
releaseToken: OneShotRelease(release: { _ in await self.release(id, generation: target) }, modelId: modelID),
@@ -119,7 +119,7 @@ extension DistributedLocalServer {
throw CancellationError()
}
guard acceptsPendingRequests else {
- throw MultiModelBatchSchedulerEngineError.requestRejected("Distributed session is unavailable")
+ throw MultiModelBatchSchedulerEngineError.requestRejected(DistributedRequestQueue.unavailableMessage)
}
// Check the original absolute ceiling before every admission,
// including the first poll after a slow replacement load.
@@ -151,7 +151,7 @@ extension DistributedLocalServer {
throw MultiModelBatchSchedulerEngineError.modelNotLoaded(modelID)
}
guard acceptsPendingRequests, let stableTokenizer else {
- throw MultiModelBatchSchedulerEngineError.requestRejected("Distributed session is unavailable")
+ throw MultiModelBatchSchedulerEngineError.requestRejected(DistributedRequestQueue.unavailableMessage)
}
return stableTokenizer
}
diff --git a/provider-swift/Sources/ProviderCore/Server/Distributed/DistributedRequestQueue.swift b/provider-swift/Sources/ProviderCore/Server/Distributed/DistributedRequestQueue.swift
index 8bdb099d33..6b94aacb5c 100644
--- a/provider-swift/Sources/ProviderCore/Server/Distributed/DistributedRequestQueue.swift
+++ b/provider-swift/Sources/ProviderCore/Server/Distributed/DistributedRequestQueue.swift
@@ -25,6 +25,7 @@ enum DistributedRequestQueue {
static let waitingEnvironmentName = "DARKBLOOM_CLUSTER_QUEUE_WAITING"
static let fullMessage = "Distributed request queue full"
static let waitedTooLongMessage = "Distributed request waited too long in the queue"
+ static let unavailableMessage = "Distributed session is unavailable"
static let pollInterval: Duration = .milliseconds(10)
/// The queue's bounds for one local server, fixed when it starts.
diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairLocalTests.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairLocalTests.swift
new file mode 100644
index 0000000000..0a3828f2cb
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairLocalTests.swift
@@ -0,0 +1,633 @@
+import Foundation
+import Testing
+import MLXLMCommon
+@testable import ProviderCore
+
+// The pair's leader takes the owner's local requests beside Darkbloom. The
+// leader member's own local API serves its published pair slot: one bridge and
+// one set of lanes for local and Darkbloom requests. The pair's owner is
+// scripted (no process, model or GPU), the coordinator is `MockCoordinator` on
+// a loopback port and the local API binds port 0: these prove the leader's
+// admission, lanes and lifecycle, never a pair.
+
+private let pairLocalToken = "pair-local-fixture-token"
+
+/// The leader's local API in these tests: loopback, port 0, with the key.
+private let keyedLocalAPI = LocalInferenceHTTPConfig(host: "127.0.0.1", port: 0, authToken: pairLocalToken)
+
+private let leaderHardware = 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)
+
+/// A member loop that has not run yet, with or without a local API: whether
+/// it may keep one is the first thing `run()` decides
+/// (`prepareClusterMemberControl`).
+private func memberLoop(name: String, localEndpoint: LocalInferenceHTTPConfig?, model: String = clusterPairFixtureModel,
+ hardware: HardwareInfo = leaderHardware,
+ coordinatorURL: String = "ws://127.0.0.1:9/ws") throws -> ProviderLoop {
+ try ProviderLoop(
+ config: .init(coordinatorURL: coordinatorURL, hardware: hardware,
+ models: [.init(id: model, modelType: "qwen3_5", sizeBytes: 1, estimatedMemoryGb: 1)],
+ config: .init(provider: .init(name: name, autoUpdate: false), backend: .init(),
+ coordinator: .init(url: coordinatorURL, heartbeatIntervalSecs: 1)),
+ localEndpoint: localEndpoint, executionRole: .clusterMember),
+ attestationSigner: ServeLoopTestSigner())
+}
+
+/// The leader's serving context for `model`. These tests publish their slots
+/// themselves, so it never builds an owner.
+private func pairServingContext(_ model: String = clusterPairFixtureModel) throws -> ClusterPairServingContext {
+ try ClusterPairServingContext(publicModelID: model, modelType: "qwen3_5",
+ tokenizer: TokenizerHandle(DistributedTestTokenizer()), eosTokenIDs: [99], profile: distributedTestProfile(),
+ makeOwner: { _ in throw ClusterPairSlotError.notServing("these tests publish their own slots") })
+}
+
+/// Set when the work it marks has ended; read without waiting.
+private final class Finished: @unchecked Sendable {
+ private let lock = NSLock()
+ private var done = false
+ func set() { lock.withLock { done = true } }
+ var value: Bool { lock.withLock { done } }
+}
+
+/// A local acquisition in its own task, so a test can watch it wait.
+private struct PendingAcquisition {
+ let task: Task
+ let finished: Finished
+
+ init(_ loop: ProviderLoop, model: String = clusterPairFixtureModel) {
+ let finished = Finished()
+ self.finished = finished
+ task = Task {
+ defer { finished.set() }
+ return try await loop.acquireModelForLocal(model)
+ }
+ }
+}
+
+extension ProviderLoop {
+ /// The serving host role a rank-0 installation gives the leader member
+ /// (`installClusterPairServing`), without a two-rank installation: these
+ /// tests publish their slots themselves, with any roster.
+ func hostClusterPairSlotForTesting(model: String = clusterPairFixtureModel) throws {
+ clusterPairServing = try pairServingContext(model)
+ }
+
+ var clusterPairLocalWaitingCount: Int { clusterPairLocalLanes.waitingCount }
+
+ /// Local requests waiting for a lane, local requests in use (waiting or
+ /// holding a lane: the owner-pause hook) and local reservations.
+ var clusterPairLocalCounts: (waiting: Int, inUse: Int, reserved: Int) {
+ (clusterPairLocalLanes.waitingCount, clusterPairLocalLanes.inUse, localReservations.totalInFlight)
+ }
+
+ func setClusterPairLocalQueueForTesting(maximumWaiting: Int) {
+ clusterPairLocalLanes = .init(limits: .init(maximumWaiting: maximumWaiting))
+ }
+
+ /// Stops the periodic capacity refresh, one of the events that wakes waiters.
+ func stopClusterPairCapacityRefreshForTesting() {
+ clusterPairCapacityTask?.cancel()
+ clusterPairCapacityTask = nil
+ }
+}
+
+/// A leader member with no coordinator, the way `run()` prepares it, hosting its pair's slot.
+private func pairLeaderLoop(warmupTimeoutSeconds: Double? = nil) async throws -> ProviderLoop {
+ let loop = try await clusterPairMemberLoop(warmupTimeoutSeconds: warmupTimeoutSeconds)
+ try await loop.hostClusterPairSlotForTesting()
+ return loop
+}
+
+/// One local request on the pair's bridge, as the local API submits it.
+private func submitLocal(_ acquired: MultiModelBatchSchedulerEngine.AcquiredModel, id: String,
+ maxTokens: Int = 3) async throws -> AsyncStream {
+ let bridge = try #require(acquired.engineV2Bridge)
+ return await bridge.submitTokenized(promptTokens: [1, 2, 3],
+ request: ChatCompletionRequest(model: clusterPairFixtureModel, messages: [], temperature: 0, max_tokens: maxTokens),
+ requestId: id, cacheEnabled: false)
+}
+
+/// A stream's delivered text and terminals, read to its end.
+private func drain(_ stream: AsyncStream) async -> (text: String, terminals: [String]) {
+ var text = "", terminals: [String] = []
+ for await event in stream {
+ switch event {
+ case .logprobs: break
+ case .chunk(let chunk): text += chunk
+ case .info(_, let completion, _, let reason): terminals.append("\(completion):\(reason ?? "none")")
+ case .error(let message): terminals.append("error: \(message)")
+ case .terminal: terminals.append("terminal")
+ }
+ }
+ return (text, terminals)
+}
+
+/// The HTTP status a local refusal surfaces as.
+private func localStatus(_ error: Error) -> UInt16 { ProviderLoop.mapInferenceErrorToStatus(error) }
+
+/// A leader member's `run()` against a `MockCoordinator`, with or without its
+/// local API (127.0.0.1, port 0, a key). Its discovery record goes to a
+/// directory of its own (`DARKBLOOM_LOCAL_DIR`), restored only once the loop
+/// has stopped.
+private struct PairLeaderFixture {
+ let mock: MockCoordinator
+ let loop: ProviderLoop
+ let directory: URL
+ let localAPI: Bool
+ let previousLocalDirectory: String?
+
+ static func make(localAPI: Bool, warmupTimeoutSeconds: Double? = nil) async throws -> PairLeaderFixture {
+ let mock = MockCoordinator()
+ let url = try await mock.start().mockProviderWebSocketURL()
+ let directory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("cluster-pair-local-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let previous = ProcessInfo.processInfo.environment["DARKBLOOM_LOCAL_DIR"]
+ if localAPI { try #require(setenv("DARKBLOOM_LOCAL_DIR", directory.path, 1) == 0) }
+ let loop = try memberLoop(name: "cluster-pair-local", localEndpoint: localAPI ? keyedLocalAPI : nil,
+ coordinatorURL: url)
+ await loop.setEngineV2RuntimeForTesting(EngineV2Runtime())
+ await loop.setServeUsesHostServicesForTesting(false)
+ await loop.setDaemonStateFileForTesting(directory.appendingPathComponent("state.json"))
+ await loop.setClusterPairWarmupForTesting(timeoutSeconds: warmupTimeoutSeconds)
+ try await loop.hostClusterPairSlotForTesting()
+ return .init(mock: mock, loop: loop, directory: directory, localAPI: localAPI, previousLocalDirectory: previous)
+ }
+
+ func start() -> Task { Task { try await loop.run() } }
+
+ /// Registration and the member acceptance; returns the provider's public key.
+ func register() async throws -> String {
+ 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 try #require(registration.publicKey)
+ }
+
+ /// The local API's port, from its discovery record.
+ func localPort() async throws -> UInt16 {
+ #expect(await clusterPairWait { LocalEndpoint.readInfo() != nil })
+ let info = try #require(LocalEndpoint.readInfo())
+ #expect(info.port != 0 && info.apiKey == pairLocalToken && info.pid == ProcessInfo.processInfo.processIdentifier)
+ return info.port
+ }
+
+ func localChat(port: UInt16, stream: Bool = true, maxTokens: Int = 3) throws -> URLRequest {
+ var request = URLRequest(url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions")!)
+ request.httpMethod = "POST"; request.timeoutInterval = 20
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.setValue("Bearer \(pairLocalToken)", forHTTPHeaderField: "Authorization")
+ request.httpBody = try JSONSerialization.data(withJSONObject: [
+ "model": clusterPairFixtureModel, "messages": [["role": "user", "content": "local"]],
+ "max_tokens": maxTokens, "stream": stream, "temperature": 0, "reasoning_parser": "none"])
+ return request
+ }
+
+ func push(_ id: String, publicKey: 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: publicKey,
+ chatRequestJSON: body, consumerKeyPair: .generate())
+ }
+
+ func completed(_ id: String, timeout: Duration = .seconds(10)) async throws -> Bool {
+ try await mock.waitForSnapshot(timeout: timeout) { snapshot in
+ snapshot.inferenceComplete.contains { $0.requestId == id } || snapshot.inferenceErrors.contains { $0.requestId == id }
+ }.map { $0.inferenceErrors.allSatisfy { $0.requestId != id } } ?? false
+ }
+
+ func cleanUp(_ task: Task) async {
+ task.cancel()
+ _ = await ServeLoopFixture.finishes(task, within: .seconds(30))
+ await mock.shutdown()
+ if localAPI {
+ if let previousLocalDirectory { setenv("DARKBLOOM_LOCAL_DIR", previousLocalDirectory, 1) }
+ else { unsetenv("DARKBLOOM_LOCAL_DIR") }
+ }
+ try? FileManager.default.removeItem(at: directory)
+ }
+}
+
+@Suite("The pair's leader takes local requests beside Darkbloom", .serialized, .timeLimit(.minutes(2)))
+struct ClusterPairLocalTests {
+ /// The leader's local API serves the pair through the slot's own bridge:
+ /// a 503 before the pair serves (never a 500), then the stream, with the
+ /// local API's own cache partition and the discovery record of its port.
+ @Test func theLeaderServesItsPairOnItsLocalAPI() async throws {
+ let fixture = try await PairLeaderFixture.make(localAPI: true, warmupTimeoutSeconds: 30)
+ let task = fixture.start()
+ do {
+ _ = try await fixture.register()
+ let port = try await fixture.localPort()
+ // No pair yet: refused for now, with a reason, not a 500.
+ let (earlyBody, earlyReply) = try await URLSession.shared.data(for: try fixture.localChat(port: port))
+ #expect((earlyReply as? HTTPURLResponse)?.statusCode == 503, "\(String(decoding: earlyBody, as: UTF8.self))")
+ #expect(String(decoding: earlyBody, as: UTF8.self).contains("\"error\""))
+
+ let owner = ScriptedPairOwner()
+ try await fixture.loop.publishClusterPairSlot(clusterPairSpecification(owner), owner: owner)
+ #expect(await fixture.loop.clusterPairWarmup?.succeeded == true)
+ let (data, reply) = try await URLSession.shared.data(for: try fixture.localChat(port: port))
+ let body = String(decoding: data, as: UTF8.self)
+ #expect((reply as? HTTPURLResponse)?.statusCode == 200, "\(body)")
+ #expect(body.contains("t5") && body.contains("t7") && body.hasSuffix("data: [DONE]\n\n"), "\(body)")
+ // The warmup canary's reservation, then this request's: the pair's own owner served it.
+ #expect(owner.reserveCount == 2)
+ // The local API's partition: no tenant salt, never a coordinator scope.
+ let local = try #require(owner.reservedRequests.last)
+ #expect(local.cacheSalt == nil && local.prefixCacheEnabled)
+ #expect(await clusterPairWait { await fixture.loop.clusterPairLocalCounts == (0, 0, 0) })
+ } catch { await fixture.cleanUp(task); throw error }
+ await fixture.cleanUp(task)
+ }
+
+ /// Only the member that hosts the slot runs a local API, and always with a
+ /// key: the real rank-0 installation serves; rank 1, a member with no pair
+ /// installation and a host without a key refuse it at once.
+ @Test func onlyTheSlotsHostRunsALocalAPIAndAlwaysWithAKey() async throws {
+ // The contract fixture's installations are for "fixture-model" on an Apple M4.
+ let contract = try MemberContractFixture()
+ let context = try pairServingContext("fixture-model")
+ func member(_ endpoint: LocalInferenceHTTPConfig = keyedLocalAPI) throws -> ProviderLoop {
+ try memberLoop(name: "cluster-pair-local-host", localEndpoint: endpoint, model: "fixture-model",
+ hardware: HardwareInfo(machineModel: "fixture", chipName: "Apple M4", chipFamily: .m4, chipTier: .pro,
+ memoryGb: 24, memoryAvailableGb: 20, cpuCores: .init(total: 12, performance: 8, efficiency: 4),
+ gpuCores: 16, memoryBandwidthGbs: 200))
+ }
+
+ let leader = try member()
+ try await leader.installNativePairMember(contract.installations[0])
+ try await leader.installClusterPairServing(context)
+ try await leader.prepareClusterMemberControlForTesting()
+ #expect(await leader.state.refusingNewWork, "the leader stays a control-only member until its slot serves")
+
+ let follower = try member()
+ try await follower.installNativePairMember(contract.installations[1])
+ await #expect(throws: ClusterMemberControlError.incompatibleConfiguration) {
+ try await follower.prepareClusterMemberControlForTesting()
+ }
+ let uninstalled = try member()
+ await #expect(throws: ClusterMemberControlError.incompatibleConfiguration) {
+ try await uninstalled.prepareClusterMemberControlForTesting()
+ }
+ let keyless = try member(.init(host: "127.0.0.1", port: 0, authToken: nil))
+ try await keyless.installNativePairMember(contract.installations[0])
+ try await keyless.installClusterPairServing(context)
+ await #expect(throws: ClusterMemberControlError.incompatibleConfiguration) {
+ try await keyless.prepareClusterMemberControlForTesting()
+ }
+ }
+
+ /// While the pair does not serve (before its slot, after it retired), a
+ /// local request is refused for now: 503, never the member guard's
+ /// untyped error (a 500). Another model is not this pair's: 404. A refused
+ /// request never counts as the owner's use.
+ @Test func aLocalRequestWhileThePairIsNotServingIs503() async throws {
+ let loop = try await pairLeaderLoop()
+ func refusal(_ model: String = clusterPairFixtureModel) async -> Error? {
+ do { _ = try await loop.acquireModelForLocal(model); return nil } catch { return error }
+ }
+ let early = try #require(await refusal())
+ #expect(early is MultiModelBatchSchedulerEngineError && localStatus(early) == 503, "\(early)")
+ let other = try #require(await refusal("fixture/other"))
+ #expect(localStatus(other) == 404, "\(other)")
+
+ let owner = ScriptedPairOwner()
+ let id = try await loop.publishClusterPairSlot(clusterPairSpecification(owner), owner: owner)
+ let served = try await loop.acquireModelForLocal(clusterPairFixtureModel)
+ await served.releaseToken.fire()
+ #expect(await loop.retireClusterPairSlot(id, reason: "test"))
+ let late = try #require(await refusal())
+ #expect(late is MultiModelBatchSchedulerEngineError && localStatus(late) == 503, "\(late)")
+ #expect(await loop.clusterPairLocalCounts == (0, 0, 0))
+ }
+
+ /// One lane: a local request that finds it busy waits, without polling,
+ /// and takes it when the request holding it is released; later ones keep
+ /// their arrival order. The owner's use counts every waiting or running
+ /// local request and returns to zero.
+ @Test func aLocalRequestWaitsForALaneAndTakesItWhenItIsReleased() async throws {
+ let loop = try await pairLeaderLoop()
+ let owner = ScriptedPairOwner()
+ let hold = DispatchSemaphore(value: 0)
+ owner.hold = hold
+ try await loop.publishClusterPairSlot(clusterPairSpecification(owner), owner: owner)
+ let first = try await loop.acquireModelForLocal(clusterPairFixtureModel)
+ #expect(first.queueExitedAt == nil, "a free lane is taken at once, not through the queue")
+ let firstStream = try await submitLocal(first, id: "local-first")
+ #expect(await clusterPairWait { owner.reserveCount == 1 })
+
+ let second = PendingAcquisition(loop)
+ #expect(await clusterPairWait { await loop.clusterPairLocalWaitingCount == 1 })
+ let third = PendingAcquisition(loop)
+ #expect(await clusterPairWait { await loop.clusterPairLocalWaitingCount == 2 })
+ try await Task.sleep(for: .milliseconds(200))
+ #expect(!second.finished.value && !third.finished.value, "the lane is busy: both wait")
+ #expect(await loop.clusterPairLocalCounts == (2, 3, 1))
+
+ hold.signal()
+ #expect(await drain(firstStream).text == "t5t6t7")
+ await first.releaseToken.fire()
+ let secondAcquired = try await second.task.value
+ #expect(secondAcquired.queueExitedAt != nil, "its first-token budget starts when the queue lets it go")
+ try await Task.sleep(for: .milliseconds(100))
+ #expect(!third.finished.value, "the lane is the second's now: the third keeps waiting")
+ #expect(await loop.clusterPairLocalCounts == (1, 2, 1))
+
+ await secondAcquired.releaseToken.fire()
+ let thirdAcquired = try await third.task.value
+ #expect(await loop.clusterPairLocalCounts == (0, 1, 1))
+ await thirdAcquired.releaseToken.fire()
+ #expect(await loop.clusterPairLocalCounts == (0, 0, 0))
+ #expect(await loop.retireClusterPairSlot(reason: "test"))
+ }
+
+ /// The queue is bounded as `cluster local`'s is: a request that finds it
+ /// full is refused with 429, and one that waited past its ceiling with
+ /// 503. A cancelled waiter leaves at once from wherever it waits: the
+ /// second here, which nothing else wakes (the capacity refresh wakes only
+ /// the first).
+ @Test func aFullQueueIs429AWaiterPastItsCeilingIs503AndACancelledWaiterLeaves() async throws {
+ let loop = try await pairLeaderLoop()
+ await loop.setClusterPairLocalQueueForTesting(maximumWaiting: 2)
+ let owner = ScriptedPairOwner()
+ // A 500 ms request lifetime: with one lane and two waiting places, a
+ // waiter's ceiling is three lifetimes.
+ let profile = try DistributedResidentExecutionProfile(id: owner.profileID, vocabularySize: 100,
+ maxPromptTokens: 8192, maxOutputTokens: 128, maxContextTokens: 8192 + 128, requestTimeout: .milliseconds(500))
+ let specification = ClusterPairSlotSpecification(publicModelID: clusterPairFixtureModel, modelType: "qwen3_5",
+ tokenizer: TokenizerHandle(DistributedTestTokenizer()), eosTokenIDs: [99], expectedIdentity: owner.identity,
+ profile: profile, artifactBytes: 1 << 30)
+ try await loop.publishClusterPairSlot(specification, owner: owner)
+ let holder = try await loop.acquireModelForLocal(clusterPairFixtureModel)
+
+ let first = PendingAcquisition(loop)
+ #expect(await clusterPairWait { await loop.clusterPairLocalWaitingCount == 1 })
+ let second = PendingAcquisition(loop)
+ #expect(await clusterPairWait { await loop.clusterPairLocalWaitingCount == 2 })
+ do { _ = try await loop.acquireModelForLocal(clusterPairFixtureModel); Issue.record("a full queue admitted") }
+ catch { #expect(localStatus(error) == 429, "\(error)") }
+
+ second.task.cancel()
+ // Bounded either way: without its own wake, the second would leave only
+ // once the first's ceiling put it in front.
+ #expect(await clusterPairWait(.milliseconds(300)) { second.finished.value },
+ "a cancelled waiter behind another leaves at once")
+ await #expect(throws: CancellationError.self) { _ = try await second.task.value }
+ #expect(await loop.clusterPairLocalCounts == (1, 2, 1), "only the first still waits")
+
+ let started = ContinuousClock.now
+ do { _ = try await first.task.value; Issue.record("a waiter outlived its ceiling") }
+ catch { #expect(localStatus(error) == 503, "\(error)") }
+ #expect(ContinuousClock.now - started < .seconds(5))
+ #expect(await loop.clusterPairLocalCounts == (0, 1, 1))
+ await holder.releaseToken.fire()
+ #expect(await loop.clusterPairLocalCounts == (0, 0, 0))
+ // The lane is free again: taken at once.
+ let next = try await loop.acquireModelForLocal(clusterPairFixtureModel)
+ #expect(next.queueExitedAt == nil)
+ await next.releaseToken.fire()
+ }
+
+ /// Nothing slips in during the warmup canary: a local request made while
+ /// it runs waits until admission opens, and a pair that retires during
+ /// the canary refuses it with 503. Two lanes: the canary holds one and
+ /// leaves the other free, so only the admission gate keeps the request out
+ /// (with one lane, the engine's own count would keep it out anyway).
+ @Test func aLocalRequestDuringTheWarmupCanaryWaitsForAdmission() async throws {
+ let loop = try await pairLeaderLoop(warmupTimeoutSeconds: 30)
+ let owner = ScriptedPairOwner()
+ owner.lanes = 2
+ let hold = DispatchSemaphore(value: 0)
+ owner.hold = hold
+ let publication = Task { try await loop.publishClusterPairSlot(clusterPairSpecification(owner), owner: owner) }
+ #expect(await clusterPairWait { await loop.clusterPairSlotSnapshot.id != nil && owner.reserveCount == 1 })
+ let early = PendingAcquisition(loop)
+ #expect(await clusterPairWait { await loop.clusterPairLocalWaitingCount == 1 })
+ try await Task.sleep(for: .milliseconds(200))
+ #expect(!early.finished.value, "admission is closed while the canary runs")
+ #expect(await loop.clusterPairLocalCounts == (1, 1, 0), "no local request holds the lane the canary left free")
+ hold.signal()
+ _ = try await publication.value
+ #expect(await loop.clusterPairWarmup?.succeeded == true)
+ let admitted = try await early.task.value
+ #expect(admitted.queueExitedAt != nil && owner.reserveCount == 1)
+ await admitted.releaseToken.fire()
+ #expect(await loop.retireClusterPairSlot(reason: "test"))
+
+ // A rank lost during the canary retires the slot: the waiter hears 503.
+ let lost = ScriptedPairOwner()
+ let lostHold = DispatchSemaphore(value: 0)
+ lost.hold = lostHold
+ let failing = Task { try await loop.publishClusterPairSlot(clusterPairSpecification(lost), owner: lost) }
+ #expect(await clusterPairWait { await loop.clusterPairSlotSnapshot.id != nil && lost.reserveCount == 1 })
+ let refused = PendingAcquisition(loop)
+ #expect(await clusterPairWait { await loop.clusterPairLocalWaitingCount == 1 })
+ lost.losePeer()
+ lostHold.signal()
+ do { _ = try await refused.task.value; Issue.record("admitted into a retired pair") }
+ catch { #expect(localStatus(error) == 503, "\(error)") }
+ _ = try? await failing.value
+ #expect(await clusterPairWait { await loop.clusterPairSlotSnapshot.id == nil })
+ #expect(await loop.clusterPairLocalCounts == (0, 0, 0))
+ }
+
+ /// A drain (a stop or an update) refuses the waiting local requests at
+ /// once, as it refuses new ones, while the request holding the lane
+ /// finishes. The capacity refresh is off here: the drain alone wakes them.
+ @Test func aDrainRefusesWaitingLocalRequestsAtOnce() async throws {
+ let loop = try await pairLeaderLoop()
+ let owner = ScriptedPairOwner()
+ try await loop.publishClusterPairSlot(clusterPairSpecification(owner), owner: owner)
+ await loop.stopClusterPairCapacityRefreshForTesting()
+ let holder = try await loop.acquireModelForLocal(clusterPairFixtureModel)
+ let waiter = PendingAcquisition(loop)
+ #expect(await clusterPairWait { await loop.clusterPairLocalWaitingCount == 1 })
+ let started = ContinuousClock.now
+ await loop.beginServingDrain(owner: .lifecycle)
+ let refused = await clusterPairWait(.milliseconds(500)) { waiter.finished.value }
+ #expect(refused && ContinuousClock.now - started < .seconds(1), "the drain refuses the waiter itself")
+ if !refused { waiter.task.cancel() }
+ do { _ = try await waiter.task.value; Issue.record("a drain admitted a waiting request") }
+ catch { #expect(localStatus(error) == 429, "\(error)") }
+ #expect(await loop.clusterPairLocalCounts == (0, 1, 1))
+ await holder.releaseToken.fire()
+ #expect(await loop.clusterPairLocalCounts == (0, 0, 0))
+ }
+
+ /// A lost rank retires the slot: a queued local request hears 503 and the
+ /// one in flight ends with its terminal, never a hang.
+ @Test func retirementWhileQueuedIs503AndTheRequestInFlightEnds() async throws {
+ let loop = try await pairLeaderLoop()
+ let owner = ScriptedPairOwner()
+ let hold = DispatchSemaphore(value: 0)
+ owner.hold = hold
+ try await loop.publishClusterPairSlot(clusterPairSpecification(owner), owner: owner)
+ let running = try await loop.acquireModelForLocal(clusterPairFixtureModel)
+ let stream = try await submitLocal(running, id: "local-running")
+ #expect(await clusterPairWait { owner.reserveCount == 1 })
+ let queued = PendingAcquisition(loop)
+ #expect(await clusterPairWait { await loop.clusterPairLocalWaitingCount == 1 })
+
+ owner.losePeer()
+ do { _ = try await queued.task.value; Issue.record("a queued request outlived its pair") }
+ catch { #expect(localStatus(error) == 503, "\(error)") }
+ hold.signal()
+ let ended = await drain(stream)
+ #expect(ended.terminals.count == 1, "one terminal: \(ended.terminals)")
+ await running.releaseToken.fire()
+ #expect(await clusterPairWait { await loop.clusterPairSlotSnapshot.id == nil })
+ #expect(await loop.clusterPairLocalCounts == (0, 0, 0))
+ #expect(owner.shutdownCount == 1)
+ }
+
+ /// Nothing keys on two Macs: a pair of three ranks with three lanes serves
+ /// three local requests at once and queues the fourth; the two members
+ /// that do not host the slot refuse a local API. A roster still needs two
+ /// distinct ranks or more, and an impostor rank is still refused.
+ @Test func nothingKeysOnTwoRanks() async throws {
+ let epoch = UUID()
+ func identity(_ peers: [String]) -> DistributedResidentIdentity {
+ .init(membershipEpoch: epoch, modelID: clusterPairFixtureModel,
+ artifactSHA256: String(repeating: "a", count: 64), configurationSHA256: String(repeating: "b", count: 64),
+ peers: peers.enumerated().map { .init(id: $0.element, buildSHA256: String(repeating: "\($0.offset)", count: 64)) })
+ }
+ #expect(throws: DistributedEngineError.self) { try identity(["rank-0"]).validate() }
+ #expect(throws: DistributedEngineError.self) { try identity(["rank-0", "rank-0"]).validate() }
+ #expect(throws: DistributedEngineError.self) { try identity(["rank-0", "rank-1", "rank-0"]).validate() }
+ let roster = identity(["rank-0", "rank-1", "rank-2"])
+ // The engine serves only an owner whose readiness is the expected
+ // roster, peer for peer: one other rank in the third place is refused.
+ let impostor = ScriptedPairOwner(identity: identity(["rank-0", "rank-1", "rank-x"]))
+ #expect(throws: DistributedEngineError.unavailable) {
+ _ = try DistributedEngineFactory.makeBridge(owner: impostor, expectedIdentity: roster,
+ profile: try distributedTestProfile(), tokenizer: TokenizerHandle(DistributedTestTokenizer()), eosTokenIDs: [99])
+ }
+ let owner = ScriptedPairOwner(identity: roster)
+ owner.lanes = 3
+ let leader = try await pairLeaderLoop()
+ try await leader.publishClusterPairSlot(clusterPairSpecification(owner), owner: owner)
+ var running: [MultiModelBatchSchedulerEngine.AcquiredModel] = []
+ for _ in 0..<3 { running.append(try await leader.acquireModelForLocal(clusterPairFixtureModel)) }
+ #expect(running.allSatisfy { $0.queueExitedAt == nil })
+ let fourth = PendingAcquisition(leader)
+ #expect(await clusterPairWait { await leader.clusterPairLocalWaitingCount == 1 })
+ #expect(await leader.clusterPairLocalCounts == (1, 4, 3))
+ await running.removeFirst().releaseToken.fire()
+ let admitted = try await fourth.task.value
+ #expect(admitted.queueExitedAt != nil)
+ for acquired in running + [admitted] { await acquired.releaseToken.fire() }
+ #expect(await leader.clusterPairLocalCounts == (0, 0, 0))
+ #expect(await leader.retireClusterPairSlot(reason: "test"))
+
+ for rank in 1...2 {
+ let member = try memberLoop(name: "cluster-rank-\(rank)", localEndpoint: keyedLocalAPI)
+ await #expect(throws: ClusterMemberControlError.incompatibleConfiguration) {
+ try await member.prepareClusterMemberControlForTesting()
+ }
+ }
+ }
+
+ /// A local request waits behind a Darkbloom request holding the one lane,
+ /// and is woken when that request ends.
+ @Test func aLocalRequestWaitsBehindADarkbloomRequestAndRunsWhenItEnds() async throws {
+ let fixture = try await PairLeaderFixture.make(localAPI: true)
+ let task = fixture.start()
+ do {
+ let publicKey = try await fixture.register()
+ let port = try await fixture.localPort()
+ let owner = ScriptedPairOwner()
+ let hold = DispatchSemaphore(value: 0)
+ owner.hold = hold
+ try await fixture.loop.publishClusterPairSlot(clusterPairSpecification(owner), owner: owner)
+ try await fixture.push("darkbloom-1", publicKey: publicKey)
+ #expect(await clusterPairWait { owner.reserveCount == 1 })
+ let local = Task { try await URLSession.shared.data(for: try fixture.localChat(port: port)) }
+ #expect(await clusterPairWait { await fixture.loop.clusterPairLocalWaitingCount == 1 })
+ hold.signal()
+ #expect(try await fixture.completed("darkbloom-1"))
+ #expect(await clusterPairWait { owner.reserveCount == 2 }, "the local request took the lane it freed")
+ hold.signal()
+ let (data, reply) = try await local.value
+ #expect((reply as? HTTPURLResponse)?.statusCode == 200, "\(String(decoding: data, as: UTF8.self))")
+ #expect(await clusterPairWait { await fixture.loop.clusterPairLocalCounts == (0, 0, 0) })
+ } catch { await fixture.cleanUp(task); throw error }
+ await fixture.cleanUp(task)
+ }
+
+ /// The local API adds nothing to a Darkbloom request's path: with no local
+ /// request queued, the leader admits Darkbloom requests as fast as a
+ /// leader without a local API (the same code path; the bound only catches
+ /// an added wait, not scheduling noise), including the moment a local
+ /// request has just released the lane.
+ @Test func aDarkbloomRequestSeesNoExtraWaitWhenNoLocalRequestIsQueued() async throws {
+ var medians: [Bool: Duration] = [:]
+ for localAPI in [false, true] {
+ let fixture = try await PairLeaderFixture.make(localAPI: localAPI)
+ let task = fixture.start()
+ do {
+ let publicKey = try await fixture.register()
+ let owner = ScriptedPairOwner()
+ try await fixture.loop.publishClusterPairSlot(clusterPairSpecification(owner), owner: owner)
+ var samples: [Duration] = []
+ for index in 0..<9 {
+ if localAPI, index % 3 == 0 {
+ // A local request has just ended: the lane is free at once.
+ let acquired = try await fixture.loop.acquireModelForLocal(clusterPairFixtureModel)
+ await acquired.releaseToken.fire()
+ }
+ let reserved = owner.reserveCount
+ let started = ContinuousClock.now
+ try await fixture.push("darkbloom-\(index)", publicKey: publicKey)
+ while owner.reserveCount == reserved, ContinuousClock.now - started < .seconds(10) {
+ try await Task.sleep(for: .milliseconds(1))
+ }
+ samples.append(ContinuousClock.now - started)
+ #expect(try await fixture.completed("darkbloom-\(index)"))
+ }
+ medians[localAPI] = samples.sorted()[samples.count / 2]
+ if localAPI { #expect(await fixture.loop.clusterPairLocalCounts == (0, 0, 0)) }
+ } catch { await fixture.cleanUp(task); throw error }
+ await fixture.cleanUp(task)
+ }
+ let baseline = try #require(medians[false]), withLocalAPI = try #require(medians[true])
+ #expect(withLocalAPI <= baseline * 2 + .milliseconds(25),
+ "admission with no local request queued: \(withLocalAPI); without a local API: \(baseline)")
+ }
+
+ /// Stopping the leader lets a local stream in flight finish, then frees
+ /// its port and removes its discovery record.
+ @Test func stoppingTheLeaderWithALocalStreamDrainsItAndFreesThePort() async throws {
+ let fixture = try await PairLeaderFixture.make(localAPI: true)
+ let task = fixture.start()
+ do {
+ _ = try await fixture.register()
+ let port = try await fixture.localPort()
+ let owner = ScriptedPairOwner()
+ let hold = DispatchSemaphore(value: 0)
+ owner.hold = hold
+ try await fixture.loop.publishClusterPairSlot(clusterPairSpecification(owner), owner: owner)
+ let local = Task { try await URLSession.shared.data(for: try fixture.localChat(port: port)) }
+ #expect(await clusterPairWait { owner.reserveCount == 1 })
+ task.cancel()
+ try await Task.sleep(for: .milliseconds(200))
+ #expect(owner.shutdownCount == 0, "the stop waits for the local stream")
+ hold.signal()
+ let (data, reply) = try await local.value
+ let body = String(decoding: data, as: UTF8.self)
+ #expect((reply as? HTTPURLResponse)?.statusCode == 200 && body.hasSuffix("data: [DONE]\n\n"), "\(body)")
+ #expect(await ServeLoopFixture.finishes(task, within: .seconds(30)))
+ #expect(owner.shutdownCount == 1)
+ #expect(LocalEndpoint.readInfo() == nil, "the discovery record is removed")
+ var probe = try fixture.localChat(port: port)
+ probe.timeoutInterval = 2
+ let closed = await clusterPairWait {
+ do { _ = try await URLSession.shared.data(for: probe); return false } catch { return true }
+ }
+ #expect(closed, "nothing listens on the port")
+ } catch { await fixture.cleanUp(task); throw error }
+ await fixture.cleanUp(task)
+ }
+}
diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairSlotTests.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairSlotTests.swift
index 3f31fb8916..32fb7d2298 100644
--- a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairSlotTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/ClusterPairSlotTests.swift
@@ -58,6 +58,7 @@ final class ScriptedPairOwner: DistributedResidentExecutionOwner, @unchecked Sen
private var available = true
private var invalidation: (@Sendable () -> Void)?
private var leases: [ScriptedPairLease] = []
+ private var requests: [CBv2Request] = []
private var shutdowns = 0
/// When set, every request waits for one signal before its first token.
var hold: DispatchSemaphore?
@@ -66,6 +67,11 @@ final class ScriptedPairOwner: DistributedResidentExecutionOwner, @unchecked Sen
var failFirstReservations = 0
/// The resident assistant both "ranks" report loaded (nil: none).
var tensorAssistant: ClusterQwenTensorAssistantReady?
+ /// The pair's batch lanes: the slot's engine admits this many requests at once.
+ var lanes = 1
+ var concurrentRequests: Int { lanes }
+ /// Every request the engine reserved, in order (the warmup canary first).
+ var reservedRequests: [CBv2Request] { lock.withLock { requests } }
init(model: String = clusterPairFixtureModel) {
identity = .init(membershipEpoch: UUID(), modelID: model,
@@ -97,6 +103,7 @@ final class ScriptedPairOwner: DistributedResidentExecutionOwner, @unchecked Sen
let lease = ScriptedPairLease(identity: identity, requestID: request.id, hold: hold,
acceptsCleanStop: leasesAcceptCleanStop)
leases.append(lease)
+ requests.append(request)
return lease
}
}