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
10 changes: 10 additions & 0 deletions changelog.d/nemotron-draft-calls-stay-reasoning.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
### Nemotron 3.5 Lightning no longer repeats parallel tool calls

- With reasoning on, Lightning sometimes closes its thought early to sketch the
calls it plans, keeps reasoning, closes the thought a second time and then
writes the real calls. The sketched calls were returned as well, so a
request for two parallel calls got four. Tool calls written before that
second close now stay in the reasoning, and only the final calls are
returned.
- When reasoning is on, Lightning's tool calls (and any text after them) now
reach a streaming client when generation ends, not while they are written.
21 changes: 21 additions & 0 deletions changelog.d/tool-call-history-nulls.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
### An earlier tool call's null arguments reach the model as null

A JSON `null` in an earlier assistant tool call's arguments (for example
`{"deadline": null}`) was dropped before the chat template rendered, because
the template engine cannot take a null value. The model was shown a different
call, such as Gemma 4's `call:clear_project_deadline{}`, and asked to repeat it
returned the wrong arguments: a missing required property, or a refusal when
the tool was strict. These nulls now render as `null` at the key or array
position the call had them: Gemma 4's argument macro and the Qwen 3.5 and
Nemotron 3.5 Lightning parameter value gain a `null` branch, and the templates
that write arguments as JSON (Qwen 3.6, Qwen 3.8, GPT-OSS, Inkling 2) print it
as they already did. GLM-5.3, MiMo, Flint and Nemotron 3.5 Super already kept
these nulls and render as before. Nulls elsewhere in a message and in tool
parameter schemas are still omitted.

The prompt contract stays `darkbloom-request-normalization-v9`, which still
renders these calls without their nulls, so a coordinator request whose
tool-call history carries such a null is served without the prompt cache: no
cache lookup, receipt or checkpoint write, and no cached-token usage. Every
other request is unchanged. `darkbloom logs` notes each such request, and the
daemon state counts them (`promptCacheSkippedToolCallNull`).
16 changes: 16 additions & 0 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -5148,6 +5148,22 @@ and the coordinator can refuse to route
(`provider-swift/Sources/ProviderCoreFoundation/TemplateRenderCheck.swift`,
`provider-swift/Sources/ProviderCore/Coordinator/CapacityQuoteEngine.swift`).

swift-jinja cannot take a JSON null, so the shared message sanitizer drops
null leaves before rendering, with one exception: an earlier tool call's
decoded `arguments` keep each null as Jinja `null`, at its key or array
position, because dropping it shows the model a different call than the one it
made (`sanitizeMessageForJinja`; Gemma 4's string-argument path does the same,
`Gemma4ToolCallArguments`). Templates that print a plain argument value with
swift-jinja's string rendering gain a branch that writes `null`: Gemma 4's
`format_argument` macro and the Qwen 3.5 / Nemotron 3.5 Lightning XML parameter
value (`renderingToolArgumentNulls`, applied by the serving tokenizer and the
render check only, not the managed Nemotron Super contract). Templates that
write arguments with `tojson` print the null as they already did. Tool
parameter schemas keep the drop policy. GLM-5.3, MiMo and Flint build their own
history and already kept these nulls. Such a request still plans and counts
under normalization v9, which drops them, so it is served without the
coordinator's prompt cache ([prefix cache](prefix-cache.md)).

A template `raise_exception` at request time is classified `jinja_template`
and returned as HTTP 500, the provider-fault class, so a caller control that
a template is known to reject must be resolved before rendering. The
Expand Down
7 changes: 7 additions & 0 deletions docs/architecture/model-registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ downloads published artifacts and verifies them. Discovery is not full weight
hashing: retain fast startup scans and on-demand verification. Broken templates
must be reported rather than silently repaired.

The template render check run at discovery (`TemplateRenderCheck.renderOK`)
compiles and feeds each template exactly as the serving tokenizer does: the
same tool-argument null rewrites (`renderingToolArgumentNulls`), normalization
and message sanitizer (`sanitizeMessageForJinja`), so "renders at discovery"
stays "renders at request time". Neither changes the prompt contract ID, which
hashes the artifact files and the declared normalization version.

