Skip to content
Merged
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
13 changes: 13 additions & 0 deletions Libraries/MLXLMCommon/ChatSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -761,11 +761,24 @@ public final class ChatSession {
pendingToolCalls.append(toolCall)
} else if let value = transform(item) {
if case .terminated = continuation.yield(value) {
genTask.cancel()
break
}
}
}

// The generation task is unstructured, so cancellation of
// this task (stream onTermination) does not propagate to
// it. Without an explicit cancel, `await genTask.value`
// would wait for the FULL generation while holding the
// cache lock — deadlocking the session's next call (e.g.
// a caller that cancels mid-stream and immediately asks
// again). The generate loop checks Task.isCancelled per
// token, so this stops it promptly.
if Task.isCancelled {
genTask.cancel()
}

// wait for the task to complete -- this is important in
// the case where we broke the loop early as the generation
// work may continue (briefly) and use the KVCache
Expand Down
Loading