diff --git a/changelog.d/gemma-json-answer-grammar.md b/changelog.d/gemma-json-answer-grammar.md
new file mode 100644
index 0000000000..cde5ca05a5
--- /dev/null
+++ b/changelog.d/gemma-json-answer-grammar.md
@@ -0,0 +1,4 @@
+### Gemma 4 JSON answers follow the requested format
+
+- A Gemma 4 26B request with a JSON `response_format` (`json_object`, or `json_schema` within the provider's supported subset) is now sampled under a grammar: after the model's thought, if any, the answer is exactly one JSON value of the requested format, with no code fences, surrounding prose or trailing text. Schemas as Pydantic, OpenAI's strict mode or zod write them (`$defs`/`$ref`, optional fields as `anyOf` with null, `$schema`) are enforced as written; a `json_schema` the grammar still does not cover is held to a JSON object when its root is an object. The thought is unchanged.
+- Requests the grammar does not cover (tools, a `tool_choice` other than `auto` without tools, `stop` sequences, images, other schemas) and cluster pairs are answered as before; an answer cut at `max_tokens` still ends as `length`, never as an error. `DARKBLOOM_GEMMA_JSON_ANSWERS=off` turns the grammar off on a Mac.
diff --git a/changelog.d/json-answer-grammar-bonsai-lightning.md b/changelog.d/json-answer-grammar-bonsai-lightning.md
new file mode 100644
index 0000000000..8a5f505332
--- /dev/null
+++ b/changelog.d/json-answer-grammar-bonsai-lightning.md
@@ -0,0 +1,16 @@
+### Valid JSON answers on Bonsai 2 27B and Nemotron 3.5 Lightning
+
+- A tool-free JSON `response_format` request on Bonsai 2 27B or on Nemotron 3.5 Lightning, on one Mac, whose prompt
+ starts in the answer (thinking off, the JSON default on Bonsai), is now sampled under the JSON-answer grammar the
+ Qwen 3.5 family already uses: for schemas inside the constrained subset the answer is one JSON value of the
+ requested schema (no extra or missing keys, no raw newline inside a string). On our checks, Lightning answers with
+ thinking off missed the schema 8 times in 72 before and 0 times after.
+- Requests whose prompt opens a thought (Lightning's default), requests served by a cluster pair, and the Bonsai 2 9B
+ keep today's prompt-only steering.
+- Like Qwen's, these answers decode without MTP (a Lightning row sharing their decode step stops speculating
+ meanwhile), and the provider checks them when generation ends: an answer that misses the schema at a natural stop
+ is the typed `422` (`tool_noncompliance`); one cut at `max_tokens` ends as a normal `length` finish with its
+ content as generated.
+- The grammar keeps an answer inside the schema, not on topic: a model that wants a forbidden key may keep writing the
+ string it is in until `max_tokens`.
+- `DARKBLOOM_JSON_ANSWER_GRAMMAR=qwen` (or `0`/`off`) keeps the grammar to the Qwen types.
diff --git a/changelog.d/qwen-strict-tool-call-grammar.md b/changelog.d/qwen-strict-tool-call-grammar.md
new file mode 100644
index 0000000000..1fba9c5109
--- /dev/null
+++ b/changelog.d/qwen-strict-tool-call-grammar.md
@@ -0,0 +1,6 @@
+### Strict Qwen tool calls always match their schemas
+
+- On Qwen 3.8 27B, Qwen 3.6 35B and Qwen 3.5 9B and 35B, a tool call to a function declared `strict: true` could miss the caller's schema (a quoted number, a wrong enum value, a missing required argument, a value inside a `$ref` definition of the wrong JSON type); the provider checks such a call when it closes, after the answer started streaming, and the response then failed partway. On one Mac the provider now constrains these calls while they are sampled: only a declared function, its declared parameters (each at most once, every required one), and values of the declared types and enums can be written, in the template's call format. Reasoning and text around the calls stay free (ordinary text, the reasoning and call markers and the end of the answer; other special tokens such as `<|im_start|>` are not sampled), text that only mentions `` stays text, and the choice whether to call, the prompt and the streamed call deltas are unchanged. With `parallel_tool_calls: false` an answer opens at most one call.
+- It applies to `tool_choice` `auto` (or absent) requests that declare at least one `strict` function; every call of such a request is held to its schema, as the check already holds it. Local `$ref`/`$defs` are inlined, `anyOf` of a type and `null` is supported, and a request whose schemas use a keyword the grammar cannot hold exactly (`pattern`, `minimum`, `minLength`, unions of several types, recursive references, ...) is served unconstrained, as before, never refused. Cluster pairs keep the previous behavior.
+- As with constrained JSON answers, MTP drafting stops while a constrained answer is decoding: it drafts nothing itself, and on these models no other answer decoding beside it on the same Mac drafts either. Qwen 3.8 and Qwen 3.5 9B draft while up to 8 answers decode at once, so their decode slows while a strict-tool answer is running; Qwen 3.6 and 3.5 35B, whose cards set a presence penalty, do not draft anyway.
+- `DARKBLOOM_STRICT_TOOL_GRAMMAR=off` turns it off on a Mac; a list of model types or model-id parts (`qwen3.8-27b,qwen3_5_moe`) limits it to those builds. `DARKBLOOM_STRICT_TOOL_GRAMMAR_ALL_TOOLS=on` also constrains the calls of requests without `strict` functions. Both reach a provider started by `darkbloom start`.
diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md
index 80e3bcf350..81544bde8f 100644
--- a/docs/architecture/inference.md
+++ b/docs/architecture/inference.md
@@ -3587,17 +3587,125 @@ spliced across a boundary the reasoning parser later hides. Required and named
(`provider-swift/Sources/ProviderCore/Inference/Tools/GemmaNoToolTokenConstraint.swift`,
`provider-swift/Sources/ProviderCore/Inference/Tools/GemmaTokenVocabulary.swift`).
+### Constrained Gemma 4 JSON answers
+
+Gemma 4 answers to a JSON `response_format` are sampled under the same JSON
+grammar as constrained Qwen answers (below), with three differences: Gemma's
+vocabulary, its thought framing, and best-effort semantics.
+`ToolConstraintFactory.make` asks `GemmaJSONAnswerPolicy` first: a text request
+on `gemma4` or `gemma4_text` with a JSON `response_format`, no `tools`, no
+`tool_choice` (or a tool-free `auto`), no client `stop`, the `gemma4` reasoning
+parser and the pinned chat template (`TokenizerHandle.toolConstraintContractVerified`)
+gets a `GemmaJSONAnswerConstraint`. The prompt is unchanged.
+
+**Vocabulary.** Gemma's tokenizer is SentencePiece BPE with byte fallback, not
+byte-level BPE. `GemmaAnswerPieces` gives every id the bytes its decoder writes:
+U+2581 becomes a space, a `<0x80>`…`<0xFF>` token is that byte, other pieces are
+their UTF-8 (the provider's tokenizer runs no clean-up for Gemma). The 24 added
+tokens and the `` slots have no piece, and neither do the ASCII
+byte-fallback tokens: a byte-fallback run is decoded as a whole, so what one byte
+becomes depends on its neighbours (a run that is not UTF-8 reads as U+FFFD),
+while every ASCII character JSON needs has a piece of its own. Non-ASCII bytes
+occur only inside strings, where U+FFFD is still a character.
+Before constraining, `GemmaAnswerPieces.vocabulary` checks `<|channel>` 100,
+`` 101, `` 106 and `` 1 by id, spelling, encoding and
+decoding, that the tokenizer has exactly 262,144 ids, and that `` and
+`` are engine stop tokens. The
+vocabulary is built on the first such request per loaded tokenizer and stop set
+and cached (two entries).
+
+**Phases.** The rendered prompt's tail selects the first phase
+(`GemmaJSONAnswerPolicy.initialPhase`). Thinking off renders an empty, closed
+thought (`<|turn>model\n<|channel>thought\n`), so output starts in the
+answer. Thinking on ends at `<|turn>model\n`, so a thought may open with
+`<|channel>`, or the answer may start at once (whitespace before either stays
+content, so an answer can read `"\n{...}"`, still one JSON value). The thought
+is free text: no EOS or added token other than the two thought markers, and the
+first ``, as its token or spelled from ordinary pieces (the stream's
+Gemma parser reads text), ends it. The answer is one JSON value of the request's
+grammar (`JSONAnswerFormat`, `FlintJSONGrammar`);
+no Gemma control spelling can complete in it, strings included. `` or
+`` is allowed once the value is complete, and a value that delimits itself
+(an object, array, string or literal) is followed by the terminator only, never
+by text a client would have to strip. JSON whitespace outside strings runs at
+most 64 bytes (`GemmaJSONAnswerBoundary.maximumWhitespaceRun`), so a model that
+keeps reaching for a refused spelling (a code fence) cannot fill its budget with
+blank lines. States that differ only in a run
+no piece can push past that cap share one mask key (`maskEquivalent`), so
+indentation does not multiply mask builds; a request keeps at most two broad
+allowed sets (about 2 MB each) and the sampler its per-key device masks.
+
+**Best effort.** Unlike constrained Qwen answers, nothing is validated after
+generation (`MultiModelBatchSchedulerEngine` checks only `JSONAnswerConstraint`
+answers): a budget that ends first stays `length` with the partial value, as
+before. A request whose interned states reach the cap
+(`GemmaJSONAnswerConstraint.defaultMaximumStates`, 16,384) continues
+unconstrained instead of failing. A `json_schema` in the shapes common clients
+generate is first rewritten into the shared subset where the result admits
+exactly the same instances (`ResponseSchemaRewrite`: `$ref`s to plainly named
+entries of the root's `$defs`/`definitions` inlined, a one-branch `allOf`
+unwrapped, `anyOf` of one schema and `{"type": "null"}` made nullable, with only
+annotations beside them; `$comment` on every node it rewrites, the root's `$id`
+and a draft-06 to 2020-12 `$schema` dropped; at most 16 levels, 8 references or
+compositions in a row and a bounded amount of copying and hashing,
+`maximumWork`).
+One still outside it (`pattern`, `format`, a recursive `$ref`, a wider `anyOf`,
+an older `$schema`, a nullable enum of 128 values, …) whose root is
+`"type": "object"` is held to a JSON object; any other
+unsupported schema, an unpinned template or tokenizer, another
+prompt end or a nonpositive budget keeps prompt-only steering with one
+content-free line (category `json-answer`). An engine that runs no token
+constraint (a cluster pair or a native-tracked engine) would refuse one, so
+`EngineV2Bridge.admittedConstraint` submits the request there unconstrained.
+`DARKBLOOM_GEMMA_JSON_ANSWERS=off` restores prompt-only answers everywhere.
+
+**Speculative decoding.** A constrained row never drafts
+(`EngineLoopV2.mtpBasicEligible`), and Gemma's target is not recurrent, so a
+step that holds one runs target-only for every row in it, as for a `stop`,
+penalty or logprob row (see the Qwen notes below). Rows in steps without one
+are unchanged.
+
+Sources: `provider-swift/Sources/ProviderCore/Inference/Tools/GemmaJSONAnswerPolicy.swift`,
+`provider-swift/Sources/ProviderCore/Inference/Tools/ResponseSchemaRewrite.swift`,
+`provider-swift/Sources/ProviderCore/Inference/GemmaJSONAnswerConstraint.swift`,
+`provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift`.
+
### Constrained Qwen JSON answers
-The format instruction alone leaves some Qwen answers outside the requested
-schema: a near-miss key, a string for an integer, or prose. On the Qwen text
-path the answer is therefore sampled under a grammar, as on
-[exact Flint](#native-flint). `ToolConstraintFactory.make` asks
-`QwenJSONAnswerPolicy` before any tool-choice constraint: a text request on
-`qwen3_5` or `qwen3_5_moe` with a JSON `response_format`, no `tools`, no
-`tool_choice` and the `qwen3` reasoning parser gets a `JSONAnswerConstraint`.
-The prompt is unchanged (the service's format instruction and the no-thinking
-default above), so the coordinator prompt sidecar needs no rule.
+Qwen, Bonsai 2 27B and Nemotron 3.5 Lightning share this machinery.
+The format instruction alone leaves some answers outside the requested schema:
+a near-miss key, a string for an integer, an invented key under
+`additionalProperties: false`, a raw newline inside a string, or prose. On the
+text path of the families with a pinned answer contract the answer is therefore
+sampled under a grammar, as on [exact Flint](#native-flint).
+`ToolConstraintFactory.make` asks `JSONAnswerPolicy` before any tool-choice
+constraint: a text request with a JSON `response_format`, no `tools`, no
+`tool_choice` and the `qwen3` reasoning parser gets a `JSONAnswerConstraint`
+when its model is admitted (`JSONAnswerPolicy.profile`):
+
+| Family | Admission | Contract (`JSONAnswerProfile`) |
+|---|---|---|
+| Qwen 3.5, 3.6, 3.8 | `model_type` `qwen3_5` or `qwen3_5_moe` | `qwen35` |
+| PrismML Bonsai 2 27B | `prism_hadamard_qwen35` and a 27B listing id (`EngineV2SupportedModels.isBonsai2ListingModelID`; the 9B shares the type) | `bonsai2`: Qwen 3.5's tokenizer and ids, its own name in messages, `<|im_end|>` its one terminator |
+| Nemotron 3.5 Lightning | `nemotron_h` and a Lightning listing id (`EngineV2SupportedModels.isNemotron35ListingModelID`; Nano shares the type) | `nemotron35` |
+
+Bonsai and Lightning are admitted for their answers only
+(`JSONAnswerProfile.constrainsReasoning` false): a prompt that opens a thought
+keeps prompt-only steering, silently and before the schema compiles, as it is
+Lightning's default. A constrained row never drafts and, on Lightning's target,
+no row in its decode step does (below); Lightning's reasoning runs long, and
+both families' thinking answers met the schema in the checks that motivated
+them. Neither is constrained on a cluster pair, which refuses any token
+constraint before reserving (`constrainedDecodingUnsupported`); their pairs
+keep prompt-only service. Qwen keeps both, as before. The Bonsai 2 9B is not
+admitted: it drafts, and its JSON prompts render thinking off by default, so
+each of its JSON rows would stop its whole decode cohort from speculating.
+
+`DARKBLOOM_JSON_ANSWER_GRAMMAR=qwen` (or `0`, `off`, `false`, `no`, `none`)
+keeps the grammar to the Qwen types, as before Bonsai and Lightning were
+admitted (read once per process; forwarded to the LaunchAgent). The prompt is
+unchanged (the service's format instruction and the Qwen no-thinking default
+above), so the coordinator prompt sidecar needs no rule.
The rendered prompt's tail selects the first phase
(`JSONAnswerProfile.initialPhase`, through `ReasoningPromptProbe.streamingPrefix`).
@@ -3608,18 +3716,27 @@ reasoning, which stays free except that every EOS is masked, the spellings
one JSON value of the grammar compiled from the schema (`JSONAnswerFormat`: the
shared fail-closed subset and the byte-level `FlintJSONGrammar` automaton), so
declared properties are the only keys generated. ``, ``,
-``, ``, ``, `<|im_end|>` and
-`<|endoftext|>` cannot complete anywhere in it, strings included, and
-`<|im_end|>` or `<|endoftext|>` is allowed only once the value is complete.
-
-`JSONAnswerVocabulary` admits the byte-level BPE ids below `<|endoftext|>`
-(248044) and the ``/`` tokens only. Other added and special tokens
-and the model's padding up to 248,320 ids are never allowed. Before constraining,
-it checks `` 248068, `` 248069, `<|im_end|>` 248046 and
-`<|endoftext|>` 248044 by id, spelling, encoding and decoding, that every base
-id decodes as a byte-level piece, and that both terminators are engine stop
-tokens. It is built on the first such request per loaded tokenizer and stop set
-and cached like Flint's (`TokenizerVocabularyCache`, four entries).
+``, ``, ``, `<|im_end|>` and,
+for Qwen and Bonsai, `<|endoftext|>` cannot complete anywhere in it, strings
+included, and an answer terminator is allowed only once the value is complete.
+Lightning's `` has no piece, so its spelling (an HTML close tag) stays
+writable.
+
+`JSONAnswerVocabulary` admits the profile's byte-level BPE ids and its
+``/`` tokens only; other added and special tokens and the model's
+padding are never allowed. Qwen and Bonsai: BPE ids below `<|endoftext|>`
+(248044), padding up to 248,320, the markers `` 248068, `` 248069;
+Qwen's terminators are `<|im_end|>` 248046 and `<|endoftext|>` 248044, Bonsai's
+`<|im_end|>` alone (its 27B artifact names no other EOS; a slot that also stops
+at 248044 never samples it). Lightning: its 1,000 special and added tokens come
+first, BPE ids 1000–131071, the markers `` 12 and `` 13 (ordinary
+output pieces), terminators `<|im_end|>` 11 and `` 2 (the checkpoint's two
+EOS ids). Before constraining, it checks that every terminator is an engine
+stop token (first, so a mismatched slot never decodes the vocabulary), each
+marker and terminator by id, spelling, encoding and decoding, and that every id
+in the BPE range decodes as a byte-level piece. It is built on the first such
+request per loaded tokenizer and stop set and cached like Flint's
+(`TokenizerVocabularyCache`, four entries).
A constraint's budget must equal the engine request's `maxTokens`, or the engine
refuses it (`CBv2SchedulerError.tokenConstraintBudgetMismatch`). The bridge
@@ -3638,25 +3755,36 @@ ends the answer as a normal `length` finish with its content as generated
apply as for the other Qwen requests; a stop that cuts the value short fails the
same check.
+Constraining keeps an answer inside the schema, not on topic: a model that wants
+a key the schema forbids may keep writing the string it is in (one Lightning
+answer ran 1,955 tokens repeating its `reply` before closing it), and one asked
+for a `json_object` without a JSON-shaped prompt may put its prose in a key.
+These rows have no loop guard; a long one ends at `max_tokens` as a `length`
+finish with its answer as generated (unchecked).
+
Every other case keeps prompt-only steering and gains no refusal. A schema
outside the subset (including an enum value containing a forbidden spelling), a
tokenizer that fails the checks, a prompt tail without a think marker or a
-nonpositive budget logs one content-free private line (category `json-answer`).
+nonpositive budget logs one content-free private line (category `json-answer`);
+a Bonsai or Lightning prompt that opens a thought logs nothing.
Tools or `tool_choice` beside the format keep today's behavior; Flint's
format-over-tools precedence does not apply. Image and video requests take the
media path, which installs no token constraint.
-A constrained row never drafts (`EngineLoopV2.mtpBasicEligible`). Qwen 3.5
-targets do not declare the row-exact recurrent fallback
+A constrained row never drafts (`EngineLoopV2.mtpBasicEligible`). Neither the
+Qwen 3.5 targets nor Lightning's declare the row-exact recurrent fallback
(`CBv2RecurrentMTPRequestScopedMediaFallback`), so
`ineligibleRowsDecodeBesideSpeculation` is false for their MTP driver and
`EngineLoopV2.mtpDraftBatchRows` keeps the whole cohort: while a constrained
row is in a decode step, no row in that step speculates. A `stop`,
`logit_bias`, penalty or logprob row has the same effect on these engines.
Decoding such rows beside speculation needs that SDK capability and row-exactness
-evidence for the Qwen target.
+evidence for each target. Bonsai 2 27B has no drafter. Lightning drafts, so only
+its answer-first prompts (thinking off) are constrained: those trigger it, and
+every Lightning row sharing their decode step, thinking or not, stops
+speculating meanwhile.
-Sources: `provider-swift/Sources/ProviderCore/Inference/Tools/QwenJSONAnswerPolicy.swift`,
+Sources: `provider-swift/Sources/ProviderCore/Inference/Tools/JSONAnswerPolicy.swift`,
`provider-swift/Sources/ProviderCore/Inference/JSONAnswerProfile.swift`,
`provider-swift/Sources/ProviderCore/Inference/JSONAnswerVocabulary.swift`,
`provider-swift/Sources/ProviderCore/Inference/JSONAnswerConstraint.swift`,
@@ -3864,10 +3992,11 @@ breaking a contract, and OpenRouter does not count a call cut by the caller's
end unparseable, as in an OpenAI stream the limit cut, and no client can run
the call; the stream finishes `length`. A call not yet exposed is not
exposed.
-- A constrained JSON answer (exact Flint, constrained Qwen) skips its final
- check. GLM's withheld JSON answer leaves normalized when it already holds a
- whole valid value (the candidate extraction, as before), and otherwise as
- generated (`GLM5NextResponseFormatOutput.finalAnswer`).
+- A constrained JSON answer (exact Flint; Qwen, Bonsai 2 27B and Lightning
+ under the JSON-answer grammar) skips its final check. GLM's withheld JSON
+ answer leaves normalized when it already holds a whole valid value (the
+ candidate extraction, as before), and otherwise as generated
+ (`GLM5NextResponseFormatOutput.finalAnswer`).
- Withheld calls (forced choices, native families, `DARKBLOOM_TTFT_STREAM_TOOL_CALLS=0`)
whose set fails its checks are checked one by one, and a call that fails is
dropped instead of refused: forced choices hold every call to its schema, as
@@ -4124,6 +4253,69 @@ provider release with them is tagged without being published to auto-update,
snapshotted into #721, and published only once #721 is deployed, each step on
the owner's go.
+### Strict tool-call grammar
+
+A `strict` `auto` call is checked against the caller's schema only when its
+frame closes ([streamed auto tool calls](#streamed-auto-tool-calls)), after the
+answer has started, so on the Qwen 3.5 template family (`qwen3_5`,
+`qwen3_5_moe`: Qwen 3.5 9B and 35B, 3.6 and 3.8) the provider also constrains
+such calls in the sampler. `QwenStrictToolGrammar` (in
+`provider-swift/Sources/ProviderCore/Inference/Tools/`) admits a request that
+is `auto`, declares a `strict` function (any tools with
+`DARKBLOOM_STRICT_TOOL_GRAMMAR_ALL_TOOLS`), parses with `.qwen35`, has no media,
+runs on an engine that samples under token constraints (not a cluster pair, not
+a native-tracked engine) and whose prompt ends in an open or closed think
+block; the scheduler's text path asks it after `ToolConstraintFactory`. Every
+declared tool must compile (`QwenStrictToolSchema`): local `$ref`s are inlined
+(cycles refused), `anyOf`/`oneOf` of one schema and `null`, a single `allOf`
+branch and objects beside an open object are folded, annotations (`format`
+included) are dropped, and the rest must fit the shared fail-closed subset
+(`ToolConstraintSchemaCompiler.compileResponseSchema`). Anything else, an
+unrecognized prompt boundary or a vocabulary that does not verify leaves the
+request as before, with a content-free log line, never a refusal.
+
+`QwenStrictToolConstraint` is a byte-level automaton over the shared Qwen
+vocabulary contract (`JSONAnswerVocabulary` with the call markers as pieces).
+Reasoning and text are free and only watched for `` and ``;
+they admit every byte-level piece, the think and call markers and the stop
+tokens, so an answer can end wherever it could before (the other added tokens,
+such as `<|im_start|>` or the media placeholders, are not sampled). After
+``, whitespace may precede `\n`, `\nVALUE\n\n`,
+`\n`): a declared function, declared parameters at most
+once, required ones before ``; with `parallel_tool_calls: false` no
+second call opens. A value's grammar follows how `Qwen35ToolCallParser` reads it
+under the rendered schema (`QwenStrictToolSchema.parserConversion`, a mirror of
+the SDK's `ToolArgumentNormalization` that `QwenStrictToolGrammarTests` checks
+against the parser): text the parser keeps as a string is free (or one of an
+enum's values), and a value it converts is one JSON value of the declared
+schema (`FlintJSONGrammar`). The request stays unconstrained where the parser's
+reading and the declared type disagree (a top-level `$ref` the render repair
+typed as a string) or where the streamed call would expose a converted value as
+text (`QwenStrictToolSchema.streamsAsText`, the mirror of
+`Qwen35ArgumentStreamer`, for example a `{"type":"null"}` parameter). No value
+can spell `` or a turn, reasoning or call marker, and a JSON value
+never writes a surrogate escape (`\uD800`…`\uDFFF`; the parser's
+JSONSerialization refuses a lone one and the value would stay a string; an
+escaped backslash followed by such text is refused too). The validator still
+checks every call.
+
+Calls drafted inside the thought are reasoning to the grammar. Where the Qwen
+route parses calls before it splits off the reasoning, such a call is parsed
+and checked like any other, unconstrained; where the reasoning is split first,
+only a call at the end of a thought that never closes is. The loop guard stays on
+(`GenerationLoopGuardPolicy`); the continuation after an exited thought runs
+without the grammar. As with constrained JSON answers (above), a constrained row
+never drafts MTP tokens and, on these engines, no row of a decode step it shares
+speculates (`ineligibleRowsDecodeBesideSpeculation` is false). Where a Mac would
+draft (at most `maxSpeculativeBatch` decode rows, 8 by default; the 3.6 and 35B
+cards' presence penalty already keeps those builds from drafting), the whole
+constrained answer, reasoning included, and every answer decoding beside it run
+target-only while it decodes.
+
### Vision constraints
- **One image per tower pass.** `EngineV2VisionTowerRun` drives the Qwen
@@ -5032,7 +5224,7 @@ these sources recursively (`provider-swift/Package.swift`, `package`).
| MTP | `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAutomaticVerificationPolicy.swift`, `provider-swift/Sources/ProviderCore/Inference/MTP/EngineV2MTPAssistant.swift`, `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift` |
| Vision | `provider-swift/Sources/ProviderCore/Inference/Vision/MediaIngest.swift`, `provider-swift/Sources/ProviderCore/Inference/Vision/VisionTowerBudget.swift`, `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionTowerRun.swift`, `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift` |
| Tool constraints, reasoning probe | `provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintFactory.swift`, `provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningPromptProbe.swift` |
-| Constrained JSON answers | `provider-swift/Sources/ProviderCore/Inference/Tools/QwenJSONAnswerPolicy.swift` (`QwenJSONAnswerPolicy`), `provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift` (`JSONAnswerFormat`, `JSONAnswerOutput`), `provider-swift/Sources/ProviderCore/Inference/JSONAnswerConstraint.swift`, `provider-swift/Sources/ProviderCore/Inference/ByteLevelVocabulary.swift` |
+| Constrained JSON answers | `provider-swift/Sources/ProviderCore/Inference/Tools/JSONAnswerPolicy.swift` (`JSONAnswerPolicy`), `provider-swift/Sources/ProviderCore/Inference/JSONAnswerProfile.swift` (`JSONAnswerProfile`), `provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift` (`JSONAnswerFormat`, `JSONAnswerOutput`), `provider-swift/Sources/ProviderCore/Inference/JSONAnswerConstraint.swift`, `provider-swift/Sources/ProviderCore/Inference/ByteLevelVocabulary.swift` |
| Engine contracts, timing, scheduler, loop | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift`, `SchedulerV2.swift`, `EngineLoopV2.swift`, `CBv2RequestTiming+Stamps.swift` |
### Native Flint
diff --git a/docs/developer/test.md b/docs/developer/test.md
index f802d7d60a..3558aad13d 100644
--- a/docs/developer/test.md
+++ b/docs/developer/test.md
@@ -2268,7 +2268,7 @@ CPU-only JSON-answer suites from `provider-swift/` together with the Flint suite
whose automaton they share:
```bash
-../scripts/run-nested-suite.sh 'QwenJSONAnswer(Constraint|Policy|Output|Serving)Tests|FlintResponseFormat|FlintNativeProtocol|FlintAnswerStop' --no-parallel
+../scripts/run-nested-suite.sh 'QwenJSONAnswer(Constraint|Policy|Output|Serving)Tests|JSONAnswerFamily(Serving)?Tests|FlintResponseFormat|FlintNativeProtocol|FlintAnswerStop' --no-parallel
```
`QwenJSONAnswerConstraintTests` drives the production constraint over a
@@ -2282,17 +2282,32 @@ every prompt-only fallback through `ToolConstraintFactory.make`, and
`QwenJSONAnswerServingTests` samples a scripted engine through the real bridge
and scheduler: streamed content, a typed 422 on truncation, requested reasoning
split before validation, and unchanged tool and other-family paths.
-
-`QwenJSONAnswerRealTokenizerTests` is opt-in. Set
+`JSONAnswerFamilyTests` covers the other admitted families through
+`JSONAnswerPolicy`: Bonsai 2 27B on Qwen's ids under its own name and
+terminator, Lightning on its Nemotron contract (a synthetic tokenizer with the
+special and added tokens at ids below 1,000 and byte pieces from 1000),
+reasoning-first prompts and cluster pairs staying prompt-only (the pair flag
+through `ToolConstraintFactory.make`), unlisted builds of a shared `model_type`
+(the Bonsai 2 9B among them), the `DARKBLOOM_JSON_ANSWER_GRAMMAR` values, a
+mismatched contract, and the Nemotron vocabulary's admitted ids and terminators.
+`JSONAnswerFamilyServingTests` streams a Bonsai and a Lightning answer through
+the scheduler's forwarding body with the routing flags production passes.
+
+`QwenJSONAnswerRealTokenizerTests`, `BonsaiJSONAnswerRealTokenizerTests` and
+`NemotronJSONAnswerRealTokenizerTests` are opt-in. Set
`DARKBLOOM_TEST_QWEN_TOKENIZER_DIR` to a local Qwen 3.5, 3.6 or 3.8 snapshot
-directory and select that suite alone; it reads only tokenizer and template
-files, checks the pinned contract and both rendered JSON prompt tails, and walks
-a real tokenization of an answer. Without the variable the suite is skipped,
-which the nested runner reports as an error. None of these suites loads weights
-or establishes answer quality or throughput. Sources:
+directory, `DARKBLOOM_TEST_BONSAI_TOKENIZER_DIR` to a Bonsai 2 27B one or
+`DARKBLOOM_TEST_NEMOTRON_TOKENIZER_DIR` to a Nemotron 3.5 Lightning one, and
+select that suite alone; it reads only tokenizer, template and config files,
+checks the pinned contract (the Bonsai and Nemotron suites against the stop set
+the slot gets: the artifact's EOS plus the tokenizer's) and both rendered JSON
+prompt tails, and walks a real tokenization of an answer. Without the variable
+the suite is skipped, which the nested runner reports as an error. None of these
+suites loads weights or establishes answer quality or throughput. Sources:
`provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerConstraintTests.swift`,
`provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerServingTests.swift`,
-`provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerRealTokenizerTests.swift`.
+`provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONAnswerRealTokenizerTests.swift`,
+`provider-swift/Tests/ProviderCoreTests/Inference/Tools/JSONAnswerFamilyTests.swift`.
## Flint native validation
diff --git a/docs/provider/direct-mode.md b/docs/provider/direct-mode.md
index ccd0dce36f..2c6c80b2f8 100644
--- a/docs/provider/direct-mode.md
+++ b/docs/provider/direct-mode.md
@@ -569,7 +569,7 @@ envelope, the same on one Mac and on a [two-Mac cluster](./two-mac-cluster.md):
| A content part whose `type` is none of `text`, `input_text`, `output_text`, `image_url`, `input_image`, `video_url`, `input_audio` (for example `input_file`, `input_video`, `refusal`) | HTTP `400` before model acquisition or SSE headers: `Content part type "" is not supported. Send text, image_url, video_url or input_audio parts.` The type is shown with at most 64 of its letters, digits and `_.-:/`. Models without native audio still refuse `input_audio` | `libs/mlx-swift-lm/Libraries/MLXLMServer/Runtime/OpenAIRequestValidation.swift` (`OpenAIRequestValidationError.unsupportedContentPart`) |
| A reasoning effort that is none of `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` (for example `turbo`), on a model that reasons | HTTP `400` before the prompt renders or any KV is reserved, code `invalid_reasoning_effort`, `param` the field it came in (`reasoning_effort`, `reasoning.effort`, or GLM-5.3-Flash's `chat_template_kwargs.reasoning_effort`): `reasoning_effort must be one of: none, minimal, low, medium, high, xhigh, max.` The request may hold its model first: a cold model loads, and with Both, me first it counts as your use of the Mac. Through the coordinator the same request gets HTTP `400` `invalid inference request` | `provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningEffort.swift` (`ReasoningEffortPolicy.validate`); `provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift` (`CORSResponder`) |
| On Nemotron 3.5 Super, `reasoning_effort` and `reasoning.effort` that differ, even two names (`high` and `max`). The same effort in both, in any spelling, is served | HTTP `400` at the same point, code `invalid_reasoning_effort`, `param` `reasoning_effort, reasoning.effort`: `reasoning_effort and reasoning.effort must be the same when both are sent, one of: none, minimal, low, medium, high, xhigh, max.` Through the coordinator, HTTP `400` `invalid inference request` | `provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperPromptContract.swift` (`controls(body:)`); `provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift` (`CORSResponder`) |
-| `response_format` `json_object`/`json_schema` whose answer stopped at `max_tokens` before it was complete (a reasoning model can spend the whole budget thinking) | HTTP `422`: `The output was cut off by max_tokens before the structured (response_format) answer was complete. Raise max_tokens or lower the reasoning effort, and retry.` Invalid JSON at a natural stop keeps its `422` with the closed internal-failure message. GLM-5.3-Flash validates its withheld JSON answer itself (`GLM5NextResponseFormat`) and answers a truncated one with that closed `422` | `libs/mlx-swift-lm/Libraries/MLXLMServer/Runtime/MLXOpenAIService.swift` (`MLXOpenAIServiceError.responseFormatCutOffByMaxTokens`); `provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift` (`CORSResponder`); `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift` (`validatedContent`) |
+| `response_format` `json_object`/`json_schema` whose answer stopped at `max_tokens` before it was complete (a reasoning model can spend the whole budget thinking) | HTTP `422`: `The output was cut off by max_tokens before the structured (response_format) answer was complete. Raise max_tokens or lower the reasoning effort, and retry.` Invalid JSON at a natural stop keeps its `422` with the closed internal-failure message. A grammar-constrained answer (Qwen 3.5, 3.6 and 3.8; Bonsai 2 27B and Nemotron 3.5 Lightning on one Mac when the prompt starts in the answer) is checked by the provider instead: one cut at `max_tokens` ends `finish_reason: length` with its content as generated; one that misses at a natural stop is HTTP `422` with the family's closed message, ` content does not satisfy the json_schema` (or `is not a single JSON value`, `json_object content must be a JSON object`), after the content already streamed. GLM-5.3-Flash validates its withheld JSON answer itself (`GLM5NextResponseFormat`) and answers a truncated one with that closed `422` | `libs/mlx-swift-lm/Libraries/MLXLMServer/Runtime/MLXOpenAIService.swift` (`MLXOpenAIServiceError.responseFormatCutOffByMaxTokens`); `provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift` (`CORSResponder`); `provider-swift/Sources/ProviderCore/Inference/Prompting/JSONAnswerFormat.swift` (`JSONAnswerOutput`); `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift` (`validatedContent`) |
| GLM-5.3-Flash with images or video and a required or named `tool_choice` on any Mac, or `response_format` `json_object`/`json_schema` on a cluster pair | HTTP `400` `Invalid inference request.` (failure code `invalid_request`) before any media decode: only the text path withholds and validates a forced call, and a pair's media routes withhold neither. One Mac serves `json_object`/`json_schema` with images or video as on text: reasoning on its own channel, the answer withheld and validated (`422` when it isn't the JSON asked for). Hidden reasoning (`reasoning.exclude: true`, `include_reasoning: false`, `thinking.display: "omitted"`) is served with media too, its reasoning withheld | `provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift` (`prepareCompletion`); `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift` (`withholdsOutput`, `withholdsReasoning`) |
| An image or video the model's processor refuses: for Qwen 3.5 and 3.8 a side below `patch_size × merge_size` (32 pixels) or an aspect ratio above 200:1, which it does not upscale; a video without a decodable track; more images or videos than the processor takes | HTTP `400` `Invalid media input.` (failure code `invalid_media`), before the vision tower or any native reservation, never the retryable `503` | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift` (`clientFault(for:)`) |
| A video whose reader fails on GLM 5.3, MiMo V2.6, Qwen4 or Nemotron Super after its metadata checks passed, or whose audio track's reader fails on MiMo V2.6 | The provider decodes the track once more with a new reader. If that succeeds, the request is served. If it fails again with a decoder, hardware or interruption code, HTTP `503` (failure code `capacity`, error reason `media_memory_unavailable`), which a coordinator retries on another provider; any other second failure is HTTP `400` `Invalid media input.` (failure code `invalid_media`). Each failed pass logs a WARN `engine_health` event, `video_reader_failed` or `audio_reader_failed`, with the reader status and error codes only | `libs/mlx-swift-lm/Libraries/MLXLMCommon/VideoReaderFailure.swift` (`VideoReaderRetry`); `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift` (`clientFault(for:)`); `provider-swift/Sources/ProviderCore/Inference/Vision/MiMo/MiMoV26EncodedMediaIngress.swift` (`outwardFailure`); `provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift` (`SuperHTTPErrors.map`) |
diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md
index 1b40191de5..1d10c11925 100644
--- a/docs/provider/two-mac-cluster.md
+++ b/docs/provider/two-mac-cluster.md
@@ -569,7 +569,9 @@ a Qwen pair before any output: a pair's ranks cannot apply the grammar
request refused this way to a single Mac, which constrains it
(darkbloom-platform `fix/coord-pair-refusal-failover`); a request to the owner's
local cluster API gets the refusal. Other JSON requests are served with the
-format instruction only, as on one Mac
+format instruction only, as on one Mac, and so is every JSON request on a
+Bonsai 2 27B or Nemotron 3.5 Lightning pair, which a single Mac would constrain
+when the prompt starts in the answer
([constrained Qwen JSON answers](../architecture/inference.md#constrained-qwen-json-answers)).
| # | Where | What you do | What it asks |
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
index 06a82e9f36..0cd029399f 100644
--- a/docs/reference/configuration.md
+++ b/docs/reference/configuration.md
@@ -542,6 +542,7 @@ and rollback are defined in the [provider configuration reference](../provider/c
| `DARKBLOOM_GLM_JSON_SCHEMA_MISS` | `release` (trimmed, case-insensitive); anything else is `refuse` | `refuse` | `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift` (`GLM5NextSchemaMiss`) | A GLM-5.3-Flash JSON `response_format` answer whose JSON value misses its `json_schema` is the typed 422 (`refuse`) or, when the model stopped by itself, is exposed as that value (`release`), for the caller's own validator to judge. Output with no complete JSON value, and output the token limit cut, are judged as with `refuse`. It applies to streamed responses (every coordinator request): a non-streamed local API request still gets the service's own schema check. Forwarded to the launchd provider job. |
| `DARKBLOOM_TTFT_FUSED_CAUSAL_PREFILL` | exact `0` disables | on | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/AttentionV1.swift` (`CBv2AttentionV1.fusedCausalPrefillEnabled`, `usesFusedCausalPrefill`) | Full-attention prompt chunks whose head geometry MLX serves with a fused kernel take one `.causal` SDPA call on either KV backend, except live packed paged KV ([eligible chunks](../architecture/inference.md#scheduler-and-loop-configuration)); `0` returns them to 128-query blocks. Read once per process; not forwarded to LaunchAgents. |
| `DARKBLOOM_CBV2_LEGACY_REQUEST_TIMEOUT` | affirmative | off | `provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+Configuration.swift` | Restores the legacy per-request timeout. |
+| `DARKBLOOM_GEMMA_JSON_ANSWERS` | `off`, `0`, `false`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Tools/GemmaJSONAnswerPolicy.swift` (`GemmaJSONAnswerPolicy.enabled`) | Gemma 4 answers to a JSON `response_format` are sampled under the request's JSON grammar after a free thought ([constrained Gemma 4 JSON answers](../architecture/inference.md#constrained-gemma-4-json-answers)); off restores prompt-only answers. Read once at launch. Forwarded by LaunchAgent. |
| `DARKBLOOM_CBV2_MTP` | negative disables | unset (beta flag decides) | `provider-swift/Sources/ProviderCore/SpecDec/SpecDecArtifactFunnel.swift`; `provider-swift/Sources/ProviderCore/Config/BetaFeatures.swift` | Kill switch for MTP speculation; beats the `provider.toml` beta flag. See [`../provider/beta-features.md`](../provider/beta-features.md). |
| `DARKBLOOM_MTP_MAX_RECTANGULAR_TOKENS` | integer | policy default | `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAutomaticVerificationPolicy.swift` | Tighten-only cap on rectangular MTP verification tokens. |
| `DARKBLOOM_TTFT_QWEN_MTP_CHAINED` | `0`, `false`, `no`, `off` disable | on | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift` (`CBv2MTPConfig.envOrdinaryDecodeHistory`) | While no Qwen inline-MTP row can speculate (more decode rows than its speculative batch of one), steps in which every MTP-eligible row is decoding run as ordinary chainable decode with no policy top-two; finalize feeds the assistant history and carry. Off restores hidden-returning seed steps. Not forwarded to LaunchAgents. |
@@ -558,6 +559,8 @@ and rollback are defined in the [provider configuration reference](../provider/c
| `DARKBLOOM_NEMOTRON_SUPER_VIDEO_PRUNING` | number in [0, 1) (surrounding spaces ignored) | `0.5` (`NemotronSuperVideoPreprocessing.defaultPruningRate`) | `provider-swift/Sources/ProviderCore/Inference/Vision/NemotronSuperVideoFeatures.swift` (`validatedPruningRate`) | EVS pruning rate `q` of Super video requests, in the managed slot and the qualification hook: a video of `T` tubelets of `N` visual rows keeps `max(N, int(T * N * (1 - q)))` rows; `0` keeps every row. Any other value fails the load before its LOAD claim and installation. A value below `0.5` keeps more rows, so a video's prompt has more tokens than the coordinator estimates for it, since that estimate assumes `0.5`. Not forwarded to LaunchAgents. |
| `DARKBLOOM_MTP_VERIFICATION_MODE` | `rectangular`, `serial`, `serial_target`, `automatic` | `automatic` | `provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift` | MTP verification strategy (benchmark session). |
| `DARKBLOOM_MTP_ACCEPTANCE` | `exact`, `typical`, `typical:` (finite positive delta) | `exact` | `provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift`; `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift` (`benchmarkOverride`) | MTP draft acceptance rule (benchmark session only). An unrecognized value uses `exact`. Serving reads no environment variable for this rule; it reads `[backend] mtp_acceptance` and `mtp_acceptance_by_model` in [`provider.toml`](../provider/cli-reference.md#providertoml-keys-read-by-the-cli). |
+| `DARKBLOOM_STRICT_TOOL_GRAMMAR` | unset or `on`, `1`, `true`, `yes`: the default builds; an off word (`off`, `0`, `false`, `no`, `none`, `disabled`) disables; otherwise a comma list of `model_type`s or model-id parts (trimmed, case-insensitive) | on for `qwen3_5`, `qwen3_5_moe` | `provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift` (`setting`) | Qwen 3.5-family `auto` requests that declare a `strict` function sample every call's function, parameters and values under the declared schemas on one Mac; a request whose schemas fall outside the grammar, or a cluster pair, is served unconstrained. While a constrained answer decodes, no answer on that Mac drafts with MTP. See [strict tool-call grammar](../architecture/inference.md#strict-tool-call-grammar). Forwarded to the LaunchAgent. |
+| `DARKBLOOM_STRICT_TOOL_GRAMMAR_ALL_TOOLS` | `on`, `1`, `true`, `yes` enable (trimmed, case-insensitive) | off | `provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift` (`allTools`) | Also constrains the calls of requests that declare no `strict` function. Forwarded to the LaunchAgent. |
| `DARKBLOOM_PREFILL_DEADLINE_MODE` | exactly `off` disables; any other value enforces | `enforce` | `provider-swift/Sources/ProviderCore/Inference/Engine/PrefillDeadlineMode.swift` (`PrefillDeadlineMode.resolve`) | Prefill-deadline admission on the provider. Read only when `[backend] prefill_deadline_mode` is absent from `provider.toml`; that key takes precedence. |
| `DARKBLOOM_TTFT_ADMISSION_FIXES` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`DeadlineAdmissionFixes`) | Deadline-admission estimator corrections: per-batch decode charging, anchored isolated-prefill rate, newest-observation freshness, a probe that re-measures stale isolated-prefill evidence after three refusals it explains. Off restores the previous estimators and turns that probe off too. Forwarded to the launchd provider job. |
| `DARKBLOOM_TTFT_NATIVE_PREFILL_EVIDENCE` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`NativePrefillEvidence`) | GLM-5.3-Flash and native MiMo V2.6 only ([deadlines](../architecture/inference.md#deadlines)): a cold prompt of at most 4,096 tokens may raise the prefill estimate but never lower it, and the smallest prompt-size bucket (up to 1,024 tokens) no longer tightens a prompt. An idle Mac at nominal posture with no calibration cell or longer prompt in the last 120 s is priced at no less than its calibration cell, so once calibrated it takes no short-prompt recovery; a busy Mac or another posture keeps one eighth of the cell as its floor. A slower isolated short sample stays out of the published isolated and observed prefill rates. Off (or `DARKBLOOM_TTFT_ADMISSION_FIXES=0`) restores the previous estimator. Other models, Diffusion Gemma included, are unchanged. Forwarded to the launchd provider job. |
@@ -572,6 +575,7 @@ and rollback are defined in the [provider configuration reference](../provider/c
| `DARKBLOOM_LENGTH_FINISH_AT_LIMIT` | `0`, `off`, `false`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Tools/ToolOutputLeniency.swift` (`TokenLimitCutPolicy`) | An answer the engine cut at the token limit ends as a normal `length` completion as generated: a streamed call stays open with its fragments, unclosed; a withheld JSON answer leaves unchecked (GLM's normalized when it holds a whole value); withheld calls are checked one by one and those that fail are dropped (for `auto`, only the last, possibly cut, call is held to the declarations without `strict`). Off restores the `tool_noncompliance` refusal. Read once per process. See [cut answers](../architecture/inference.md#answers-cut-at-the-token-limit). Forwarded to the LaunchAgent. |
| `DARKBLOOM_STRICT_CALLS_AS_GENERATED` | `0`, `off`, `false`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Tools/ToolOutputLeniency.swift` (`StrictToolCallPolicy`) | A `strict` `auto` call that fails its check returns as generated once a streaming client's response has started; before that, and for a client that does not stream, it is refused. Off restores the refusal. Read once per process. See [strict calls after the start](../architecture/inference.md#strict-calls-after-the-response-started). Forwarded to the LaunchAgent. |
| `DARKBLOOM_TTFT_THINK_CONTENT_SEED` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningPromptProbe.swift` (`seedsPlainTailContentByDefault`) | Qwen3-VL (`qwen3_vl_moe`, `plainTailContentModelTypes`) requests on the `qwen3` reasoning parser whose prompt tail has no think marker start in content state, so the answer streams instead of waiting for a tag or the end of generation. Other model types, including close-only Qwen reasoners, keep undecided parsing. `0` restores undecided parsing. Forwarded to the LaunchAgent. |
+| `DARKBLOOM_JSON_ANSWER_GRAMMAR` | `qwen`, `0`, `off`, `false`, `no`, `none` (trimmed, case-insensitive) narrow; any other value or unset admits every family | every admitted family | `provider-swift/Sources/ProviderCore/Inference/Tools/JSONAnswerPolicy.swift` (`JSONAnswerPolicy.Families`) | Which families sample a tool-free JSON `response_format` answer under the grammar ([constrained Qwen JSON answers](../architecture/inference.md#constrained-qwen-json-answers)): Qwen 3.5/3.6/3.8, and for answer-first prompts on a single Mac Bonsai 2 27B and Nemotron 3.5 Lightning. The narrowing values keep it to the Qwen types, as before Bonsai and Lightning were admitted; the others then keep prompt-only steering. Read once per process. Forwarded to the LaunchAgent. |
### Managed Nemotron Super slot
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift
index 3a3a3548d3..c1c20cfe2d 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift
@@ -168,6 +168,8 @@ extension EngineV2Bridge {
/// (`GenerationLoopGuardPolicy`); nil leaves it unguarded.
loopGuard: GenerationLoopGuard? = nil
) async throws -> AsyncStream {
+ let tokenConstraint = Self.admittedConstraint(tokenConstraint, servesDistributedPair: servesDistributedPair,
+ tracksNativeShutdown: tracksNativeShutdown)
if let clusterStillImages {
guard mimoClusterImages == nil, multimodal == nil,
let binding = try clusterGLMImageIngress() else { throw DistributedEngineError.refused(.mediaUnsupported) }
diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
index 4c9f1c4098..3536601161 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift
@@ -1071,7 +1071,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
}
// Parser resolution precedes both text and qualified native media.
- let tokenConstraint: (any CBv2TokenConstraint)?
+ var tokenConstraint: (any CBv2TokenConstraint)?
do {
try checkFirstContentDeadline()
guard let bridge = engineV2Bridge else {
@@ -1094,7 +1094,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
modelId: request.model, modelType: modelType),
defaultMaxTokens: bridge.defaultMaxTokens,
stopTokenIDs: bridge.stopTokenIds,
- nativePromptTokens: promptTokens)
+ nativePromptTokens: promptTokens,
+ servesDistributedPair: request.responseFormat?.requiresJSONOutput == true
+ ? await bridge.servesDistributedPair : false)
// Grammar compile (Gemma) can take the tool-constraint lock on the
// first build per stop-set, and a JSON answer builds its vocabulary
// on the first request per tokenizer; only those are worth a lock.
@@ -1106,6 +1108,22 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
await releaseBox.fire()
throw error
}
+ // `strict` calls on the Qwen 3.5 text route: their arguments follow the
+ // declared schemas in the sampler. A request the grammar declines, or
+ // a slot that cannot run it, is served as before.
+ if tokenConstraint == nil, let bridge = engineV2Bridge,
+ QwenStrictToolGrammar.isEnabled(modelId: request.model, modelType: modelType),
+ QwenStrictToolGrammar.isCandidate(prepared: prepared, parser: toolHandler?.format) {
+ let start = SuspendingClock.now
+ let pair = await bridge.servesDistributedPair
+ let native = await bridge.tracksNativeShutdown
+ tokenConstraint = QwenStrictToolGrammar.constraint(
+ prepared: prepared, request: request, parser: toolHandler?.format, tokenizer: tokenizer,
+ modelType: modelType, defaultMaxTokens: bridge.defaultMaxTokens, stopTokenIDs: bridge.stopTokenIds,
+ promptTokens: promptTokens, runsTokenConstraints: !pair && !native)
+ // The first such request per tokenizer builds its vocabulary.
+ profile?.markDuration(.toolConstraint, start: start)
+ }
let answerStopFilter = (tokenConstraint as? FlintAnswerStopConstraint)?.makeStreamFilter()
// A constrained JSON answer is validated when generation ends, so its
// reasoning must already be a separate channel: validation sees only
@@ -2013,10 +2031,10 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
let cutAtLimit = prepared.cutAtLimit(finishReason: stopReason)
&& answerStops?.matchedSequence == nil
/// The answer's own end checks, after the calls': constrained
- /// response_format (exact Flint, Qwen) holds the completed
- /// content, not a truncated or schema-invalid prefix, and GLM's
- /// withheld JSON answer leaves only once it validates; a cut
- /// answer leaves as generated.
+ /// response_format (exact Flint, the JSON-answer families) holds
+ /// the completed content, not a truncated or schema-invalid
+ /// prefix, and GLM's withheld JSON answer leaves only once it
+ /// validates; a cut answer leaves as generated.
/// At a cut: a structured answer whose check, which the cut
/// skips, would have refused it.
var answerLeftUnchecked = false
@@ -2246,6 +2264,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
promotesTrailingReasoningCalls: Bool = false,
recordsWithheldOutput: Bool = false,
usageSignal: EngineV2RequestUsageSignal = EngineV2RequestUsageSignal(),
+ preserveInnerReasoningSpans: Bool = false,
+ absorbStrayThinkClose: Bool = false,
answerStopFilter: FlintAnswerStopFilter? = nil,
answerFormat: JSONAnswerFormat? = nil,
rewriteHarmonyFinalHeaders: Bool = false
@@ -2254,7 +2274,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
toolHandler: toolHandler, prepared: prepared, releaseBox: releaseBox,
usageSignal: usageSignal, reasoningPrefix: reasoningPrefix,
nativeReasoningPrefix: nativeReasoningPrefix, recordsWithheldOutput: recordsWithheldOutput,
- promotesTrailingReasoningCalls: promotesTrailingReasoningCalls,
+ preserveInnerReasoningSpans: preserveInnerReasoningSpans,
+ promotesTrailingReasoningCalls: promotesTrailingReasoningCalls, absorbStrayThinkClose: absorbStrayThinkClose,
answerStopFilter: answerStopFilter, answerFormat: answerFormat,
rewriteHarmonyFinalHeaders: rewriteHarmonyFinalHeaders)
}
diff --git a/provider-swift/Sources/ProviderCore/Inference/GemmaJSONAnswerConstraint.swift b/provider-swift/Sources/ProviderCore/Inference/GemmaJSONAnswerConstraint.swift
new file mode 100644
index 0000000000..fb9dc9d53a
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Inference/GemmaJSONAnswerConstraint.swift
@@ -0,0 +1,399 @@
+// Copyright © 2026 Eigen Labs.
+//
+// JSON `response_format` answers on Gemma 4. Its tokenizer is SentencePiece
+// BPE, not byte-level: pieces spell a space as U+2581 and reach other bytes
+// through 256 byte-fallback tokens. `GemmaAnswerPieces` gives each id the bytes
+// the stream decodes it to, so the shared byte-level JSON lexer
+// (`FlintJSONState`) drives the mask as it does for Qwen. The thought
+// (`<|channel>` ... ``) stays free; the answer is one JSON value of
+// the request's format, then `` or ``.
+
+import Foundation
+import MLXLMCommon
+
+extension JSONAnswerProfile {
+ /// Gemma 4 (`gemma4`, `gemma4_text`): 262,144 SentencePiece ids. No id is
+ /// byte-level BPE (`bpeIDs` empty): `GemmaAnswerPieces` spells them.
+ /// The thought markers are pieces so the thought can open and close; every
+ /// control spelling stays impossible in the answer. Answers end with
+ /// `` or ``.
+ static let gemma4 = JSONAnswerProfile(
+ family: "Gemma",
+ thinkClose: GemmaAnswerPieces.thoughtClose,
+ reasoningStops: [],
+ contentMarkers: GemmaAnswerPieces.controlSpellings,
+ bpeIDs: 0..<0,
+ pieceTokens: [.init(spelling: GemmaAnswerPieces.thoughtOpen, id: 100),
+ .init(spelling: GemmaAnswerPieces.thoughtClose, id: 101)],
+ answerEOS: [.init(spelling: "", id: 106), .init(spelling: "", id: 1)],
+ vocabularySize: 262_144)
+}
+
+/// A Gemma 4 JSON-answer vocabulary and the longest run of JSON whitespace any
+/// of its pieces starts with (31 bytes for Gemma 4: thirty-one newlines).
+struct GemmaAnswerVocabulary: Sendable {
+ let json: JSONAnswerVocabulary
+ let leadingWhitespace: Int
+
+ init(_ json: JSONAnswerVocabulary) {
+ self.json = json
+ leadingWhitespace = json.pieceTokenIDs.reduce(0) { longest, id in
+ max(longest, json.pieces[id].prefix(while: FlintJSONState.whitespace).count)
+ }
+ }
+}
+
+/// Gemma 4's vocabulary as the bytes its decoder produces (U+2581 to a space,
+/// byte fallback, fuse; no strip). The provider's tokenizer runs no
+/// clean-up for Gemma (`LocalTokenizerLoader`).
+enum GemmaAnswerPieces {
+ static let thoughtOpen = "<|channel>"
+ static let thoughtClose = ""
+ /// Gemma 4's added tokens. None is text, and no answer may spell one:
+ /// the stream's parsers read them as framing.
+ static let controlSpellings = [
+ "", "", "", "", "", "<|tool>", "", "<|tool_call>", "",
+ "<|tool_response>", "", "<|\"|>", "<|think|>", "<|channel>", "", "<|turn>",
+ "", "<|image>", "<|audio>", "<|image|>", "<|audio|>", "", "`.
+enum QwenStrictToolFraming: Int8, Hashable, Sendable {
+ /// After the function name's `>`, and after a text value's ``.
+ case lineBreak
+ /// ``.
+ case valueOpen
+ /// After a complete choice or JSON value, entered after its line break.
+ case valueClose
+ /// `\n`, entered after its first two bytes.
+ case callClose
+
+ var bytes: [UInt8] {
+ switch self {
+ case .lineBreak, .valueOpen: Self.lineBreakBytes
+ case .parameterOpen: Self.parameterOpenBytes
+ case .valueClose: QwenStrictToolSchema.valueClose
+ case .callClose: Self.callCloseBytes
+ }
+ }
+
+ private static let lineBreakBytes: [UInt8] = [10]
+ private static let parameterOpenBytes = Array("\n".utf8)
+}
+
+/// The spellings each span of a call watches, built once per constraint,
+/// and whether a second call may follow the first.
+struct QwenStrictToolMarkers: Sendable {
+ /// A text value: its closing tag ends it; any other is refused.
+ let text: [[UInt8]]
+ /// A JSON value: every one is refused.
+ let value: [[UInt8]]
+ /// `parallel_tool_calls: false`: no call opens after one closed.
+ let singleCall: Bool
+
+ init(forbidding markers: [[UInt8]], singleCall: Bool = false) {
+ text = markers + [QwenStrictToolBoundary.parameterClose]
+ value = text + QwenStrictToolBoundary.surrogateEscapes
+ self.singleCall = singleCall
+ }
+}
+
+/// Interned parse position of a Qwen 3.5 response under the strict-tool
+/// grammar. Reasoning and text outside calls are free and only watched for
+/// the marker that leaves them; inside a call every byte follows the call
+/// framing and the declared schemas. No reasoning, text or argument body is
+/// accumulated.
+struct QwenStrictToolBoundary: Hashable {
+ enum Step: Hashable {
+ /// Prompt-opened reasoning, free until ``.
+ case reasoning
+ /// Free text, until `` opens a call.
+ case content
+ /// After ``: whitespace, then the bytes of ``.
+ case text
+ /// A choice value and its closing framing, typed so far.
+ case choice([UInt8])
+ case json(FlintJSONState)
+ }
+
+ static let thinkClose = Array("".utf8)
+ static let callOpen = Array("".utf8)
+ static let parameterClose = Array("".utf8)
+ static let functionOpen = Array("`).
+ var isOpaqueSpan: Bool {
+ switch step {
+ case .reasoning, .content, .text: true
+ default: false
+ }
+ }
+
+ var inJSONStringBody: Bool {
+ if case .json(let state) = step { return state.inStringBody }
+ return false
+ }
+
+ mutating func consume(_ byte: UInt8, schema: QwenStrictToolSchema, markers: QwenStrictToolMarkers) -> Bool {
+ switch step {
+ case .reasoning:
+ if Self.advance(&window, with: byte, markers: Self.reasoningMarkers) != nil {
+ window = []
+ step = .content
+ }
+ return true
+ case .content:
+ if Self.advance(&window, with: byte, markers: Self.contentMarkers) != nil {
+ guard !(markers.singleCall && closedCall) else { return false }
+ window = []
+ step = .opening(0)
+ }
+ return true
+ case .opening(let matched):
+ if matched == 0, (9...13).contains(byte) || byte == 32 { return true }
+ if byte == Self.functionOpen[Int(matched)] {
+ step = Int(matched) + 1 == Self.functionOpen.count ? .name([]) : .opening(matched + 1)
+ return true
+ }
+ if matched == 0, byte == 123 || byte >= 0x80 { return false }
+ // Text again, watched from the bytes after `` on.
+ step = .content
+ for previous in Self.functionOpen.prefix(Int(matched)) {
+ _ = Self.advance(&window, with: previous, markers: Self.contentMarkers)
+ }
+ return consume(byte, schema: schema, markers: markers)
+ case .fixed(let framing, let offset):
+ let bytes = framing.bytes
+ guard bytes[Int(offset)] == byte else { return false }
+ if Int(offset) + 1 < bytes.count {
+ step = .fixed(framing, offset + 1)
+ } else {
+ complete(framing, schema: schema)
+ }
+ return true
+ case .name(let prefix):
+ if byte == 62 {
+ guard let index = schema.tools.firstIndex(where: { $0.name == prefix }) else { return false }
+ tool = Int16(index)
+ seen = FlintJSONPropertySet()
+ step = .fixed(.lineBreak, 0)
+ return true
+ }
+ let extended = prefix + [byte]
+ guard schema.tools.contains(where: { $0.name.starts(with: extended) }) else { return false }
+ step = .name(extended)
+ return true
+ case .between(let afterAngle):
+ let declared = schema.tools[Int(tool)]
+ guard afterAngle else {
+ guard byte == 60 else { return false }
+ step = .between(true)
+ return true
+ }
+ if byte == 112, declared.parameters.indices.contains(where: { !seen.contains($0) }) {
+ step = .fixed(.parameterOpen, 2)
+ return true
+ }
+ if byte == 47, seen.isSuperset(of: declared.required) {
+ step = .fixed(.callClose, 2)
+ return true
+ }
+ return false
+ case .key(let prefix):
+ let parameters = schema.tools[Int(tool)].parameters
+ if byte == 62 {
+ guard let index = parameters.indices.first(where: { !seen.contains($0) && parameters[$0].name == prefix })
+ else { return false }
+ seen.insert(index)
+ parameter = Int16(index)
+ step = .fixed(.valueOpen, 0)
+ return true
+ }
+ let extended = prefix + [byte]
+ guard parameters.indices.contains(where: { !seen.contains($0) && parameters[$0].name.starts(with: extended) })
+ else { return false }
+ step = .key(extended)
+ return true
+ case .text:
+ guard let marker = Self.advance(&window, with: byte, markers: markers.text) else {
+ return true
+ }
+ guard marker == Self.parameterClose else { return false }
+ window = []
+ parameter = -1
+ step = .fixed(.lineBreak, 0)
+ return true
+ case .choice(let prefix):
+ guard case .choice(let spellings) = schema.tools[Int(tool)].parameters[Int(parameter)].value else {
+ return false
+ }
+ let extended = prefix + [byte]
+ guard spellings.contains(where: { $0.starts(with: extended) }) else { return false }
+ if spellings.contains(extended) {
+ parameter = -1
+ step = .between(false)
+ } else {
+ step = .choice(extended)
+ }
+ return true
+ case .json(var state):
+ guard case .json(let grammar) = schema.tools[Int(tool)].parameters[Int(parameter)].value else {
+ return false
+ }
+ if byte == 10, state.isComplete(grammar) {
+ window = []
+ step = .fixed(.valueClose, 1)
+ return true
+ }
+ // A value may never spell a marker, the tag that ends it, or a
+ // surrogate escape.
+ guard Self.advance(&window, with: byte, markers: markers.value) == nil,
+ state.consume(byte, grammar: grammar) else { return false }
+ step = .json(state)
+ return true
+ }
+ }
+
+ private mutating func complete(_ framing: QwenStrictToolFraming, schema: QwenStrictToolSchema) {
+ switch framing {
+ case .lineBreak:
+ step = .between(false)
+ case .parameterOpen:
+ step = .key([])
+ case .valueOpen:
+ switch schema.tools[Int(tool)].parameters[Int(parameter)].value {
+ case .text: step = .text
+ case .choice: step = .choice([])
+ case .json(let grammar): step = .json(FlintJSONState(grammar: grammar))
+ }
+ case .valueClose:
+ parameter = -1
+ step = .between(false)
+ case .callClose:
+ tool = -1
+ seen = FlintJSONPropertySet()
+ closedCall = true
+ step = .content
+ }
+ }
+
+ /// Keeps the longest window suffix that still starts a marker and returns
+ /// a marker this byte completed, however the output was split into tokens.
+ private static func advance(_ window: inout [UInt8], with byte: UInt8, markers: [[UInt8]]) -> [UInt8]? {
+ window.append(byte)
+ while !window.isEmpty && !markers.contains(where: { $0.starts(with: window) }) {
+ window.removeFirst()
+ }
+ return markers.first { window.count >= $0.count && window.suffix($0.count).elementsEqual($0) }
+ }
+}
+
+/// Constrains the arguments of every call a Qwen 3.5 answer opens to the
+/// declared schemas (`QwenStrictToolSchema`), and nothing else: reasoning and
+/// text stay free, an answer may end wherever it could before, and `auto`
+/// still lets the model choose whether to call. Inside a call the function
+/// must be declared, each parameter is declared and at most once, required
+/// ones come before ``, and each value is one the parser reads as
+/// a schema-valid argument. Per-request and host-only, like
+/// `JSONAnswerConstraint`, whose vocabulary and interning it shares.
+///
+/// Should the interned states ever run out, the constraint releases the rest
+/// of the answer to free sampling (as before the grammar) instead of failing
+/// it.
+final class QwenStrictToolConstraint: CBv2TokenConstraint, @unchecked Sendable {
+ let mode = CBv2TokenConstraintMode.auto
+ let maxTokens: Int
+ let initialState = 0
+ let fallbackTokenID: Int
+ let schema: QwenStrictToolSchema
+ let startsInReasoning: Bool
+ private let vocabulary: JSONAnswerVocabulary
+ private let markers: QwenStrictToolMarkers
+ /// Stop tokens sampled outside calls end the answer, as without a grammar.
+ private let freeStops: [Int]
+ private let lock = NSLock()
+ private var states: [QwenStrictToolBoundary]
+ private var stateIndex: [QwenStrictToolBoundary: Int]
+ private var allowedCache: [(state: Int, tokens: [Int])] = []
+ /// Opaque-span masks by refused pieces and whether stops are allowed.
+ private var broadMasks: [(rejected: Set, free: Bool, tokens: [Int])] = []
+ /// A call's opening masks by bytes of ` 0 else {
+ throw ToolConstraintSchemaError.invalid("strict tool grammars require a positive output budget")
+ }
+ self.schema = schema
+ self.vocabulary = vocabulary
+ self.markers = QwenStrictToolMarkers(forbidding: markers, singleCall: !allowsParallelCalls)
+ self.startsInReasoning = startsInReasoning
+ self.maxTokens = maxTokens
+ fallbackTokenID = vocabulary.fallbackTokenID
+ freeStops = vocabulary.stopTokenIDs.filter { vocabulary.pieces.indices.contains($0) }.sorted()
+ let initial = QwenStrictToolBoundary(reasoning: startsInReasoning)
+ states = [initial]
+ stateIndex = [initial: 0]
+ }
+
+ func allowedTokenIDs(state: Int, remainingTokens: Int) -> [Int] {
+ lock.lock(); defer { lock.unlock() }
+ guard remainingTokens > 0 else { return [] }
+ if state == Self.releasedState { return Self.merged(vocabulary.pieceTokenIDs, freeStops) }
+ guard states.indices.contains(state) else { return [] }
+ if let index = allowedCache.firstIndex(where: { $0.state == state }) {
+ let entry = allowedCache.remove(at: index)
+ allowedCache.append(entry)
+ return entry.tokens
+ }
+ let boundary = states[state]
+ var allowed: [Int]
+ if case .opening(let matched) = boundary.step {
+ if let mask = openingMasks[Int(matched)] {
+ allowed = mask
+ } else {
+ allowed = openingMask(boundary, matched: Int(matched))
+ openingMasks[Int(matched)] = allowed
+ }
+ } else if let sensitive = broadCandidates(boundary) {
+ // Opaque spans: only sensitive pieces can be refused, so the rest
+ // of the vocabulary is admitted without simulation. Outside calls
+ // an answer may also end.
+ let rejected = Set(sensitive.filter { transition(boundary, token: $0) == nil })
+ let free = boundary.isFree
+ if let index = broadMasks.firstIndex(where: { $0.rejected == rejected && $0.free == free }) {
+ let mask = broadMasks.remove(at: index)
+ broadMasks.append(mask)
+ allowed = mask.tokens
+ } else {
+ allowed = rejected.isEmpty ? vocabulary.pieceTokenIDs
+ : vocabulary.pieceTokenIDs.filter { !rejected.contains($0) }
+ if free { allowed = Self.merged(allowed, freeStops) }
+ if broadMasks.count == Self.maximumMaskEntries { broadMasks.removeFirst() }
+ broadMasks.append((rejected, free, allowed))
+ }
+ } else {
+ // Structural positions are inside calls, where no answer ends.
+ allowed = vocabulary.acceptedTokens(from: boundary) {
+ $0.consume($1, schema: schema, markers: markers)
+ }
+ }
+ if allowedCache.count == Self.maximumMaskEntries { allowedCache.removeFirst() }
+ allowedCache.append((state, allowed))
+ return allowed
+ }
+
+ /// The allowed set depends on the budget only through `remainingTokens > 0`,
+ /// and interned state ids are never reused, so the CBv2 sampler may keep one
+ /// uploaded device mask per state.
+ func maskCacheKey(state: Int, remainingTokens: Int) -> Int? {
+ lock.lock(); defer { lock.unlock() }
+ guard remainingTokens > 0, state == Self.releasedState || states.indices.contains(state) else { return nil }
+ return state
+ }
+
+ /// `allowedTokenIDs` has no observable effect beyond its result, and
+ /// `nextState` interns only host-confirmed tokens.
+ var allowsChainedDecode: Bool { true }
+
+ func nextState(state: Int, tokenID: Int) -> Int? {
+ lock.lock(); defer { lock.unlock() }
+ guard vocabulary.pieces.indices.contains(tokenID) else { return nil }
+ if state == Self.releasedState {
+ return vocabulary.stopTokenIDs.contains(tokenID) ? -1 : Self.releasedState
+ }
+ guard states.indices.contains(state) else { return nil }
+ let boundary = states[state]
+ if vocabulary.stopTokenIDs.contains(tokenID) { return boundary.isFree ? -1 : nil }
+ guard let next = transition(boundary, token: tokenID) else { return nil }
+ if let known = stateIndex[next] { return known }
+ guard states.count < Self.maximumStates else { return Self.releasedState }
+ states.append(next)
+ stateIndex[next] = states.count - 1
+ return states.count - 1
+ }
+
+ var cachedStateCount: Int { lock.lock(); defer { lock.unlock() }; return states.count }
+
+ /// After `` most pieces leave the opening at their first byte
+ /// that is not whitespace (the answer goes on as free text), so only pieces
+ /// that keep matching ` [Int] {
+ let open = QwenStrictToolBoundary.functionOpen
+ var allowed: [Int] = []
+ allowed.reserveCapacity(vocabulary.pieceTokenIDs.count + freeStops.count)
+ for id in vocabulary.pieceTokenIDs {
+ let piece = vocabulary.pieces[id]
+ var index = 0
+ if matched == 0 {
+ while index < piece.count, (9...13).contains(piece[index]) || piece[index] == 32 { index += 1 }
+ if index == piece.count {
+ allowed.append(id)
+ continue
+ }
+ }
+ let byte = piece[index]
+ let keepsOpening = byte == open[matched]
+ if !keepsOpening, matched == 0, byte == 123 || byte >= 0x80 { continue }
+ if keepsOpening || piece[index...].contains(62) {
+ if transition(boundary, token: id) != nil { allowed.append(id) }
+ } else {
+ allowed.append(id)
+ }
+ }
+ // Ascending already: pieces are listed in id order.
+ return Self.merged(allowed, freeStops)
+ }
+
+ /// Two ascending lists of distinct ids as one.
+ private static func merged(_ lhs: [Int], _ rhs: [Int]) -> [Int] {
+ var result: [Int] = []
+ result.reserveCapacity(lhs.count + rhs.count)
+ var i = 0, j = 0
+ while i < lhs.count || j < rhs.count {
+ if j == rhs.count || (i < lhs.count && lhs[i] < rhs[j]) {
+ result.append(lhs[i]); i += 1
+ } else {
+ result.append(rhs[j]); j += 1
+ }
+ }
+ return result
+ }
+
+ /// Reasoning, text and text values are opaque until a marker; JSON string
+ /// bodies are opaque until a quote, escape, control byte or marker.
+ private func broadCandidates(_ boundary: QwenStrictToolBoundary) -> [Int]? {
+ if boundary.isOpaqueSpan { return vocabulary.reasoningSensitive }
+ return boundary.inJSONStringBody ? vocabulary.stringSensitive : nil
+ }
+
+ private func transition(_ boundary: QwenStrictToolBoundary, token: Int) -> QwenStrictToolBoundary? {
+ let piece = vocabulary.pieces[token]
+ guard !piece.isEmpty else { return nil }
+ var next = boundary
+ for byte in piece {
+ guard next.consume(byte, schema: schema, markers: markers) else { return nil }
+ }
+ return next
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuardPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuardPolicy.swift
index 076dd67214..9eef5e903e 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuardPolicy.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GenerationLoopGuardPolicy.swift
@@ -70,7 +70,9 @@ enum GenerationLoopGuardPolicy {
) -> GenerationLoopGuard? {
guard case .modelTypes(let enabled) = setting,
let modelType = modelType?.lowercased(), enabled.contains(modelType) else { return nil }
- guard tokenConstraint == nil, !prepared.requiresToolCall,
+ // The strict-tool grammar leaves reasoning and text free: a loop there
+ // is still stopped, and one inside a call ends it as at `max_tokens`.
+ guard tokenConstraint == nil || tokenConstraint is QwenStrictToolConstraint, !prepared.requiresToolCall,
prepared.responseFormat == nil, prepared.glmResponseFormat == nil,
request.responseFormat?.requiresJSONOutput != true else { return nil }
var markers = genericToolCallMarkers
diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/GPTOSSForcedToolConstraint.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/GPTOSSForcedToolConstraint.swift
index 8dce0a9d3d..828c7b5b03 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Tools/GPTOSSForcedToolConstraint.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Tools/GPTOSSForcedToolConstraint.swift
@@ -160,7 +160,7 @@ final class GPTOSSForcedToolConstraint: CBv2TokenConstraint, @unchecked Sendable
}
let profile = JSONAnswerProfile.gptOSS
framing = try GPTOSSHarmonyFraming(tokenizer: tokenizer, names: selected.map(\.name),
- firstAddedTokenID: profile.firstAddedTokenID)
+ firstAddedTokenID: profile.bpeIDs.upperBound)
guard !vocabulary.stopTokenIDs.contains(framing.end) else {
throw ToolConstraintSchemaError.invalid("GPT-OSS analysis must not end the request")
}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/GemmaJSONAnswerPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/GemmaJSONAnswerPolicy.swift
new file mode 100644
index 0000000000..a060af00b6
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Inference/Tools/GemmaJSONAnswerPolicy.swift
@@ -0,0 +1,130 @@
+// Copyright © 2026 Eigen Labs.
+
+import Foundation
+import MLXLMCommon
+import MLXLMServer
+
+/// Grammar-constrained JSON `response_format` answers on Gemma 4. Eligibility
+/// never changes the rendered prompt: the service's format instruction still
+/// steers the model, and every request this policy declines keeps today's
+/// prompt-only behavior without a new refusal.
+enum GemmaJSONAnswerPolicy {
+ /// `off`, `0`, `false` or `no` restores prompt-only Gemma JSON answers.
+ /// Read once at launch.
+ static let environmentKey = "DARKBLOOM_GEMMA_JSON_ANSWERS"
+ static let enabled = isEnabled(ProcessInfo.processInfo.environment[environmentKey])
+
+ private static let modelTypes: Set = ["gemma4", "gemma4_text"]
+ /// The pinned template's generation prompt: thinking on leaves the model
+ /// at its turn, thinking off adds an empty, closed thought.
+ private static let turnBoundary = "<|turn>model\n"
+ private static let closedThoughtBoundary = turnBoundary + "<|channel>thought\n"
+
+ private static let logger = ProviderLogger(
+ subsystem: BuildEnvironment.current.serviceLogSubsystem, category: "json-answer")
+
+ static func isEnabled(_ value: String?) -> Bool {
+ guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(),
+ !value.isEmpty else { return true }
+ return !["off", "0", "false", "no"].contains(value)
+ }
+
+ /// The constraint for an eligible request, or nil. Requests with media,
+ /// tools, a `tool_choice` other than a tool-free `auto`, or client stop
+ /// sequences are out of scope. A schema outside the constrained subset is
+ /// held to a JSON object when its root is one, else prompt-only; an
+ /// unpinned template or tokenizer, an unrecognized prompt end or a
+ /// nonpositive budget falls back with a content-free log line.
+ static func constraint(
+ request: OpenAIChatCompletionRequest,
+ tokenizer: TokenizerHandle,
+ modelType: String?,
+ defaultMaxTokens: Int,
+ stopTokenIDs: Set,
+ promptTokens: [Int]?,
+ enabled: Bool = enabled
+ ) -> GemmaJSONAnswerConstraint? {
+ guard enabled, let modelType, modelTypes.contains(modelType),
+ let format = request.responseFormat, format.requiresJSONOutput,
+ request.tools?.isEmpty ?? true, request.toolChoice == nil || request.toolChoice == .mode(.auto),
+ request.stop?.isEmpty ?? true, request.reasoningParser == .gemma4,
+ !MediaIngest.hasMedia(request) else { return nil }
+ guard tokenizer.toolConstraintContractVerified else {
+ return declined("unpinned Gemma 4 chat template")
+ }
+ guard case let (answer, heldToObject)? = answerFormat(format) else {
+ return declined("schema outside the constrained subset and not an object")
+ }
+ guard let promptTokens, !promptTokens.isEmpty,
+ let phase = initialPhase(promptTail: tokenizer.inner.decode(
+ tokenIds: Array(promptTokens.suffix(ReasoningPromptProbe.tailTokenCount)),
+ skipSpecialTokens: false)) else {
+ return declined("unrecognized prompt boundary")
+ }
+ guard let vocabulary = try? GemmaAnswerPieces.cachedVocabulary(for: tokenizer,
+ stopTokenIDs: stopTokenIDs) else {
+ return declined("tokenizer does not match the pinned vocabulary")
+ }
+ guard let constraint = try? GemmaJSONAnswerConstraint(format: answer, vocabulary: vocabulary,
+ initialPhase: phase, maxTokens: request.maxTokens ?? defaultMaxTokens) else {
+ return declined("no positive output budget")
+ }
+ if heldToObject { logger.info("Gemma json_schema outside the constrained subset: held to a JSON object") }
+ return constraint
+ }
+
+ /// Where output starts after the rendered prompt, or nil for any other
+ /// prompt end (an assistant prefill, another template).
+ static func initialPhase(promptTail tail: String) -> GemmaJSONAnswerBoundary.Phase? {
+ if tail.hasSuffix(closedThoughtBoundary) { return .answer }
+ if tail.hasSuffix(turnBoundary) { return .opening }
+ return nil
+ }
+
+ /// The request's format (a `json_schema` rewritten into the shared subset
+ /// where that is exact, `ResponseSchemaRewrite`), or a JSON-object answer
+ /// (`heldToObject`) for a `json_schema` outside it whose root is an object.
+ static func answerFormat(_ format: OpenAIResponseFormat) -> (format: JSONAnswerFormat, heldToObject: Bool)? {
+ let profile = JSONAnswerProfile.gemma4
+ func compiled(_ candidate: OpenAIResponseFormat) -> JSONAnswerFormat? {
+ try? JSONAnswerFormat(candidate, forbidding: profile.contentMarkers, family: profile.family)
+ }
+ if let exact = compiled(format) { return (exact, false) }
+ guard format.type == .jsonSchema, var payload = format.jsonSchema else { return nil }
+ let schema = payload.schema
+ if let rewritten = ResponseSchemaRewrite.subset(schema) {
+ payload.schema = rewritten
+ if let exact = compiled(.jsonSchema(payload)) { return (exact, false) }
+ }
+ // The fallback reads the request's own root, not the rewrite's.
+ guard rootIsObject(schema), let object = compiled(.jsonObject()) else { return nil }
+ return (object, true)
+ }
+
+ /// A schema whose every instance is an object: `type` is exactly
+ /// `"object"`, which every other keyword narrows, except a draft-7 `$ref`
+ /// that would replace it.
+ private static func rootIsObject(_ schema: MLXLMCommon.JSONValue) -> Bool {
+ guard case .object(let object) = schema else { return false }
+ return object["type"] == .string("object") && object["$ref"] == nil
+ }
+
+ /// Fixed reasons only: never schema text, prompt content or token IDs.
+ private static func declined(_ reason: StaticString) -> GemmaJSONAnswerConstraint? {
+ logger.info("Gemma JSON response_format served prompt-only: \(reason)")
+ return nil
+ }
+}
+
+extension EngineV2Bridge {
+ /// A Gemma JSON answer's grammar is best effort. An engine that runs no
+ /// token constraint (a cluster pair, a native-tracked engine) refuses one,
+ /// so there the request is submitted unconstrained, as before.
+ static func admittedConstraint(_ constraint: (any CBv2TokenConstraint)?, servesDistributedPair: Bool,
+ tracksNativeShutdown: Bool) -> (any CBv2TokenConstraint)? {
+ guard constraint is GemmaJSONAnswerConstraint, servesDistributedPair || tracksNativeShutdown else {
+ return constraint
+ }
+ return nil
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/JSONAnswerPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/JSONAnswerPolicy.swift
new file mode 100644
index 0000000000..e9a5805e96
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Inference/Tools/JSONAnswerPolicy.swift
@@ -0,0 +1,109 @@
+// Copyright © 2026 Eigen Labs.
+
+import Foundation
+import MLXLMServer
+
+/// Grammar-constrained JSON `response_format` answers on the text path of the
+/// families with a pinned answer contract (`JSONAnswerProfile`): Qwen 3.5, 3.6
+/// and 3.8, PrismML Bonsai 2 27B, and Nemotron 3.5 Lightning.
+/// Eligibility never changes the rendered prompt: the service's format
+/// instruction still steers the model, and every request this policy declines
+/// keeps that prompt-only behavior without a new refusal.
+enum JSONAnswerPolicy {
+ /// `DARKBLOOM_JSON_ANSWER_GRAMMAR=qwen` (or `0`, `off`, `false`, `no`,
+ /// `none`) keeps the grammar to the Qwen 3.5, 3.6 and 3.8 types, as before
+ /// Bonsai and Lightning were admitted; unset or any other value admits
+ /// every family below. Read once per process.
+ static let familiesEnvironmentKey = "DARKBLOOM_JSON_ANSWER_GRAMMAR"
+
+ enum Families: Equatable, Sendable {
+ case all
+ case qwenOnly
+
+ static let current = Families(environmentValue: ProcessInfo.processInfo.environment[familiesEnvironmentKey])
+
+ init(environmentValue: String?) {
+ let value = environmentValue?.trimmingCharacters(in: .whitespaces).lowercased() ?? ""
+ self = ["qwen", "0", "off", "false", "no", "none"].contains(value) ? .qwenOnly : .all
+ }
+ }
+
+ private static let logger = ProviderLogger(
+ subsystem: BuildEnvironment.current.serviceLogSubsystem, category: "json-answer")
+
+ /// The answer contract of an admitted model, or nil. The Qwen types are
+ /// admitted by `model_type` alone; `prism_hadamard_qwen35` and
+ /// `nemotron_h`, which Lightning shares with Nano, only for a listed
+ /// build, and only on a single Mac: a cluster pair refuses any token
+ /// constraint before reserving (`constrainedDecodingUnsupported`), so their
+ /// pairs keep today's prompt-only service instead of gaining that refusal.
+ /// A Qwen pair's refusal predates them and is failed over upstream. The
+ /// Bonsai 2 9B is not admitted: it drafts, and its JSON rows (thinking off
+ /// by default) would stop its whole decode cohort from speculating.
+ static func profile(modelID: String?, modelType: String?, families: Families = .current,
+ servesDistributedPair: Bool = false) -> JSONAnswerProfile?
+ {
+ switch modelType {
+ case "qwen3_5", "qwen3_5_moe":
+ return .qwen35
+ case "prism_hadamard_qwen35" where families == .all && !servesDistributedPair:
+ return EngineV2SupportedModels.isBonsai2ListingModelID(modelID) ? .bonsai2 : nil
+ case "nemotron_h" where families == .all && !servesDistributedPair:
+ return EngineV2SupportedModels.isNemotron35ListingModelID(modelID) ? .nemotron35 : nil
+ default:
+ return nil
+ }
+ }
+
+ /// The constraint for an eligible request, or nil. Requests with media,
+ /// tools or a `tool_choice` are out of scope, and so is a prompt that
+ /// opens a thought on a family admitted for its answers alone (Lightning's
+ /// default). An unsupported schema, an unrecognized prompt boundary, an
+ /// unverified tokenizer or a nonpositive budget falls back with a
+ /// content-free log line.
+ static func constraint(
+ request: OpenAIChatCompletionRequest,
+ tokenizer: TokenizerHandle,
+ modelID: String?,
+ modelType: String?,
+ defaultMaxTokens: Int,
+ stopTokenIDs: Set,
+ promptTokens: [Int]?,
+ servesDistributedPair: Bool,
+ families: Families = .current
+ ) -> JSONAnswerConstraint? {
+ guard let profile = profile(modelID: modelID, modelType: modelType, families: families,
+ servesDistributedPair: servesDistributedPair),
+ let format = request.responseFormat, format.requiresJSONOutput,
+ request.tools?.isEmpty ?? true, request.toolChoice == nil,
+ request.reasoningParser == .qwen3, !MediaIngest.hasMedia(request) else { return nil }
+ let phase = promptTokens.flatMap { tokens in
+ tokens.isEmpty ? nil : profile.initialPhase(promptTail: tokenizer.inner.decode(
+ tokenIds: Array(tokens.suffix(ReasoningPromptProbe.tailTokenCount)), skipSpecialTokens: false))
+ }
+ if phase == .reasoning, !profile.constrainsReasoning { return nil }
+ guard let answer = try? JSONAnswerFormat(format, forbidding: profile.contentMarkers,
+ family: profile.family) else {
+ return declined(profile, "schema outside the constrained subset")
+ }
+ guard let phase else {
+ return declined(profile, "unrecognized prompt boundary")
+ }
+ guard let vocabulary = try? JSONAnswerVocabulary.cached(for: tokenizer, profile: profile,
+ stopTokenIDs: stopTokenIDs) else {
+ return declined(profile, "tokenizer does not match the pinned vocabulary")
+ }
+ guard let constraint = try? JSONAnswerConstraint(format: answer, profile: profile, vocabulary: vocabulary,
+ initialPhase: phase,
+ maxTokens: request.maxTokens ?? defaultMaxTokens) else {
+ return declined(profile, "no positive output budget")
+ }
+ return constraint
+ }
+
+ /// Fixed reasons only: never schema text, prompt content or token IDs.
+ private static func declined(_ profile: JSONAnswerProfile, _ reason: StaticString) -> JSONAnswerConstraint? {
+ logger.info("\(profile.family) JSON response_format served prompt-only: \(reason)")
+ return nil
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/QwenJSONAnswerPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/QwenJSONAnswerPolicy.swift
deleted file mode 100644
index 3891835403..0000000000
--- a/provider-swift/Sources/ProviderCore/Inference/Tools/QwenJSONAnswerPolicy.swift
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright © 2026 Eigen Labs.
-
-import Foundation
-import MLXLMServer
-
-/// Grammar-constrained JSON `response_format` answers on the Qwen 3.5/3.6/3.8
-/// text path. Eligibility never changes the rendered prompt: the service's
-/// format instruction still steers the model, and every request this policy
-/// declines keeps that prompt-only behavior without a new refusal.
-enum QwenJSONAnswerPolicy {
- private static let modelTypes: Set = ["qwen3_5", "qwen3_5_moe"]
-
- private static let logger = ProviderLogger(
- subsystem: BuildEnvironment.current.serviceLogSubsystem, category: "json-answer")
-
- /// The constraint for an eligible request, or nil. Requests with media,
- /// tools or a `tool_choice` are out of scope; an unsupported schema, an
- /// unrecognized prompt boundary, an unverified tokenizer or a nonpositive
- /// budget falls back with a content-free log line.
- static func constraint(
- request: OpenAIChatCompletionRequest,
- tokenizer: TokenizerHandle,
- modelType: String?,
- defaultMaxTokens: Int,
- stopTokenIDs: Set,
- promptTokens: [Int]?
- ) -> JSONAnswerConstraint? {
- guard let modelType, modelTypes.contains(modelType),
- let format = request.responseFormat, format.requiresJSONOutput,
- request.tools?.isEmpty ?? true, request.toolChoice == nil,
- request.reasoningParser == .qwen3, !MediaIngest.hasMedia(request) else { return nil }
- let profile = JSONAnswerProfile.qwen35
- guard let answer = try? JSONAnswerFormat(format, forbidding: profile.contentMarkers,
- family: profile.family) else {
- return declined("schema outside the constrained subset")
- }
- guard let promptTokens, !promptTokens.isEmpty,
- let phase = profile.initialPhase(promptTail: tokenizer.inner.decode(
- tokenIds: Array(promptTokens.suffix(ReasoningPromptProbe.tailTokenCount)),
- skipSpecialTokens: false)) else {
- return declined("unrecognized prompt boundary")
- }
- guard let vocabulary = try? JSONAnswerVocabulary.cached(for: tokenizer, profile: profile,
- stopTokenIDs: stopTokenIDs) else {
- return declined("tokenizer does not match the pinned vocabulary")
- }
- guard let constraint = try? JSONAnswerConstraint(format: answer, profile: profile, vocabulary: vocabulary,
- initialPhase: phase,
- maxTokens: request.maxTokens ?? defaultMaxTokens) else {
- return declined("no positive output budget")
- }
- return constraint
- }
-
- /// Fixed reasons only: never schema text, prompt content or token IDs.
- private static func declined(_ reason: StaticString) -> JSONAnswerConstraint? {
- logger.info("Qwen JSON response_format served prompt-only: \(reason)")
- return nil
- }
-}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift
new file mode 100644
index 0000000000..cdbbb4e66c
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift
@@ -0,0 +1,159 @@
+// Copyright © 2026 Eigen Labs.
+
+import Foundation
+import MLXLMCommon
+import MLXLMServer
+
+/// Grammar-constrained arguments for `strict` tool calls on the Qwen
+/// 3.5-family text route (Qwen 3.5 9B and 35B, 3.6 and 3.8 on one Mac).
+///
+/// A `strict` call is validated against the caller's schema when its frame
+/// closes, after the answer has started streaming, so a call that misses the
+/// schema fails a started response. Under this grammar the model can only
+/// write calls that validate: the sampler holds every call's function name,
+/// parameter names and values to the declared schemas
+/// (`QwenStrictToolConstraint`), while reasoning and text stay free and `auto`
+/// still decides whether to call. The rendered prompt does not change.
+///
+/// It applies to `auto` requests that declare a `strict` function (with
+/// `DARKBLOOM_STRICT_TOOL_GRAMMAR_ALL_TOOLS`, any request with tools), on an
+/// engine that runs token constraints, when every declared schema compiles
+/// (`$ref`s inlined as the coordinator does). Such a request has every call
+/// validated already, so every call is constrained. A request the policy
+/// declines (an unsupported schema keyword, a union of several types, an
+/// unrecognized prompt boundary, an unverified tokenizer, a cluster pair) is
+/// served exactly as before, never refused.
+///
+/// A token constraint keeps the engine from drafting with MTP on that row
+/// and, on these engines, on every row of a decode step it shares
+/// (`EngineLoopV2.mtpDraftBatchRows`), as for constrained JSON answers.
+enum QwenStrictToolGrammar {
+ /// Unset, `on`, `1`, `true` or `yes`: the Qwen 3.5-family builds (`qwen3_5`,
+ /// `qwen3_5_moe`). An off word (`off`, `0`, `false`, `no`, `none`,
+ /// `disabled`, any case) restores unconstrained calls. Any other value is a
+ /// comma-separated list: a `model_type`, or a case-insensitive part of a
+ /// model id (`qwen3.8-27b`); only Qwen 3.5-family builds qualify.
+ static let environmentKey = "DARKBLOOM_STRICT_TOOL_GRAMMAR"
+ /// `on`, `1`, `true` or `yes` (any case): also requests whose tools are not `strict`.
+ static let allToolsEnvironmentKey = "DARKBLOOM_STRICT_TOOL_GRAMMAR_ALL_TOOLS"
+
+ static let modelTypes: Set = ["qwen3_5", "qwen3_5_moe"]
+
+ enum Setting: Sendable, Equatable {
+ case off
+ case models(Set)
+ }
+
+ static let current = setting(environment: ProcessInfo.processInfo.environment)
+ static let currentAllTools = allTools(environment: ProcessInfo.processInfo.environment)
+
+ private static let offWords: Set = ["off", "0", "false", "no", "none", "disabled"]
+ private static let onWords: Set = ["on", "1", "true", "yes"]
+
+ private static let logger = ProviderLogger(
+ subsystem: BuildEnvironment.current.serviceLogSubsystem, category: "strict-tool-grammar")
+
+ static func setting(environment: [String: String]) -> Setting {
+ guard let raw = environment[environmentKey]?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(),
+ !raw.isEmpty, !onWords.contains(raw) else { return .models(modelTypes) }
+ if offWords.contains(raw) { return .off }
+ let entries = Set(raw.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }
+ .filter { !$0.isEmpty && !offWords.contains($0) && !onWords.contains($0) })
+ return entries.isEmpty ? .off : .models(entries)
+ }
+
+ static func allTools(environment: [String: String]) -> Bool {
+ environment[allToolsEnvironmentKey].map {
+ onWords.contains($0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased())
+ } ?? false
+ }
+
+ static func isEnabled(modelId: String, modelType: String?, setting: Setting = current) -> Bool {
+ guard case .models(let entries) = setting,
+ let type = modelType?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(),
+ modelTypes.contains(type) else { return false }
+ let id = modelId.lowercased()
+ return entries.contains { $0 == type || id.contains($0) }
+ }
+
+ /// Cheap pre-check before the engine is asked whether it runs constraints:
+ /// an `auto` request with tools on the Qwen 3.5 call parser.
+ static func isCandidate(prepared: ToolChoicePromptPolicy.Prepared, parser: ToolCallFormat?,
+ allTools: Bool = currentAllTools) -> Bool {
+ guard prepared.mode == .auto, parser == .qwen35, let tools = prepared.tools, !tools.isEmpty else { return false }
+ return allTools || tools.contains { $0.function.strict == true }
+ }
+
+ /// The constraint for an eligible request, or nil (today's unconstrained
+ /// calls). `runsTokenConstraints`: the slot's engine samples under one
+ /// (not a cluster pair, not a native-tracked engine).
+ static func constraint(
+ prepared: ToolChoicePromptPolicy.Prepared,
+ request: OpenAIChatCompletionRequest,
+ parser: ToolCallFormat?,
+ tokenizer: TokenizerHandle,
+ modelType: String?,
+ defaultMaxTokens: Int,
+ stopTokenIDs: Set,
+ promptTokens: [Int]?,
+ runsTokenConstraints: Bool,
+ setting: Setting = current,
+ allTools: Bool = currentAllTools
+ ) -> QwenStrictToolConstraint? {
+ guard isEnabled(modelId: request.model, modelType: modelType, setting: setting),
+ isCandidate(prepared: prepared, parser: parser, allTools: allTools),
+ let rendered = prepared.tools else { return nil }
+ guard runsTokenConstraints else { return declined("the engine does not run token constraints") }
+ guard !MediaIngest.hasMedia(request) else { return declined("media request") }
+ let schema: QwenStrictToolSchema
+ do {
+ schema = try QwenStrictToolSchema(declared: prepared.declaredTools ?? rendered, rendered: rendered,
+ forbidding: forbiddenMarkers, family: profile.family)
+ } catch {
+ return declined("a schema outside the constrained subset")
+ }
+ guard let promptTokens, !promptTokens.isEmpty,
+ let prefix = ReasoningPromptProbe.streamingPrefix(forPromptTail: tokenizer.inner.decode(
+ tokenIds: Array(promptTokens.suffix(ReasoningPromptProbe.tailTokenCount)),
+ skipSpecialTokens: false)) else {
+ return declined("unrecognized prompt boundary")
+ }
+ guard let vocabulary = try? JSONAnswerVocabulary.cached(for: tokenizer, profile: profile,
+ stopTokenIDs: stopTokenIDs) else {
+ return declined("tokenizer does not match the pinned vocabulary")
+ }
+ guard let constraint = try? QwenStrictToolConstraint(schema: schema, vocabulary: vocabulary,
+ forbidding: forbiddenMarkers, startsInReasoning: prefix == ReasoningPromptProbe.thinkOpen,
+ allowsParallelCalls: prepared.allowsParallelCalls, maxTokens: request.maxTokens ?? defaultMaxTokens) else {
+ return declined("no positive output budget")
+ }
+ return constraint
+ }
+
+ /// Spellings no argument value may contain: the turn, reasoning and call
+ /// markers (each also an added token of these tokenizers).
+ static let forbiddenMarkers: [[UInt8]] = forbiddenSpellings.map { Array($0.utf8) }
+ private static let forbiddenSpellings = [
+ "", "", "", "", "<|im_start|>", "<|im_end|>", "<|endoftext|>",
+ ]
+
+ /// The Qwen 3.5 vocabulary contract (`JSONAnswerProfile.qwen35`) with the
+ /// call markers as ordinary pieces. Every watched marker ends in `>`, so
+ /// the pieces holding one are the only ones that can end a free span.
+ static let profile = JSONAnswerProfile(
+ family: "Qwen tools",
+ thinkClose: "",
+ reasoningStops: ["", ""] + forbiddenSpellings,
+ contentMarkers: forbiddenSpellings + [""],
+ bpeIDs: 0..<248044,
+ pieceTokens: [.init(spelling: "", id: 248068), .init(spelling: "", id: 248069),
+ .init(spelling: "", id: 248058), .init(spelling: "", id: 248059)],
+ answerEOS: [.init(spelling: "<|im_end|>", id: 248046), .init(spelling: "<|endoftext|>", id: 248044)],
+ vocabularySize: 248320)
+
+ /// Fixed reasons only: never names, schemas, prompt content or token IDs.
+ private static func declined(_ reason: StaticString) -> QwenStrictToolConstraint? {
+ logger.info("Qwen strict tool calls served unconstrained: \(reason)")
+ return nil
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolSchema.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolSchema.swift
new file mode 100644
index 0000000000..b6993c656b
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolSchema.swift
@@ -0,0 +1,472 @@
+// Copyright © 2026 Eigen Labs.
+//
+// The declared tools of one request as the Qwen 3.5 XML call grammar sees
+// them (`QwenStrictToolConstraint`). Arguments travel as
+// `\nVALUE\n`, and the call parser
+// (`Qwen35ToolCallParser`) keeps a value as text or converts it to one JSON
+// type by the parameter's rendered schema. A parameter is constrained only
+// when that conversion and the caller's schema agree on the type, so every
+// value the grammar admits parses to an argument the schema accepts. Anything
+// else (a keyword the subset cannot hold exactly, a union of several types,
+// a cyclic `$ref`) leaves the request unconstrained, as before.
+
+import Foundation
+import MLXLMCommon
+import MLXLMServer
+
+private typealias StrictJSON = MLXLMCommon.JSONValue
+
+struct QwenStrictToolSchema: Sendable {
+ enum Value: Sendable {
+ /// Free text up to ``; the parser keeps it as a string.
+ case text
+ /// One of these texts, each followed by the value's closing framing
+ /// (`QwenStrictToolSchema.valueClose`).
+ case choice([[UInt8]])
+ /// One JSON value of the parameter's schema; the parser converts the
+ /// text to that JSON type.
+ case json(FlintJSONGrammar)
+ }
+
+ struct Parameter: Sendable {
+ let name: [UInt8]
+ let value: Value
+ }
+
+ struct Tool: Sendable {
+ let name: [UInt8]
+ /// Declared parameters, by name. A call never names another.
+ let parameters: [Parameter]
+ let required: FlintJSONPropertySet
+ }
+
+ /// Closes a choice or JSON value: the template's line break before the
+ /// closing tag and after it.
+ static let valueClose = Array("\n\n".utf8)
+
+ let tools: [Tool]
+
+ /// `declared`: the caller's declarations as sent, which `strict` calls are
+ /// validated against. `rendered`: the same tools after ingress
+ /// normalization, which the call parser reads. `markers`: spellings no
+ /// value may contain.
+ init(declared: [OpenAITool], rendered: [OpenAITool], forbidding markers: [[UInt8]], family: String) throws {
+ guard !declared.isEmpty, declared.count <= ToolConstraintSchemaCompiler.maxTools else {
+ throw ToolConstraintSchemaError.unsupported("strict tool grammars need 1...\(ToolConstraintSchemaCompiler.maxTools) tools")
+ }
+ var names = Set()
+ var budget = Self.maximumInlinedNodes
+ var tools: [Tool] = []
+ for tool in declared {
+ let name = tool.function.name
+ guard tool.type == "function", ToolChoicePromptPolicy.isValidFunctionName(name), names.insert(name).inserted,
+ let parsed = rendered.first(where: { $0.function.name == name }) else {
+ throw ToolConstraintSchemaError.unsupported("tool declarations differ from the rendered tools")
+ }
+ let root = try Self.compileRoot(tool.function.parameters, budget: &budget)
+ guard case .object(let properties, _, _) = root else {
+ throw ToolConstraintSchemaError.unsupported("\(name).parameters must be an object")
+ }
+ let parsedProperties: [String: StrictJSON]
+ if case .object(let object)? = parsed.function.parameters, case .object(let map)? = object["properties"] {
+ parsedProperties = map
+ } else {
+ parsedProperties = [:]
+ }
+ var parameters: [Parameter] = []
+ var required = FlintJSONPropertySet()
+ for (index, property) in properties.enumerated() {
+ let rendered = parsedProperties[property.name]
+ let conversion = Self.parserConversion(rendered)
+ // A value the parser converts must not stream as text: the
+ // streamed call would then disagree with the parsed one.
+ guard conversion.kind == .text || !Self.streamsAsText(rendered) else {
+ throw ToolConstraintSchemaError.unsupported("a parameter the streamed call exposes as text")
+ }
+ let value = try Self.value(property.schema, conversion: conversion, forbidding: markers, family: family)
+ parameters.append(Parameter(name: Array(property.name.utf8), value: value))
+ if property.required { required.insert(index) }
+ }
+ tools.append(Tool(name: Array(name.utf8), parameters: parameters, required: required))
+ }
+ self.tools = tools
+ }
+
+ // MARK: - Compiling one tool
+
+ /// The parameters schema with local `$ref`s inlined and the shapes the
+ /// subset can hold exactly rewritten into it, compiled. A missing or empty
+ /// schema takes no arguments.
+ private static func compileRoot(_ raw: StrictJSON?, budget: inout Int) throws -> ToolValueSchema {
+ guard let raw, raw != .object([:]) else {
+ return .object(properties: [], allowsAdditional: false, nullable: false)
+ }
+ guard case .object(var root) = try clean(inlineReferences(raw, budget: &budget), depth: 0) else {
+ throw ToolConstraintSchemaError.unsupported("parameters must be a schema object")
+ }
+ // No undeclared argument is ever generated, so a schema-valued
+ // `additionalProperties` at the root only widens what is accepted.
+ if let extra = root["additionalProperties"], extra != .bool(true), extra != .bool(false) {
+ root.removeValue(forKey: "additionalProperties")
+ }
+ if root["type"] == nil { root["type"] = .string("object") }
+ return try ToolConstraintSchemaCompiler.compileResponseSchema(.object(root))
+ }
+
+ /// What the grammar admits for one parameter. The caller's schema and the
+ /// parser's reading must name the same type; nullability the parser cannot
+ /// read back is dropped, as are choices whose text would not survive its
+ /// framing.
+ private static func value(_ schema: ToolValueSchema, conversion: ParserConversion,
+ forbidding markers: [[UInt8]], family: String) throws -> Value {
+ let null = conversion.acceptsNull && conversion.kind != .text
+ let json: ToolValueSchema
+ switch (schema, conversion.kind) {
+ case (.string(let values, _), .text):
+ guard let values else { return .text }
+ let spellings = Set(values.compactMap { value -> [UInt8]? in
+ let bytes = Array(value.utf8)
+ // The parser drops one framing line break on each side; a value
+ // ending in CR would lose it as part of CRLF.
+ guard bytes.last != 13, !(markers + [Array("".utf8)]).contains(where: { marker in
+ bytes.count >= marker.count && (0...(bytes.count - marker.count)).contains { start in
+ bytes[start..<(start + marker.count)].elementsEqual(marker)
+ }
+ }) else { return nil }
+ return bytes + valueClose
+ })
+ guard !spellings.isEmpty else {
+ throw ToolConstraintSchemaError.unsupported("no enum value survives the call framing")
+ }
+ return .choice(spellings.sorted { $0.lexicographicallyPrecedes($1) })
+ case (.integer(let values, let nullable), .integer), (.integer(let values, let nullable), .number):
+ json = .integer(values: values, nullable: nullable && null)
+ case (.number(nil, let nullable), .number):
+ json = .number(values: nil, nullable: nullable && null)
+ case (.number(nil, let nullable), .integer):
+ // The parser reads only integral text here; every integer is a number.
+ json = .integer(values: nil, nullable: nullable && null)
+ case (.boolean(let values, let nullable), .boolean):
+ json = .boolean(values: values, nullable: nullable && null)
+ case (.object(let properties, let additional, let nullable), .object):
+ json = .object(properties: properties, allowsAdditional: additional, nullable: nullable && null)
+ case (.array(let items, let minItems, let maxItems, let nullable), .array):
+ json = .array(items: items, minItems: minItems, maxItems: maxItems, nullable: nullable && null)
+ case (.null, _) where null:
+ json = .null
+ default:
+ throw ToolConstraintSchemaError.unsupported("a parameter the call parser reads as another type")
+ }
+ return .json(try FlintJSONGrammar(schema: json, forbidding: markers, family: family))
+ }
+
+ // MARK: - The parser's reading of a parameter
+
+ /// How `Qwen35ToolCallParser` reads one parameter's text: a mirror of the
+ /// SDK's `ToolArgumentNormalization.normalize` for a top-level string,
+ /// over the rendered schema (`QwenStrictToolGrammarTests` checks it against
+ /// the parser itself).
+ struct ParserConversion: Equatable, Sendable {
+ enum Kind: Equatable, Sendable { case text, integer, number, boolean, object, array, null }
+ let kind: Kind
+ /// `null` (also `none`, `nil`) is read as JSON null.
+ let acceptsNull: Bool
+ }
+
+ /// Whether the streamed call exposes the parameter's text as a string while
+ /// it is generated: a mirror of the SDK's `Qwen35ArgumentStreamer`
+ /// (`streamsAsString`), which reads only a string `type` of the rendered
+ /// schema. Other parameters are exposed when they close, converted as the
+ /// parser converts them.
+ static func streamsAsText(_ schema: MLXLMCommon.JSONValue?) -> Bool {
+ guard case .object(let object)? = schema, case .string(let raw)? = object["type"] else { return true }
+ let type = raw.lowercased()
+ if ["string", "str", "text", "varchar", "char", "enum"].contains(type) { return true }
+ let converts = ["int", "uint", "long", "short", "unsigned", "num", "float", "dict", "list"]
+ .contains(where: type.hasPrefix) || ["boolean", "bool", "binary", "object", "array"].contains(type)
+ return !converts
+ }
+
+ static func parserConversion(_ schema: MLXLMCommon.JSONValue?) -> ParserConversion {
+ let text = ParserConversion(kind: .text, acceptsNull: false)
+ guard case .object(let object)? = schema, object["type"] != .string("string"),
+ let types = declaredTypes(object, depth: 0) else { return text }
+ var concrete = types.subtracting(["null"])
+ if concrete.contains("number") { concrete.remove("integer") }
+ guard !types.contains("string"), concrete.count <= 1 else { return text }
+ let null = types.contains("null")
+ switch concrete.first {
+ case nil: return .init(kind: .null, acceptsNull: null)
+ case "integer": return .init(kind: .integer, acceptsNull: null)
+ case "number": return .init(kind: .number, acceptsNull: null)
+ case "boolean": return .init(kind: .boolean, acceptsNull: null)
+ case "object": return .init(kind: .object, acceptsNull: null)
+ case "array": return .init(kind: .array, acceptsNull: null)
+ default: return .init(kind: .text, acceptsNull: null)
+ }
+ }
+
+ private static func declaredTypes(_ schema: [String: StrictJSON], depth: Int) -> Set? {
+ guard depth < 32, ["$ref", "$dynamicRef", "not", "if", "then", "else"].allSatisfy({ schema[$0] == nil }) else {
+ return nil
+ }
+ var result: Set?
+ if let raw = schema["type"] {
+ let names: [String]
+ switch raw {
+ case .string(let name):
+ names = [name]
+ case .array(let members):
+ let strings = members.compactMap { member -> String? in
+ if case .string(let name) = member { return name }
+ return nil
+ }
+ names = strings.count == members.count ? strings : []
+ default:
+ names = []
+ }
+ let mapped = names.compactMap(canonicalType)
+ guard !names.isEmpty, mapped.count == names.count else { return nil }
+ var set = Set(mapped)
+ if set.contains("number") { set.insert("integer") }
+ if schema["nullable"] == .bool(true) { set.insert("null") }
+ result = set
+ }
+ for key in ["anyOf", "oneOf", "allOf"] where schema[key] != nil {
+ guard case .array(let rawBranches)? = schema[key], !rawBranches.isEmpty else { return nil }
+ var types: [Set] = []
+ for branch in rawBranches {
+ guard case .object(let object) = branch, let branchTypes = declaredTypes(object, depth: depth + 1) else {
+ return nil
+ }
+ types.append(branchTypes)
+ }
+ let combined = types.dropFirst().reduce(types[0]) {
+ key == "allOf" ? $0.intersection($1) : $0.union($1)
+ }
+ result = result.map { $0.intersection(combined) } ?? combined
+ }
+ return result
+ }
+
+ private static func canonicalType(_ name: String) -> String? {
+ let type = name.lowercased()
+ switch type {
+ case "string", "str", "text", "varchar", "char", "enum": return "string"
+ case "integer", "int", "uint", "long", "short", "unsigned": return "integer"
+ case "number", "float": return "number"
+ case "boolean", "bool", "binary": return "boolean"
+ case "object", "dict": return "object"
+ case "array", "arr", "list": return "array"
+ case "null": return "null"
+ default:
+ if ["int", "uint", "long", "short", "unsigned"].contains(where: type.hasPrefix) { return "integer" }
+ if type.hasPrefix("num") || type.hasPrefix("float") { return "number" }
+ if type.hasPrefix("dict") { return "object" }
+ if type.hasPrefix("list") { return "array" }
+ return nil
+ }
+ }
+
+ // MARK: - `$ref`
+
+ /// Keywords whose values are schemas, maps of schemas or lists of schemas.
+ private static let schemaKeywords: Set = [
+ "items", "additionalProperties", "additionalItems", "not", "if", "then", "else", "contains",
+ "propertyNames", "unevaluatedItems", "unevaluatedProperties", "contentSchema",
+ ]
+ private static let schemaMapKeywords: Set = [
+ "properties", "patternProperties", "dependentSchemas", "$defs", "definitions",
+ ]
+ private static let schemaListKeywords: Set = ["anyOf", "oneOf", "allOf", "prefixItems"]
+ /// Keywords no validator asserts.
+ private static let annotationKeywords: Set = [
+ "description", "title", "default", "examples", "deprecated", "readOnly", "writeOnly", "$comment", "$id",
+ "$schema", "$anchor", "format", "contentMediaType", "contentEncoding",
+ ]
+ /// Schema nodes per request, after inlining: references expand copies, so
+ /// a deep diamond of them is refused instead of grown.
+ static let maximumInlinedNodes = 20_000
+
+ /// Replaces every local `$ref` (`#/...`, a JSON pointer into the tool's
+ /// parameters) with a copy of its target, as the coordinator's resolver
+ /// does for the builds it lists; the definitions themselves are dropped.
+ /// Recursive references, references to other documents and references
+ /// with asserting siblings are refused. The validator ignores the render
+ /// type the normalizer writes beside a reference, so it is dropped too.
+ static func inlineReferences(_ root: MLXLMCommon.JSONValue, budget: inout Int) throws -> MLXLMCommon.JSONValue {
+ var remaining = budget
+ defer { budget = remaining }
+ func target(_ pointer: String) throws -> StrictJSON {
+ guard pointer.hasPrefix("#/"), !pointer.contains("%") else {
+ throw ToolConstraintSchemaError.unsupported("only local $ref pointers are resolved")
+ }
+ var node = root
+ for raw in pointer.dropFirst(2).split(separator: "/", omittingEmptySubsequences: false) {
+ let token = raw.replacingOccurrences(of: "~1", with: "/").replacingOccurrences(of: "~0", with: "~")
+ switch node {
+ case .object(let object):
+ guard let next = object[token] else {
+ throw ToolConstraintSchemaError.unsupported("$ref target is missing")
+ }
+ node = next
+ case .array(let items):
+ guard let index = Int(token), items.indices.contains(index) else {
+ throw ToolConstraintSchemaError.unsupported("$ref target is missing")
+ }
+ node = items[index]
+ default:
+ throw ToolConstraintSchemaError.unsupported("$ref target is missing")
+ }
+ }
+ return node
+ }
+ func schema(_ node: StrictJSON, _ open: [String]) throws -> StrictJSON {
+ remaining -= 1
+ guard remaining > 0, open.count <= 32 else {
+ throw ToolConstraintSchemaError.unsupported("$ref expansion exceeds its bounds")
+ }
+ guard case .object(let object) = node else { return node }
+ if let reference = object["$ref"] {
+ guard case .string(let pointer) = reference, !open.contains(pointer),
+ object.keys.allSatisfy({ ["$ref", "type", "$defs", "definitions"].contains($0)
+ || annotationKeywords.contains($0) }) else {
+ throw ToolConstraintSchemaError.unsupported("recursive, non-local or constrained $ref")
+ }
+ return try schema(target(pointer), open + [pointer])
+ }
+ var result: [String: StrictJSON] = [:]
+ for (key, value) in object {
+ if key == "$defs" || key == "definitions" { continue }
+ if schemaKeywords.contains(key) {
+ if case .array(let items) = value, key == "items" {
+ result[key] = .array(try items.map { try schema($0, open) })
+ } else {
+ result[key] = try schema(value, open)
+ }
+ } else if schemaMapKeywords.contains(key), case .object(let map) = value {
+ result[key] = .object(try map.mapValues { try schema($0, open) })
+ } else if schemaListKeywords.contains(key), case .array(let items) = value {
+ result[key] = .array(try items.map { try schema($0, open) })
+ } else {
+ result[key] = value
+ }
+ }
+ return .object(result)
+ }
+ return try schema(root, [])
+ }
+
+ // MARK: - Rewriting into the subset
+
+ /// Drops annotations the subset compiler refuses and folds the unions it
+ /// can hold exactly: one type and null (`anyOf`/`oneOf` of a schema and
+ /// `{"type":"null"}`, Pydantic's `Optional`), a single `allOf` branch,
+ /// and objects beside an open object (any object). The validator ignores
+ /// the render type the normalizer writes beside a union, so it is dropped.
+ static func clean(_ node: MLXLMCommon.JSONValue, depth: Int) throws -> MLXLMCommon.JSONValue {
+ guard depth <= ToolConstraintSchemaCompiler.maxDepth * 2 else {
+ throw ToolConstraintSchemaError.unsupported("schema nesting exceeds its bounds")
+ }
+ guard case .object(var object) = node else { return node }
+ guard object[ToolSchemaNormalization.originalBooleanSchemaKey] == nil else {
+ throw ToolConstraintSchemaError.unsupported("an allow-all schema")
+ }
+ for key in annotationKeywords where !["description", "title", "default", "examples", "deprecated",
+ "readOnly", "writeOnly"].contains(key) {
+ object.removeValue(forKey: key)
+ }
+ let unions = ["anyOf", "oneOf", "allOf"].filter { object[$0] != nil }
+ if let union = unions.first {
+ guard unions.count == 1, case .array(let rawBranches)? = object[union], !rawBranches.isEmpty,
+ object.keys.allSatisfy({ $0 == union || $0 == "type" || $0 == "nullable"
+ || annotationKeywords.contains($0) }) else {
+ throw ToolConstraintSchemaError.unsupported("keywords beside a union")
+ }
+ let branches = try rawBranches.map { try clean($0, depth: depth + 1) }
+ if union == "allOf" {
+ // allOf is conjunctive with a sibling type, so they must agree.
+ guard branches.count == 1, object["nullable"] == nil,
+ object["type"].map({ $0 == branches[0].objectValue?["type"] }) ?? true else {
+ throw ToolConstraintSchemaError.unsupported("allOf beyond one schema")
+ }
+ return branches[0]
+ }
+ return try fold(branches, exclusive: union == "oneOf")
+ }
+ if case .object(let properties)? = object["properties"] {
+ object["properties"] = .object(try properties.mapValues { try clean($0, depth: depth + 1) })
+ }
+ if let items = object["items"] { object["items"] = try clean(items, depth: depth + 1) }
+ return .object(object)
+ }
+
+ private static func fold(_ branches: [StrictJSON], exclusive: Bool) throws -> StrictJSON {
+ let nulls = branches.filter(isNullOnly)
+ let others = branches.filter { !isNullOnly($0) }
+ guard others.count <= 1 || exclusive == false else {
+ throw ToolConstraintSchemaError.unsupported("oneOf of several schemas")
+ }
+ var result: StrictJSON
+ switch others.count {
+ case 0:
+ return .object(["type": .string("null")])
+ case 1:
+ result = others[0]
+ default:
+ // Objects beside an open object: the union is every object.
+ guard let open = others.first(where: isOpenObject),
+ others.allSatisfy({ $0.objectValue?["type"] == .string("object") }) else {
+ throw ToolConstraintSchemaError.unsupported("a union of several schemas")
+ }
+ result = open
+ }
+ guard !nulls.isEmpty else { return result }
+ guard case .object(var object) = result else {
+ throw ToolConstraintSchemaError.unsupported("a nullable union branch that is not a schema object")
+ }
+ // oneOf: null must match exactly one branch.
+ if exclusive, admitsNull(object) {
+ throw ToolConstraintSchemaError.unsupported("oneOf whose branches both admit null")
+ }
+ object["nullable"] = .bool(true)
+ if case .array(var values)? = object["enum"], !values.contains(.null) {
+ values.append(.null)
+ object["enum"] = .array(values)
+ }
+ if let constant = object.removeValue(forKey: "const") {
+ object["enum"] = .array(constant == .null ? [.null] : [constant, .null])
+ }
+ return .object(object)
+ }
+
+ private static func isNullOnly(_ schema: StrictJSON) -> Bool {
+ guard case .object(let object) = schema else { return false }
+ let assertions = object.filter { !annotationKeywords.contains($0.key) }
+ return assertions == ["type": .string("null")] || assertions == ["enum": .array([.null])]
+ || assertions == ["const": .null]
+ }
+
+ private static func isOpenObject(_ schema: StrictJSON) -> Bool {
+ guard case .object(let object) = schema else { return false }
+ let assertions = object.filter { !annotationKeywords.contains($0.key) }
+ guard assertions["type"] == .string("object"), assertions["additionalProperties"].map({ $0 == .bool(true) }) ?? true
+ else { return false }
+ if case .object(let properties)? = assertions["properties"], !properties.isEmpty { return false }
+ return assertions.keys.allSatisfy { ["type", "additionalProperties", "properties"].contains($0) }
+ }
+
+ private static func admitsNull(_ object: [String: StrictJSON]) -> Bool {
+ if object["nullable"] == .bool(true) { return true }
+ if case .array(let types)? = object["type"], types.contains(.string("null")) { return true }
+ if case .array(let values)? = object["enum"], values.contains(.null) { return true }
+ return object["const"] == .null
+ }
+}
+
+private extension MLXLMCommon.JSONValue {
+ var objectValue: [String: MLXLMCommon.JSONValue]? {
+ if case .object(let object) = self { return object }
+ return nil
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/ResponseSchemaRewrite.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/ResponseSchemaRewrite.swift
new file mode 100644
index 0000000000..b7c6f808d3
--- /dev/null
+++ b/provider-swift/Sources/ProviderCore/Inference/Tools/ResponseSchemaRewrite.swift
@@ -0,0 +1,186 @@
+// Copyright © 2026 Eigen Labs.
+
+import Foundation
+import MLXLMCommon
+
+/// Rewrites a `json_schema` in the shapes common clients generate (Pydantic,
+/// OpenAI's strict conversion, zod-to-json-schema) into the shared constrained
+/// subset, where the result admits exactly the same instances: references to
+/// plainly named entries of the root's `$defs` or `definitions` (no `~`, `/`
+/// or `%`) are inlined, a one-branch `allOf` is its branch, an `anyOf` of one
+/// schema and `{"type": "null"}` is that schema made nullable (null joins its
+/// finite values, so a 128-value enum outgrows the subset), and `$comment`
+/// on every node it rewrites, the root's `$id` and a root `$schema` naming
+/// draft-06 to 2020-12 are dropped. A reference or composition may carry
+/// annotations beside it, nothing else. Nil when anything else would be needed
+/// (a recursive, remote or escaped reference, an older or unknown `$schema`, a
+/// wider `anyOf`, more than `ToolConstraintSchemaCompiler.maxDepth` levels,
+/// `maximumUnwraps` references or compositions in a row, more than
+/// `maximumWork`, a definition name over 256 bytes, or what the compiler
+/// refuses wherever it reads it, refused here at every node so that no copy
+/// is read at length: a key over 20 bytes, a `type` name over 7, more than
+/// 128 `required` names or one over 64), so the caller keeps its fallback. It
+/// rewrites `properties` and `items` whatever the node's type, so those
+/// checks and references hold there too.
+enum ResponseSchemaRewrite {
+ /// Bounds the walk's work: a node it visits costs one plus its keys and
+ /// the members of its `type` and `required` arrays, a reference or a
+ /// property name one per 64 bytes it hashes, and an enum made nullable
+ /// its values. A definition used from many places is copied, and paid
+ /// for, each time.
+ static let maximumWork = 16_384
+ /// Bounds the references and compositions one position unwraps in a row.
+ static let maximumUnwraps = 8
+ private static let annotations: Set = [
+ "title", "description", "default", "examples", "deprecated", "readOnly", "writeOnly", "$comment",
+ ]
+ /// Draft-04 has no `const` and draft-03 spells `required` as a boolean, so
+ /// only these read as the subset does.
+ private static let metaSchemas: Set = [
+ "json-schema.org/draft-06/schema", "json-schema.org/draft-07/schema",
+ "json-schema.org/draft/2019-09/schema", "json-schema.org/draft/2020-12/schema",
+ ]
+
+ static func subset(_ schema: MLXLMCommon.JSONValue) -> MLXLMCommon.JSONValue? {
+ guard case .object(var root) = schema else { return nil }
+ if let metaSchema = root.removeValue(forKey: "$schema") {
+ guard case .string(let uri) = metaSchema, readsAsTheSubset(uri) else { return nil }
+ }
+ root.removeValue(forKey: "$id")
+ var walk = Walk()
+ for container in ["$defs", "definitions"] {
+ guard let value = root.removeValue(forKey: container) else { continue }
+ guard case .object(let entries) = value else { return nil }
+ // A name a pointer must escape or percent-encode is never
+ // resolved, so no reference can reach the wrong definition; nor is
+ // one over 256 bytes, so every lookup compares short keys.
+ for (name, definition) in entries
+ where name.utf8.count <= 256 && !name.contains(where: { "~/%".contains($0) }) {
+ walk.definitions["#/\(container)/\(name)"] = definition
+ }
+ }
+ return walk.rewrite(.object(root), depth: 0, unwraps: 0)
+ }
+
+ private static func readsAsTheSubset(_ uri: String) -> Bool {
+ var name = Substring(uri)
+ if name.hasSuffix("#") { name = name.dropLast() }
+ guard let scheme = ["http://", "https://"].first(where: { name.hasPrefix($0) }) else { return false }
+ return metaSchemas.contains(String(name.dropFirst(scheme.count)))
+ }
+
+ private struct Walk {
+ var definitions: [String: MLXLMCommon.JSONValue] = [:]
+ var budget = maximumWork
+ /// The references being inlined on the current path.
+ var expanding: Set = []
+
+ /// `depth` counts levels as the compiler does (a property or the
+ /// items one deeper); `unwraps` counts the references and
+ /// compositions replaced in a row at this position.
+ mutating func rewrite(_ schema: MLXLMCommon.JSONValue, depth: Int, unwraps: Int) -> MLXLMCommon.JSONValue? {
+ guard depth <= ToolConstraintSchemaCompiler.maxDepth, unwraps <= maximumUnwraps, spend(1) else { return nil }
+ guard case .object(var object) = schema else { return schema }
+ // Paid before any change below copies the node. Where the compiler
+ // compiles, it refuses a key longer than `additionalProperties`
+ // (20 bytes): refused here first, every lookup compares short keys.
+ guard spend(object.count), object.keys.allSatisfy({ $0.utf8.count <= 20 }), readsBounded(object)
+ else { return nil }
+ object.removeValue(forKey: "$comment")
+ if let reference = object["$ref"] {
+ guard case .string(let path) = reference, spend(path.utf8.count / 64),
+ onlyAnnotations(object, besides: "$ref"), let target = definitions[path],
+ expanding.insert(path).inserted else { return nil }
+ defer { expanding.remove(path) }
+ return rewrite(target, depth: depth, unwraps: unwraps + 1)
+ }
+ if let composition = object["allOf"] {
+ guard case .array(let branches) = composition, branches.count == 1,
+ onlyAnnotations(object, besides: "allOf") else { return nil }
+ return rewrite(branches[0], depth: depth, unwraps: unwraps + 1)
+ }
+ if let union = object["anyOf"] {
+ guard case .array(let branches) = union, branches.count == 2, onlyAnnotations(object, besides: "anyOf"),
+ let nullIndex = branches.firstIndex(where: isNull) else { return nil }
+ let other = branches[1 - nullIndex]
+ guard !isNull(other), let rewritten = rewrite(other, depth: depth, unwraps: unwraps + 1)
+ else { return nil }
+ return nullable(rewritten)
+ }
+ if case .object(let properties)? = object["properties"] {
+ var rewritten: [String: MLXLMCommon.JSONValue] = [:]
+ for (name, property) in properties {
+ guard spend(name.utf8.count / 64), let value = rewrite(property, depth: depth + 1, unwraps: 0)
+ else { return nil }
+ rewritten[name] = value
+ }
+ object["properties"] = .object(rewritten)
+ }
+ if let items = object["items"] {
+ guard let value = rewrite(items, depth: depth + 1, unwraps: 0) else { return nil }
+ object["items"] = value
+ }
+ return .object(object)
+ }
+
+ /// The schema also admitting null, in the subset's spellings:
+ /// `nullable`, and null among the finite values, since `type` and
+ /// `enum` apply together.
+ private mutating func nullable(_ schema: MLXLMCommon.JSONValue) -> MLXLMCommon.JSONValue? {
+ guard case .object(var object) = schema, object["anyOf"] == nil, object["$ref"] == nil else { return nil }
+ if let constant = object.removeValue(forKey: "const") {
+ guard object["enum"] == nil else { return nil }
+ object["enum"] = .array([constant])
+ }
+ if case .array(let values)? = object["enum"] {
+ guard spend(values.count) else { return nil }
+ if !values.contains(.null) { object["enum"] = .array(values + [.null]) }
+ }
+ object["nullable"] = .bool(true)
+ return .object(object)
+ }
+
+ /// The compiler reads `type` and `required` on every copy of a node,
+ /// so each is bounded to what the compiler takes where it reads it: a
+ /// type name (lowercased; `boolean` and `integer`, 7 bytes, are the
+ /// longest), and at most 128 required property names of at most 64
+ /// bytes. Arrays are paid per member.
+ private mutating func readsBounded(_ object: [String: MLXLMCommon.JSONValue]) -> Bool {
+ func names(_ value: MLXLMCommon.JSONValue, longest: Int) -> Bool {
+ guard case .string(let name) = value else { return false }
+ return name.utf8.count <= longest
+ }
+ switch object["type"] {
+ case .string(let name)?:
+ guard name.utf8.count <= 7 else { return false }
+ case .array(let types)?:
+ guard spend(types.count), types.allSatisfy({ names($0, longest: 7) }) else { return false }
+ default:
+ break
+ }
+ if case .array(let required)? = object["required"] {
+ guard required.count <= ToolConstraintSchemaCompiler.maxProperties, spend(required.count),
+ required.allSatisfy({ names($0, longest: 64) }) else { return false }
+ }
+ return true
+ }
+
+ private mutating func spend(_ cost: Int) -> Bool {
+ budget -= cost
+ return budget >= 0
+ }
+ }
+
+ /// No keyword or annotation is longer than 11 bytes, so a longer key is
+ /// refused before it is hashed.
+ private static func onlyAnnotations(_ object: [String: MLXLMCommon.JSONValue], besides keyword: String) -> Bool {
+ object.keys.allSatisfy { $0.utf8.count <= 11 && ($0 == keyword || annotations.contains($0)) }
+ }
+
+ /// Keys and the type's length are checked before any longer comparison.
+ private static func isNull(_ schema: MLXLMCommon.JSONValue) -> Bool {
+ guard case .object(let object) = schema, onlyAnnotations(object, besides: "type"),
+ case .string(let type)? = object["type"], type.utf8.count == 4 else { return false }
+ return type == "null"
+ }
+}
diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintFactory.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintFactory.swift
index 3472a65daf..839980af86 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintFactory.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintFactory.swift
@@ -5,7 +5,8 @@
// and grammar state remain per request. Qwen4 uses its rendered native channel
// boundary and opaque framed arguments; Gemma keeps its own schema automaton;
// GPT-OSS frames its Harmony call (GPTOSSForcedToolConstraint); tool-free
-// Qwen 3.5 JSON answers use JSONAnswerConstraint.
+// JSON answers of the families `JSONAnswerPolicy` admits use
+// JSONAnswerConstraint.
import Foundation
import ProviderCoreFoundation
@@ -23,7 +24,8 @@ enum ToolConstraintFactory {
modelContext: ChatTemplateFixContext,
defaultMaxTokens: Int,
stopTokenIDs: Set,
- nativePromptTokens: [Int]? = nil
+ nativePromptTokens: [Int]? = nil,
+ servesDistributedPair: Bool = false
) throws -> (any CBv2TokenConstraint)? {
// Flint's automatic reasoning protocol needs framing even for no-tool
// and auto requests. Do not broaden another family's admission policy.
@@ -51,13 +53,20 @@ enum ToolConstraintFactory {
throw MultiModelBatchSchedulerEngineError.invalidToolPayload(error.localizedDescription)
}
}
- // A tool-free Qwen JSON answer is constrained when everything it needs
- // verifies; otherwise it keeps prompt-only steering, never a refusal.
- if let answer = QwenJSONAnswerPolicy.constraint(request: request, tokenizer: tokenizer,
+ // A tool-free Gemma 4 JSON answer: a free thought, then one JSON value.
+ if let answer = GemmaJSONAnswerPolicy.constraint(request: request, tokenizer: tokenizer,
modelType: modelContext.modelType, defaultMaxTokens: defaultMaxTokens,
stopTokenIDs: stopTokenIDs, promptTokens: nativePromptTokens) {
return answer
}
+ // A tool-free JSON answer of a `JSONAnswerPolicy` family is constrained when everything it needs
+ // verifies; otherwise it keeps prompt-only steering, never a refusal.
+ if let answer = JSONAnswerPolicy.constraint(request: request, tokenizer: tokenizer,
+ modelID: modelContext.modelId, modelType: modelContext.modelType, defaultMaxTokens: defaultMaxTokens,
+ stopTokenIDs: stopTokenIDs, promptTokens: nativePromptTokens,
+ servesDistributedPair: servesDistributedPair) {
+ return answer
+ }
guard prepared.mode.requiresInferenceConstraint else { return nil }
// `.none` keeps Gemma's sampler guard when its prompt contract is
// pinned, while every other family retains the existing prompt-only
diff --git a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift
index b321d82325..66d7a722f2 100644
--- a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift
+++ b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift
@@ -404,9 +404,15 @@ public enum LaunchAgent: Sendable {
/// `DARKBLOOM_TTFT_PROMPT_CACHE` and its `_MB` / `_VERIFY` knobs: scoped
/// prompt-token reuse is on by default; `0` / `false` / `off` / `no` is
/// the rollback.
+ /// `DARKBLOOM_STRICT_TOOL_GRAMMAR` / `DARKBLOOM_STRICT_TOOL_GRAMMAR_ALL_TOOLS`:
+ /// `strict` Qwen 3.5-family calls follow their schemas in the sampler by
+ /// default (an off word restores unconstrained calls, a list picks the
+ /// builds); `on` extends it to calls of tools that are not `strict`.
/// `DARKBLOOM_TTFT_TEMPLATE_LOOPS=0` renders cached prompts with the
/// template as served. `DARKBLOOM_TTFT_COLD_LOAD_RELEASE=0` restores the
/// fully serial FIFO.
+ /// `DARKBLOOM_GEMMA_JSON_ANSWERS`: Gemma 4 JSON `response_format` answers
+ /// are grammar-constrained by default; `off` restores prompt-only answers.
/// `DARKBLOOM_TTFT_SHAPE_WARMUP`: the load-time shape warmup is on by
/// default; its `0` rollback must reach the job too.
/// `DARKBLOOM_GLM_RECTANGULAR_VERIFY`: rectangular adaptive MTP verification
@@ -455,9 +461,12 @@ public enum LaunchAgent: Sendable {
SSDPrefixCachePolicy.terminalBeforePublicationFlag,
"DARKBLOOM_TTFT_GDN_BLOCKED",
EngineV2SlotFactory.mimoRectangularVerifyEnvironmentKey,
+ GemmaJSONAnswerPolicy.environmentKey,
PromptTokenCachePolicy.environmentKey,
PromptTokenCachePolicy.capacityEnvironmentKey,
PromptTokenCachePolicy.verifyEnvironmentKey,
+ QwenStrictToolGrammar.environmentKey,
+ QwenStrictToolGrammar.allToolsEnvironmentKey,
ChatTemplateLoopRewrites.environmentKey,
WorkFIFOPolicy.coldLoadReleaseEnvironmentKey,
ModelCalibrationPolicy.shapeWarmupEnvironmentKey,
@@ -468,6 +477,7 @@ public enum LaunchAgent: Sendable {
EngineV2Factory.glm5NextDecodeStepsKey,
NemotronSuperLocalPrefill.decodeStepsKey,
ToolStreamPreparation.streamToolCallsEnvironmentKey,
+ JSONAnswerPolicy.familiesEnvironmentKey,
ReasoningPromptProbe.plainTailContentSeedEnvironmentKey,
"DARKBLOOM_GEMMA4_NAX_ROW_MAP",
// SDK-read (`EngineLoopV2.nativeSegmentReleaseEnvironmentKey`): idle seconds
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/GemmaJSONAnswerConstraintTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/GemmaJSONAnswerConstraintTests.swift
new file mode 100644
index 0000000000..93e2977f9a
--- /dev/null
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/GemmaJSONAnswerConstraintTests.swift
@@ -0,0 +1,460 @@
+import Foundation
+import MLXLMCommon
+import MLXLMServer
+import Testing
+@testable import ProviderCore
+
+/// Gemma 4-shaped SentencePiece tokenizer: the 24 added tokens at their real
+/// ids, `\n` and `\n\n` at 107/108, the 256 byte-fallback tokens at 238...493,
+/// one piece per printable ASCII character at 1000 + byte (the space spelled
+/// `▁`), a few multi-character pieces from 2000, and `` everywhere
+/// else up to the model's 262,144 ids. Decoding follows the shipped decoder:
+/// U+2581 to a space, byte-fallback runs fused as UTF-8 (one U+FFFD per byte
+/// when a run is not UTF-8), no strip.
+struct GemmaPieceTestTokenizer: MLXLMCommon.Tokenizer {
+ static let vocabularySize = 262_144
+ static let specials: [Int: String] = [
+ 0: "", 1: "", 2: "", 3: "", 4: "", 46: "<|tool>", 47: "",
+ 48: "<|tool_call>", 49: "", 50: "<|tool_response>", 51: "", 52: "<|\"|>",
+ 98: "<|think|>", 100: "<|channel>", 101: "", 105: "<|turn>", 106: "",
+ 255_999: "<|image>", 256_000: "<|audio>", 258_880: "<|image|>", 258_881: "<|audio|>",
+ 258_882: "", 258_883: "\n"]
+ var random = StrictGrammarRandom(seed: UInt64(function.utf8.count))
+ for _ in 0..<60 {
+ var text = "\n\n"
+ var state = try #require(F.walk(text, constraint))
+ var steps = 0
+ while !constraint.allowedTokenIDs(state: state, remainingTokens: 10).contains(F.imEnd), steps < 4_000 {
+ steps += 1
+ if steps > 40 || random.next() % 8 == 0,
+ let closer = closers.first(where: { F.walk($0, constraint, from: state) != nil }) {
+ state = try #require(F.walk(closer, constraint, from: state))
+ text += closer
+ continue
+ }
+ let candidates = constraint.allowedTokenIDs(state: state, remainingTokens: 10)
+ .filter { (32...126).contains($0) || $0 == 10 }
+ let token = try #require(candidates.randomElement(using: &random))
+ state = try #require(constraint.nextState(state: state, tokenID: token))
+ text += String(UnicodeScalar(UInt8(token)))
+ }
+ #expect(steps < 4_000, "the draw closed its call")
+ let calls = try F.calls(text, request, prepared)
+ #expect(calls.count == 1 && calls[0].function.name == function, "\(text)")
+ let streamed = try F.streamedCalls(text, body)
+ #expect(streamed.map(\.function.name) == calls.map(\.function.name), "\(text)")
+ #expect(streamed.map(\.function.arguments) == calls.map(\.function.arguments), "\(text)")
+ }
+ }
+
+ // MARK: - Policy
+
+ @Test func autoStrictRequestsTakeTheGrammarRequiredAndOthersDoNot() throws {
+ #expect(try F.constraint(F.body(tools: F.order)) != nil)
+ #expect(try F.constraint(F.body(tools: F.order, choice: #""auto""#)) != nil)
+ for choice in [#""required""#, #"{"type":"function","function":{"name":"get_time"}}"#, #""none""#] {
+ #expect(try F.constraint(F.body(tools: F.order, choice: choice)) == nil, "\(choice)")
+ }
+ // Without `strict`, calls are returned as generated: no grammar unless asked for every tool.
+ let loose = F.order.replacingOccurrences(of: #""strict":true,"#, with: "")
+ #expect(try F.constraint(F.body(tools: loose)) == nil)
+ #expect(try F.constraint(F.body(tools: loose), allTools: true) != nil)
+ // One strict tool holds every call of the request to its schema, so all are constrained.
+ let mixed = F.order.replacingOccurrences(of: #""name":"get_time","strict":true"#, with: #""name":"get_time""#)
+ let constraint = try #require(try F.constraint(F.body(tools: mixed)))
+ #expect(!F.allows("", constraint, after: "\n\n"))
+ }
+
+ @Test func otherEnginesFamiliesAndBoundariesKeepTodaysCalls() throws {
+ let body = F.body(tools: F.order)
+ // Cluster pairs and native-tracked engines run no token constraint.
+ #expect(try F.constraint(body, runsTokenConstraints: false) == nil)
+ for type in ["qwen4_exp", "prism_hadamard_qwen35", "gemma4", "nemotron_h", "gpt_oss", "mimo_v2"] {
+ #expect(try F.constraint(body, modelType: type) == nil, "\(type)")
+ }
+ #expect(try F.constraint(body, setting: .off) == nil)
+ let (request, prepared) = try F.prepared(body)
+ func make(prompt: String? = nil, parser: ToolCallFormat? = .qwen35,
+ handle: TokenizerHandle = F.handle) -> QwenStrictToolConstraint? {
+ QwenStrictToolGrammar.constraint(prepared: prepared, request: request, parser: parser, tokenizer: handle,
+ modelType: "qwen3_5", defaultMaxTokens: 512, stopTokenIDs: F.stops,
+ promptTokens: QwenByteTestTokenizer.tokens(prompt ?? QwenByteTestTokenizer.prompt(thinking: false)),
+ runsTokenConstraints: true, setting: F.qwenTypes, allTools: false)
+ }
+ #expect(make() != nil)
+ #expect(make(prompt: "<|im_start|>assistant\n") == nil)
+ #expect(make(parser: .xmlFunction) == nil)
+ let moved = QwenByteTestTokenizer.pinned.map { $0.0 == "" ? ($0.0, 248_070) : $0 }
+ #expect(make(handle: TokenizerHandle(QwenByteTestTokenizer(markers: moved))) == nil)
+ }
+
+ @Test func theSwitchIsPerModelAndReachesTheProviderJob() {
+ typealias G = QwenStrictToolGrammar
+ #expect(G.environmentKey == "DARKBLOOM_STRICT_TOOL_GRAMMAR")
+ #expect(G.setting(environment: [:]) == .models(["qwen3_5", "qwen3_5_moe"]))
+ #expect(G.setting(environment: [G.environmentKey: " On "]) == .models(["qwen3_5", "qwen3_5_moe"]))
+ for off in ["off", "0", "FALSE", " no ", "none", "Disabled"] {
+ #expect(G.setting(environment: [G.environmentKey: off]) == .off, "\(off)")
+ }
+ let listed = G.setting(environment: [G.environmentKey: "Qwen3.8-27B, qwen3_5_moe"])
+ #expect(listed == .models(["qwen3.8-27b", "qwen3_5_moe"]))
+ #expect(G.isEnabled(modelId: "EigenLabs/Qwen3.8-27B-4bit-mtp", modelType: "qwen3_5", setting: listed))
+ #expect(!G.isEnabled(modelId: "EigenLabs/Qwen3.5-9B-MLX-4bit-mtp", modelType: "qwen3_5", setting: listed))
+ #expect(G.isEnabled(modelId: "qwen3.6-35b-a3b-vl-mtp-mxfp8", modelType: "qwen3_5_moe", setting: listed))
+ // Only the Qwen 3.5 template's builds qualify, whatever the list says.
+ #expect(!G.isEnabled(modelId: "gemma-4-26b", modelType: "gemma4",
+ setting: G.setting(environment: [G.environmentKey: "gemma4,gemma"])))
+ #expect(!G.allTools(environment: [:]) && G.allTools(environment: [G.allToolsEnvironmentKey: "1"]))
+ let keys = [G.environmentKey, G.allToolsEnvironmentKey]
+ #expect(keys.allSatisfy { LaunchAgent.inferencePassthroughEnvKeys.contains($0) })
+ let values = [G.environmentKey: "off", G.allToolsEnvironmentKey: "on"]
+ #expect(LaunchAgent.passthroughEnvironment(from: values.merging(["UNRELATED": "x"]) { a, _ in a }) == values)
+ }
+
+ // MARK: - Streaming
+
+ /// The constrained call streams as OpenAI fragments: the name first, then
+ /// arguments that add up to the validated call.
+ @Test func aConstrainedCallStreamsAsDeltas() throws {
+ var request = try F.prepared(F.body(tools: F.order)).0
+ request.streamToolCallDeltas = true
+ var prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "qwen3_5")
+ prepared.declaredTools = try F.prepared(F.body(tools: F.order)).1.declaredTools
+ let constraint = try #require(try F.constraint(F.body(tools: F.order)))
+ #expect(F.walk(F.validOrder, constraint) != nil)
+ for chunking in [1, 3, 17] {
+ let handler = try #require(try ToolStreamPreparation.makeHandler(
+ request: request, prepared: prepared, modelType: "qwen3_5", streamToolCalls: true))
+ #expect(handler.streamsCalls)
+ var router = NativeToolStreamRouter(handler: handler, requiresToolCall: false, nativePrefix: nil,
+ streamedCalls: prepared)
+ var events: [MLXServerGenerationEvent] = []
+ let characters = Array(F.validOrder)
+ for start in stride(from: 0, to: characters.count, by: chunking) {
+ events += try router.process(String(characters[start.. UInt64 {
+ state &+= 0x9E37_79B9_7F4A_7C15
+ var z = state
+ z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
+ z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
+ return z ^ (z >> 31)
+ }
+}
+
+/// Samples a fixed script through the submitted constraint like a model whose
+/// sampler applies the masks: a scripted token the mask refuses is never
+/// drawn, so it is skipped. Without a constraint the script is emitted as is.
+private final class MaskedScriptEngine: CBv2Engine, @unchecked Sendable {
+ private let script: [Int]
+ private let lock = NSLock()
+ private var requests: [CBv2Request] = []
+
+ init(script: String) { self.script = QwenByteTestTokenizer.tokens(script) }
+
+ var submitted: [CBv2Request] { lock.withLock { requests } }
+
+ func submit(_ request: CBv2Request) throws -> AsyncStream {
+ if let constraint = request.tokenConstraint, constraint.maxTokens != request.maxTokens {
+ throw CBv2SchedulerError.tokenConstraintBudgetMismatch(
+ request: request.maxTokens, constraint: constraint.maxTokens)
+ }
+ lock.withLock { requests.append(request) }
+ var deltas: [(text: String, token: Int)] = []
+ var finish = CBv2FinishReason.length
+ var state = request.tokenConstraint?.initialState ?? 0
+ var next = 0
+ while deltas.count < request.maxTokens {
+ var token: Int?
+ if let constraint = request.tokenConstraint {
+ let allowed = constraint.allowedTokenIDs(state: state, remainingTokens: request.maxTokens - deltas.count)
+ while next < script.count, !Self.contains(allowed, script[next]) { next += 1 }
+ if next < script.count {
+ token = script[next]
+ next += 1
+ } else {
+ token = allowed.first(where: request.stopTokens.contains)
+ }
+ if let token { state = constraint.nextState(state: state, tokenID: token) ?? state }
+ } else {
+ token = next < script.count ? script[next] : request.stopTokens.min()
+ next += 1
+ }
+ guard let token else { break }
+ if request.stopTokens.contains(token) {
+ deltas.append(("", token))
+ finish = .stop
+ break
+ }
+ deltas.append((String(decoding: QwenByteTestTokenizer.piece(token), as: UTF8.self), token))
+ }
+ let (stream, continuation) = AsyncStream.makeStream()
+ for delta in deltas { continuation.yield(.delta(text: delta.text, tokens: [delta.token], logprobs: nil)) }
+ continuation.yield(.finished(reason: finish,
+ usage: CBv2Usage(promptTokens: request.promptTokens.count, completionTokens: deltas.count)))
+ continuation.finish()
+ return stream
+ }
+
+ private static func contains(_ sorted: [Int], _ token: Int) -> Bool {
+ var low = 0, high = sorted.count
+ while low < high {
+ let middle = (low + high) / 2
+ if sorted[middle] < token { low = middle + 1 } else { high = middle }
+ }
+ return low < sorted.count && sorted[low] == token
+ }
+
+ func cancel(_ id: CBv2RequestID) {}
+ func capacity() -> CBv2CapacitySnapshot {
+ .init(activeRequests: 0, waitingRequests: 0, kvBytesInUse: 0, kvBytesCapacity: 0, activeTokens: 0)
+ }
+ func shutdown() async {}
+}
+
+/// Client view of one stream: reasoning and text through the qwen3 parser,
+/// as downstream of the scheduler, and the streamed calls.
+private struct StrictToolOutcome {
+ var content = ""
+ var reasoning = ""
+ var deltas: [ServerToolCallDelta] = []
+ var info: ServerGenerationInfo?
+ var error: (any Error)?
+ private var parser = StreamingReasoningParser(format: .qwen3)
+
+ var calls: [ToolCall] { deltas.compactMap(\.completed) }
+
+ mutating func record(_ event: MLXServerGenerationEvent) {
+ switch event {
+ case .content(let text): parser.parse(text).forEach { apply($0) }
+ case .parsed(let parsed): apply(parsed)
+ case .toolCallDelta(let delta): deltas.append(delta)
+ case .info(let info): self.info = info
+ case .toolCall, .logprobs: break
+ }
+ }
+
+ mutating func finish() { parser.finish().forEach { apply($0) } }
+
+ private mutating func apply(_ parsed: ParsedReasoning) {
+ content += parsed.content
+ reasoning += parsed.reasoningContent ?? ""
+ }
+}
+
+@Suite("Strict tool grammar through the scheduler and bridge")
+struct QwenStrictToolServingTests {
+ private static let tokenizer = TokenizerHandle(QwenByteTestTokenizer())
+ private static let tools = #"""
+ [{"type":"function","function":{"name":"get_time","strict":true,"parameters":{"type":"object",
+ "properties":{"city":{"type":"string"},"offset":{"type":"integer"},
+ "zone":{"type":"object","properties":{"dst":{"type":"boolean"}},"required":["dst"],
+ "additionalProperties":false}},
+ "required":["city","offset","zone"],"additionalProperties":false}}}]
+ """#
+ /// What the model would write: the offset quoted, the flag as a word.
+ private static let script = "Need the time.\n\n\n\n"
+ + "\nRome\n\n\n\"5\"\n\n"
+ + "\n{\"dst\": yes true}\n\n\n<|im_end|>"
+
+ private func serve(_ engine: MaskedScriptEngine, tools: String = tools, strict: Bool = true,
+ setting: String? = nil) async throws -> StrictToolOutcome {
+ let id = StrictToolFixture.model
+ let bridge = EngineV2Bridge(engine: engine, modelId: id, tokenizer: Self.tokenizer,
+ eosTokenIds: [248046, 248044], defaultMaxTokens: 512, maxConcurrentRequests: 1)
+ let tokenizer = Self.tokenizer
+ let scheduler = MultiModelBatchSchedulerEngine(registryProvider: {
+ [id: .init(tokenizer: tokenizer, modelType: "qwen3_5", engineV2Bridge: bridge)]
+ })
+ let declared = strict ? tools : tools.replacingOccurrences(of: #""strict":true,"#, with: "")
+ let body = StrictToolFixture.body(tools: declared)
+ var request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self,
+ from: ToolSchemaNormalization.ensureParameterTypes(in: Data(body.utf8)))
+ request.stream = true
+ request.streamToolCallDeltas = true
+ var outcome = StrictToolOutcome()
+ do {
+ for try await event in try await scheduler.streamChatCompletion(request: request) { outcome.record(event) }
+ } catch { outcome.error = error }
+ outcome.finish()
+ await bridge.shutdown()
+ return outcome
+ }
+
+ @Test func aStrictCallThatWouldMissItsSchemaStreamsValid() async throws {
+ let engine = MaskedScriptEngine(script: Self.script)
+ let outcome = try await serve(engine)
+ let constraint = try #require(engine.submitted.first?.tokenConstraint as? QwenStrictToolConstraint)
+ #expect(constraint.startsInReasoning && constraint.maxTokens == engine.submitted.first?.maxTokens)
+ #expect(outcome.error == nil)
+ #expect(outcome.reasoning == "Need the time.")
+ let call = try #require(outcome.calls.first)
+ #expect(outcome.calls.count == 1 && call.function.name == "get_time")
+ #expect(call.function.arguments == ["city": .string("Rome"), "offset": .int(5),
+ "zone": .object(["dst": .bool(true)])])
+ #expect(outcome.deltas.first?.name == "get_time", "the call streams name first")
+ #expect(outcome.deltas.count > 2, "and its arguments as they are generated")
+ }
+
+ @Test func withoutStrictTheCallIsReturnedAsGeneratedAsBefore() async throws {
+ let engine = MaskedScriptEngine(script: Self.script)
+ let outcome = try await serve(engine, strict: false)
+ #expect(engine.submitted.first?.tokenConstraint == nil)
+ #expect(outcome.error == nil)
+ #expect(outcome.calls.first?.function.arguments["offset"] == .string("\"5\""))
+ }
+}
+
+/// Run against a local Qwen 3.5/3.6/3.8 snapshot (tokenizer and template files
+/// only; no weights are read): `DARKBLOOM_TEST_QWEN_TOKENIZER_DIR=`.
+@Suite("Strict tool grammar real tokenizer",
+ .enabled(if: ProcessInfo.processInfo.environment["DARKBLOOM_TEST_QWEN_TOKENIZER_DIR"] != nil))
+struct QwenStrictToolRealTokenizerTests {
+ @Test func theShippedTokenizerWalksARealCall() async throws {
+ let directory = URL(fileURLWithPath: try #require(
+ ProcessInfo.processInfo.environment["DARKBLOOM_TEST_QWEN_TOKENIZER_DIR"]))
+ let tokenizer = try await LocalTokenizerLoader(environment: [:]).load(from: directory)
+ let clock = ContinuousClock()
+ let started = clock.now
+ let vocabulary = try JSONAnswerVocabulary(tokenizer: tokenizer, profile: QwenStrictToolGrammar.profile,
+ stopTokenIDs: StrictToolFixture.stops)
+ let elapsed = clock.now - started
+ // The base pieces and the four markers; stop tokens are sampled separately.
+ #expect(vocabulary.pieceTokenIDs.count == 248_044 + 4)
+ let (request, prepared) = try StrictToolFixture.prepared(StrictToolFixture.body(tools: StrictToolFixture.order))
+ let tools = try #require(prepared.tools).map { $0.toolSpec() }
+ for thinking in [true, false] {
+ let prompt = try tokenizer.applyChatTemplate(messages: [["role": "user", "content": "Order it."]],
+ tools: tools, additionalContext: ["enable_thinking": thinking])
+ let schema = try QwenStrictToolSchema(declared: try #require(prepared.declaredTools),
+ rendered: try #require(prepared.tools), forbidding: QwenStrictToolGrammar.forbiddenMarkers,
+ family: QwenStrictToolGrammar.profile.family)
+ let tail = tokenizer.decode(tokenIds: Array(prompt.suffix(ReasoningPromptProbe.tailTokenCount)),
+ skipSpecialTokens: false)
+ let prefix = try #require(ReasoningPromptProbe.streamingPrefix(forPromptTail: tail))
+ #expect((prefix == ReasoningPromptProbe.thinkOpen) == thinking)
+ let constraint = try QwenStrictToolConstraint(schema: schema, vocabulary: vocabulary,
+ forbidding: QwenStrictToolGrammar.forbiddenMarkers, startsInReasoning: thinking, maxTokens: 4096)
+ let answer = (thinking ? "The user wants an order.\n\n\n" : "") + StrictToolFixture.validOrder
+ var state = constraint.initialState
+ for token in tokenizer.encode(text: answer, addSpecialTokens: false) {
+ #expect(constraint.allowedTokenIDs(state: state, remainingTokens: 100).contains(token), "token \(token)")
+ state = try #require(constraint.nextState(state: state, tokenID: token), "token \(token)")
+ }
+ #expect(constraint.nextState(state: state, tokenID: 248046) == -1)
+ _ = request
+ }
+ print("qwen-strict-tool-vocabulary-build: \(elapsed)")
+ }
+}