diff --git a/changelog.d/glm-stray-tool-call-text.md b/changelog.d/glm-stray-tool-call-text.md new file mode 100644 index 0000000000..b72b23f66e --- /dev/null +++ b/changelog.d/glm-stray-tool-call-text.md @@ -0,0 +1,5 @@ +### A stray `` no longer fails a GLM-5.3-Flash response + +- GLM's tool parser reads a response from its first `` to the end as one batch of calls, and on `auto` tool requests that includes the model's reasoning. A tag the model only mentioned or a call it drafted in its thought, or a text answer that mentions the tag, failed the whole response with a 500 (`native GLM tool output is invalid`). +- Such output is now text instead of a failure, as vLLM's and SGLang's GLM parsers never fail a response on tool syntax, with a stricter rule for what is still a call: the calls are the frames that end the response, when all of them are well-formed; everything before them is text, which the service's reasoning parser splits at ``. A frame inside or after another frame's arguments, or after arguments that break the parser's grammar, is never a call. Output with no such calls (a malformed or cut-off final call, a malformed call among the final ones, text after the calls) is all text, and so is output cut off at `max_tokens` whose tool suffix does not parse. No call is completed or salvaged. +- Still a 500, as before: output whose released text would hold a think marker from inside a tool frame (the reasoning parser would read it as the end of the thought), and a tool suffix over the parser's 1 MiB bound. Output the parser cannot read safely, such as a thought that spells out the tags in order (``, ``, ``) or a refused call with quotes before the final calls, recovers no call: it is text, or still a 500 when the thought's `` comes after it. Required and named `tool_choice` still fail closed (422). `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the 500 for every unparsed suffix; `darkbloom start` passes it to the launchd provider. diff --git a/changelog.d/parallel-tool-calls-false-first-call.md b/changelog.d/parallel-tool-calls-false-first-call.md new file mode 100644 index 0000000000..37b799e7f5 --- /dev/null +++ b/changelog.d/parallel-tool-calls-false-first-call.md @@ -0,0 +1,4 @@ +### `parallel_tool_calls: false` returns the first tool call instead of failing the response + +- With `parallel_tool_calls: false`, a model that made a second call failed the whole response: a streamed answer ended in an error after its first call had already been sent, and a complete answer was a 422. Under automatic tool choice the prompt does not ask for a single call (only a GLM pair's prompt does), so these were requests the provider should have served. +- The response now carries the first call, as OpenAI and vLLM return it, and the calls the model makes after it are dropped, streamed or not, on every model, Nemotron Super's path included. A later frame that does not parse keeps the existing rule for malformed output: GLM, MiMo, Flint and Nemotron Super fail the response, as for any malformed frame, and a frame that never reads as a call (an undeclared name on Qwen or Gemma) stays text. diff --git a/changelog.d/qwen35-9b-card-presence-penalty.md b/changelog.d/qwen35-9b-card-presence-penalty.md new file mode 100644 index 0000000000..e757beaf70 --- /dev/null +++ b/changelog.d/qwen35-9b-card-presence-penalty.md @@ -0,0 +1,5 @@ +### Qwen 3.5 9B keeps its model card's presence penalty + +- Provider 0.10.12 dropped the default `presence_penalty` of 1.5 from the catalog `Qwen3.5-9B` for requests that send none. In production its answers with `max_tokens` of 8,192 or more then ran to the limit about three times as often (5.5 % against 1.7 % on 0.10.11), and JSON `response_format` answers ran out and failed about twice as often (51 % against 23 % in the same 10-minute windows). 0.10.13 restores the model card's 1.5 for those requests, as on the other catalog Qwen 3.5/3.6 builds. +- A request that sends its own `presence_penalty` is unchanged. With `presence_penalty` 0 the 9B still speculates under exact MTP acceptance. A penalty row does not speculate but still donates prefix-cache checkpoints. +- `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` (or `off`) restores 0.10.12's default. `darkbloom start` passes it to the launchd job. A coordinator registry `presence_penalty` arrives as the request's own value and wins, so while the registry sets one for the 9B the switch changes only local requests; rolling routed traffic back also needs the registry value removed or set to 0. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index a88327753d..61c90bce8c 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-11-12 +> Last updated: 2026-11-13 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -1781,6 +1781,45 @@ commit a partial call batch. Its retained suffix is capped at 1 MiB; rejection returns the original text through the existing parser-failure path. Ambiguous string unions and unsupported indirect schemas are not inferred. This parser does not implement constrained decoding or advertise function calling. +The suffix starts at the response's first ``, and GLM `auto` tool +requests do not split reasoning off first, so it also holds a tag the model only +mentioned or a call it drafted in its thought, or a tag its answer mentions. +Such a suffix does not parse as one batch. On an `auto` request it is no longer a +failure: like the reference GLM parsers (vLLM, SGLang), which never fail a +response on tool syntax, the provider returns it as text, under its own stricter +rule for what still counts as a call (`NativeToolStreamRouter.finishCompleteCalls`, +`GLM5ToolSuffix`). The calls are the trailing run of top-level frames, separated +only by whitespace and ending the response, when the SDK parser accepts every one +of them (like the SDK, the batch is taken whole or not at all); everything before +them is text, which the service's reasoning parser then splits at ``. A frame that has started its +arguments must follow the SDK parser's grammar to its own `` (a +string-typed value raw to ``, any other value structurally valid +JSON, whose quoted delimiters are data). One that does not (malformed JSON, a raw +value holding frame tags, which the SDK refuses, its own tags after a malformed +header, a key that only canonically equals a declared one, a value whose declared +type is a union of `string` with `object` or `array`, which the template could +have written either way) or that is still open at the end owns the rest of the +response: no frame inside or after its arguments is ever a call. Where the SDK +accepts a frame on its own, the lexer reads it as the SDK does; a frame the SDK +refuses keeps its end only without a `"` (one may open a JSON string that a raw +reading ends inside, or end a raw string that a JSON reading runs past), else it +owns the rest too, as does a frame's tag in top-level text (from the first +frame or `` read as a mention before it). A `` +followed by anything else, with no frame tags before the next ``, is a +mention; a thought that spells out the tags in order (`` … ``) +therefore owns the rest, and fails as before when its `` follows. A suffix +with no such run (a malformed or cut-off final frame, text after the calls) is +all text, and so is a suffix that did not parse in an output cut at the token +limit; no frame is completed or salvaged. A suffix whose release would put a think marker from +inside a frame (its name, a key or a value, or anything after a frame that owns +the rest) before the reasoning parser keeps failing (500), at a stop or at the +token limit, as does a suffix the SDK refuses as oversized while it streams, and +a required or named call (422). Unlike vLLM and SGLang, a call followed by text +or by a malformed frame, or next to one in the final run, commits nothing, and a +call drafted inside a closed thought stays reasoning. A suffix that parses keeps its calls as before. The +rule follows the handler's `glm5` parser format, so a request that selects that +parser for another family gets it too. `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` +restores the whole-suffix failure (500). The request-local [GLM prompt contract](../reference/protocol-messages.md#glm-native-prompt-contract) also preserves original schema values only after a trusted loaded-model check. It renders reasoning that OpenRouter returns on earlier assistant turns @@ -2958,7 +2997,9 @@ When neither a global nor a per-model acceptance value is configured, serving defaults to typical acceptance for eligible sampled target-prefix rows, except on the builds whose built-in rule is exact (`MTPAcceptancePolicy.builtInIsExact`): the owned Bonsai 9B candidate; the catalog `Qwen3.5-9B`, which looped under -typical acceptance in the 0.10.12 gate (see the Qwen 3.5/3.6 defaults below); +typical acceptance in the 0.10.12 gate (its default carries the card's presence +penalty again, so only its rows with `presence_penalty` 0 draft; see the Qwen +3.5/3.6 defaults below); the catalog `gemma-4-26b-qat-4bit`, which drafted every answer of OpenRouter's 10-31 GPQA run, 30 % of which ended at the 32,768-token cap; and every Qwen 3.8 27B build (`EigenLabs/Qwen3.8-27B-4bit-mtp` and its head-less target, @@ -3095,7 +3136,7 @@ production assembly and encrypted store. | `top_p` | `topP` | artifact default, else `1.0` | | `top_k` | `topK` | artifact default, else `0` | | `repetition_penalty` | `repetitionPenalty` | artifact default, else `1.0` | -| `frequency_penalty` / `presence_penalty` | `frequencyPenalty` / `presencePenalty` | `0`; `presence_penalty` takes a model-card default on the catalog 35B Qwen 3.5/3.6 builds (`Qwen3.5-9B` has none) | +| `frequency_penalty` / `presence_penalty` | `frequencyPenalty` / `presencePenalty` | `0`; `presence_penalty` takes the model card's 1.5 on the catalog Qwen 3.5/3.6 builds (`DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` drops it on `Qwen3.5-9B`) | | `seed` | `seed`; also keys a stable engine request id | nil | | `logit_bias` | `logitBias` — string keys parsed to non-negative `Int`; invalid keys dropped and counted | `[:]` | | `logprobs` + `top_logprobs` | `topLogprobs = logprobs ? min(20, max(1, top_logprobs ?? 0)) : 0` | `0` | @@ -3153,29 +3194,27 @@ The catalog `Qwen3.5-9B`, `qwen3.5-35b-a3b` and `qwen3.6-35b-a3b-vl-mtp-mxfp8` builds (`EngineV2SamplingDefaults.qwen35CardModelTypes`, each bound to its `model_type`) take their model cards' thinking-mode values for omitted knobs: `temperature 1.0`, `top_p 0.95`, `top_k 20`. Greedy decoding made them repeat -themselves until `max_tokens` (#1530). The cards' `presence_penalty 1.5` is a -per-build default, set by the 0.10.12 gate on the signed 0.10.11 (temperature 1 -/ 0.95 / 20; #1652's four loopers and five tool transcripts at 32,768 tokens and -nineteen everyday prompts at 8,192, three seeds each; the Studio M3 Ultra for -the 9B, an M5 Ultra for the 35B): +themselves until `max_tokens` (#1530). Every build also takes the cards' +`presence_penalty 1.5` for a request that omits one (`qwen35CardDefaults`): -| Build | Omitted `presence_penalty` | Built-in MTP acceptance | The gate without the penalty | +| Build | Omitted `presence_penalty` | Built-in MTP acceptance | Without the penalty | |---|---|---|---| -| `qwen3.5-35b-a3b`, `qwen3.6-35b-a3b-vl-mtp-mxfp8` (`qwen35CardDefaults`) | 1.5 | typical | `qwen3.5-35b-a3b` ran away under typical acceptance (5 of 19 everyday prompts, 8 of 12 loopers to 32,768, MTP running at concurrency 1) and under exact (2 of 12 loopers); the 3.6 build shares its architecture | -| `Qwen3.5-9B` (`qwen35NineBCardDefaults`) | none | **exact** (`MTPAcceptancePolicy.builtInIsExact`) | ran away on 13 of 31 draws under typical acceptance and on 0 of 31 under exact, MTP running; the penalty-free body cached 8,192 tokens on the second send, the penalty body none | +| `qwen3.5-35b-a3b`, `qwen3.6-35b-a3b-vl-mtp-mxfp8` | 1.5 | typical | The 0.10.12 gate on the signed 0.10.11 (temperature 1 / 0.95 / 20; #1652's four loopers and five tool transcripts at 32,768 tokens, nineteen everyday prompts at 8,192, three seeds each; an M5 Ultra): `qwen3.5-35b-a3b` ran away under typical acceptance (5 of 19 everyday prompts, 8 of 12 loopers to 32,768, MTP running at concurrency 1) and under exact (2 of 12 loopers); the 3.6 build shares its architecture | +| `Qwen3.5-9B` | 1.5; none under `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` (`qwen35NineBNoPenaltyDefaults`, 0.10.12's default) | **exact** (`MTPAcceptancePolicy.builtInIsExact`) | The same gate (the Studio M3 Ultra) saw it run away on 13 of 31 draws under typical acceptance and on 0 of 31 under exact, so 0.10.12 shipped it without the penalty. In production that was a regression. On 2026-11-12, on 0.10.12 Macs against 0.10.11 Macs (the penalty, MTP off) over the same period, answers with `max_tokens` ≥ 8,192 hit the cap on 5.5 % against 1.7 %, about three times as often. On the 4,096-token JSON `response_format` workload, in the same 10-minute windows, answers ran out and failed in 51 % of requests against 23 %. Its constrained JSON rows never speculate and their template is unchanged since 0.10.4, so the penalty is the difference we can establish: with nothing else running they failed 32.7 % against 13.6 %. A registry `presence_penalty` 1.5 brought both back within the hour | A row with a penalty does not speculate (`EngineLoopV2.mtpBasicEligible`), so -the 35B builds' requests that omit the penalty stay without MTP, the cost the -gate accepted for loop safety; they still stage prefix checkpoints +these builds' requests that omit the penalty stay without MTP, the cost taken +for loop safety. They still stage prefix checkpoints ([prefix caching](prefix-cache.md#invariants), invariant 9). A request's own -`presence_penalty` always wins: `0` on a 35B build speculates under typical -acceptance and donates checkpoints (the configuration that looped in the gate, -now the caller's choice); a nonzero value on the 9B turns its MTP off for that -request (it still donates checkpoints). The coordinator forwards a build's -registry runtime defaults for the fields a request omits -([`requestRuntimeDefaultKeys`](https://github.com/Layr-Labs/darkbloom-platform/blob/c69380d91fd3f9e4ef3ff1e3775690d80adbbe57/coordinator/api/inference/request/model_runtime_defaults.go)); -on 2026-11-10 the registry set `temperature`, `top_p` and `top_k` for these -builds and no `presence_penalty`, so the provider default above decides it. +`presence_penalty` always wins: `0` speculates (typical acceptance on the 35B +builds, the configuration that looped in the gate; exact on the 9B) and donates +checkpoints. The coordinator forwards a build's registry runtime defaults for +the fields a request omits +([`requestRuntimeDefaultKeys`](https://github.com/Layr-Labs/darkbloom-platform/blob/a9c111db3e235fa979a914d6a46bf93cba8e4268/coordinator/api/inference/request/model_runtime_defaults.go), +`presence_penalty` included). Since 2026-11-12 19:17Z the registry sets +`presence_penalty` 1.5 on `Qwen3.5-9B`, which reaches 0.10.12 Macs too; to +the provider it is the request's own value, so `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` +changes nothing while the registry sets it. Other model identities keep the legacy defaults in the table byte-for-byte. `do_sample: false` or an absent/unreadable file is legacy. The sampler is not part of prompt or cache identity, so prefix-cache and SSD @@ -3543,8 +3582,15 @@ read bare scalars and composites as raw strings. When the frame closes, the complete parse must agree with everything already exposed (`libs/mlx-swift-lm/Libraries/MLXLMCommon/Tool/ToolCallStreaming.swift`). `NativeToolStreamRouter` admits `parallel_tool_calls` cardinality at the first -fragment and, when the request is `strict` (below), validates name and schema -at frame close; the service renders OpenAI fragments (`index`, `id`, `type` +fragment: with `parallel_tool_calls: false` it exposes the first call only and +drops every later call frame, unexposed and unvalidated, as OpenAI returns one +call and vLLM keeps the first; the complete-call paths, Nemotron Super's +included, keep the first the same way (`ParallelToolCallPolicy`). A later +frame keeps its family's malformed-output rule: one the parser returns as +text (an undeclared name it cannot read) stays visible text, and one that does +not parse still fails a GLM, MiMo, Flint or Nemotron Super response. When +the request is `strict` (below), it validates name and schema at frame close; +the service renders OpenAI fragments (`index`, `id`, `type` and `function.name` first, then `function.arguments` pieces). A response that begins with a call therefore reaches its first content frame at the function name instead of the engine terminal, which also ends the frame loop's diff --git a/docs/architecture/prefix-cache.md b/docs/architecture/prefix-cache.md index f8fa6dd092..42e9a44592 100644 --- a/docs/architecture/prefix-cache.md +++ b/docs/architecture/prefix-cache.md @@ -964,7 +964,7 @@ rules applied to these signals. text request that cannot speculate (a token constraint, logprobs, `logit_bias`, a repetition, frequency or presence penalty, a `stop` string: `EngineLoopV2.mtpBasicEligible`), including a Qwen request with the card's - presence penalty (the 35B builds' default), records the head's history over + presence penalty (every catalog Qwen 3.5/3.6 build's default), records the head's history over its prompt chunks. It therefore stages the same resident and SSD checkpoints a speculating request stages, byte for byte. It never drafts, verifies or seeds a carry, and its history is released once its prompt diff --git a/docs/provider/direct-mode.md b/docs/provider/direct-mode.md index 68d6eaad23..5404c2282d 100644 --- a/docs/provider/direct-mode.md +++ b/docs/provider/direct-mode.md @@ -1,6 +1,6 @@ # The local API: an OpenAI-compatible server on your Mac -> Last updated: 2026-11-12 +> Last updated: 2026-11-13 Your Mac's models as an OpenAI-compatible HTTP server for your own tools, served two ways: **Both**, the default (`darkbloom start`: beside the Darkbloom @@ -660,7 +660,7 @@ frame-timestamp label. | `enable_thinking` absent or `true` | Template default; `reasoning_content` streams until `` | | `enable_thinking: false` | All output is `content`, including literal markers | | `chat_template_kwargs.force_nonempty_content` | Unterminated reasoning becomes `content`: moved in a complete response; a stream sends it as reasoning, then repeats it as `content` at the end | -| `tools`, `tool_choice`, `parallel_tool_calls` (text, image or video) | `` frames become validated `tool_calls`; violations return 422, or end a stream with an error event | +| `tools`, `tool_choice`, `parallel_tool_calls` (text, image or video) | `` frames become validated `tool_calls` (with `parallel_tool_calls: false`, the first one only); violations return 422, or end a stream with an error event | | `response_format` `json_object`/`json_schema` (text, image or video) | Content is withheld and validated; invalid JSON returns 422, or ends a stream with an error event. With `tools`, calls return as `tool_calls` and only an answer without calls must be JSON | | `logprobs: true`, `top_logprobs` 0 to 20 (text, image or video) | `choices[0].logprobs.content`, streamed and complete: one entry per generated token in generation order, covering reasoning, answer and tool-call tokens (as vLLM and SGLang return them), each with at least one alternative. Joined, the entry tokens spell the reasoning, the `` marker and then the answer, not the answer alone. Reasoning chunks carry their tokens' entries, and a response that ends while reasoning still carries them. A complete response carries the stream's entries. Tool-call tokens lack entries only in the rare case that nothing follows the call. The request does not speculate; others keep speculating ([logprob rows](../architecture/inference.md#nemotron-super-logprobs)) | | Contradictory controls, `top_logprobs` outside 0 to 20, `logit_bias`, `min_p` other than 0, `n > 1`, `prompt_cache_key` (text, image or video) | 400 `Invalid inference request.` before generation | diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 6bf4cd8d16..8a419a7574 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -560,11 +560,13 @@ and rollback are defined in the [provider configuration reference](../provider/c | `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_REFUSAL_PROBE` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`DeadlineRefusalProbe`) | The refusal streak's idle probe alone ([deadlines](../architecture/inference.md#deadlines)): off, refusals neither count nor start a probe, and the estimator corrections stay on. Forwarded to the launchd provider job. | +| `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY` | trimmed, case-insensitive `0`, `false`, `no`, `off` drop the default; any other value keeps it | on: the model card's 1.5 | `provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift` (`qwen35NineBKeepsCardPenalty`) | The catalog `Qwen3.5-9B`'s `presence_penalty` for a request that omits one (0.10.13; 0.10.12 had none, and its answers with `max_tokens` ≥ 8,192 ran to the limit about three times as often: 5.5 % against 1.7 %). `0` restores 0.10.12's no-penalty default. A request's own value, the coordinator's registry default included, always wins: while the registry sets `presence_penalty` for `Qwen3.5-9B`, routed requests carry it and `0` affects only local requests, so rolling routed traffic back also needs the registry value removed or set to `0`. `darkbloom start` passes it to the launchd job. | | `DARKBLOOM_TTFT_SHAPE_WARMUP` | trimmed, case-insensitive `0`, `false`, `no`, `off` disable; `always` skips the probe | unset: probe-gated warmup | `provider-swift/Sources/ProviderCore/Inference/Performance/ModelCalibrationPolicy.swift` (`shapeWarmupMode`) | Excluded load-time [shape warmup](../architecture/inference.md#model-startup-calibration) for ordinary `EngineV2` slots: a 128-token shader-cache probe runs twice and only a cold cache runs the shape cells, within 20 seconds per engine. Trains no rate or counter. Forwarded to the LaunchAgent. | | `DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL` | integer layers | projected from `provider.toml` (`18`) | `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift` | Gemma-4 prefill chunk-eval layers; the provider sets it for the engine, `scripts/install.sh` sets `18` for the smoke test. | | `DARKBLOOM_TTFT_GDN_BLOCKED` | `0`, `false`, `no`, `off` keep the stock kernel; `packed` or `rows` force that kernel; unset or any other value probes. Case-insensitive; surrounding whitespace is ignored | probe | `libs/mlx-swift-lm/Libraries/MLXLMCommon/GatedDelta.swift` (`GatedDeltaPrefill.mode`, `GatedDeltaPrefill.kernel`) | Selects the Gated DeltaNet prompt-window kernel of `qwen3_5`, `qwen3_5_moe` and `prism_hadamard_qwen35` models ([mechanism](../architecture/inference.md#context)). The default probe keeps a four-row kernel only where it reproduces `gated_delta_step` bit for bit on the GPU; it does not compare speed, so `0` is the rollback where a kept kernel is slower. Forced kernels skip that check and are for A/B measurement only. Decode, MTP verification and masked updates always use the stock kernel. Read once per process. Forwarded to the LaunchAgent. | | `DARKBLOOM_ENGINE_V2_VLM_PARITY_CHECK` | `0` skips | on | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VLMTextExtraction.swift` | VLM text-extraction parity check. | | `DARKBLOOM_TTFT_STREAM_TOOL_CALLS` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/ToolStreamPreparation.swift` (`streamsToolCallsByDefault`) | Chat streams send `tool_choice` `auto` calls in the Gemma, Qwen 3.5, Harmony and framed-JSON formats as OpenAI `tool_calls` fragments while they are generated; each call is still validated when its frame closes. Required/named calls and other formats are unchanged. `0` restores complete calls at the engine terminal. See [streamed auto tool calls](../architecture/inference.md#streamed-auto-tool-calls). Forwarded to the LaunchAgent. | +| `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift` (`returnsUnparsedOutputAsTextByDefault`) | GLM-5.3-Flash `auto` tool output whose tool suffix does not parse as one call batch (a `` mentioned or drafted in the thought, or mentioned in the answer) is returned as text, with the frames that end the response as its calls when all of them are well-formed (`GLM5ToolSuffix`). Output whose released text would hold a think marker from inside a tool frame, and a suffix over the parser's 1 MiB bound, still fail (500); required/named calls still fail closed (422). `0` restores the 500 for any such response. See [GLM5Next implementation boundary](../architecture/inference.md#glm5next-implementation-boundary). 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. | ### Managed Nemotron Super slot diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift index 5f977d1730..4287ab057d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift @@ -23,10 +23,12 @@ // identities (catalog `glm-5.3-flash` and the local qualification download) // honor their artifact defaults. // The catalog Qwen 3.5/3.6 builds take their model cards' thinking-mode -// values instead of the greedy decoding that looped to `max_tokens`. The -// 35B builds keep the cards' presence penalty (`qwen35CardDefaults`); -// Qwen3.5-9B has none (`qwen35NineBCardDefaults`), as the 0.10.12 gate -// decided per build. +// values instead of the greedy decoding that looped to `max_tokens`, +// including the cards' presence penalty 1.5 (`qwen35CardDefaults`). +// 0.10.12 dropped it on Qwen3.5-9B, whose long answers then ran to +// `max_tokens` about three times as often in production (5.5 % against +// 1.7 %); 0.10.13 gives it back (`DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` +// is the rollback). // Every other model keeps the legacy defaults byte-for-byte. // * `do_sample: false` in the file means greedy (legacy), matching HF // semantics; an absent or unreadable file is legacy. @@ -70,18 +72,44 @@ public struct EngineV2SamplingDefaults: Sendable, Equatable { public static let legacy = EngineV2SamplingDefaults() /// The model cards' thinking-mode values (the template default), shared by - /// these exact catalog builds and their `model_type`. The 35B builds keep - /// the cards' presence penalty: without it qwen3.5-35b-a3b looped under - /// typical and exact MTP acceptance alike. + /// these exact catalog builds and their `model_type`, with the cards' + /// presence penalty. Without it qwen3.5-35b-a3b looped under typical and + /// exact MTP acceptance alike, and Qwen3.5-9B's answers ran on to + /// `max_tokens` (`qwen35NineBNoPenaltyDefaults`). A penalty row does not + /// speculate; it still stages the prefix checkpoints a speculating row + /// stages. static let qwen35CardDefaults = EngineV2SamplingDefaults( temperature: 1.0, topP: 0.95, topK: 20, presencePenalty: 1.5) - /// Qwen3.5-9B's: the same values without the penalty. Without it the 9B - /// looped only under typical MTP acceptance, and its built-in rule is exact - /// (`MTPAcceptancePolicy`); a penalty would keep its rows from speculating - /// (they would still stage prefix checkpoints). - static let qwen35NineBCardDefaults = EngineV2SamplingDefaults( + /// Qwen3.5-9B under `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0`: the card's + /// values without the penalty, 0.10.12's default. Its 31-draw gate saw no + /// loop under exact acceptance. In production, 0.10.12 against 0.10.11 + /// Macs over the same period, its answers with `max_tokens` ≥ 8,192 ran + /// to the limit about three times as often (5.5 % against 1.7 %), and + /// its constrained JSON `response_format` rows, which never speculate, + /// ran out and failed about twice as often (51 % against 23 % in the same + /// 10-minute windows). The penalty is the difference we can establish: + /// with nothing else running those rows failed 32.7 % against 13.6 %. + /// The registry's `presence_penalty` 1.5 restored it on 2026-11-12. + static let qwen35NineBNoPenaltyDefaults = EngineV2SamplingDefaults( temperature: 1.0, topP: 0.95, topK: 20) static let qwen35NineBModelID = "Qwen3.5-9B" + + /// `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY`: `0`, `off`, `false` or `no` + /// (trimmed, case-insensitive) restores 0.10.12's no-penalty default for + /// Qwen3.5-9B requests that omit a presence penalty; unset or any other + /// value keeps the card's 1.5. Only the 9B reads it. A request's own + /// `presence_penalty`, the coordinator's registry default included, always + /// wins, so while the registry sets one the switch does not reach routed + /// traffic. + static let qwen35NineBPenaltyEnvironmentKey = "DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY" + + static func qwen35NineBKeepsCardPenalty(environment: [String: String]) -> Bool { + guard let raw = environment[qwen35NineBPenaltyEnvironmentKey]? + .trimmingCharacters(in: .whitespacesAndNewlines).lowercased(), !raw.isEmpty + else { return true } + return !["0", "off", "false", "no"].contains(raw) + } + static let qwen35CardModelTypes = [ "Qwen3.5-9B": "qwen3_5", "qwen3.5-35b-a3b": "qwen3_5_moe", @@ -110,12 +138,17 @@ public struct EngineV2SamplingDefaults: Sendable, Equatable { /// Resolve once at slot construction. `.legacy` when the gate is off, /// the checkpoint directory is unknown, the file is absent or - /// unreadable, or the artifact declares `do_sample: false`. + /// unreadable, or the artifact declares `do_sample: false`. `environment` + /// is read for `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY` alone. static func resolve( - modelId: String, modelType: String?, modelDirectory: URL? + modelId: String, modelType: String?, modelDirectory: URL?, + environment: [String: String] = ProcessInfo.processInfo.environment ) -> EngineV2SamplingDefaults { if let type = qwen35CardModelTypes[modelId], type == modelType { - return modelId == qwen35NineBModelID ? qwen35NineBCardDefaults : qwen35CardDefaults + if modelId == qwen35NineBModelID, !qwen35NineBKeepsCardPenalty(environment: environment) { + return qwen35NineBNoPenaltyDefaults + } + return qwen35CardDefaults } guard honorsArtifactDefaults(modelId: modelId, modelType: modelType), let modelDirectory diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift index ab4626a57b..41db0e0949 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift @@ -328,7 +328,8 @@ enum EngineV2SlotFactory { let samplingDefaults = EngineV2SamplingDefaults.resolve( modelId: modelId, modelType: modelType, - modelDirectory: modelDirectory) + modelDirectory: modelDirectory, + environment: environment) // SSD offload never carves the live KV grant. let engineKVBytesCapacity = kvBytesCapacity diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index e7ea281696..72379bc52e 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -1917,18 +1917,17 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { continuation.finish() return } - let toolCalls = toolHandler?.finish() ?? [] + let finished: (calls: [ToolCall], residual: String?) do { + finished = try router.finishCompleteCalls(truncated: stopReason == "length") try router.checkNativeToolFailure() } catch { await releaseBox.fire() continuation.finish(throwing: error) return } - if prepared.mode == .auto, - let residual = toolHandler?.takeResidualText(), - !residual.isEmpty - { + let toolCalls = ParallelToolCallPolicy.admitted(finished.calls, prepared: prepared) + if prepared.mode == .auto, let residual = finished.residual, !residual.isEmpty { emit(router.visibleEvent(residual)) } if prepared.mode == .auto, (toolHandler?.parseFailureCount ?? 0) > 0 { diff --git a/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift b/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift index 8b3b72d45b..ce1ae42a9d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift @@ -48,8 +48,10 @@ public enum MTPAcceptancePolicy { /// The built-in rule is exact for: /// - the owned Bonsai 9B candidate; - /// - the catalog Qwen3.5-9B: with no default presence penalty its rows - /// speculate, and at temperature 1 typical acceptance made them loop to + /// - the catalog Qwen3.5-9B: its default carries the card's presence + /// penalty again (a penalty row does not speculate), but a request with + /// `presence_penalty` 0, or a Mac on the no-penalty rollback, drafts, and + /// at temperature 1 typical acceptance made such rows loop to /// `max_tokens` where exact acceptance did not; /// - the catalog Gemma 4 26B QAT, whose assistant drafts most of its rows: /// on OpenRouter's GPQA run of 10-31 every answer drafted under typical diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift index f018df79fe..bdcf4580d3 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift @@ -20,7 +20,8 @@ enum ToolChoicePromptPolicy { /// choice, JSON output and withheld reasoning are served alike on /// every GLM slot; a pair also asks for at most one call when /// automatic choice has `parallel_tool_calls: false` - /// (`singleCallInstruction`), which the validator holds it to. + /// (`singleCallInstruction`); a response keeps only its first call + /// (`ParallelToolCallPolicy.admitted`). var glm5PairPostValidation = false /// The caller's declarations as sent, before ingress normalization /// (`ToolSchemaNormalization`) filled in render types. Validation of @@ -57,7 +58,7 @@ enum ToolChoicePromptPolicy { var choice = try prepareToolChoice( request, modelType: modelType, allowInternalSchemaMetadata: allowInternalSchemaMetadata) // GLM on a pair: `parallel_tool_calls: false` with automatic choice - // asks for at most one call, which the validator then holds it to. + // asks for at most one call; the response keeps only its first. if glm5PairPostValidation, choice.mode == .auto, !choice.allowsParallelCalls, choice.tools?.isEmpty == false { choice = Prepared(messages: appendingToLastUser(singleCallInstruction, in: choice.messages), diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift new file mode 100644 index 0000000000..0440c8b362 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/GLM5ToolSuffix.swift @@ -0,0 +1,422 @@ +import Foundation +import MLXLMCommon + +/// The calls in a GLM tool suffix that does not parse as one batch. +/// +/// The SDK's `GLM5ToolStream` withholds a response from its first +/// `` to EOS and parses that suffix as one call batch. On the legacy +/// text path the suffix also holds reasoning, so a `` the model only +/// mentioned or drafted in its thought, or one its answer mentions, fails the +/// batch. Reference GLM parsers (vLLM, SGLang) never fail a response on tool +/// syntax; here such a suffix is text too, under a stricter, provider-specific +/// rule for what is still a call: the trailing run of top-level frames, +/// separated only by whitespace and ending the response, when every frame of +/// it parses. Everything before them is text. +/// +/// Only text the lexer can place outside every frame's arguments starts a +/// frame. A frame that has started its arguments must follow the SDK's grammar +/// to its own ``; one that does not, or is still open at the end, +/// owns the rest of the response, so a `` inside or after an +/// argument is never a call. A frame is never completed or salvaged. +enum GLM5ToolSuffix { + /// `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure: + /// an `auto` response whose suffix does not parse fails with a 500. + static let environmentKey = "DARKBLOOM_GLM_TOOL_TEXT_FALLBACK" + static let returnsUnparsedOutputAsTextByDefault = + ProcessInfo.processInfo.environment[environmentKey] != "0" + + enum Split: Equatable { + /// `text` precedes `calls`, which may be empty. + case text(String, calls: [ToolCall]) + /// The text to release holds a think marker inside a tool frame, which + /// the service's reasoning parser would read as a channel boundary. + /// Such a suffix keeps failing, as before. + case ambiguous + } + + /// `truncated`: the token limit cut the output off; its suffix is text. + static func split(_ suffix: String, tools: [[String: any Sendable]]?, truncated: Bool = false) -> Split { + let bytes = Array(suffix.utf8) + var lexer = Lexer(bytes: bytes, tools: tools) + lexer.run() + var start = bytes.count + var calls: [ToolCall] = [] + if !truncated, lexer.unclosed == nil { + // The run of whitespace-separated frames that ends the response. + var head = lexer.frames.endIndex + var from = bytes.count + while head > 0, Lexer.isWhitespace(bytes[lexer.frames[head - 1].upperBound ..< from]) { + head -= 1 + from = lexer.frames[head].lowerBound + } + let run = head ..< lexer.frames.endIndex + // The run is the response's call batch: like the SDK, take all of + // it or none, so a member the SDK refuses runs no other member. + if !run.isEmpty, run.allSatisfy({ lexer.verdicts[$0] ?? lexer.accepts(lexer.frames[$0]) }) { + let parsed = GLM5ToolCallParser().parseEOS( + String(decoding: bytes[from...], as: UTF8.self), tools: tools) + // The SDK reads the same frames; anything else stays text. + if parsed.count == run.count { + start = from + calls = parsed + } + } + } + // Decided on exactly the text that will be released. + if lexer.holdsThinkMarker(before: start) { return .ambiguous } + return calls.isEmpty + ? .text(suffix, calls: []) : .text(String(decoding: bytes[..`, or `` pairs. A `` followed by + /// anything else is a mention and stays text, unless a frame's own tags + /// follow it before the next ``. A string-typed value runs raw + /// to `` (the template writes strings raw) and may not hold the + /// frame tags the SDK refuses there; any other value is JSON, structurally + /// checked as the SDK reads it, so quoted delimiters are data. An argument + /// whose declared type is unknown is JSON if it opens like JSON, raw + /// otherwise. Where the SDK accepts a frame, this is its own reading; a + /// frame it refuses keeps its boundary only when no other reading could + /// move it. + struct Lexer { + let bytes: [UInt8] + /// Each declaration the SDK's parser accepts, by name, and its schema. + private let declarations: [String: [String: any Sendable]] + private let parameters: [String: [String: any Sendable]] + /// Closed top-level frames, in order. + private(set) var frames: [Range] = [] + /// Whether the SDK's parser accepts each frame on its own, where that + /// was needed while lexing (a frame with a `"`); nil: not asked yet. + private(set) var verdicts: [Bool?] = [] + /// Start of a frame whose arguments break the grammar, are still open + /// at the end or end where another reading would not; it owns the + /// rest of the response. For a frame's tag in top-level text, the + /// first frame or mention before it, or the tag. + private(set) var unclosed: Int? + /// The first `` read as a mention. + private var firstMention: Int? + private var index = 0 + + init(bytes: [UInt8], tools: [[String: any Sendable]]?) { + self.bytes = bytes + // Only a declaration the SDK's parser accepts types arguments: one + // per name, an object schema without indirect types. A `function` + // that is not an object makes it refuse every name. + var declarations: [String: [String: any Sendable]] = [:] + var parameters: [String: [String: any Sendable]] = [:] + var seen: Set = [] + var duplicates: Set = [] + for tool in tools ?? [] { + let function: [String: any Sendable] + if let wrapped = tool["function"] { + guard let object = wrapped as? [String: any Sendable] else { + declarations = [:] + parameters = [:] + break + } + function = object + } else { + function = tool + } + guard let name = function["name"] as? String else { continue } + if !seen.insert(name).inserted { duplicates.insert(name) } + let schema: [String: any Sendable] + if let declared = function["parameters"] { + guard let object = declared as? [String: any Sendable], + object["type"] == nil || object["type"] as? String == "object", + !Self.hasIndirectType(object), + object["properties"].map({ $0 is [String: any Sendable] }) ?? true + else { continue } + schema = object + } else { + schema = [:] + } + declarations[name] = tool + parameters[name] = schema + } + for name in duplicates { + declarations[name] = nil + parameters[name] = nil + } + self.declarations = declarations + self.parameters = parameters + } + + mutating func run() { + while true { + let next = find("", from: index) + // A frame's tag in top-level text belongs to no frame: what + // follows it may be that frame's arguments, and a header read + // as a mention before it, or a closed frame whose raw value + // runs on through it, may be that frame's. Own from the first. + if let stray = first(of: Self.frameTags, in: index ..< (next ?? bytes.count)) { + unclosed = min(stray, firstMention ?? stray, frames.first?.lowerBound ?? stray) + return + } + guard let start = next, let tag = find("<", from: start + 11) else { return } + if starts("", at: tag) { + index = tag + 12 + guard record(start ..< index) else { return } + } else if starts("", at: tag) { + let name = frameName(start ..< tag) + let declared = Self.isFunctionName(name) ? parameters[name] : nil + guard let end = arguments(from: tag, parameters: declared) else { + unclosed = start + return + } + index = end + guard record(start ..< end) else { return } + } else { + // Anything else after the name is a mention, unless a + // frame's own tags follow before the next ``: + // then it is a malformed frame, which owns the rest. + let following = find("", from: tag) ?? bytes.count + if holdsAny(Self.frameTags, in: tag ..< following) { + unclosed = start + return + } + firstMention = firstMention ?? start + index = following + } + } + } + + /// Records a closed frame. A frame the SDK refuses keeps its boundary + /// only without a `"`: one may open a JSON string that a raw reading + /// ends inside, or end a raw string that a JSON reading runs past. Only + /// such a frame is checked here; false when it owns the rest. + private mutating func record(_ frame: Range) -> Bool { + guard bytes[frame].contains(34) else { + frames.append(frame) + verdicts.append(nil) + return true + } + guard accepts(frame) else { + unclosed = frame.lowerBound + return false + } + frames.append(frame) + verdicts.append(true) + return true + } + + /// Whether the SDK's parser accepts `frame` on its own. A name it + /// would refuse before reading arguments is refused without asking it; + /// otherwise it is asked with that name's one declaration, which it + /// resolves the same way as from the whole list, without scanning it. + func accepts(_ frame: Range) -> Bool { + guard let tag = find("<", from: frame.lowerBound + 11) else { return false } + let name = frameName(frame.lowerBound ..< tag) + guard Self.isFunctionName(name), let declaration = declarations[name] else { return false } + return GLM5ToolCallParser().parse( + content: String(decoding: bytes[frame], as: UTF8.self), tools: [declaration]) != nil + } + + /// The name of the frame opening at `header.lowerBound`, up to its first `<`. + private func frameName(_ header: Range) -> String { + String(decoding: bytes[header.lowerBound + 11 ..< header.upperBound], as: UTF8.self) + .trimmingCharacters(in: CharacterSet(charactersIn: " \t\r\n")) + } + + /// The tags of a frame after its ``. + private static let frameTags = ["", "", "", "", ""] + /// The tags the SDK refuses inside a raw value. + private static let rawValueCollisions = ["", "", "", "", ""] + + /// Whether text released before `end` holds a think marker inside a frame. + func holdsThinkMarker(before end: Int) -> Bool { + frames.contains { $0.lowerBound < end && containsThinkMarker($0) } + || unclosed.map { $0 < end && containsThinkMarker($0 ..< bytes.count) } == true + } + + /// The end of the frame whose first `` is at `start`, read as + /// the SDK reads it; nil when it breaks that grammar or is open at the end. + private func arguments(from start: Int, parameters: [String: any Sendable]?) -> Int? { + var index = start + while true { + index = skipWhitespace(from: index) + if starts("", at: index) { return index + 12 } + guard starts("", at: index), let close = find("", from: index + 9), + close > index + 9, !bytes[index + 9 ..< close].contains(60) + else { return nil } + let key = String(decoding: bytes[index + 9 ..< close], as: UTF8.self) + index = close + 10 + guard starts("", at: index) else { return nil } + index += 11 + guard let raw = readsRaw(parameters: parameters, key: key, value: index) else { return nil } + if raw { + // A raw value holding frame tags is refused by the SDK; its + // `` may be a nested frame's. + guard let end = find("", from: index), + !holdsAny(Self.rawValueCollisions, in: index ..< end) + else { return nil } + index = end + 12 + } else { + guard jsonValue(&index, depth: 0) else { return nil } + index = skipWhitespace(from: index) + guard starts("", at: index) else { return nil } + index += 12 + } + } + } + + /// The SDK reads a value raw only when its declared type is `string`. + /// It takes the type of a declared key only from the key as declared, + /// byte for byte, and refuses one that only canonically equals it (nil: + /// the frame owns the rest); an undeclared key takes + /// `additionalProperties`. A union of `string` with `object` or `array` + /// could have been written either way, ending in different places: nil + /// too. A union with bare literals ends where its raw reading does (the + /// SDK refuses any union with `string`). Without a type the SDK accepts, + /// a value that opens like JSON is read as JSON, which never ends before + /// its raw reading would; any other value is raw (a JSON literal has no + /// delimiters to end early on). + private func readsRaw(parameters: [String: any Sendable]?, key: String, value: Int) -> Bool? { + if let parameters { + let schema: (any Sendable)? + if let properties = parameters["properties"] as? [String: any Sendable], + let declared = properties.index(forKey: key) + { + guard properties[declared].key.utf8.elementsEqual(key.utf8) else { return nil } + schema = properties[declared].value + } else { + schema = parameters["additionalProperties"] + } + if let schema = schema as? [String: any Sendable], !Self.hasIndirectType(schema), + let type = schema["type"] + { + if let type = type as? String { return type == "string" } + if let types = type as? [String], types.contains("string") { + return types.contains("object") || types.contains("array") ? nil : true + } + return false + } + } + let first = skipWhitespace(from: value) + return first >= bytes.count || ![34, 91, 123].contains(bytes[first]) + } + + /// One JSON value from `index`, structurally as the SDK's reader takes + /// it (strings, objects, arrays, literals, number characters). + private func jsonValue(_ index: inout Int, depth: Int) -> Bool { + guard depth <= 64 else { return false } + index = skipWhitespace(from: index) + guard index < bytes.count else { return false } + switch bytes[index] { + case 34: + return jsonString(&index) + case 123: + index = skipWhitespace(from: index + 1) + if consume("}", &index) { return true } + while true { + guard jsonString(&index) else { return false } + index = skipWhitespace(from: index) + guard consume(":", &index), jsonValue(&index, depth: depth + 1) else { return false } + index = skipWhitespace(from: index) + if consume("}", &index) { return true } + guard consume(",", &index) else { return false } + index = skipWhitespace(from: index) + } + case 91: + index = skipWhitespace(from: index + 1) + if consume("]", &index) { return true } + while true { + guard jsonValue(&index, depth: depth + 1) else { return false } + index = skipWhitespace(from: index) + if consume("]", &index) { return true } + guard consume(",", &index) else { return false } + } + case 116: return consume("true", &index) + case 102: return consume("false", &index) + case 110: return consume("null", &index) + default: + let start = index + while index < bytes.count, Self.isNumberByte(bytes[index]) { index += 1 } + return index > start + } + } + + private func jsonString(_ index: inout Int) -> Bool { + guard index < bytes.count, bytes[index] == 34 else { return false } + index += 1 + while index < bytes.count { + let byte = bytes[index] + index += 1 + if byte < 32 { return false } + if byte == 34 { return true } + if byte == 92 { index += 1 } + } + return false + } + + private func containsThinkMarker(_ range: Range) -> Bool { + holdsAny(["", ""], in: range) + } + + private func holdsAny(_ tags: [String], in range: Range) -> Bool { + first(of: tags, in: range) != nil + } + + /// Where one of `tags` (each opening with `<`) first starts in `range`. + private func first(of tags: [String], in range: Range) -> Int? { + var index = range.lowerBound + while index < range.upperBound { + if bytes[index] == 60, tags.contains(where: { starts($0, at: index) }) { return index } + index += 1 + } + return nil + } + + private func consume(_ literal: String, _ index: inout Int) -> Bool { + guard starts(literal, at: index) else { return false } + index += literal.utf8.count + return true + } + + private func skipWhitespace(from start: Int) -> Int { + var index = start + while index < bytes.count, Self.isWhitespaceByte(bytes[index]) { index += 1 } + return index + } + + private func find(_ literal: String, from start: Int) -> Int? { + let marker = Array(literal.utf8) + var index = start + while index + marker.count <= bytes.count { + if bytes[index] == marker[0], starts(literal, at: index) { return index } + index += 1 + } + return nil + } + + private func starts(_ literal: String, at index: Int) -> Bool { + let marker = literal.utf8 + return index + marker.count <= bytes.count && bytes[index ..< index + marker.count].elementsEqual(marker) + } + + /// The SDK's function-name rule: 1-64 ASCII letters, digits, `-`, `_`. + private static func isFunctionName(_ name: String) -> Bool { + (1 ... 64).contains(name.utf8.count) && name.utf8.allSatisfy { + (48 ... 57).contains($0) || (65 ... 90).contains($0) || (97 ... 122).contains($0) || $0 == 45 || $0 == 95 + } + } + + private static func hasIndirectType(_ schema: [String: any Sendable]) -> Bool { + ["$ref", "$dynamicRef", "anyOf", "oneOf", "allOf", "not", "if", "then", "else"].contains { schema[$0] != nil } + } + + static func isWhitespace(_ bytes: ArraySlice) -> Bool { + bytes.allSatisfy(isWhitespaceByte) + } + + private static func isWhitespaceByte(_ byte: UInt8) -> Bool { + byte == 9 || byte == 10 || byte == 13 || byte == 32 + } + + /// The bytes the SDK's JSON number reader takes: digits, `+ - . E e`. + private static func isNumberByte(_ byte: UInt8) -> Bool { + (48 ... 57).contains(byte) || byte == 43 || byte == 45 || byte == 46 || byte == 69 || byte == 101 + } + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift index 6d6382d476..341a2a6d8d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift @@ -17,12 +17,24 @@ struct NativeToolStreamRouter { private var rejectedNativeGemmaReasoning = false private let withholdReasoning: Bool private var withheldReasoning = "" + private let tools: [[String: any Sendable]]? + /// An `auto` GLM tool suffix that does not parse at EOS is text + /// (`GLM5ToolSuffix`). + private let glmUnparsedOutputIsText: Bool + /// The request's tool choice is `auto`: the only mode whose residual text + /// the caller publishes. + private let autoToolChoice: Bool + /// `finishCompleteCalls` has released the EOS suffix that way, which + /// answers its parse failure. + private var glmSuffixSplit = false /// Validation contract for calls exposed while generated; nil keeps the /// complete-call path (calls flushed at the engine terminal). private let streamedCallPolicy: ToolChoicePromptPolicy.Prepared? private var exposedCallCount = 0 private var openCallIndex: Int? private var openCallName: String? + /// `parallel_tool_calls: false`: the frames of calls after the first. + private var laterCalls = ParallelToolCallPolicy.LaterCallFilter() /// Every call exposed so far whose frame parsed, each already accepted by /// `ToolConstraintValidation` (which returns `auto` calls as generated /// unless the request is `strict`). @@ -36,15 +48,20 @@ struct NativeToolStreamRouter { nativeGemmaReasoningEnabled: Bool = true, nativeMiMoChannels: Bool = false, nativeMiMoThinkingEnabled: Bool = true, nativeMiMoRequiresConstraint: Bool = false, absorbStrayThinkClose: Bool = false, withholdReasoning: Bool = false, - streamedCalls: ToolChoicePromptPolicy.Prepared? = nil) { + streamedCalls: ToolChoicePromptPolicy.Prepared? = nil, + glmUnparsedOutputIsText: Bool = GLM5ToolSuffix.returnsUnparsedOutputAsTextByDefault) { self.handler = handler self.withholdReasoning = withholdReasoning + self.tools = tools + self.glmUnparsedOutputIsText = glmUnparsedOutputIsText self.requiresToolCall = requiresToolCall self.nativeGemmaReasoningEnabled = nativeGemmaReasoningEnabled self.nativeMiMoChannels = nativeMiMoChannels self.nativeMiMoRequiresConstraint = nativeMiMoRequiresConstraint self.rejectMiMoThought = nativeMiMoChannels && !nativeMiMoThinkingEnabled self.streamedCallPolicy = handler?.streamsCalls == true ? streamedCalls : nil + // The scheduler passes the prepared choice here on every path. + self.autoToolChoice = streamedCalls.map { $0.mode == .auto } ?? !requiresToolCall if nativeGemmaChannels { gemmaParser = DiffusionGemmaChannelSplitter() } else if let nativePrefix { @@ -136,10 +153,14 @@ struct NativeToolStreamRouter { } /// Also called after the SDK EOS flush, before residual text or any call - /// is published. GLM validates the entire retained suffix only at EOS. + /// is published. GLM validates the entire retained suffix only at EOS; on + /// an `auto` request a suffix that does not parse there is text + /// (`finishCompleteCalls`), not a failure. A suffix the SDK rejects as + /// oversized while streaming still fails. func checkNativeToolFailure() throws { guard nativeMiMoChannels || handler?.format == .glm5 || handler?.format == .flint, (handler?.parseFailureCount ?? 0) > 0 else { return } + if glmSuffixSplit { return } let model = handler?.format == .glm5 ? "GLM" : handler?.format == .flint ? "Flint" : "MiMo" let message = "native \(model) tool output is invalid" if requiresToolCall || nativeMiMoRequiresConstraint { @@ -148,6 +169,30 @@ struct NativeToolStreamRouter { throw MultiModelBatchSchedulerEngineError.generationFailed(message) } + /// End of generation on the complete-call path: the handler's calls and + /// its residual text. An `auto` GLM suffix that did not parse as one batch + /// is split into text and its final calls (`GLM5ToolSuffix`; such a suffix + /// in an output the token limit cut off is all text, while one that parses + /// keeps its calls). A suffix whose release would expose a think marker + /// from inside a tool frame keeps failing, as before. + mutating func finishCompleteCalls(truncated: Bool) throws -> (calls: [ToolCall], residual: String?) { + guard let handler else { return ([], nil) } + let calls = handler.finish() + let residual = handler.takeResidualText() + guard returnsUnparsedGLMOutputAsText, calls.isEmpty, let residual else { return (calls, residual) } + switch GLM5ToolSuffix.split(residual, tools: tools, truncated: truncated) { + case .text(let text, calls: let found): + glmSuffixSplit = true + return (found, text) + case .ambiguous: + throw MultiModelBatchSchedulerEngineError.generationFailed("native GLM tool output is invalid") + } + } + + private var returnsUnparsedGLMOutputAsText: Bool { + handler?.format == .glm5 && glmUnparsedOutputIsText && autoToolChoice + } + private mutating func route(_ pieces: [ParsedReasoning]) throws -> [MLXServerGenerationEvent] { var events: [MLXServerGenerationEvent] = [] for piece in pieces { @@ -204,6 +249,7 @@ struct NativeToolStreamRouter { private mutating func routeToolSegment( _ segment: ToolCallStreamSegment, prepared: ToolChoicePromptPolicy.Prepared, truncated: Bool = false ) throws -> [MLXServerGenerationEvent] { + if laterCalls.drops(segment, exposedCalls: exposedCallCount, prepared: prepared) { return [] } switch segment { case .text(let text): return text.isEmpty ? [] : [visibleEvent(text)] diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NemotronSuperLocalOutput.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NemotronSuperLocalOutput.swift index c06d614e42..17f8842cbf 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NemotronSuperLocalOutput.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NemotronSuperLocalOutput.swift @@ -79,7 +79,7 @@ struct NemotronSuperLocalOutput { reasoning = split.reasoning ?? "" _ = try route([.init(content: split.content ?? "", reasoningContent: nil)]) } - let calls = handler?.finish() ?? [] + let calls = ParallelToolCallPolicy.admitted(handler?.finish() ?? [], prepared: plan.toolPolicy) let residual = handler?.takeResidualText() ?? "" let forced = plan.toolPolicy.requiresToolCall // route refuses mid-stream parse failures, so any failure here is the diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/ParallelToolCallPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/ParallelToolCallPolicy.swift new file mode 100644 index 0000000000..6e81e9b4fe --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/ParallelToolCallPolicy.swift @@ -0,0 +1,45 @@ +// Copyright © 2026 Eigen Labs. + +import MLXLMCommon + +/// `parallel_tool_calls: false`: a response carries one call, the first. OpenAI +/// returns at most one, and vLLM keeps the first +/// (`maybe_filter_parallel_tool_calls`). The calls a model makes after it are +/// dropped instead of failing a response that may already have streamed the +/// first; under automatic choice the prompt does not ask for one call (only a +/// GLM pair's does). A later frame that does not parse keeps its family's +/// malformed-output rule. `ToolConstraintValidation.validate` keeps its +/// cardinality check as defense in depth. +enum ParallelToolCallPolicy { + /// The calls a response returns from those withheld until the end. + static func admitted(_ calls: [ToolCall], prepared: ToolChoicePromptPolicy.Prepared) -> [ToolCall] { + prepared.allowsParallelCalls ? calls : Array(calls.prefix(1)) + } + + /// Drops the streamed segments of every call after the first: a dropped + /// frame is consumed, never exposed or validated. + struct LaterCallFilter { + private var droppingFrame = false + + /// `exposedCalls`: calls of this response already exposed. + mutating func drops( + _ segment: ToolCallStreamSegment, exposedCalls: Int, prepared: ToolChoicePromptPolicy.Prepared + ) -> Bool { + guard !prepared.allowsParallelCalls else { return false } + switch segment { + case .text: + return false + case .callStarted: + droppingFrame = exposedCalls > 0 + return droppingFrame + case .callArguments: + return droppingFrame + case .callCompleted, .callFailed: + defer { droppingFrame = false } + return droppingFrame + case .call: + return exposedCalls > 0 + } + } + } +} diff --git a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift index 72f7edd7ff..2fa9681852 100644 --- a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift +++ b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift @@ -421,6 +421,10 @@ public enum LaunchAgent: Sendable { /// `DARKBLOOM_LOOP_GUARD` / `DARKBLOOM_LOOP_EXIT_THINKING`: the loop guard /// and its exit from a repeating Gemma 4 thought are on by default; `0` /// turns each off, a list of `model_type`s replaces its default list. + /// `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY`: Qwen3.5-9B keeps the card's + /// presence penalty by default; its `0` rollback must reach the job. + /// `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK`: unparsed `auto` GLM tool output is + /// text by default; exact `0` restores the 500. static let inferencePassthroughEnvKeys = [ EngineV2Factory.maxPartialPrefillsKey, EngineV2Factory.prefillChunkKey, @@ -453,6 +457,8 @@ public enum LaunchAgent: Sendable { "DARKBLOOM_GEMMA4_NAX_ROW_MAP", GenerationLoopGuardPolicy.environmentKey, GenerationLoopExitThinkingPolicy.environmentKey, + EngineV2SamplingDefaults.qwen35NineBPenaltyEnvironmentKey, + GLM5ToolSuffix.environmentKey, ] + MiMoV26DecodeDefaults.environmentKeys + MiMoV26DecodeDefaults.verifyEnvironmentKeys static let passthroughEnvKeys = [ diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift index 4d4e8836fc..d5067ffc8f 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2SamplingDefaultsTests.swift @@ -83,18 +83,18 @@ struct EngineV2SamplingDefaultsTests { } /// The catalog Qwen 3.5/3.6 builds have no generation_config.json: omitted - /// knobs take the model cards' thinking-mode values, explicit ones win. + /// knobs take the model cards' thinking-mode values, the presence penalty + /// 1.5 included, on every build; explicit ones win. @Test func qwen35CatalogBuildsUseTheirModelCardDefaults() throws { for (id, type) in EngineV2SamplingDefaults.qwen35CardModelTypes { - #expect(EngineV2SamplingDefaults.resolve(modelId: id, modelType: type, modelDirectory: nil) - == (id == "Qwen3.5-9B" ? EngineV2SamplingDefaults(temperature: 1.0, topP: 0.95, topK: 20) - : EngineV2SamplingDefaults.qwen35CardDefaults)) + #expect(EngineV2SamplingDefaults.resolve(modelId: id, modelType: type, modelDirectory: nil, environment: [:]) + == EngineV2SamplingDefaults(temperature: 1.0, topP: 0.95, topK: 20, presencePenalty: 1.5), "\(id)") } let defaults = EngineV2SamplingDefaults.resolve( - modelId: "Qwen3.5-9B", modelType: "qwen3_5", modelDirectory: nil) + modelId: "Qwen3.5-9B", modelType: "qwen3_5", modelDirectory: nil, environment: [:]) let omitted = EngineV2Translation.samplingParams(from: try request(bareRequest), defaults: defaults) #expect(omitted.temperature == 1 && omitted.topP == 0.95 && omitted.topK == 20) - #expect(omitted.presencePenalty == 0 && omitted.repetitionPenalty == 1) + #expect(omitted.presencePenalty == 1.5 && omitted.repetitionPenalty == 1) let explicit = EngineV2Translation.samplingParams( from: try request(#"{"model":"m","messages":[],"temperature":0,"presence_penalty":0}"#), defaults: defaults) @@ -104,31 +104,35 @@ struct EngineV2SamplingDefaultsTests { } } - /// The 0.10.12 gate on the signed 0.10.11 (temperature 1, top_p 0.95, - /// top_k 20) decided each build's omitted presence penalty. Without the - /// cards' 1.5, qwen3.5-35b-a3b looped under both MTP acceptance rules, so - /// the two 35B builds (one architecture) keep it. Qwen3.5-9B looped only - /// under typical acceptance and not under exact (13 against 0 of 31 draws - /// with MTP running), so it has no default penalty (its rows can speculate - /// and stage prefix checkpoints) and takes exact acceptance - /// (MTPAcceptancePolicy). The coordinator's body adds the registry's - /// temperature, top_p and top_k, and no penalty unless the registry sets - /// one. A request's own presence_penalty wins on every build. - @Test func qwen35OmittedPresencePenaltyFollowsEachBuildsGate() throws { + /// Every catalog Qwen 3.5/3.6 build keeps the cards' 1.5 for a request + /// that omits the penalty. Without it qwen3.5-35b-a3b looped under both MTP + /// acceptance rules in the 0.10.12 gate. Qwen3.5-9B passed that gate under + /// exact acceptance (0 of 31 draws), so 0.10.12 dropped its penalty. In + /// production, against 0.10.11 Macs over the same period, its answers with + /// `max_tokens` ≥ 8,192 then ran to the limit about three times as often + /// (5.5 % against 1.7 %), and its constrained JSON `response_format` rows, + /// which never speculate, ran out and failed about twice as often (51 % + /// against 23 % in the same 10-minute windows). The penalty is the + /// difference we can establish: with nothing else running those rows + /// failed 32.7 % against 13.6 % (9B-MIDFAIL). The coordinator's body adds + /// the registry's temperature, top_p and top_k, and the penalty only where + /// the registry sets one. A request's own presence_penalty wins on every + /// build. + @Test func qwen35OmittedPresencePenaltyIsTheCardsOnEveryBuild() throws { let coordinatorBody = #"{"model":"m","messages":[{"role":"user","content":"hi"}],"temperature":1,"top_p":0.95,"top_k":20}"# - let builds: [(id: String, type: String, penalty: Float)] = [ - ("Qwen3.5-9B", "qwen3_5", 0), - ("qwen3.5-35b-a3b", "qwen3_5_moe", 1.5), - ("qwen3.6-35b-a3b-vl-mtp-mxfp8", "qwen3_5_moe", 1.5), + let builds: [(id: String, type: String)] = [ + ("Qwen3.5-9B", "qwen3_5"), + ("qwen3.5-35b-a3b", "qwen3_5_moe"), + ("qwen3.6-35b-a3b-vl-mtp-mxfp8", "qwen3_5_moe"), ] for build in builds { let defaults = EngineV2SamplingDefaults.resolve( - modelId: build.id, modelType: build.type, modelDirectory: nil) + modelId: build.id, modelType: build.type, modelDirectory: nil, environment: [:]) for body in [bareRequest, coordinatorBody] { let sampling = EngineV2Translation.samplingParams(from: try request(body), defaults: defaults) #expect(sampling.temperature == 1 && sampling.topP == 0.95 && sampling.topK == 20, "\(build.id)") - #expect(sampling.presencePenalty == build.penalty, "\(build.id): \(body)") + #expect(sampling.presencePenalty == 1.5, "\(build.id): \(body)") #expect(sampling.frequencyPenalty == 0 && sampling.repetitionPenalty == 1, "\(build.id)") } for own in ["0", "1.5"] { @@ -140,6 +144,48 @@ struct EngineV2SamplingDefaultsTests { } } + /// `DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY=0` (or `off`, `false`, `no`) restores + /// 0.10.12's no-penalty default on Qwen3.5-9B alone; anything else keeps + /// the card's 1.5, and the 35B builds ignore it. A request's own value + /// still wins under the rollback. + @Test func qwen35NineBPresencePenaltyRollbackSwitch() throws { + let key = EngineV2SamplingDefaults.qwen35NineBPenaltyEnvironmentKey + #expect(key == "DARKBLOOM_QWEN35_9B_PRESENCE_PENALTY") + func nineB(_ environment: [String: String]) -> EngineV2SamplingDefaults { + EngineV2SamplingDefaults.resolve( + modelId: "Qwen3.5-9B", modelType: "qwen3_5", modelDirectory: nil, environment: environment) + } + let card = EngineV2SamplingDefaults(temperature: 1.0, topP: 0.95, topK: 20, presencePenalty: 1.5) + let noPenalty = EngineV2SamplingDefaults(temperature: 1.0, topP: 0.95, topK: 20) + for value in ["0", "off", "false", "no", " OFF\n", "False"] { + #expect(nineB([key: value]) == noPenalty, "\(value)") + } + for value in ["", "1", "on", "true", "1.5", "card", "yes"] { + #expect(nineB([key: value]) == card, "\(value)") + } + #expect(nineB([:]) == card) + let rolledBack = EngineV2Translation.samplingParams(from: try request(bareRequest), defaults: nineB([key: "0"])) + #expect(rolledBack.presencePenalty == 0 && rolledBack.temperature == 1) + let ownUnderRollback = EngineV2Translation.samplingParams( + from: try request(#"{"model":"m","messages":[],"presence_penalty":1.5}"#), defaults: nineB([key: "0"])) + #expect(ownUnderRollback.presencePenalty == 1.5) + for (id, type) in [("qwen3.5-35b-a3b", "qwen3_5_moe"), ("qwen3.6-35b-a3b-vl-mtp-mxfp8", "qwen3_5_moe")] { + #expect(EngineV2SamplingDefaults.resolve( + modelId: id, modelType: type, modelDirectory: nil, environment: [key: "0"]) == card, "\(id)") + } + // Other families never read it. + #expect(EngineV2SamplingDefaults.resolve( + modelId: "mlx-community/Qwen3.5-397B", modelType: "qwen3_5", modelDirectory: nil, + environment: [key: "on"]) == .legacy) + } + + /// `darkbloom start` passes the 9B penalty rollback switch to the launchd daemon. + @Test func qwen35NineBPenaltySwitchReachesTheDaemon() { + let key = EngineV2SamplingDefaults.qwen35NineBPenaltyEnvironmentKey + #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(key)) + #expect(LaunchAgent.passthroughEnvironment(from: [key: "0"])[key] == "0") + } + /// The exact locally qualified GLM artifact declares temperature 1.0 and /// top_p 0.95 without `do_sample`; other GLM IDs or types stay legacy. @Test func gateAdmitsOnlyTheQualifiedGLMArtifact() throws { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/PrefixCache/Qwen35CardDefaultDonationTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/PrefixCache/Qwen35CardDefaultDonationTests.swift index 4be370cd3e..e8edc8e3c1 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/PrefixCache/Qwen35CardDefaultDonationTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/PrefixCache/Qwen35CardDefaultDonationTests.swift @@ -9,10 +9,10 @@ import Testing @testable import ProviderCore /// A Qwen 3.5/3.6 request with the model card's presence penalty (1.5) cannot speculate: on -/// `qwen3.5-35b-a3b` that is the provider's default for a request that sends no sampling field -/// (`EngineV2SamplingDefaults.qwen35CardDefaults`); on `Qwen3.5-9B` the request sends it, since -/// the 9B's default may carry no penalty. On the production paged assembly, with the inline MTP -/// assistant and the encrypted complete-checkpoint store, such a request must still donate its +/// `qwen3.5-35b-a3b` and `Qwen3.5-9B` alike that is the provider's default for a request that +/// sends no sampling field (`EngineV2SamplingDefaults.qwen35CardDefaults`; 0.10.12 had none on +/// the 9B). On the production paged assembly, with the inline MTP assistant and the encrypted +/// complete-checkpoint store, such a request must still donate its /// prompt's checkpoints, answer exactly as it does with the cache off, and let the next /// identical request restore them and answer exactly as its cold run. Synthetic weights, no /// model load. @@ -182,7 +182,8 @@ struct Qwen35CardDefaultDonationTests { let bridge = EngineV2Bridge( engine: build.engine, modelId: self.build.rawValue, tokenizer: TokenizerHandle(tokenizer), eosTokenIds: [], samplingDefaults: EngineV2SamplingDefaults.resolve( - modelId: self.build.rawValue, modelType: self.build.modelType, modelDirectory: nil), + modelId: self.build.rawValue, modelType: self.build.modelType, modelDirectory: nil, + environment: [:]), maxConcurrentRequests: 1, prefillDeadlineMode: .off, fixedRequestBytes: build.fixedRequestBytes, ssdHybridCheckpointStore: store, kvBackendKind: .paged) @@ -212,7 +213,7 @@ struct Qwen35CardDefaultDonationTests { static func request(_ build: Build, _ extra: Extra) -> ChatCompletionRequest { ChatCompletionRequest( model: build.rawValue, messages: [ChatMessage(role: "user", content: "pre-tokenized")], - max_tokens: maxTokens, presence_penalty: build == .dense ? 1.5 : nil, + max_tokens: maxTokens, stop: extra == .stop ? .single("") : nil, seed: 77, logprobs: extra == .logprobs ? true : nil, top_logprobs: extra == .logprobs ? 5 : nil) @@ -275,11 +276,9 @@ struct Qwen35CardDefaultDonationTests { let defaults = await coldBridge.samplingDefaults #expect(defaults.temperature == 1 && defaults.topP == 0.95 && defaults.topK == 20, "the card's sampling defaults apply") - if build == .moe { - #expect(defaults == EngineV2SamplingDefaults.qwen35CardDefaults, - "the 35B build keeps the card's presence penalty by default") - #expect(defaults.presencePenalty == 1.5) - } + #expect(defaults == EngineV2SamplingDefaults.qwen35CardDefaults, + "every catalog build keeps the card's presence penalty by default") + #expect(defaults.presencePenalty == 1.5) let cold = try await Self.serve(coldBridge, request, id: "cold") #expect(cold.finish == "length") #expect(cold.hit == 0) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift index f231b7b081..9f62dae47c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GLM5ToolFailureTests.swift @@ -9,25 +9,510 @@ import Testing struct GLM5ToolFailureTests { private let valid = "echotextSAFE" + /// A malformed suffix commits no call. A required call fails (422); an + /// `auto` response returns the suffix as text instead of failing. @Test(arguments: [false, true], [1, 7, 4096]) func malformedSuffixNeverCommitsEarlierCall(forced: Bool, width: Int) async throws { - try await check(output: valid + "PRIVATE_STRAY", forced: forced, width: width, invalid: true) + let output = valid + "PRIVATE_STRAY" + let result = try await run(output, forced: forced, width: width) + expectUnparsed(result, output: output, forced: forced) } @Test(arguments: [false, true]) func truncatedSecondCallNeverCommitsEarlierCall(forced: Bool) async throws { - try await check(output: valid + "echotext", forced: forced, width: 1, invalid: true) + let output = valid + "echotext" + let result = try await run(output, forced: forced, width: 1) + expectUnparsed(result, output: output, forced: forced) } @Test(arguments: [false, true]) func validCallSurvives(forced: Bool) async throws { - try await check(output: valid, forced: forced, width: 1, invalid: false) + let result = try await run(valid, forced: forced, width: 1) + #expect(result.failure == nil) + #expect(result.calls.map(\.function.name) == ["echo"]) + #expect(result.visible.isEmpty) } + /// The SDK refuses an oversized suffix while it streams, before EOS: that + /// still fails the response, `auto` included, before any of it is released. @Test(arguments: [false, true]) func oversizedFrameFailsBeforeFallback(forced: Bool) async throws { - try await check(output: "echo" + String(repeating: "x", count: (1 << 20) + 1), - forced: forced, width: 65536, invalid: true) + let output = "echo" + String(repeating: "x", count: (1 << 20) + 1) + let result = try await run(output, forced: forced, width: 65536) + #expect(result.calls.isEmpty && result.visible.isEmpty) + #expect(result.failure == (forced ? .toolChoiceViolation("native GLM tool output is invalid") + : .generationFailed("native GLM tool output is invalid"))) + } + + /// An oversized suffix never bypasses the EOS checks: a think marker inside + /// a drafted call is not released, whether the suffix arrives in pieces or + /// in one delivery. + @Test(arguments: [65536, 1 << 22]) + func oversizedSuffixIsNeverReleased(width: Int) async throws { + let draft = "echotext" + let output = "Draft " + draft + "PRIVATEAnswer" + String(repeating: "x", count: 1 << 20) + let result = try await run(output, forced: false, width: width) + #expect(result.calls.isEmpty && !result.visible.contains("PRIVATE")) + #expect(result.failure == .generationFailed("native GLM tool output is invalid")) + } + + /// The model's raw output after the prompt's open `` (the legacy + /// text path: the tool parser also reads the reasoning), the calls an + /// `auto` response returns, and its visible text, which the service's + /// reasoning parser then splits at ``. Shapes from the + /// conformance replay: a tag mentioned or a call drafted in the thought, a + /// text answer that mentions the tag, clean calls. + static let strayCases: [(name: String, output: String, calls: [String], visible: String)] = { + let call = "echotextSAFE" + let other = "echotextMORE" + let draft = "echotextDRAFT" + return [ + ("call", "Need it." + call, ["SAFE"], "Need it."), + ("call drafted in the thought", "I'll do " + draft + " maybe." + call, ["SAFE"], + "I'll do " + draft + " maybe."), + ("tag mentioned in the thought", "Wrap it in tags." + call, ["SAFE"], + "Wrap it in tags."), + ("tag mentioned in the thought, text answer", + "The tool would need syntax, but I can answer.Zürich is cool.", [], + "The tool would need syntax, but I can answer.Zürich is cool."), + ("text answer mentions the tag", "Simple.To call a tool, GLM writes first.", [], + "Simple.To call a tool, GLM writes first."), + ("answer quotes a frame, then calls", + "Simple.The format is … . Calling: " + call, ["SAFE"], + "Simple.The format is … . Calling: "), + ("two calls", "Two." + call + "\n" + other, ["SAFE", "MORE"], "Two."), + ("call from an unclosed thought", "Need it." + call, ["SAFE"], "Need it."), + ("call drafted in the thought, no call", "I'd do " + draft + "", [], + "I'd do " + draft + ""), + ("tag mentioned before two calls", "Use ." + call + " " + other + "\n", + ["SAFE", "MORE"], "Use ."), + ] + }() + + @Test(arguments: GLM5ToolFailureTests.strayCases.indices, [1, 4096]) + func strayToolTagsAreTextAndTheFinalCallsParse(index: Int, width: Int) async throws { + let shape = Self.strayCases[index] + let result = try await run(shape.output, forced: false, width: width) + #expect(result.failure == nil, "\(shape.name)") + #expect(result.calls.count == shape.calls.count, "\(shape.name)") + #expect(result.calls.compactMap { $0.function.arguments["text"]?.anyValue as? String } == shape.calls, + "\(shape.name)") + #expect(result.visible == shape.visible, "\(shape.name)") + } + + /// A required call keeps failing closed when its suffix does not parse: the + /// parser's own refusal, or the visible-text check when text precedes it. + @Test(arguments: [#""required""#, #"{"type":"function","function":{"name":"echo"}}"#]) + func forcedChoiceStillRefusesAStraySuffix(choice: String) async throws { + let stray = try await run("." + valid, forced: true, width: 1, choice: choice) + #expect(stray.calls.isEmpty && stray.visible.isEmpty) + #expect(stray.failure == .toolChoiceViolation("native GLM tool output is invalid")) + let mentioned = try await run("Wrap it in tags." + valid, forced: true, width: 1, + choice: choice) + #expect(mentioned.calls.isEmpty && mentioned.visible.isEmpty) + let failure = try #require(mentioned.failure) + #expect(ProviderLoop.mapInferenceErrorToStatus(failure) == 422) + } + + static let storeTool = #"{"type":"function","function":{"name":"store","parameters":{"type":"object","properties":{"doc":{"type":"object"}},"required":["doc"]}}}"# + + /// The delimiters quoted inside a JSON argument are data: the calls start + /// at the real frame, not at a quoted tag. + @Test func quotedDelimitersStayArgumentData() async throws { + let tool = Self.storeTool + let output = "See here.storedoc" + + #"{"x":"store"}"# + let result = try await run(output, forced: false, width: 3, tool: tool) + #expect(result.failure == nil) + #expect(result.calls.count == 1) + #expect(result.calls.first?.function.arguments["doc"] == .object(["x": .string("store")])) + #expect(result.visible == "See here.") + } + + /// An undeclared or malformed final call is not salvaged: the response is + /// text, as are its earlier calls. + @Test func malformedFinalCallIsText() async throws { + let output = "Use ." + valid + + "nopetexta" + let result = try await run(output, forced: false, width: 5) + #expect(result.failure == nil) + #expect(result.calls.isEmpty) + #expect(result.visible == output) + } + + /// Calls are never split out of a suffix that did not parse in an output + /// the token limit cut off; a suffix that parses keeps its calls, as before. + @Test func truncatedOutputIsNotSplit() async throws { + let output = "Wrap it in tags." + valid + let result = try await run(output, forced: false, width: 4, finishReason: "length") + #expect(result.failure == nil) + #expect(result.calls.isEmpty) + #expect(result.visible == output) + let clean = try await run("Need it." + valid, forced: false, width: 4, finishReason: "length") + #expect(clean.failure == nil && clean.calls.count == 1 && clean.visible == "Need it.") + } + + /// A frame that has started its arguments owns everything up to its own + /// ``: a frame inside an argument, or after one, is data and + /// never becomes a call, whether the outer frame is cut off or closed. + @Test(arguments: [nil, "length"], [1, 7, 4096]) + func framesInsideAFrameAreNeverCalls(finishReason: String?, width: Int) async throws { + let nested = "storedoc{}" + let cases: [(output: String, tool: String?)] = [ + ("storedoc{\"x\":\"" + nested, Self.storeTool), + ("echotextdraft " + valid, nil), + ("Use .echotextajunk" + valid, nil), + ] + for shape in cases { + let result = try await run(shape.output, forced: false, width: width, finishReason: finishReason, + tool: shape.tool) + #expect(result.failure == nil && result.calls.isEmpty, "\(shape.output)") + #expect(result.visible == shape.output, "\(shape.output)") + } + } + + /// Arguments that break the SDK's grammar end the lexer's reading of + /// frames: a frame after them (here quoted in a JSON string the malformed + /// value opened) stays data and never becomes a call, whether the output + /// stops or is cut off. So does one after a name followed by anything but + /// `` or `` that belongs to a frame. + @Test(arguments: ["stop", "length"], [1, 7, 4096]) + func framesAfterMalformedArgumentsAreNeverCalls(finishReason: String, width: Int) async throws { + let inner = "storedoc{}" + let open = "storedoc" + let outputs = [ + open + #"{"x": ],"y":""# + "" + inner, + open + #"{"x": ,"y":""# + "" + inner, + open + #"{"x": 1 "y":""# + "" + inner, + "store" + inner, + "store" + inner, + "store" + inner, + ] + for output in outputs { + let result = try await run(output, forced: false, width: width, finishReason: finishReason, + tool: Self.storeTool) + #expect(result.failure == nil && result.calls.isEmpty, "\(output)") + #expect(result.visible == output, "\(output)") + } + } + + /// Released text would hand a think marker from inside a drafted call to + /// the service's reasoning parser as a channel boundary: that response keeps + /// failing, as before. + @Test func thinkMarkerInsideAReleasedFrameStillFails() async throws { + let draft = "Draft echotext" + for output in [draft + "PRIVATEAnswer", draft + " more." + valid] { + let result = try await run(output, forced: false, width: 5) + #expect(result.calls.isEmpty && result.visible == "Draft ") + #expect(result.failure == .generationFailed("native GLM tool output is invalid")) + } + } + + /// The same holds for a think marker in a key, after a frame whose + /// arguments break the grammar (which owns the rest of the response), and + /// in an output cut off at the token limit, whose whole suffix would be + /// released. + @Test(arguments: [1, 5, 4096]) + func thinkMarkerAnywhereInAReleasedFrameStillFails(width: Int) async throws { + let cases: [(output: String, finishReason: String, tool: String?)] = [ + ("Draft echo0PRIVATEAnswer", + "stop", nil), + ("Draft storedoc{bad}PRIVATEAnswer", + "stop", Self.storeTool), + ("Draft . echotextPRIVATE", + "length", nil), + ("Draft echotextPRIVATEAnswer", + "stop", nil), + ("Draft echotextPRIVATEAnswer", + "length", nil), + ] + for shape in cases { + let result = try await run(shape.output, forced: false, width: width, finishReason: shape.finishReason, + tool: shape.tool) + #expect(result.calls.isEmpty && result.visible == "Draft ", "\(shape.output)") + #expect(result.failure == .generationFailed("native GLM tool output is invalid"), "\(shape.output)") + } + } + + /// `store` with a declared object key `é` (U+00E9) and string-typed + /// additional properties. + static let accentTool = #"{"type":"function","function":{"name":"store","parameters":{"type":"object","properties":{"\u00e9":{"type":"object"}},"additionalProperties":{"type":"string"}}}}"# + + /// A frame never borrows a later frame's closing tags: a raw value holding + /// the SDK's frame tags (which the SDK refuses), a malformed header that + /// leads into arguments, and a key the SDK refuses because it only + /// canonically equals a declared one each make the frame own the rest, so + /// no frame after it is a call, at a stop or the token limit. + @Test(arguments: ["stop", "length"], [1, 7, 4096]) + func framesNeverBorrowALaterFramesClose(finishReason: String, width: Int) async throws { + let echo = { (text: String) in "echotext\(text)" } + let inner = "storedoc{}" + let cases: [(output: String, tool: String?)] = [ + ("echotextdraft " + echo("ONE") + echo("TWO"), nil), + ("storedoc{\"x\":\"" + inner, Self.storeTool), + ("storee\u{301}{\"x\":\"store", + Self.accentTool), + ] + for shape in cases { + let result = try await run(shape.output, forced: false, width: width, finishReason: finishReason, + tool: shape.tool) + #expect(result.failure == nil && result.calls.isEmpty, "\(shape.output)") + #expect(result.visible == shape.output, "\(shape.output)") + } + } + + /// A frame the SDK refuses keeps its boundary only when no reading could + /// move it: a `"` in it may open a JSON string that runs past its + /// `` (a raw guess for a schema the SDK refuses), or a raw + /// string a JSON reading runs past (swallowing the next frame's opening). + /// Such a frame owns the rest. And a frame's tags in top-level text, here + /// after a closed frame that follows a malformed header, own the rest too. + /// No call either way, at a stop or the token limit. + @Test(arguments: ["stop", "length"], [1, 7, 4096]) + func refusedFramesWithAMovableBoundaryOwnTheRest(finishReason: String, width: Int) async throws { + let refusedObject = #"{"type":"function","function":{"name":"f","parameters":{"type":"object","properties":{"x":{"type":"object","anyOf":[{"type":"object"}]}}}}}"# + let arrayTools = #"[{"type":"function","function":{"name":"put","parameters":{"type":"object","properties":{"m":{"type":"array"}}}}},{"type":"function","function":{"name":"g","parameters":{"type":"object","properties":{}}}},{"type":"function","function":{"name":"h","parameters":{"type":"object","properties":{"z":{"type":"string"}}}}}]"# + let headerTools = #"[{"type":"function","function":{"name":"store","parameters":{"type":"object","properties":{"doc":{"type":"object"}}}}},{"type":"function","function":{"name":"x"}},{"type":"function","function":{"name":"g","parameters":{"type":"object","properties":{}}}}]"# + let cases: [(output: String, tool: String)] = [ + (#"fx]{"y":"f"#, + refusedObject), + (#"gx]{"y":"f"#, + refusedObject), + (#"putm"xputm["ghz"]"#, + arrayTools), + (#"storexdoc{"x":"g"#, + headerTools), + ] + for shape in cases { + let result = try await run(shape.output, forced: false, width: width, finishReason: finishReason, + tool: shape.tool) + #expect(result.failure == nil && result.calls.isEmpty, "\(shape.output)") + #expect(result.visible == shape.output, "\(shape.output)") + } + } + + /// Their think markers are then inside a frame: released text holding one + /// still fails, at a stop or the token limit. + @Test(arguments: ["stop", "length"], [1, 5, 4096]) + func thinkMarkersAfterAMovableBoundaryStillFail(finishReason: String, width: Int) async throws { + let refusedObject = #"{"type":"function","function":{"name":"f","parameters":{"type":"object","properties":{"x":{"type":"object","anyOf":[{"type":"object"}]}}}}}"# + let headerTools = #"[{"type":"function","function":{"name":"echo","parameters":{"type":"object","properties":{"text":{"type":"string"}}}}},{"type":"function","function":{"name":"x"}}]"# + let cases: [(output: String, tool: String)] = [ + (#"fx]{"y":"PRIVATEAnswer"#, + refusedObject), + ("echoxtextPRIVATEAnswer", + headerTools), + ] + for shape in cases { + let result = try await run(shape.output, forced: false, width: width, finishReason: finishReason, + tool: shape.tool) + #expect(result.calls.isEmpty && result.visible.isEmpty, "\(shape.output)") + #expect(result.failure == .generationFailed("native GLM tool output is invalid"), "\(shape.output)") + } + } + + /// A frame's tag in top-level text also takes back the malformed header + /// read as a mention before it: a think marker in that header's region, + /// either way, still fails. + @Test(arguments: ["stop", "length"], [1, 5, 4096]) + func orphanTagsTakeBackAnEarlierMention(finishReason: String, width: Int) async throws { + let headerTools = #"[{"type":"function","function":{"name":"echo","parameters":{"type":"object","properties":{"text":{"type":"string"}}}}},{"type":"function","function":{"name":"x"}}]"# + let orphan = "xtextv" + for (output, visible) in [ + ("echoPRIVATE" + orphan, ""), + ("Done.echoPRIVATE" + orphan, "Done."), + ] { + let result = try await run(output, forced: false, width: width, finishReason: finishReason, + tool: headerTools) + #expect(result.calls.isEmpty && result.visible == visible, "\(output)") + #expect(result.failure == .generationFailed("native GLM tool output is invalid"), "\(output)") + } + } + + /// And a closed frame before it: its value may run on, unescaped, through + /// the orphan tags (the template writes strings raw), so a think marker + /// between them, either way, still fails. + @Test(arguments: ["stop", "length"], [1, 5, 4096]) + func orphanTagsTakeBackAnEarlierFrame(finishReason: String, width: Int) async throws { + let echo = "echotextx" + for (output, visible) in [ + (echo + "PRIVATE", ""), + ("Done." + echo + "HIDDEN", "Done."), + ] { + let result = try await run(output, forced: false, width: width, finishReason: finishReason) + #expect(result.calls.isEmpty && result.visible == visible, "\(output)") + #expect(result.failure == .generationFailed("native GLM tool output is invalid"), "\(output)") + } + } + + /// A trailing run with a member the SDK refuses is not a batch to take + /// part of: no member of it runs, as the SDK's own batch rule says (an + /// undeclared name, a missing required argument). + @Test(arguments: [1, 7, 4096]) + func aRefusedMemberCancelsTheWholeRun(width: Int) async throws { + let london = "echotextLondon" + for output in [ + "Checking.echtextParis\n" + london, + "Checking.echo\n" + london, + ] { + let result = try await run(output, forced: false, width: width, finishReason: "stop") + #expect(result.failure == nil && result.calls.isEmpty, "\(output)") + #expect(result.visible == output, "\(output)") + } + } + + /// Declared keys (byte for byte) and additional properties keep their + /// types after a mention: the final call parses. + @Test func declaredAndAdditionalKeysStillParse() async throws { + for (frame, key, value) in [ + ("store\u{e9}{}", "\u{e9}", + JSONValue.object([:])), + ("storenoteplain {text}", "note", + JSONValue.string("plain {text}")), + ] { + let result = try await run("Use ." + frame, forced: false, width: 3, finishReason: "stop", + tool: Self.accentTool) + #expect(result.failure == nil && result.visible == "Use .", "\(frame)") + #expect(result.calls.map { $0.function.arguments } == [[key: value]], "\(frame)") + } + } + + /// A think marker inside the final call's own argument is that call's + /// data: the call parses and nothing of it is released. + @Test func thinkMarkerInsideTheFinalCallStaysItsArgument() async throws { + let call = "echotextstrip tags" + let result = try await run("Use ." + call, forced: false, width: 3, finishReason: "stop") + #expect(result.failure == nil) + #expect(result.calls.compactMap { $0.function.arguments["text"]?.anyValue as? String } == ["strip tags"]) + #expect(result.visible == "Use .") + } + + /// Finding the calls is linear in the suffix: many mentions before them. + @Test func manyMentionsBeforeTheCalls() async throws { + let mentions = String(repeating: " ", count: 20_000) + let result = try await run(mentions + valid, forced: false, width: 65536) + #expect(result.failure == nil && result.calls.count == 1 && result.visible == mentions) + } + + /// And many adjacent frames after a mention: the run that ends the + /// response is collected in one pass. + @Test func manyFramesAfterAMention() throws { + let tools: [[String: any Sendable]] = [["type": "function", "function": ["name": "a"] as [String: any Sendable]]] + let suffix = "." + String(repeating: "a", count: 40_000) + let split = GLM5ToolSuffix.split(suffix, tools: tools) + guard case .text(let text, let calls) = split else { + Issue.record("expected text and calls, got \(split)") + return + } + #expect(text == "." && calls.count == 40_000) + #expect(calls.allSatisfy { $0.function.name == "a" && $0.function.arguments.isEmpty }) + } + + /// And many additional properties against a large declared schema: each + /// key's type is one lookup. + @Test func manyAdditionalKeysAgainstALargeSchema() throws { + var properties: [String: any Sendable] = [:] + for index in 0 ..< 5_000 { properties["p\(index)"] = ["type": "string"] as [String: any Sendable] } + let parameters: [String: any Sendable] = ["type": "object", "properties": properties, + "additionalProperties": ["type": "string"] as [String: any Sendable]] + let tools: [[String: any Sendable]] = [["type": "function", + "function": ["name": "f", "parameters": parameters] as [String: any Sendable]]] + let arguments = (0 ..< 5_000).map { "x\($0)v" }.joined() + let split = GLM5ToolSuffix.split(".f" + arguments + "", tools: tools) + guard case .text(let text, let calls) = split else { + Issue.record("expected text and calls, got \(split)") + return + } + #expect(text == "." && calls.count == 1 && calls.first?.function.arguments.count == 5_000) + } + + /// And many quote-free frames discarded before the end against many + /// tools: only frames whose boundary needs it, and the final run, are + /// checked by the SDK's parser. + @Test func manyDiscardedFramesAgainstManyTools() throws { + let tools: [[String: any Sendable]] = (0 ..< 500).map { + ["type": "function", "function": ["name": "f\($0)"] as [String: any Sendable]] + } + let suffix = "." + String(repeating: "f0.", count: 20_000) + #expect(GLM5ToolSuffix.split(suffix, tools: tools) == .text(suffix, calls: [])) + } + + /// And many discarded frames that the SDK must check (they hold a `"`) + /// against many tools: each check resolves the frame's one declaration. + @Test func manyQuotedDiscardedFramesAgainstManyTools() throws { + var tools: [[String: any Sendable]] = (1 ..< 500).map { + ["type": "function", "function": ["name": "f\($0)"] as [String: any Sendable]] + } + tools.insert(["type": "function", "function": ["name": "f0", "parameters": ["type": "object", + "properties": ["x": ["type": "string"] as [String: any Sendable]] as [String: any Sendable]] + as [String: any Sendable]] as [String: any Sendable]], at: 0) + let frame = #"f0x"."# + let suffix = "." + String(repeating: frame, count: 12_000) + #expect(GLM5ToolSuffix.split(suffix, tools: tools) == .text(suffix, calls: [])) + } + + /// And a long generated name with many arguments: the name is looked up + /// once per frame, not once per argument. + @Test func longNameWithManyArguments() throws { + let tools: [[String: any Sendable]] = [["type": "function", "function": ["name": "echo"] as [String: any Sendable]]] + let suffix = "" + String(repeating: "a", count: 200_000) + + String(repeating: "xv", count: 5_000) + "" + #expect(GLM5ToolSuffix.split(suffix, tools: tools) == .text(suffix, calls: [])) + } + + /// `DARKBLOOM_GLM_TOOL_TEXT_FALLBACK=0` restores the whole-suffix failure. + @Test func rollbackRestoresTheSuffixFailure() throws { + let request = try MiMoConsumerFixture.request(choice: #""auto""#) + let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "glm5_next") + for textFallback in [true, false] { + let handler = try #require(try ToolStreamPreparation.makeHandler( + request: request, prepared: prepared, modelType: "glm5_next")) + var router = NativeToolStreamRouter(handler: handler, requiresToolCall: false, nativePrefix: nil, + tools: prepared.tools?.map { $0.toolSpec() }, glmUnparsedOutputIsText: textFallback) + _ = try router.process("Wrap it in tags." + valid) + _ = try router.finishText() + let finished = try router.finishCompleteCalls(truncated: false) + if textFallback { + try router.checkNativeToolFailure() + #expect(finished.calls.count == 1) + #expect(finished.residual == " tags.") + } else { + #expect(finished.calls.isEmpty) + #expect(throws: MultiModelBatchSchedulerEngineError.generationFailed( + "native GLM tool output is invalid")) { try router.checkNativeToolFailure() } + } + } + #expect(GLM5ToolSuffix.environmentKey == "DARKBLOOM_GLM_TOOL_TEXT_FALLBACK") + #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(GLM5ToolSuffix.environmentKey)) + } + + /// Only an `auto` request returns an unparsed GLM suffix as text. With any + /// other prepared choice (here `none`, which the Flint response format + /// forces while a client-selected parser keeps its handler) no residual + /// is published, so the suffix still fails. + @Test func onlyAutoChoiceReturnsTheSuffixAsText() throws { + let auto = try MiMoConsumerFixture.request(choice: #""auto""#) + let autoPrepared = try ToolChoicePromptPolicy.prepare(auto, modelType: "glm5_next") + let nonePrepared = try ToolChoicePromptPolicy.prepare( + try MiMoConsumerFixture.request(choice: #""none""#), modelType: "glm5_next") + #expect(nonePrepared.mode == .none) + for (prepared, fallsBack) in [(autoPrepared, true), (nonePrepared, false)] { + let handler = try #require(try ToolStreamPreparation.makeHandler( + request: auto, prepared: autoPrepared, modelType: "glm5_next")) + var router = NativeToolStreamRouter(handler: handler, requiresToolCall: false, nativePrefix: nil, + tools: autoPrepared.tools?.map { $0.toolSpec() }, streamedCalls: prepared) + _ = try router.process("Wrap it in tags." + valid) + _ = try router.finishText() + let finished = try router.finishCompleteCalls(truncated: false) + if fallsBack { + try router.checkNativeToolFailure() + #expect(finished.calls.count == 1) + } else { + #expect(finished.calls.isEmpty) + #expect(throws: MultiModelBatchSchedulerEngineError.generationFailed( + "native GLM tool output is invalid")) { try router.checkNativeToolFailure() } + } + } } /// Forced choice is served by structured post-validation: the production @@ -49,8 +534,40 @@ struct GLM5ToolFailureTests { } } - private func check(output: String, forced: Bool, width: Int, invalid: Bool) async throws { - let request = try MiMoConsumerFixture.request(choice: forced ? #""required""# : #""auto""#) + private struct Outcome { + var calls: [ToolCall] = [] + var visible = "" + var failure: MultiModelBatchSchedulerEngineError? + } + + /// A required call fails closed (422); an `auto` response returns the + /// unparsed suffix as text, with no call and no failure. + private func expectUnparsed(_ result: Outcome, output: String, forced: Bool) { + #expect(result.calls.isEmpty) + if forced { + #expect(result.visible.isEmpty) + #expect(result.failure == .toolChoiceViolation("native GLM tool output is invalid")) + if let failure = result.failure { #expect(ProviderLoop.mapInferenceErrorToStatus(failure) == 422) } + } else { + #expect(result.failure == nil) + #expect(result.visible == output) + } + } + + /// The production event stream on the legacy text path (no native + /// channel), fed `width` characters at a time. `tool` is one tool or a + /// JSON array of tools. + private func run(_ output: String, forced: Bool, width: Int, finishReason: String? = nil, + tool: String? = nil, choice forcedChoice: String = #""required""#) async throws -> Outcome { + let choice = forced ? forcedChoice : #""auto""# + var request = try MiMoConsumerFixture.request(choice: choice) + if let tool { + var body = try #require(JSONSerialization.jsonObject(with: MiMoConsumerFixture.body( + choice: choice)) as? [String: Any]) + let tools = try JSONSerialization.jsonObject(with: Data(tool.utf8)) + body["tools"] = (tools as? [Any]) ?? [tools] + request = try ProviderLoop.decodeOpenAIRequest(JSONSerialization.data(withJSONObject: body)) + } let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "glm5_next") let handler = try #require(try ToolStreamPreparation.makeHandler( request: request, prepared: prepared, modelType: "glm5_next")) @@ -60,36 +577,27 @@ struct GLM5ToolFailureTests { for start in stride(from: 0, to: chars.count, by: width) { continuation.yield(.chunk(String(chars[start..Paris<|"|>"#) - var exposed: [ServerToolCallDelta] = [] - for character in Self.characters(first) { exposed += Self.deltas(try router.process(character)) } - #expect(exposed.last?.completed != nil) - var thrown: Error? - for character in Self.characters(first) { - do { _ = try router.process(character) } catch { thrown = error; break } + /// `parallel_tool_calls: false` returns the first call, as OpenAI and vLLM + /// do. The calls the model makes after it, valid or not, are consumed and + /// dropped; none fails the stream after the first call already left. + @Test func laterCallsAreDroppedWhenParallelCallsAreDisabled() throws { + for strict in [false, true] { + let request = try Self.request(parallel: false, strict: strict) + var router = try Self.router(request) + let text = Self.gemmaCall(#"location:<|"|>Paris<|"|>"#) + + Self.gemmaCall(#"location:<|"|>Rome<|"|>,days:3"#) + + Self.gemmaCall(#"path:<|"|>a.py<|"|>,content:<|"|>x<|"|>"#, name: "write_file") + // Off the schema: `strict` would refuse it if it were returned. + + Self.gemmaCall(#"location:<|"|>Oslo<|"|>,unit:<|"|>kelvin<|"|>"#) + var events: [MLXServerGenerationEvent] = [] + for character in Self.characters(text) { events += try router.process(character) } + events += try router.finishText() + events += try router.finishToolCalls(truncated: false) + let deltas = Self.deltas(events) + #expect(events.count == deltas.count, "strict \(strict): no visible text from a dropped frame") + #expect(deltas.allSatisfy { $0.index == 0 }, "strict \(strict)") + #expect(deltas.compactMap(\.name) == ["get_weather"], "strict \(strict)") + #expect(deltas.compactMap(\.completed).map(\.function.arguments) == [["location": .string("Paris")]], + "strict \(strict)") + #expect(router.completedToolCalls.map(\.function.arguments) == [["location": .string("Paris")]]) + try ToolConstraintValidation.validate(router.completedToolCalls, + prepared: ToolChoicePromptPolicy.prepare(request, modelType: "gemma4")) + } + } + + /// A later call that completes without being exposed (Harmony parses an + /// undeclared name, which `strict` refuses) is dropped too, before + /// validation could refuse it. + @Test func laterUnexposedCallIsDroppedUnvalidated() throws { + var router = try Self.router(Self.request(parallel: false, strict: true), modelType: "gpt_oss") + let text = "<|start|>assistant to=functions.get_weather<|channel|>commentary json" + + #"<|message|>{"location":"Paris"}<|call|>"# + + "<|start|>assistant to=functions.delete_everything<|channel|>commentary json" + + #"<|message|>{"path":"/"}<|call|>"# + var events: [MLXServerGenerationEvent] = [] + for character in Self.characters(text) { events += try router.process(character) } + events += try router.finishText() + events += try router.finishToolCalls(truncated: false) + #expect(Self.deltas(events).compactMap(\.completed).map(\.function.name) == ["get_weather"]) + #expect(router.completedToolCalls.map(\.function.name) == ["get_weather"]) + } + + /// The complete-call paths (native channel families, required/named, + /// surfaces that take calls in one piece, Nemotron Super's owner) keep + /// the first call the same way. + @Test func completeCallPathsKeepTheFirstCall() throws { + let first = ToolCall(function: .init(name: "get_weather", arguments: ["location": "Paris"])) + let second = ToolCall(function: .init(name: "get_weather", arguments: ["location": "Rome"])) + for choice in [nil, OpenAIToolChoice.mode(.required), .function(name: "get_weather")] { + let single = try ToolChoicePromptPolicy.prepare(Self.request(choice, parallel: false), modelType: "gemma4") + let admitted = ParallelToolCallPolicy.admitted([first, second], prepared: single) + #expect(admitted == [first]) + try ToolConstraintValidation.validate(admitted, prepared: single) + let parallel = try ToolChoicePromptPolicy.prepare(Self.request(choice), modelType: "gemma4") + #expect(ParallelToolCallPolicy.admitted([first, second], prepared: parallel) == [first, second]) + } + let none = try ToolChoicePromptPolicy.prepare(Self.request(parallel: false), modelType: "gemma4") + #expect(ParallelToolCallPolicy.admitted([], prepared: none).isEmpty) + } + + /// A later frame that fails is dropped as quietly as one that parses: one + /// that closes against what it streamed (a repeated key), one cut by the + /// end of generation (unterminated or diverged), and one whose end tag is + /// the stop token, at the token limit or not. + @Test(arguments: [ + #"<|tool_call>call:get_weather{location:<|"|>Rome<|"|>,location:<|"|>Oslo<|"|>}"#, + #"<|tool_call>call:write_file{path:<|"|>a.py<|"|>,content:<|"|>print("#, + #"<|tool_call>call:write_file{path:<|"|>a.py<|"|>,content:<|"|>def f(): return {"a": 1}"#, + #"<|tool_call>call:get_weather{location:<|"|>Rome<|"|>}"#, + ]) + func failedLaterFramesAreDroppedToo(later: String) throws { + for strict in [false, true] { + for truncated in [false, true] { + var router = try Self.router(Self.request(parallel: false, strict: strict)) + var events: [MLXServerGenerationEvent] = [] + for character in Self.characters(Self.gemmaCall(#"location:<|"|>Paris<|"|>"#) + later) { + events += try router.process(character) + } + events += try router.finishText() + events += try router.finishToolCalls(truncated: truncated) + let deltas = Self.deltas(events) + #expect(events.count == deltas.count, "strict \(strict) truncated \(truncated)") + #expect(deltas.allSatisfy { $0.index == 0 }, "strict \(strict) truncated \(truncated)") + #expect(deltas.compactMap(\.name) == ["get_weather"], "strict \(strict) truncated \(truncated)") + #expect(router.completedToolCalls.map(\.function.arguments) == [["location": .string("Paris")]], + "strict \(strict) truncated \(truncated)") + } + } + } + + /// The engine's complete-call terminal (here a forced choice, whose calls + /// are withheld until generation ends) returns the first call as well. + @Test func completeCallTerminalReturnsTheFirstCall() async throws { + let upstream = AsyncStream.makeStream() + let text = Self.gemmaCall(#"location:<|"|>Paris<|"|>"#) + Self.gemmaCall(#"location:<|"|>Rome<|"|>"#) + for chunk in Self.characters(text) { upstream.continuation.yield(.chunk(chunk)) } + upstream.continuation.yield(.info(promptTokens: 9, completionTokens: 30, tokensPerSecond: 0, + finishReason: nil)) + upstream.continuation.finish() + var frames: [String] = [] + for try await frame in try await MLXOpenAIService( + engine: RoutedEngine(upstream: upstream.stream, modelType: "gemma4") + ).streamChatCompletionFrames(request: try Self.request(.mode(.required), parallel: false)) { + frames.append(frame) } - #expect(thrown is MultiModelBatchSchedulerEngineError) + let parsed = frames.compactMap(ProviderLoop.parseStreamChunk) + let deltas = parsed.flatMap { $0.toolCallsDelta ?? [] } + #expect(deltas.allSatisfy { $0.index == 0 }) + #expect(deltas.compactMap { $0.function?.name } == ["get_weather"]) + let arguments = deltas.compactMap { $0.function?.arguments }.joined() + #expect(try JSONDecoder().decode([String: MLXLMCommon.JSONValue].self, from: Data(arguments.utf8)) + == ["location": .string("Paris")]) + #expect(parsed.contains { $0.finishReason == "tool_calls" }) } /// The second partial holds a `}`, so Gemma's lenient EOS parse reads a diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/StructuredForcedToolAdmissionTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/StructuredForcedToolAdmissionTests.swift index a7accc2686..f67bc8951c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/StructuredForcedToolAdmissionTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/StructuredForcedToolAdmissionTests.swift @@ -160,6 +160,13 @@ struct StructuredForcedToolAdmissionTests { let parallel = try serve(build, request, prepared, output: parallelOutput, width: width) #expect(parallel.map(\.function.name) == ["get_weather", "get_time"], "\(build.id) width \(width)") } + // parallel_tool_calls=false returns the first call, as OpenAI and vLLM do. + let single = try self.request(build, choice: Self.required, parallel: false) + let singlePrepared = try ToolChoicePromptPolicy.prepare(single, modelType: build.modelType) + for width in [1, 5, Int.max] { + let first = try serve(build, single, singlePrepared, output: parallelOutput, width: width) + #expect(first.map(\.function.name) == ["get_weather"], "\(build.id) width \(width)") + } } } @@ -224,15 +231,6 @@ struct StructuredForcedToolAdmissionTests { output: answer(build, frame(build, "delete_files", ["path": "/"]))) } - // parallel_tool_calls=false admits exactly one call. - let single = try self.request(build, choice: Self.required, parallel: false) - let singlePrepared = try ToolChoicePromptPolicy.prepare(single, modelType: build.modelType) - try expectViolation(build) { - _ = try serve(build, single, singlePrepared, output: answer(build, - frame(build, "get_weather", ["city": "Paris"]) + "\n" - + frame(build, "get_weather", ["city": "Rome"]))) - } - // Malformed policies are client errors before any generation. let undeclared = try self.request(build, choice: ["type": "function", "function": ["name": "get_stock_price"]] as [String: Any]) @@ -320,7 +318,7 @@ struct StructuredForcedToolAdmissionTests { continue } } - let calls = handler.finish() + let calls = ParallelToolCallPolicy.admitted(handler.finish(), prepared: prepared) try router.checkNativeToolFailure() try ToolConstraintValidation.validate(calls, prepared: prepared) return calls diff --git a/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift b/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift index d05051133d..dadccdcc44 100644 --- a/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/NemotronSuperLocalOutputTests.swift @@ -244,9 +244,6 @@ final class NemotronSuperLocalOutputTests: XCTestCase { _ = try none.append("" + one) XCTAssertThrowsError(try none.finish(), tools) } - var parallel = try output(Self.weather + #","parallel_tool_calls":false"#) - _ = try parallel.append("" + one + one) - XCTAssertThrowsError(try parallel.finish()) var required = try output(Self.weather + #","tool_choice":"required""#) XCTAssertThrowsError(try required.append("Sure, here it is.")) var requiredMissing = try output(Self.weather + #","tool_choice":"required""#) @@ -257,6 +254,23 @@ final class NemotronSuperLocalOutputTests: XCTestCase { ["R:plan", #"F:get_weather{"city":"A"}"#]) } + /// `parallel_tool_calls: false` returns the first call, as OpenAI and + /// vLLM do, instead of failing a response that made a second one. + func testParallelCallsDisabledKeepTheFirstCall() throws { + let one = "\n\n\nA\n\n\n" + let two = one.replacingOccurrences(of: "\nA\n", with: "\nB\n") + for streaming in [true, false] { + var parallel = try output(Self.weather + #","parallel_tool_calls":false"#, streaming: streaming) + _ = try parallel.append("" + one + two) + let finished = try parallel.finish() + XCTAssertEqual(finished.result.calls.map(\.function.arguments), [["city": .string("A")]]) + XCTAssertEqual(try trace(finished.events).filter { $0.hasPrefix("F:") }, [#"F:get_weather{"city":"A"}"#]) + } + var parallel = try output(Self.weather) + _ = try parallel.append("" + one + two) + XCTAssertEqual(try parallel.finish().result.calls.count, 2) + } + func testStructuredOutputIsWithheldValidatedAndNormalized() throws { var object = try output(#""response_format":{"type":"json_object"}"#) XCTAssertEqual(try object.append("Short plan."), [.parsed(.init(content: "", reasoningContent: "Short plan."))]) diff --git a/provider-swift/Tests/ProviderCoreTests/Server/NemotronSuperMediaControlsHTTPTests.swift b/provider-swift/Tests/ProviderCoreTests/Server/NemotronSuperMediaControlsHTTPTests.swift index 52db79d382..19397a8aac 100644 --- a/provider-swift/Tests/ProviderCoreTests/Server/NemotronSuperMediaControlsHTTPTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Server/NemotronSuperMediaControlsHTTPTests.swift @@ -162,9 +162,10 @@ struct NemotronSuperMediaControlsHTTPTests { #expect(none.content == "Sunny." && none.toolCalls.isEmpty, "\(name)") #expect(!script.prompt.contains("get_weather") && script.prompt.contains("Do not call any tool."), "\(name)") - // `parallel_tool_calls: false` with two calls: the model broke the contract (422). - _ = try await send(body(media, Self.twoCalls, stream: false, - ["tools": [Self.weather], "parallel_tool_calls": false]), status: .unprocessableContent) + // `parallel_tool_calls: false` with two calls: the first is returned, as OpenAI and vLLM do. + let single = try SuperJSON(try await send(body(media, Self.twoCalls, stream: false, + ["tools": [Self.weather], "parallel_tool_calls": false]))) + #expect(single.toolCalls.map(\.arguments) == [#"{"city":"Paris"}"#], "\(name)") // Media in a tool result, which `native_media_tools` advertises. let result = try SuperJSON(try await send(toolResultBody(media, ["", "Sunny."]))) #expect(result.content == "Sunny.", "\(name)")