Skip to content
Merged
3 changes: 3 additions & 0 deletions changelog.d/loop-guard-exit-thinking-handoff-cancel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### A local client that leaves while a looping thought is being ended no longer starts the answer

- On the scheduler's text and image/video paths (Gemma 4, GPT-OSS and the proven Qwen 3.5 builds by default; other Qwen builds when listed in `DARKBLOOM_LOOP_EXIT_THINKING`): when the loop guard ends a thought and a local API client disconnects while the stopped row is still releasing its slot (up to 5 s), the provider no longer submits the answer's continuation only to cancel it at once. The request ends as `length`, as before, with no second prefill. Nemotron 3.5 Super's route already behaved this way.
Original file line number Diff line number Diff line change
Expand Up @@ -202,12 +202,12 @@ actor NemotronSuperLocalBinding {
exit: exit,
promptTokens: tokens,
outputBudget: bridge.outputTokens(requested: request.max_tokens, promptTokens: tokens.count),
submit: { continuationPrompt, budget in
submit: { continuationPrompt, budget, cancelled in
guard await bridge.waitForRowRelease(requestId: requestID, within: .seconds(5)) else {
throw LoopExitThinkingContinuation.RowNotReleased()
}
// A request cancelled or drained during the wait gets no second row.
guard !cancel.cancelled else { throw CancellationError() }
guard !cancel.cancelled, !cancelled() else { throw CancellationError() }
// As `run` checks the first prompt.
guard !continuationPrompt.contains(18),
continuationPrompt.allSatisfy({ (0..<131072).contains($0) })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,13 @@ import Logging
/// after its first token ends the answer there, as `length`; only the client's
/// cancel keeps its error.
enum LoopExitThinkingContinuation {
typealias Submit = @Sendable (_ promptTokens: [Int], _ maxTokens: Int) async throws
-> AsyncStream<GenerationEvent>
/// `cancelled` is the splice's own cancel (its `cancel`, which an owner's
/// disconnect hook can call while the splice's task keeps running): an
/// owner checks it after its release wait and submits nothing once it is
/// set, as it does for the task's cancellation.
typealias Submit = @Sendable (
_ promptTokens: [Int], _ maxTokens: Int, _ cancelled: @Sendable () -> Bool
) async throws -> AsyncStream<GenerationEvent>

/// What happened to one request whose loop guard ended its thought.
enum Outcome: Sendable, Equatable, CustomStringConvertible {
Expand Down Expand Up @@ -151,10 +156,11 @@ enum LoopExitThinkingContinuation {
let continuation: AsyncStream<GenerationEvent>
do {
continuation = try await EngineAdmissionPriority.$current.withValue(admissionPriority) {
try await submit(promptTokens + generated + exit.exitTokens, budget)
try await submit(promptTokens + generated + exit.exitTokens, budget, { control.isCancelled })
}
} catch {
return endAsLength("continuation refused: \(error)")
return endAsLength(control.isCancelled || error is CancellationError
? "cancelled" : "continuation refused: \(error)")
}
guard control.markStarted() else {
await cancelContinuation()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -933,10 +933,14 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
exit: exitThinking,
promptTokens: promptTokens,
outputBudget: bridge.outputTokens(requested: base.maxTokens, promptTokens: promptTokens.count),
submit: { continuationPrompt, budget in
submit: { continuationPrompt, budget, cancelled in
guard await bridge.waitForRowRelease(requestId: visionRequestId, within: .seconds(5)) else {
throw LoopExitThinkingContinuation.RowNotReleased()
}
// As the text path: no continuation row once the
// consumer or the splice's control was cancelled.
try Task.checkCancellation()
guard !cancelled() else { throw CancellationError() }
var next = base
next.maxTokens = budget
return try await LocalPrefillProgress.$current.withValue(nil) {
Expand Down Expand Up @@ -1279,7 +1283,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
// The output the bridge resolved for the row, as it sized the
// row's service allowance.
outputBudget: bridge.outputTokens(requested: base.maxTokens, promptTokens: promptTokens.count),
submit: { continuationPrompt, budget in
submit: { continuationPrompt, budget, cancelled in
// The stopped row's stream can end before it releases its
// serving slot (a row with a retirement handle): until then
// it still counts against the Mac's width.
Expand All @@ -1288,11 +1292,10 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
}
// A consumer that stopped reading the spliced stream (its
// `onTermination(.cancelled)` cancels this task) gets no
// continuation row. A cancel that reaches only the splice's
// `Control` (the local API's disconnect hook) is seen once the
// row is submitted, and cancels it at once (closing that
// window is a follow-up).
// continuation row, nor does a cancel that reached only the
// splice's control (the local API's disconnect hook).
try Task.checkCancellation()
guard !cancelled() else { throw CancellationError() }
var next = base
next.maxTokens = budget
// As model calibration submits: the request's prompt progress
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ struct LoopExitThinkingContinuationTests {
LoopExitThinkingContinuation.splice(
first: first, cancelFirst: { calls.cancelFirst() }, exit: exit, promptTokens: Self.prompt,
outputBudget: outputBudget,
submit: { prompt, maxTokens in
submit: { prompt, maxTokens, _ in
calls.submit(prompt, maxTokens)
return try continuation()
},
Expand Down Expand Up @@ -359,7 +359,7 @@ struct LoopExitThinkingContinuationTests {
let spliced = LoopExitThinkingContinuation.splice(
first: first, cancelFirst: { calls.cancelFirst() }, exit: exit(requested: true, tokens: thought),
promptTokens: Self.prompt, outputBudget: 8_192,
submit: { prompt, maxTokens in
submit: { prompt, maxTokens, _ in
// The owner's hand-off (the row's release, the submission) is still running.
await gate.enterAndWait()
calls.submit(prompt, maxTokens)
Expand All @@ -376,6 +376,44 @@ struct LoopExitThinkingContinuationTests {
#expect(await drain(spliced.events) == ["info:5/4200/length"])
}

@Test("an owner that checks the splice's cancel after its release wait submits nothing")
func ownerChecksTheSplicesCancel() async throws {
let calls = Calls()
let gate = HandOffGate()
let outcomes = Outcomes()
let first = stream([.info(promptTokens: 5, completionTokens: 4_200, tokensPerSecond: 10, finishReason: "length")])
let spliced = LoopExitThinkingContinuation.splice(
first: first, cancelFirst: { calls.cancelFirst() }, exit: exit(requested: true, tokens: thought),
promptTokens: Self.prompt, outputBudget: 8_192,
submit: { prompt, maxTokens, cancelled in
// The owner's release wait, then its check, as both owners do.
await gate.enterAndWait()
guard !cancelled() else { throw CancellationError() }
calls.submit(prompt, maxTokens)
return self.stream([.chunk("never")], finish: false)
},
cancelContinuation: { calls.cancelContinuation() },
onOutcome: { outcomes.add($0) })
await gate.waitUntilEntered()
// A cancel that reaches the splice but not its task, as the local API's disconnect hook's.
await spliced.cancel()
gate.release()
await spliced.finished()
#expect(calls.submits.isEmpty)
#expect(calls.cancels.continuation == 0)
#expect(await drain(spliced.events) == ["info:5/4200/length"])
// The owner's refusal is the cancel's, and is logged as one.
#expect(outcomes.all == [.endedAsLength(reason: "cancelled")])
}

/// The splice's outcomes, in order.
private final class Outcomes: @unchecked Sendable {
private let lock = NSLock()
private var items: [LoopExitThinkingContinuation.Outcome] = []
func add(_ outcome: LoopExitThinkingContinuation.Outcome) { lock.withLock { items.append(outcome) } }
var all: [LoopExitThinkingContinuation.Outcome] { lock.withLock { items } }
}

@Test("a cancel before the continuation starts keeps it from starting")
func cancelBeforeStart() async {
let calls = Calls()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,17 +133,40 @@ private final class RetirementGate: @unchecked Sendable {

/// The coordinator's path: the row is admitted atomically against its
/// first-content deadline, so its stream ends before its retirement, which this
/// engine holds 50 ms past the stop. The continuation (no deadline) is an
/// engine holds 50 ms past the stop (or, with `holdFirstRetirement`, until the
/// test releases the first row's). The continuation (no deadline) is an
/// ordinary submission: it answers "Answer: B" and stops.
private final class AdmittedThoughtLoopEngine: CBv2Engine, @unchecked Sendable {
private let lock = NSLock()
private var submitted: [CBv2Request] = []
private var continuations: [CBv2RequestID: AsyncStream<CBv2Event>.Continuation] = [:]
private var produced: [CBv2RequestID: Int] = [:]
private var gates: [CBv2RequestID: RetirementGate] = [:]
private var firstFinished = false
private var firstFinishedWaiters: [CheckedContinuation<Void, Never>] = []
/// The first row keeps its slot after its terminal until `releaseFirstRetirement()`.
let holdFirstRetirement: Bool

init(holdFirstRetirement: Bool = false) { self.holdFirstRetirement = holdFirstRetirement }

var requests: [CBv2Request] { lock.withLock { submitted } }

/// Returns once the first row's terminal has gone out.
func waitUntilFirstFinished() async {
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
let now = lock.withLock { () -> Bool in
if firstFinished { return true }
firstFinishedWaiters.append(continuation)
return false
}
if now { continuation.resume() }
}
}

func releaseFirstRetirement() {
lock.withLock { submitted.first.flatMap { gates[$0.id] } }?.release()
}

func submit(
_ request: CBv2Request, firstTokenDeadline: CBv2FirstTokenDeadlineAdmission
) async throws -> CBv2FirstTokenDeadlineResult {
Expand Down Expand Up @@ -184,14 +207,23 @@ private final class AdmittedThoughtLoopEngine: CBv2Engine, @unchecked Sendable {
}

private func finish(_ id: CBv2RequestID, _ reason: CBv2FinishReason) {
let (continuation, prompt, completion, gate) = lock.withLock {
let (continuation, prompt, completion, gate, isFirst) = lock.withLock {
defer { continuations[id] = nil }
return (continuations[id], submitted.first { $0.id == id }?.promptTokens.count ?? 0, produced[id] ?? 0,
gates[id])
gates[id], submitted.first?.id == id)
}
continuation?.yield(.finished(
reason: reason, usage: CBv2Usage(promptTokens: prompt, completionTokens: completion)))
continuation?.finish()
if isFirst, holdFirstRetirement {
let waiters = lock.withLock { () -> [CheckedContinuation<Void, Never>] in
firstFinished = true
defer { firstFinishedWaiters.removeAll() }
return firstFinishedWaiters
}
waiters.forEach { $0.resume() }
return
}
// The row's engine resources retire a little after its terminal.
Task {
try? await Task.sleep(for: .milliseconds(50))
Expand Down Expand Up @@ -639,6 +671,51 @@ struct GenerationLoopExitThinkingServingTests {
#expect(outcome.content == "Answer: B")
}

@Test("a local client that leaves while the stopped row releases its slot gets no continuation row",
.timeLimit(.minutes(1)))
func localDisconnectDuringTheReleaseWait() async throws {
let engine = AdmittedThoughtLoopEngine(holdFirstRetirement: true)
let budget = GlobalKVCacheBudget(capFraction: 0.9, activationReserveBytes: 0) {
.init(total: 8 << 30, active: 0, cache: 0, systemAvailable: 8 << 30)
}
let bridge = EngineV2Bridge(engine: engine, modelId: modelID, tokenizer: Self.tokenizer,
eosTokenIds: [GemmaThoughtTestTokenizer.turnClose, GemmaThoughtTestTokenizer.eos], defaultMaxTokens: 64,
maxConcurrentRequests: 1, prefillDeadlineMode: .enforce, kvBytesPerToken: 4_000, kvBudget: budget)
await bridge.setMeasurementActivity(EngineMeasurementActivity())
await bridge.updatePrefillTpsEwma(2_000, isolated: true)
let id = modelID
let tokenizer = Self.tokenizer
var scheduler = MultiModelBatchSchedulerEngine(
registryProvider: { [id: .init(tokenizer: tokenizer, modelType: "gemma4", engineV2Bridge: bridge)] },
firstContentDeadline: FirstContentDeadline(relativeBudgetMilliseconds: 60_000))
scheduler.exitThinkingSetting = Self.cleanProcess
let served = scheduler
let scope = LocalRequestCancellationScope()
let request = Task { () -> (stop: String?, content: String) in
await LocalRequestCancellation.$current.withValue(scope) {
let outcome = try? await self.consume(served, maxTokens: 8_192)
return (outcome?.info?.stopReason, outcome?.content ?? "")
}
}
// The guard stopped the row and its `length` went out, but the row
// still holds its slot: the splice waits in `waitForRowRelease`. The
// local API's disconnect hook then reaches only the splice's control.
// The 200 ms let the splice pass its own pre-submit check first (a
// cancel before it would end the request there, without reaching the
// owner's check; the red run shows the wait is reached).
await engine.waitUntilFirstFinished()
try await Task.sleep(for: .milliseconds(200))
scope.cancel()
try await Task.sleep(for: .milliseconds(100))
engine.releaseFirstRetirement()
let result = await request.value
await bridge.shutdown()
#expect(engine.requests.count == 1)
// The held `length`, with no answer.
#expect(result.stop == "length")
#expect(result.content.isEmpty)
}

@Test("on a busy Mac the continuation takes its stopped row's place, ahead of the queue, before its admission lease ends",
.timeLimit(.minutes(1)))
func continuationAheadOfTheQueue() async throws {
Expand Down
Loading