Foreground downloads (`darkbloom models download` and the `darkbloom start`
picker) show one progress line for the whole model, never a line per file:
`ManifestDownloadProgress` sums each file's bytes on disk and
Expand Down
16 changes: 16 additions & 0 deletions docs/architecture/prefix-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,22 @@ the hint when it carries one; the frame supplies the rest
`provider-swift/Sources/ProviderCore/Inference/PrefixCache/SealedPrefixCacheMetadata.swift`;
[protocol](../reference/protocol-messages.md#inference_request)).

A coordinator request whose earlier tool call carries a JSON null in its
arguments is served without that context. The shared chat-template path
renders the null, while the prompt contract the coordinator plans and counts
with (normalization v9) renders the call without it, so the provider's prompt
anchor would not match the plan. Once the slot's model type is known, the
handler replaces the planned context with one without scope or receipt nonce:
no lookup or ready receipt, no cached-token usage, no checkpoint write. The
coordinator's attempt then expires unanswered, which carries no proof fence or
holder invalidation; only the request's exact prompt-work count stops
qualifying, so it is admitted without calibrated first-content admission.
GLM-5.3, MiMo, Flint and the managed Nemotron Super owner build their own
history, already kept these nulls and keep their plan. The template controls
still come from the planned context. `darkbloom logs` notes each such request
and the daemon state counts them (`promptCacheSkippedToolCallNull`)
(`provider-swift/Sources/ProviderCore/Inference/PrefixCache/ToolCallHistoryNullCache.swift`).

Native MiMo historical checkpoints retain only actual uniform-chunk frontiers
whose target and optional assistant state completed their native observation
and promotion fences. Their fork target is the deepest successfully captured
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ public final class AtomicProviderStats: Sendable {
// Local to `darkbloom status`: the requests that ended early, by cause
// (`cancellationsPartialComplete` is their total).
private let _endedEarly = LockedEndedEarlyCounts()
// Local to `darkbloom status`: planned requests served without the prompt
// cache because their tool-call history carries a null argument
// (`ToolCallHistoryNullCache`).
private let _promptCacheSkippedToolCallNull = ManagedAtomic<UInt64>(0)

public init() {}

Expand Down Expand Up @@ -165,6 +169,12 @@ public final class AtomicProviderStats: Sendable {

public var endedEarly: EndedEarlyCounts { _endedEarly.counts }

public var promptCacheSkippedToolCallNull: UInt64 { _promptCacheSkippedToolCallNull.load() }

public func incrementPromptCacheSkippedToolCallNull() {
_promptCacheSkippedToolCallNull.add(1)
}

public func incrementGenerationErrorsAfterOutput() {
_generationErrorsAfterOutput.add(1)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
modelType: modelType,
allowInternalSchemaMetadata: allowInternalToolSchemaMetadata,
glm5PairPostValidation: glm5PairPostValidation)
policy.declaredTools = templateControls.declaredTools
policy = policy.withDeclaredTools(templateControls.declaredTools, modelType: modelType)
// The coordinator path serves every request as a stream; the body
// says whether the client streams (`StrictToolCallPolicy`).
policy.clientStreams = templateControls.clientStreams ?? (request.stream == true)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import MLXLMServer
import ProviderCoreFoundation

/// An earlier tool call whose arguments carry a JSON null renders that null
/// on the shared chat-template path (`sanitizeMessageForJinja`), while the
/// prompt contract the coordinator plans and counts with (normalization v9)
/// renders it without. Such a request is served without the coordinator's
/// prompt cache: no lookup, no receipt, no cache usage and no checkpoint write,
/// so no receipt ever names a prompt the coordinator did not plan. Every other
/// request keeps its planned cache context.
enum ToolCallHistoryNullCache {
/// Whether any message's tool call carries such arguments.
static func carriesNull(_ request: OpenAIChatCompletionRequest) -> Bool {
request.messages.contains { message in
(message.toolCalls ?? []).contains { toolCallArgumentsCarryNull($0.function.arguments) }
}
}

/// Whether `modelType` renders history through the shared chat-template
/// sanitizer. GLM-5.3, MiMo, Flint and the managed Nemotron Super owner
/// build their own history and already kept these nulls, so their prompts
/// did not change.
static func rendersThroughSharedSanitizer(modelType: String?, managedSuper: Bool) -> Bool {
!managedSuper && !GLM5NextPromptPolicy.applies(modelType: modelType)
&& !MiMoV26TemplateFix.applies(to: .init(modelType: modelType))
&& modelType != "flint"
}

/// The cache context `request` is served with: `planned`, or one without a
/// scope or receipt nonce when the coordinator planned a cache attempt,
/// the model renders through the shared sanitizer and the request's
/// tool-call history carries a null. `servedCold` reports that second case.
static func servingContext(
_ planned: RemotePrefixCacheContext, for request: OpenAIChatCompletionRequest,
modelType: String?, managedSuper: Bool
) -> (context: RemotePrefixCacheContext, servedCold: Bool) {
guard planned.scope != nil || planned.receiptNonce != nil,
rendersThroughSharedSanitizer(modelType: modelType, managedSuper: managedSuper),
carriesNull(request)
else { return (planned, false) }
return (RemotePrefixCacheContext(cacheScope: nil, cacheReceiptNonce: nil), true)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,16 @@ func sanitizeJinjaObject(

/// Sanitize a chat-template `messages` array: strip raw Harmony channel tags
/// from assistant string fields, then drop null / `Optional` leaves from each
/// message dictionary (e.g. a `null` value inside an assistant tool call's
/// decoded `arguments`). Behavior-preserving for messages that carry neither
/// null leaves nor Harmony channel framing.
/// message dictionary, except inside an assistant tool call's decoded
/// `arguments`, where a null stays Jinja `null` (`sanitizeMessageForJinja`).
/// Behavior-preserving for messages that carry neither null leaves nor
/// Harmony channel framing.
func sanitizeJinjaMessages(
_ messages: [[String: any Sendable]]
) -> [[String: any Sendable]] {
messages.map { sanitizeJinjaObject(stripHarmonyFramingFromMessage($0)) }
messages.map {
sanitizeMessageForJinja(stripHarmonyFramingFromMessage($0)) as? [String: any Sendable] ?? [:]
}
}

/// Strip raw Harmony channel framing from assistant string fields before the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ private struct LocalTokenizerBridge: @unchecked Sendable, MLXLMCommon.Tokenizer,
self.chatTemplate = chatTemplate.map {
HFTemplateFilters.bindingFilters(
in: NemotronTemplateFilters.bindingFilters(
in: normalizeSwiftJinjaTemplate($0), modelType: modelType),
in: normalizeSwiftJinjaTemplate(renderingToolArgumentNulls($0)), modelType: modelType),
modelType: modelType, environment: environment)
}
self.modelType = modelType
Expand Down Expand Up @@ -257,7 +257,7 @@ private struct LocalTokenizerBridge: @unchecked Sendable, MLXLMCommon.Tokenizer,
return try TemplateRenderStack.run {
try upstream.applyChatTemplate(
messages: messages,
chatTemplate: .literal(normalizeSwiftJinjaTemplate(chatTemplate)),
chatTemplate: .literal(normalizeSwiftJinjaTemplate(renderingToolArgumentNulls(chatTemplate))),
addGenerationPrompt: true, truncation: false, maxLength: nil,
tools: tools, additionalContext: additionalContext)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ enum ToolChoicePromptPolicy {
/// (`ToolSchemaNormalization`) filled in render types. Validation of
/// `auto` calls reads these; nil falls back to `tools`.
var declaredTools: [OpenAITool]? = nil
/// The declarations the call parser reads arguments with
/// (`ToolArgumentSchemas.reading`): `tools`, each with the caller's
/// parameters instead of their render types. Nil reads `tools`.
var argumentTools: [OpenAITool]? = nil
/// An answer the engine cut at the token limit ends as a normal
/// `length` finish, as generated (`TokenLimitCutPolicy`).
var cutAnswersEndAtLength = TokenLimitCutPolicy.endsAtLength
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import MLXLMServer
/// Content-state `</think>` handling follows the vendor-documented Nemotron
/// parser (vLLM `nemotron_v3`, which reuses the qwen3 parser-engine config):
/// when explicitly enabled, a close already in content is absorbed and the text
/// before it stays content. It is never reinterpreted as a reasoning boundary.
/// before it stays content. It is never reinterpreted as a reasoning boundary,
/// except for frames held after a closed thought (`holdsFramesAfterThought`).
struct NativeChannelSplitter {
private enum State { case content, reasoning, tool(end: String) }
private var state: State
Expand All @@ -25,6 +26,11 @@ struct NativeChannelSplitter {
private var flintScanner: FlintToolFrameScanner?
private let preserveInnerReasoningSpans: Bool
private let absorbStrayThinkClose: Bool
/// `heldFrames`: content from the first tool frame after a closed
/// thought, held until a stray `</think>` or the end of output.
private let holdsFramesAfterThought: Bool
private var closedThought = false
private var heldFrames: String?
private var promotesTrailingCalls: Bool
/// The open thought's text (kept only with `promotesTrailingCalls`).
private var openThought = ""
Expand All @@ -43,10 +49,17 @@ struct NativeChannelSplitter {
/// so they parse as calls. A frame followed by more thought, or by
/// `</think>`, stays reasoning, and so does a thought the token limit cut
/// off (`outputReachedTokenLimit`).
///
/// `holdsFramesAfterThought` (with `absorbStrayThinkClose`): a model that
/// closes its thought, writes tool frames as a draft, keeps thinking and
/// closes the thought again was still thinking. Content from the first
/// frame after a closed thought is held; a stray `</think>` makes the held
/// text reasoning, so its frames never become calls. At the end of the
/// output the held text is content.
init(prefix: String, protectToolFrames: Bool, qwenStructuredFrames: Bool = false, flintFrames: Bool = false,
glmFrames: Bool = false, tools: [[String: any Sendable]]? = nil,
preserveInnerReasoningSpans: Bool = false, absorbStrayThinkClose: Bool = false,
promotesTrailingCalls: Bool = false) {
holdsFramesAfterThought: Bool = false, promotesTrailingCalls: Bool = false) {
state = prefix == "<think>" ? .reasoning : .content
self.protectToolFrames = protectToolFrames
self.qwenStructuredFrames = qwenStructuredFrames
Expand All @@ -55,6 +68,7 @@ struct NativeChannelSplitter {
self.tools = tools
self.preserveInnerReasoningSpans = preserveInnerReasoningSpans
self.absorbStrayThinkClose = absorbStrayThinkClose
self.holdsFramesAfterThought = holdsFramesAfterThought && absorbStrayThinkClose
self.promotesTrailingCalls = promotesTrailingCalls
}

Expand All @@ -67,6 +81,10 @@ struct NativeChannelSplitter {
mutating func finish() -> [ParsedReasoning] {
guard !reasoningNestingLimitExceeded else { return [] }
var pieces = drain(final: true)
if let held = heldFrames {
heldFrames = nil
append(held, reasoning: false, to: &pieces)
}
toolScanner = nil
flintScanner = nil
if promotesTrailingCalls, case .reasoning = state,
Expand Down Expand Up @@ -224,7 +242,12 @@ struct NativeChannelSplitter {
else if marker == "</think>" {
// Stray close after a prompt-side `<think></think>` (or a
// duplicate close): drop the marker, stay in content.
if let held = heldFrames {
heldFrames = nil
append(held, reasoning: true, to: &result)
}
} else {
if holdsFramesAfterThought, closedThought, heldFrames == nil { heldFrames = "" }
append(marker, reasoning: false, to: &result)
state = .tool(end: marker == "<tool_call>" ? "</tool_call>" : "</function>")
if qwenStructuredFrames && marker == "<tool_call>" {
Expand All @@ -251,6 +274,7 @@ struct NativeChannelSplitter {
append(String(buffer[..<range.lowerBound]), reasoning: true, to: &result)
state = .content
openThought = ""
closedThought = true
}
case .tool:
append(String(buffer[..<range.upperBound]), reasoning: false, to: &result)
Expand Down Expand Up @@ -279,6 +303,10 @@ struct NativeChannelSplitter {

private mutating func append(_ text: String, reasoning: Bool, to result: inout [ParsedReasoning]) {
guard !text.isEmpty else { return }
if !reasoning, heldFrames != nil {
heldFrames! += text
return
}
if reasoning && promotesTrailingCalls { openThought += text }
result.append(.init(content: reasoning ? "" : text, reasoningContent: reasoning ? text : nil))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ struct NativeToolStreamRouter {
tools: tools,
preserveInnerReasoningSpans: preserveInnerReasoningSpans,
absorbStrayThinkClose: absorbStrayThinkClose,
// Nemotron 3.5 drafts calls after an early `</think>`, then closes again.
holdsFramesAfterThought: handler?.format == .nemotron,
promotesTrailingCalls: promotesTrailingReasoningCalls)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,8 @@ enum ToolStreamPreparation {
try ToolChoiceEnforcementPolicy.validateParser(
format, strategy: strategy, modelContext: context)
return BatchedToolStreamHandler(format: format,
tools: (isMiMo && prepared.mode == .none ? request.tools : prepared.tools)?.map { $0.toolSpec() },
tools: (isMiMo && prepared.mode == .none ? request.tools : prepared.argumentTools ?? prepared.tools)?
.map { $0.toolSpec() },
strictGemma: modelType == "diffusion_gemma",
streaming: streamToolCalls && exposesCallsWhileGenerated(request: request, prepared: prepared,
context: context, strategy: strategy, format: format, forced: streamForcedToolCalls,
Expand Down
Loading
Loading