Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog.d/provider-disconnected-chunk-drop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Drop disconnected response chunks before reconnect

- Drop response frames processed by the chunk queue while no connection is
bound, so their deferred flush cannot deliver them to a replacement session.
16 changes: 15 additions & 1 deletion docs/architecture/inference.md
Original file line number Diff line number Diff line change
@@ -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`
Expand Down Expand Up @@ -1284,6 +1284,20 @@ sequenceDiagram
S-->>C: SSE chunks / final response
```

For coordinator requests, `ProviderLoop+InferenceHandler.swift` encrypts each
SSE frame and sends it through `SendHandle.sendChunk`. The serial queue in
`provider-swift/Sources/ProviderCore/Coordinator/ChunkBatcher.swift` coalesces
frames for `ChunkFrameWriter`, while `SendHandle.send` flushes queued frames
before sending a terminal message. On that queue, `ChunkBatcher.enqueue`
drops a frame immediately if no session sink is bound. It cannot leave that
frame pending for a deferred flush after a replacement session binds.
`CoordinatorClient+Connection.swift` unbinds the old session during teardown;
`ProviderLoop+Cancellation.swift` cancels its in-flight requests separately.
The sink check occurs when the enqueue closure runs, not when its caller
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.

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`):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ final class ChunkBatcher: @unchecked Sendable {
/// once the byte threshold is crossed.
func enqueue(_ frame: Data) {
queue.async {
// A deferred flush can run after the next connection binds. Drop
// disconnected frames here so they cannot enter that session.
guard self.sink != nil else { return }
self.pending.append(frame)
self.pendingBytes += frame.count
if self.pendingBytes >= Self.flushThresholdBytes {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import Foundation
import Network
import Testing
@testable import ProviderCore

@Suite("ChunkBatcherLifecycleTests", .serialized)
struct ChunkBatcherLifecycleTests {
@Test("reconnect does not deliver frames enqueued while unbound",
arguments: [0, 1, 64, 1399, 1400, 4096])
func reconnectDropsUnboundFrames(size: Int) {
let batcher = ChunkBatcher()
let oldConnection = NWConnection(host: "127.0.0.1", port: 9, using: .tcp)
let newConnection = NWConnection(host: "127.0.0.1", port: 9, using: .tcp)
defer { oldConnection.cancel(); newConnection.cancel() }
let oldFrames = FrameRecorder()
let newFrames = FrameRecorder()
let entered = DispatchSemaphore(value: 0)
let release = DispatchSemaphore(value: 0)
let primer = Data(repeating: 0xA0, count: ChunkBatcher.flushThresholdBytes)
batcher.bind(connection: oldConnection) { frames in
oldFrames.append(frames)
entered.signal()
#expect(release.wait(timeout: .now() + .seconds(10)) == .success)
}
batcher.enqueue(primer)
guard entered.wait(timeout: .now() + .seconds(10)) == .success else {
release.signal()
Issue.record("old session did not enter its sink")
return
}

// Hold the real serial queue in its sink so all three operations are
// queued before the stale frame can schedule a deferred flush. No
// sleep or private queue access controls this interleaving.
batcher.unbind(ifCurrent: oldConnection)
batcher.enqueue(Data(repeating: 0xB0, count: size))
batcher.bind(connection: newConnection) { newFrames.append($0) }
release.signal()
batcher.flush()

#expect(oldFrames.snapshot() == [primer])
#expect(newFrames.snapshot().isEmpty,
"a disconnected request's frame reached the new session")

let fresh = Data([0xC0])
batcher.enqueue(fresh)
batcher.flush()
#expect(newFrames.snapshot() == [fresh])
}

@Test("unbound flush drops frames and subsequent bind still works")
func disconnectedFlushDropsFrames() {
let batcher = ChunkBatcher()
batcher.enqueue(Data([1]))
batcher.flush()
let connection = NWConnection(host: "127.0.0.1", port: 9, using: .tcp)
defer { connection.cancel() }
let frames = FrameRecorder()
batcher.bind(connection: connection) { frames.append($0) }
batcher.enqueue(Data([2]))
batcher.flush()
#expect(frames.snapshot() == [Data([2])])
}

@Test("stale teardown preserves the replacement connection")
func staleUnbindPreservesNewConnection() {
let batcher = ChunkBatcher()
let oldConnection = NWConnection(host: "127.0.0.1", port: 9, using: .tcp)
let newConnection = NWConnection(host: "127.0.0.1", port: 9, using: .tcp)
defer { oldConnection.cancel(); newConnection.cancel() }
let frames = FrameRecorder()
batcher.bind(connection: oldConnection) { _ in }
batcher.unbind(ifCurrent: oldConnection)
batcher.bind(connection: newConnection) { frames.append($0) }
batcher.unbind(ifCurrent: oldConnection)
batcher.enqueue(Data([3]))
batcher.flush()
#expect(frames.snapshot() == [Data([3])])
}

@Test("flush preserves same-session bytes and order", arguments: [1, 200])
func flushPreservesFrames(count: Int) {
let batcher = ChunkBatcher()
let connection = NWConnection(host: "127.0.0.1", port: 9, using: .tcp)
defer { connection.cancel() }
let frames = FrameRecorder()
batcher.bind(connection: connection) { frames.append($0) }
let expected = (0..<count).map { Data(repeating: UInt8($0 % 256), count: $0 % 3 == 0 ? 4096 : 8) }
for frame in expected { batcher.enqueue(frame) }
batcher.flush()
#expect(frames.snapshot() == expected)
batcher.flush()
#expect(frames.snapshot() == expected)
}

@Test("concurrent requests retain every frame and each request's order")
func concurrentRequestsPreserveOrder() {
let batcher = ChunkBatcher()
let connection = NWConnection(host: "127.0.0.1", port: 9, using: .tcp)
defer { connection.cancel() }
let frames = FrameRecorder()
batcher.bind(connection: connection) { frames.append($0) }
DispatchQueue.concurrentPerform(iterations: 4) { request in
for sequence in 0..<40 {
batcher.enqueue(Data([UInt8(request), UInt8(sequence)]))
}
}
batcher.flush()
let delivered = frames.snapshot()
#expect(delivered.count == 160)
for request in 0..<4 {
#expect(delivered.filter { $0.first == UInt8(request) }
== (0..<40).map { Data([UInt8(request), UInt8($0)]) })
}
}
}

private final class FrameRecorder: @unchecked Sendable {
private let lock = NSLock()
private var frames: [Data] = []

func append(_ batch: [Data]) {
lock.lock()
defer { lock.unlock() }
frames.append(contentsOf: batch)
}

func snapshot() -> [Data] {
lock.lock()
defer { lock.unlock() }
return frames
}
}
Loading