diff --git a/changelog.d/coordinator-decode-rate-age-decay.md b/changelog.d/coordinator-decode-rate-age-decay.md new file mode 100644 index 0000000000..24e34ee539 --- /dev/null +++ b/changelog.d/coordinator-decode-rate-age-decay.md @@ -0,0 +1,11 @@ +### An idle Mac keeps its decode rate when the coordinator decays stale rates + +The coordinator can now say, in `trust_status.coordinator_features`, that it +decays a stale `observed_decode_tps` by its `observed_decode_tps_age_ms` +(`decode_rate_age_decay`). While the connected coordinator says so, an idle +slot keeps publishing its decode rate and its age after +`DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS`, instead of omitting it; the +coordinator moves an old rate toward the fleet median, so the slot keeps its +rank instead of alternating between no rate and an old one. Without the field +(every coordinator before it), with any other list, and after a disconnect, the +heartbeat is unchanged. diff --git a/changelog.d/gemma-m5-ultra-long-prompt-plain-decode.md b/changelog.d/gemma-m5-ultra-long-prompt-plain-decode.md new file mode 100644 index 0000000000..ab9ded49ec --- /dev/null +++ b/changelog.d/gemma-m5-ultra-long-prompt-plain-decode.md @@ -0,0 +1,12 @@ +### Gemma 4 26B: on M5 Ultra, long prompts decode without speculation + +- On M5 Ultra, a Gemma 4 26B QAT request whose prompt holds more than 16,384 + tokens no longer drafts while it decodes alone: those steps run ordinary + chained decode, with the tokens of decode without MTP. On these prompts a lone + request's two-draft rounds cost more than they gain. Beside a shorter request + it follows the chip's usual table (on M5 Ultra two decoding requests already + decode without drafts), so it never stops another request from drafting. + Shorter prompts and other chips are unchanged. +- `DARKBLOOM_GEMMA_MTP_MAX_PROMPT_TOKENS=0` (or `off`, `false`, `no`) lets every + prompt draft again; a positive integer moves the limit. The provider's + launchd job forwards it. diff --git a/changelog.d/gemma-typeless-render-positions.md b/changelog.d/gemma-typeless-render-positions.md new file mode 100644 index 0000000000..26f6fbf001 --- /dev/null +++ b/changelog.d/gemma-typeless-render-positions.md @@ -0,0 +1,19 @@ +### Gemma 4 renders more untyped tool parameters as untyped + +When the caller's tool declarations reach the provider as sent, Gemma 4 now +also shows these tool parameters untyped (`type:<|"|><|"|>`), as its template +renders a parameter without a type, instead of the `STRING` the schema repair +fills in: + +- a parameter that is only a local `$ref` (`#/$defs/...` or + `#/definitions/...`) to a schema with no type; +- an `anyOf` or `oneOf` whose members accept any value, a `null` member aside + (it still renders `nullable`), and an `allOf` of such members; +- a typeless `enum` whose values have more than one JSON type, such as + `["default", "inherit", "archive", -1]`. The template prints an enum only + for a `STRING` parameter, which made Gemma quote `-1`. + +A tuple parameter (`prefixItems` with `items` false or absent) no longer shows +the repair's `STRING` items. Every other parameter renders as before, and other +model families are unchanged. As for the untyped parameters already covered, a +coordinator request this changes is served without the prompt cache. diff --git a/changelog.d/gptoss-auto-grammar-render-hints.md b/changelog.d/gptoss-auto-grammar-render-hints.md new file mode 100644 index 0000000000..ba74adb3a6 --- /dev/null +++ b/changelog.d/gptoss-auto-grammar-render-hints.md @@ -0,0 +1,12 @@ +### GPT-OSS auto tool grammar reads the repair's render type as a hint + +Under `tool_choice: "auto"`, GPT-OSS's call grammar compiles each declared +tool's arguments. Beside a `not` of the same type, the schema repair writes a +`type` (`{"not": {"type": "string"}, "type": "string"}`), and the grammar held +the argument to that type, which the declaration itself refuses. The grammar +now drops a type that is only a render hint (beside a union naming it, a +mixed `enum`, a `not` of that type or an `if` typed otherwise), as the call +parser and the strict check already do, and keeps `null` where the node is +marked `nullable`. Unions and mixed enums with that type were already left +free and still are; declarations without such a type compile exactly as +before, and forced tool choices, the prompt and validation are unchanged. diff --git a/changelog.d/gptoss-tool-call-recovery.md b/changelog.d/gptoss-tool-call-recovery.md new file mode 100644 index 0000000000..e4486f78ef --- /dev/null +++ b/changelog.d/gptoss-tool-call-recovery.md @@ -0,0 +1,12 @@ +### GPT-OSS tool calls written as the answer or inside the analysis are returned as calls + +- For an `auto` request that declares tools, GPT-OSS sometimes answers after + the loop guard ended its analysis with the call's JSON arguments and no + recipient, or writes a complete call frame at the end of an analysis it + never closes. The provider now returns such an answer as the call when it + is a single JSON object that exactly one declared tool admits (every key a + declared property, the schema holding), and such a frame when it is + complete, names a declared function and its arguments hold. Anything else + is returned as before. No rendered prompt changes. +- `DARKBLOOM_GPTOSS_TOOL_CALL_RECOVERY`: `0`, `off`, `false` or `no` turns it + off. diff --git a/changelog.d/inkling-mtp-coupled-switch.md b/changelog.d/inkling-mtp-coupled-switch.md new file mode 100644 index 0000000000..fcc9281683 --- /dev/null +++ b/changelog.d/inkling-mtp-coupled-switch.md @@ -0,0 +1,5 @@ +### Inkling 2 Mini can draft with coupled proposals (off by default) + +- `DARKBLOOM_INKLING_MTP_COUPLED=1` turns on coupled drafting for Inkling 2 Mini. With it on, a sampled request under exact acceptance proposes the draft that the target's own sampling at that position would most likely pick, instead of the drafter's single most likely token. +- Output is the same with it on or off, because exact acceptance keeps only the target's own tokens. Only how many drafts are kept, and so speed, can change. +- Greedy requests, constrained output and typical acceptance are unchanged. The setting is off unless the variable turns it on. diff --git a/changelog.d/inkling-mtp-logprob-rows.md b/changelog.d/inkling-mtp-logprob-rows.md new file mode 100644 index 0000000000..9b780a8482 --- /dev/null +++ b/changelog.d/inkling-mtp-logprob-rows.md @@ -0,0 +1,10 @@ +### Inkling 2 Mini: speculative decoding for requests with logprobs + +- Inkling 2 Mini requests that ask for `logprobs` / `top_logprobs` now use the + model's speculative decoding head, with exact acceptance only. Each token's + logprob and top logprobs are read from the same target pass that checks the + drafts, and Inkling checks each position with the arithmetic of a one-token + step, so tokens, logprobs and the top-logprob list (members, order and ties) + are the same as without speculation. +- `DARKBLOOM_MTP_LOGPROB_ROWS=0` (or `off`, `false`, `no`) keeps such rows + target-only; the LaunchAgent forwards it. diff --git a/changelog.d/inkling-mtp-max-draft.md b/changelog.d/inkling-mtp-max-draft.md new file mode 100644 index 0000000000..b17dd3f956 --- /dev/null +++ b/changelog.d/inkling-mtp-max-draft.md @@ -0,0 +1,4 @@ +### Inkling 2 Mini's draft cap can be set per Mac + +- `DARKBLOOM_INKLING_MTP_MAX_DRAFT` sets the most drafts one Inkling 2 Mini MTP round may propose: a whole number from 1 to 7, with values outside that range clamped. Unset, it stays at 7, the drafter's whole block, as before. +- The adaptive depth policy still picks each round's depth at or below the cap, and every draft is verified exactly, so tokens are the same at any cap. Only how much each round tries changes. diff --git a/changelog.d/inkling-non-drafting-row-checkpoints.md b/changelog.d/inkling-non-drafting-row-checkpoints.md new file mode 100644 index 0000000000..40b99b9077 --- /dev/null +++ b/changelog.d/inkling-non-drafting-row-checkpoints.md @@ -0,0 +1,5 @@ +### Inkling 2 Mini requests that cannot draft write prefix checkpoints + +- An Inkling 2 Mini request that cannot draft (a logit bias, a token constraint or a reasoning budget) now records the drafter's prompt history when its prompt can be cached, as the Qwen 3.5/3.6, Qwen4, Nemotron Super and MiMo heads already do. It writes the same checkpoints a drafting request writes, so a later request with the same prefix can restore from it. Requests with media still record nothing, by design. +- Inkling requests with logprobs, a repetition, presence or frequency penalty, or a stop string draft in this release (see their own entries), so they save checkpoints as drafting requests do. When one of those rows is kept target-only by its switch, it saves checkpoints through this path instead. +- Output is unchanged: a restored request answers exactly as its cold run. The change comes with the SDK pin; there is no setting. diff --git a/changelog.d/inkling-withheld-reasoning-heartbeat.md b/changelog.d/inkling-withheld-reasoning-heartbeat.md new file mode 100644 index 0000000000..610ad28c7c --- /dev/null +++ b/changelog.d/inkling-withheld-reasoning-heartbeat.md @@ -0,0 +1,8 @@ +### Inkling 2 streams with reasoning off start sooner + +- When a streamed Inkling 2 request turns reasoning off, the model still + thinks before it answers and that thought is withheld. The provider now + sends one empty `content` delta (`{"content": ""}`, no role) when it starts + withholding, so the stream shows progress before the answer. The delta + carries nothing from the withheld thought. Reasoning-on streams, other + models and non-streamed responses are unchanged. diff --git a/changelog.d/mtp-repetition-penalty-rows.md b/changelog.d/mtp-repetition-penalty-rows.md new file mode 100644 index 0000000000..35fa798496 --- /dev/null +++ b/changelog.d/mtp-repetition-penalty-rows.md @@ -0,0 +1,10 @@ +### Requests with a repetition penalty draft on the MTP builds + +On the catalog Qwen 3.5/3.6 builds, Gemma 4 26B QAT and Inkling 2 Mini, requests +with a `repetition_penalty` other than 1 now draft, as requests with a presence +or frequency penalty already do. Before, they decoded without the drafter on +every model. Each draft position is penalized exactly as ordinary decoding +would after sampling the drafts before it (the same repetition window over +prompt, output and those drafts), and these rows accept a draft only +when it equals the model's own sample, so output is the same as with the +drafter off. `DARKBLOOM_MTP_REPETITION_PENALTY_ROWS=0` turns them off again. diff --git a/changelog.d/tool-constraint-annotated-render-markers.md b/changelog.d/tool-constraint-annotated-render-markers.md new file mode 100644 index 0000000000..07558b0dca --- /dev/null +++ b/changelog.d/tool-constraint-annotated-render-markers.md @@ -0,0 +1,8 @@ +### Forced tool choices accept `{}` parameters that keep a description + +- Under `tool_choice` `required` or a named function, a parameter schema the + coordinator forwards as a render-marked `{}` that keeps its annotations + (`description`, `title`, `default`, `examples`, …) now compiles as the bare + `{}` does, as free text, instead of refusing the request. A marker beside + an assertion, or one standing for `false`, is still refused. `auto` is + unchanged. No rendered prompt changes. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 780ae21df5..6136f84155 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3054,8 +3054,12 @@ measured `0` restores publishing the last rate however old). The heartbeat also sends the published rate's own age, `observed_decode_tps_age_ms`: the time since the newest sample that moved it, which a short reply does not reset -(`DecodeRateIdleAge.publishedAgeMilliseconds`); it changes nothing the provider -decides. The published rate moves +(`DecodeRateIdleAge.publishedAgeMilliseconds`). While the connected +coordinator's latest `trust_status` lists `decode_rate_age_decay` in +`coordinator_features`, the coordinator decays a stale rate by that age itself, +and the provider stops omitting an idle slot's rate +(`DecodeRateIdleAge.effectiveMaximum`); without it, and after a disconnect, the +heartbeat is unchanged. The published rate moves only on a request that generated at least 32 tokens (`EngineV2Bridge.minimumPublishedDecodeTokens`, the coordinator's `completion_tokens >= 32` convention; `updatePublishedDecodeTps` keeps the same @@ -3464,7 +3468,17 @@ M5 Ultra, M3 Ultra and M5 Max only a lone row drafts (per-row table Two or more rows get depth 0 and run ordinary chained decode. `DARKBLOOM_GEMMA_MTP_M5_ULTRA_LONE_ROW=0` restores M5 Ultra's earlier table: one or two rows draft (`[2, 2, 0]`, envelope 6, a `[2, 3]` rectangle at most), and the -deadline projection again charges three rows depth 1, more than they run. Width-3 +deadline projection again charges three rows depth 1, more than they run. On M5 +Ultra a request whose prompt holds more than 16,384 tokens does not draft while it +decodes alone (`MTPAutomaticVerificationPolicy.maxDraftPromptTokens(modelID:chipName:)`, +passed to `CBv2MTPConfig.maxDraftPromptTokens`): a plan whose speculation-eligible +decode rows all have prompts over the limit runs at depth 0, as ordinary chained +decode, while a plan with any row under the limit keeps the table's depth, so a +long-prompt row never stops another row from drafting. With M5 Ultra's `[2, 0]` +table two or more rows run at depth 0 anyway, so the limit changes only a +long-prompt row decoding alone, where two-draft rounds cost more than they gain. +`DARKBLOOM_GEMMA_MTP_MAX_PROMPT_TOKENS=0` removes the limit; a positive integer +moves it. Width-3 verification below 64 expert assignments (`[1, 3]`, and `[2, 3]` under that switch), outside the batch-decode and prompt projection scopes, takes Gemma's compiled feed-forward trace, with the @@ -3508,8 +3522,20 @@ the served Inkling 2 Mini, whose answer-channel stop scope the row's detokenizer token through the row's detokenizer and ends the row at the first match, rolling back the rest: given the committed tokens, stop matching, scope, truncation and the finish reason follow ordinary decode; `DARKBLOOM_MTP_STOP_STRING_ROWS=0` keeps -them target-only. Repetition penalty, bias, logprobs and token constraints retain their -ordinary-decode exclusions. Explicit offline serial +them target-only. Since 0.10.18 rows with a repetition penalty speculate on the builds in +`SDKFeatureDefaults.repetitionPenaltyRowBuilds` (the same builds; +`CBv2MTPConfig.repetitionPenaltySpeculation`): each verify position's window is the last +`repetitionContextSize` tokens of prompt, confirmed output and the drafts before it, penalized +with `LogitsPipelineV2.process`'s ops before presence/frequency, and such rows accept exactly +(`CBv2DefaultSampler.applyWindowRepetition`); `DARKBLOOM_MTP_REPETITION_PENALTY_ROWS=0` keeps +them target-only. Rows that request logprobs speculate on the builds in +`SDKFeatureDefaults.logprobRowBuilds` (Inkling 2 Mini; `CBv2MTPConfig.logprobSpeculation`), +which the SDK honours only on a `.rectangularExact` target under exact acceptance: each +committed token's logprob and top logprobs are gathered from the verify window's raw +logits, which on that target equal a one-token decode step's, so they are drafter-off's +bit for bit; `DARKBLOOM_MTP_LOGPROB_ROWS=0` keeps them target-only. Bias, token +constraints and logprobs on other builds retain their ordinary-decode exclusions. +Explicit offline serial verification remains available as a diagnostic oracle; drafter-required modes retain priority (`provider-swift/Sources/ProviderCore/Inference/MTP/EngineV2MTPAssistant.swift`, `providerMTPVerificationPolicy`). @@ -3530,6 +3556,13 @@ change with the all-model default are GLM-5.3-Flash (`glm5_next`) and Qwen 4 was already exact. Greedy rows accept exactly under either rule. Exact keeps the model's output distribution; its tokens are not bit-identical to MTP off, since verify windows round differently. +Inkling 2 Mini replaces the generic depth with its drafter's own profile +(`Inkling2DSparkDrafter.defaultMTPConfig`: up to 7 drafts, adaptive), and +`DARKBLOOM_INKLING_MTP_MAX_DRAFT` (1 to 7) lowers that cap, and +`DARKBLOOM_INKLING_MTP_COUPLED=1` turns on coupled drafting (off by default: +sampled rows under exact acceptance propose their verify draw's keyed race; +tokens are unchanged); the acceptance setting still applies (`Inkling2MTPProfilePolicy` in +`provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift`). Under typical acceptance a draft is kept when the sampler-filtered target row gives it probability above `min(1, 0.2 * exp(-H))`, `H` the row's entropy in nats; the first rejected position and the bonus position still commit the keyed @@ -3622,7 +3655,7 @@ disabled for this hybrid model. On the Qwen 3.5/3.6 (also Qwen3.8-27B, which uses the same embedded head), Nemotron Super and native Qwen4 assistants (not the embedded Nemotron head -above), a request the assistant cannot draft for still records its prompt +above), and Inkling 2 Mini's DSpark drafter, a request the assistant cannot draft for still records its prompt history when its prompt can be cached ([prefix-cache invariant 9](prefix-cache.md#invariants)). That covers a token constraint, logprobs, `logit_bias`, a penalty or a `stop` string, so it @@ -4893,6 +4926,16 @@ the call is constrained: byte vocabulary), and `<|call|>` is admitted only once the object is complete. The schema is compiled from the caller's declaration with local `$ref`s inlined (`ToolSchemaRefResolution`, same bounds). +- Before compiling, a `type` that is only a render hint is dropped + (`GPTOSSAutoToolGrammar.withoutRenderHintTypes`, the rule + `QwenParserLiteralReading.rendersSiblingType` the call parser and the strict + check read): the type beside an `anyOf` / `oneOf` naming one of their + branches, a mixed `enum`, a `not` of that type or an `if`/`then`/`else` typed + otherwise; a node marked `nullable` then carries `null` in its union or + `enum`. A `not` of the render type was held to that type before; unions and + mixed enums beside it already compiled to free arguments. A declaration + without such a type is unchanged; forced choices compile the request's tools + as before. - A schema outside the compiled subset as written is widened (`GPTOSSAutoToolGrammar.widenedArguments`): the render type that ingress normalization writes beside a nullable `anyOf` (`type`, `nullable`, and an @@ -5206,7 +5249,13 @@ Unions with more members, non-scalar members or an `enum` keep `STRING`, and other families keep the shared repair's render type. A property the caller declared without any type or schema keyword (`{}`) renders an empty type (`type:<|"|><|"|>`, the served template's rendering of a typeless property) -instead of the injected `string` (invariant 8). Gemma's render reads the +instead of the injected `string` (invariant 8). The same holds for a +property that is only a local `$ref` to such a schema, for an +`anyOf`/`oneOf`/`allOf` whose non-null members all accept any value (a `null` +member still renders `nullable`), and for a typeless `enum` whose values have +more than one JSON type, which the template would otherwise print under +STRING. A tuple (`prefixItems` with `items` false or absent) renders no `items` +block, as the template renders an array without a mapping `items`. Gemma's render reads the caller's declarations as sent (`ChatTemplateControls.declaredTools`) on every path that renders a coordinator request: serving, prompt recount and the diffusion media path. Such a request is also diff --git a/docs/architecture/prefix-cache.md b/docs/architecture/prefix-cache.md index b8d4bb9874..8482c9ff74 100644 --- a/docs/architecture/prefix-cache.md +++ b/docs/architecture/prefix-cache.md @@ -1008,7 +1008,8 @@ rules applied to these signals. checkpoint — `HybridPrefixCache.swift` (`lookup`), `HybridPrefixCacheContract.swift` (`CBv2RecurrentCheckpointGeometry`). 9. On a slot with a prefix cache and a history-keeping MTP head that opted in - (the embedded Qwen 3.5/3.6 heads, Nemotron Super, native Qwen4, MiMo V2.6), history + (the embedded Qwen 3.5/3.6 heads, Nemotron Super, native Qwen4, MiMo V2.6, + Inkling 2 Mini's DSpark drafter), history observation follows cache eligibility, not speculation eligibility. A cached text request that cannot speculate (a token constraint, logprobs, `logit_bias`, a repetition, frequency or presence penalty, a `stop` string: diff --git a/docs/developer/serving-performance-qualification.md b/docs/developer/serving-performance-qualification.md index bec5b04376..0aaa32e53e 100644 --- a/docs/developer/serving-performance-qualification.md +++ b/docs/developer/serving-performance-qualification.md @@ -27,7 +27,13 @@ either: it is informational and changes no rate, admission or profile. Nor does the decode rate a slot uses before its first completed request (the slowest delivered cadence of requests decoding on it, charged per row; see [deadlines](../architecture/inference.md#deadlines)): a request carrying a -reviewed calibration never takes it. +reviewed calibration never takes it. Nor does the coordinator's +`decode_rate_age_decay` advertisement (`trust_status.coordinator_features`; +shared wire cases in +`provider-swift/Tests/ProviderCoreTests/Fixtures/Protocol/coordinator_features_wire.json`, +checked by `CoordinatorDecodeRateDecayTests` and +`provider-swift/Tests/test_protocol_fixture_resources.py`): it decides only +whether an idle slot keeps advertising its rate to routing. Profile qualification is separate work required to introduce a measured prediction-error envelope. diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 4e2650dfda..531a296ff3 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -4254,10 +4254,18 @@ see the [scheduler environment reference](../reference/configuration.md#engine-a `DARKBLOOM_MTP_PENALTY_ROWS` is read once when the process starts; the LaunchAgent forwards an operator value to the installed service. On the catalog Qwen 3.5/3.6 builds (card default presence 1.5), Gemma 4 26B QAT and Inkling 2 Mini, rows with a presence or frequency penalty speculate with exact acceptance by default; `0` (or `false`, `no`, `off`) keeps them target-only, as before these builds opted in. The [configuration reference](../reference/configuration.md#engine-and-scheduler) gives its scope. +### MTP repetition-penalty-row switch + +`DARKBLOOM_MTP_REPETITION_PENALTY_ROWS` is read once when the process starts; the LaunchAgent forwards an operator value to the installed service. On the catalog Qwen 3.5/3.6 builds, Gemma 4 26B QAT and Inkling 2 Mini, rows with a repetition penalty speculate with exact acceptance by default, so their output is the same as without speculation; `0` (or `false`, `no`, `off`) keeps them target-only, as before these builds opted in. The [configuration reference](../reference/configuration.md#engine-and-scheduler) gives its scope. + ### MTP stop-string-row switch `DARKBLOOM_MTP_STOP_STRING_ROWS` is read once when the process starts; the LaunchAgent forwards an operator value to the installed service. On the catalog Gemma 4 26B QAT build and Inkling 2 Mini, rows with `stop` strings speculate by default and stop at the first match exactly as without speculation; `0` (or `false`, `no`, `off`) keeps them target-only. The [configuration reference](../reference/configuration.md#engine-and-scheduler) gives its scope. +### MTP logprob-row switch + +`DARKBLOOM_MTP_LOGPROB_ROWS` is read once when the process starts; the LaunchAgent forwards an operator value to the installed service. On Inkling 2 Mini, rows that request `logprobs` / `top_logprobs` speculate by default (with exact acceptance only), and every token's logprob and top logprobs are the values the same request gets without speculation; `0` (or `false`, `no`, `off`) keeps them target-only. The [configuration reference](../reference/configuration.md#engine-and-scheduler) gives its scope. + ## LaunchAgent environment passthrough `DARKBLOOM_NATIVE_REASONING_BUDGET` is forwarded to the service when the operator @@ -4389,6 +4397,7 @@ must support the checkpoint contract described in | `DARKBLOOM_MTP_MAX_RECTANGULAR_TOKENS` | MTP verification policy (tighten-only cap) | | `DARKBLOOM_GEMMA_MTP_TWO_DRAFTS` | MTP verification policy: `0` returns `gemma-4-26b-qat-4bit` on M5 Ultra, M3 Ultra and M5 Max from two drafts per round to the one-draft lone-row policy (other chips already use it) | | `DARKBLOOM_GEMMA_MTP_M5_ULTRA_LONE_ROW` | MTP verification policy (while the two-draft policy is on): `0` lets `gemma-4-26b-qat-4bit` on M5 Ultra draft two tokens at one or two decode rows again (table `[2, 2, 0]`; default: a lone row only) | +| `DARKBLOOM_GEMMA_MTP_MAX_PROMPT_TOKENS` | MTP verification policy (while the two-draft policy is on): on M5 Ultra a `gemma-4-26b-qat-4bit` decode step whose rows all have prompts over the limit (default 16384 tokens) runs without drafts, so a long-prompt row decoding alone decodes plain; `0` lets every prompt draft again, a positive integer moves the limit | | `DARKBLOOM_GEMMA_MTP_LONE_ROW` | MTP verification policy (where the two-draft policy is off or the chip has none): `0` lets `gemma-4-26b-qat-4bit` speculate at two to four decode rows again on M3–M5 (two on M1/M2; default: a lone row only) | | `DARKBLOOM_GEMMA_NATIVE_ROWS_BEFORE_ASSISTANT` | Checkpoint layout (`provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2KVQuantizationPolicy.swift`, `gemmaNativeRowsBeforeAssistantEnabled`): `0` keeps `gemma-4-26b-qat-4bit`'s two assistant-access layers native only while the assistant is attached (the earlier rule), with MTP left on (default: native also while it is configured but not attached yet) | | `DARKBLOOM_KV_BACKEND_GUARD` | `provider-swift/Sources/ProviderCore/Service/KVBackendGuard.swift` | diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 4dd3c62a0e..3e2214bc54 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -603,6 +603,7 @@ and rollback are defined in the [provider configuration reference](../provider/c | `DARKBLOOM_MTP_MAX_RECTANGULAR_TOKENS` | integer | policy default | `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAutomaticVerificationPolicy.swift` | Tighten-only cap on rectangular MTP verification tokens. | | `DARKBLOOM_GEMMA_MTP_TWO_DRAFTS` | boolean | on | `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAutomaticVerificationPolicy.swift` (`gemmaTwoDraftsEnabled`, `gemmaTwoDrafts(chipName:m5UltraLoneRow:)`) | On when unset, empty or `1`/`true`/`yes`/`on` (trimmed, any case): `gemma-4-26b-qat-4bit` drafts two tokens a round at fixed depth on M5 Ultra, M3 Ultra and M5 Max while one row decodes (table `[2, 0]`, envelope 3; two or more rows decode without drafts); other chips keep the lone-row policy. Any other value (e.g. `0`) restores the lone-row policy everywhere. Read once from the process environment; the LaunchAgent forwards non-empty values. | | `DARKBLOOM_GEMMA_MTP_M5_ULTRA_LONE_ROW` | boolean | on | `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAutomaticVerificationPolicy.swift` (`gemmaM5UltraLoneRowEnabled`) | On when unset, empty or `1`/`true`/`yes`/`on` (trimmed, any case): on M5 Ultra, `gemma-4-26b-qat-4bit` drafts two tokens a round only while one row decodes (table `[2, 0]`, envelope 3). Any other value (e.g. `0`) restores M5 Ultra's earlier table, one or two decode rows drafting two (`[2, 2, 0]`, envelope 6); other chips are unchanged. Applies only while `DARKBLOOM_GEMMA_MTP_TWO_DRAFTS` is on. Read once from the process environment; the LaunchAgent forwards non-empty values. | +| `DARKBLOOM_GEMMA_MTP_MAX_PROMPT_TOKENS` | `0`/`off`/`false`/`no`, or a positive integer (trimmed, any case) | 16384 on M5 Ultra | `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAutomaticVerificationPolicy.swift` (`gemmaDraftPromptLimit`, `maxDraftPromptTokens(modelID:chipName:)`) | Under the two-draft policy on M5 Ultra, a `gemma-4-26b-qat-4bit` decode step whose speculation-eligible rows all have prompts over the limit runs without drafts, as ordinary chained decode (`CBv2MTPConfig.maxDraftPromptTokens`): a long-prompt row decoding alone has the MTP-off engine's tokens, and a row under the limit beside it keeps the chip's table, so a long-prompt row never stops another row from drafting. Unset, empty or not a positive integer: 16384, the build default (`gemmaPromptLimitOnByDefault`; when a build turns it off, unset means no limit). `0` (or `off`, `false`, `no`): no limit, every prompt drafts as before, the same engine behaviour as without the limit. A positive integer sets the limit. Other chips never get a limit. Applies only while `DARKBLOOM_GEMMA_MTP_TWO_DRAFTS` is on. Read once from the process environment; the LaunchAgent forwards non-empty values. | | `DARKBLOOM_GEMMA_MTP_LONE_ROW` | boolean | on (applies where the two-draft policy is off or the chip has none) | `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAutomaticVerificationPolicy.swift` (`gemmaLoneRowEnabled`) | On when unset, empty or `1`/`true`/`yes`/`on` (trimmed, any case): `gemma-4-26b-qat-4bit` speculates only while one row decodes (envelope 2). Any other value (e.g. `0`) restores the chip's envelope (8 on M3–M5, 4 on M1/M2). Read once from the process environment; the LaunchAgent forwards non-empty values. | | `DARKBLOOM_GEMMA_NATIVE_ROWS_BEFORE_ASSISTANT` | boolean | on | `provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2KVQuantizationPolicy.swift` (`gemmaNativeRowsBeforeAssistantEnabled`, `gemmaAssistantAccessExpected`) | On when unset, empty or `1`/`true`/`yes`/`on` (trimmed, any case): a `gemma-4-26b-qat-4bit` slot whose MTP assistant is configured but not attached yet keeps the assistant's two access layers native in its prefix-cache checkpoints, as an attached slot does. Any other value (e.g. `0`) restores the earlier rule, native only with the assistant attached, and leaves MTP on. Read once from the process environment; the LaunchAgent forwards non-empty values. | | `DARKBLOOM_TTFT_QWEN_MTP_CHAINED` | `0`, `false`, `no`, `off` disable | on | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift` (`CBv2MTPConfig.envOrdinaryDecodeHistory`) | While no Qwen inline-MTP row can speculate (more decode rows than its speculative batch of one), steps in which every MTP-eligible row is decoding run as ordinary chainable decode with no policy top-two; finalize feeds the assistant history and carry. Off restores hidden-returning seed steps. Not forwarded to LaunchAgents. | @@ -624,22 +625,27 @@ and rollback are defined in the [provider configuration reference](../provider/c | `DARKBLOOM_MTP_ACCEPTANCE` | `exact`, `typical`, `typical:` (finite positive delta) | `exact` | `provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift`; `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift` (`benchmarkOverride`) | MTP draft acceptance rule (benchmark session only). An unrecognized value uses `exact`. Serving reads no environment variable for this rule; it reads `[backend] mtp_acceptance` and `mtp_acceptance_by_model` in [`provider.toml`](../provider/cli-reference.md#providertoml-keys-read-by-the-cli). | | `DARKBLOOM_CONSTRAINT_SPANS` | trimmed, case-insensitive `1`, `true`, `on`, `yes`; other values disable | **on for `EigenLabs/Qwen3.8-27B-4bit-mtp`** (the measured build; provider default since 0.10.13, `SDKFeatureDefaults`); off for every other build; `0` restores 0.10.12, `1` turns it on for every eligible build | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift` (`CBv2MTPConfig.envFreeSpanSpeculation`) | Opts eligible constrained rows into MTP only while the provider proves an ordinary free-text span. Existing sampler, model and ownership eligibility still apply. Does not enable MTP or admit new strict-tool requests. Read at engine construction. Applies to admitted Qwen strict-auto reasoning/content and JSON reasoning; JSON values and trailing whitespace remain protected. Forwarded by the LaunchAgent. Native completion-tracked engines remain ineligible. | | `DARKBLOOM_STRICT_TOOL_GRAMMAR` | unset: the default builds; `on`, `1`, `true`, `yes`: every Qwen 3.5-family build (`qwen3_5`, `qwen3_5_moe`); an off word (`off`, `0`, `false`, `no`, `none`, `disabled`) disables; otherwise a comma list of `model_type`s or model-id parts (trimmed, case-insensitive) that replaces the default builds | on for `qwen3_5_moe` (Qwen 3.6, Qwen 3.5 35B) and `qwen3.8-27b` (Qwen 3.8 27B); Qwen 3.5 9B only when set | `provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift` (`setting`) | Qwen 3.5-family `auto` requests that declare a `strict` function sample every call's function, parameters and values under the declared schemas on one Mac; a request whose schemas fall outside the grammar, or a cluster pair, is served unconstrained. With `DARKBLOOM_CONSTRAINT_SPANS` off, constrained decoding retains its existing drafting restriction. `DARKBLOOM_CONSTRAINT_SPANS`, where it is on, only relaxes eligible free spans. See [strict tool-call grammar](../architecture/inference.md#strict-tool-call-grammar). Forwarded to the LaunchAgent. | -| `DARKBLOOM_MTP_PENALTY_ROWS` | `0`, `false`, `no`, `off` (any case) disable; anything else, or unset, enables | on for the catalog `Qwen3.5-9B`, `qwen3.5-35b-a3b`, `qwen3.6-35b-a3b-vl-mtp-mxfp8` (since 0.10.16), `gemma-4-26b-qat-4bit` and `thinkingmachines/Inkling-2-Mini` (0.10.18) (`SDKFeatureDefaults.penaltyRowBuilds`, which sets `CBv2MTPConfig.penaltySpeculation`); every other build keeps penalty rows target-only | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift` (`CBv2MTPConfig.envPenaltySpeculation`, `effectivePenaltySpeculation`); `EngineLoopV2+MTPPlanning.swift` (`mtpPenaltiesEligible`); `provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift` (`applyMTPDefaults`) | Lets rows with a presence or frequency penalty draft on those builds (their card default is presence 1.5, so ~0 % of their rows drafted before). Each verify position is penalized with the row's confirmed output counts plus the drafts before it, with the ordinary sampler's ops and order, and such rows always accept exactly, so a committed token is the draw sequential sampling makes from the same logits. Repetition penalty, logprobs, `logit_bias`, constraints and reasoning budgets keep their exclusions (`stop` strings: `DARKBLOOM_MTP_STOP_STRING_ROWS`). `0` keeps penalty rows target-only, as before these builds opted in. Read once per process. Forwarded by the LaunchAgent. | +| `DARKBLOOM_MTP_PENALTY_ROWS` | `0`, `false`, `no`, `off` (any case) disable; anything else, or unset, enables | on for the catalog `Qwen3.5-9B`, `qwen3.5-35b-a3b`, `qwen3.6-35b-a3b-vl-mtp-mxfp8` (since 0.10.16), `gemma-4-26b-qat-4bit` and `thinkingmachines/Inkling-2-Mini` (0.10.18) (`SDKFeatureDefaults.penaltyRowBuilds`, which sets `CBv2MTPConfig.penaltySpeculation`); every other build keeps penalty rows target-only | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift` (`CBv2MTPConfig.envPenaltySpeculation`, `effectivePenaltySpeculation`); `EngineLoopV2+MTPPlanning.swift` (`mtpPenaltiesEligible`); `provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift` (`applyMTPDefaults`) | Lets rows with a presence or frequency penalty draft on those builds (their card default is presence 1.5, so ~0 % of their rows drafted before). Each verify position is penalized with the row's confirmed output counts plus the drafts before it, with the ordinary sampler's ops and order, and such rows always accept exactly, so a committed token is the draw sequential sampling makes from the same logits. Repetition penalty rows follow `DARKBLOOM_MTP_REPETITION_PENALTY_ROWS`; logprobs, `logit_bias`, constraints and reasoning budgets keep their exclusions (`stop` strings: `DARKBLOOM_MTP_STOP_STRING_ROWS`). `0` keeps penalty rows target-only, as before these builds opted in. Read once per process. Forwarded by the LaunchAgent. | +| `DARKBLOOM_MTP_REPETITION_PENALTY_ROWS` | `0`, `false`, `no`, `off` (any case) disable; anything else, or unset, enables | on for the catalog `Qwen3.5-9B`, `qwen3.5-35b-a3b`, `qwen3.6-35b-a3b-vl-mtp-mxfp8`, `gemma-4-26b-qat-4bit` and `thinkingmachines/Inkling-2-Mini` (0.10.18) (`SDKFeatureDefaults.repetitionPenaltyRowBuilds`, which sets `CBv2MTPConfig.repetitionPenaltySpeculation`); every other build keeps repetition-penalty rows target-only | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift` (`CBv2MTPConfig.envRepetitionPenaltySpeculation`, `effectiveRepetitionPenaltySpeculation`); `EngineLoopV2+MTPPlanning.swift` (`mtpRepetitionPenaltyEligible`); `DefaultSamplerV2.swift` (`applyWindowRepetition`); `provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift` (`applyMTPDefaults`) | Lets rows with `repetition_penalty` other than 1 draft on those builds. Each verify position is penalized as ordinary decode would after sampling the drafts before it: every token among the last `repetitionContextSize` tokens of prompt, confirmed output and those drafts has a positive logit divided by the penalty and a negative one multiplied, before any presence/frequency penalty, with the ordinary sampler's ops. Such rows always accept exactly, so the committed tokens are the MTP-off engine's. A row that also has a presence or frequency penalty needs `DARKBLOOM_MTP_PENALTY_ROWS` as well. A kill switch only: `0` keeps such rows target-only, as before; it cannot widen the builds. Read once per process. Forwarded by the LaunchAgent. | | `DARKBLOOM_MTP_STOP_STRING_ROWS` | `0`, `false`, `no`, `off` (any case) disable; anything else, or unset, enables | on for the catalog `gemma-4-26b-qat-4bit` and `thinkingmachines/Inkling-2-Mini` (0.10.18) (`SDKFeatureDefaults.stopStringRowBuilds`, which sets `CBv2MTPConfig.stopStringSpeculation`); every other build keeps `stop`-string rows target-only | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift` (`CBv2MTPConfig.envStopStringSpeculation`, `effectiveStopStringSpeculation`); `EngineLoopV2+MTPPlanning.swift` (`mtpHistoryEligible`); `EngineLoopV2+MTPFinalize.swift`; `provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift` (`applyMTPDefaults`) | Lets rows with `stop` strings draft on those builds. The round's finalize confirms committed tokens one at a time through the row's detokenizer and ends the row at the first match, as ordinary decode does; tokens past the match are rolled back, so given the committed tokens, stop matching, scope, truncation and the finish reason follow ordinary decode. A kill switch only: `0` keeps such rows target-only, as before; it cannot widen the builds. Read once per process. Forwarded by the LaunchAgent. | +| `DARKBLOOM_MTP_LOGPROB_ROWS` | `0`, `false`, `no`, `off` (any case) disable; anything else, or unset, enables | on for Inkling 2 Mini (`thinkingmachines/Inkling-2-Mini`; `SDKFeatureDefaults.logprobRowBuilds`, which sets `CBv2MTPConfig.logprobSpeculation`), taken only under exact MTP acceptance; every other build keeps logprob rows target-only | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift` (`CBv2MTPConfig.envLogprobSpeculation`, `effectiveLogprobSpeculation`); `EngineLoopV2+MTPPlanning.swift` (`mtpLogprobRowEligible`); `EngineLoopV2+MTPTargetVerification.swift` (`mtpWindowLogprobs`); `EngineLoopV2+MTPFinalize.swift`; `provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift` (`applyMTPDefaults`) | Lets rows that request `logprobs` / `top_logprobs` draft on that build. The SDK honours it only on a `.rectangularExact` target with exact acceptance, where each verify position's logits equal a one-token decode step's; each committed token's logprob and top logprobs are gathered from those logits as ordinary decode gathers them, so tokens and logprob values equal the same request without speculation, bit for bit. Rows with a token constraint stay target-only. The load log reports the result as the engine runs it (`MTP logprob rows: on (verification rectangular_exact, acceptance exact)`); `off` there means the build's acceptance or verification does not qualify. A kill switch only: `0` keeps such rows target-only, as before; it cannot widen the builds. Read once per process. Forwarded by the LaunchAgent. | | `DARKBLOOM_CBV2_MTP_GRAMMAR` | case-insensitive `1`, `true`, `on`, `yes`; other values disable | **on for `EigenLabs/Qwen3.8-27B-4bit-mtp` where constraint spans are on** (measured together) **and for GLM-5.3-Flash** (`glm-5.3-flash` and `EigenLabs/GLM-5.3-Flash-MLX-NVFP4-mtp`; native, no spans: `nativeGrammarMTPBuilds`) (provider default since 0.10.13, `SDKFeatureDefaults`); off for every other build (Gemma 4, Super); `0` restores target-only constrained rows (any value also re-keys the SSD checkpoint namespace), `1` turns it on for every MTP engine | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPContractsV2.swift` (`CBv2MTPConfig.envConstrainedSpeculation`) | Lets constrained rows draft with MTP and verifies each committed position with the ordinary sampler under the row's grammar (accept up to the first violation; the correction and bonus tokens are sampled under the mask). A row inside a free span (`DARKBLOOM_CONSTRAINT_SPANS`) keeps the pure free-span preview instead. Native completion-tracked engines stay target-only, except GLM-5.3-Flash's page bank, whose issued contract qualifies it (`CBv2NativeExecutionContract.supportsConstrainedMTPVerification`): each committed position is sampled under the native work protocol. Read when an engine is built. Forwarded by the LaunchAgent. | | `DARKBLOOM_STRICT_TOOL_GRAMMAR_ALL_TOOLS` | `on`, `1`, `true`, `yes` enable (trimmed, case-insensitive) | off | `provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift` (`allTools`) | Also constrains the calls of requests that declare no `strict` function. Forwarded to the LaunchAgent. | | `DARKBLOOM_GLM_REFERENCE_TOOL_HISTORY` | `0`, `off`, `false`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift` (`referenceToolHistoryEnabled`) | GLM-5.3-Flash serves history tool-call arguments and tool schemas in shapes vLLM and the OpenAI API accept: a repeated argument key keeps its last value, a number that no JSON value holds exactly is read as a JSON value holds it, and GLM tool-call markers in argument keys and strings are text. Off refuses them as `invalid tool arguments`, `invalid tool schema` and `native delimiter in history`. Requests accepted before render identically. Read once per process; forwarded to the LaunchAgent. See [GLM-5.3-Flash](../architecture/inference.md). | | `DARKBLOOM_QWEN_CALL_END_GUARD` | `0`, `off`, `false`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/QwenCallEndGuard.swift` (`enabled`) | Qwen 3.5-family text requests with a `required` or named `tool_choice` admit no stop token while a call frame is open, on one Mac that runs token constraints; everything else is sampled as without it. See [no end of turn inside a Qwen call frame](../architecture/inference.md#no-end-of-turn-inside-a-qwen-call-frame). Forwarded to the LaunchAgent. | +| `DARKBLOOM_GPTOSS_TOOL_CALL_RECOVERY` | `0`, `off`, `false`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Tools/GPTOSSToolCallRecovery.swift` (`enabled`) | GPT-OSS `auto` requests with tools: an answer after the loop guard ended the analysis that is a single JSON object exactly one declared tool admits, or a complete declared call frame ending an analysis that never closed, is returned as that call. Anything else is returned as before. Read once per process; forwarded to the LaunchAgent. | | `DARKBLOOM_LOCAL_ALLOW_TOOL_SCHEMA_METADATA` | exactly `1` enables (trimmed) | off | `provider-swift/Sources/ProviderCore/Inference/Tools/LocalToolSchemaMetadata.swift` (`current`) | Testing switch: the local API (`darkbloom start --local`) accepts tool schemas carrying the ingress repair's render marker (`x-darkbloom-original-boolean-schema`), as the coordinator forwards them, instead of refusing them. Logs a warning when on. The coordinator path is unchanged. Read once per process. | | `DARKBLOOM_MEDIA_ON_EVERY_ROLE` | `0`, `off`, `false`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Vision/MediaIngest.swift` (`everyRoleEnabled`) | Images and videos in system, assistant and tool messages are kept and placed by the model's chat template on one Mac and on GLM tensor-parallel pairs; media the template refuses or leaves without a placeholder is a 400 `media_role_not_rendered`. Off restores the family's previous media handling. Inkling and Diffusion Gemma still keep tool-result media on their native paths. Read once per process; forwarded to the LaunchAgent. | | `DARKBLOOM_PREFILL_DEADLINE_MODE` | exactly `off` disables; any other value enforces | `enforce` | `provider-swift/Sources/ProviderCore/Inference/Engine/PrefillDeadlineMode.swift` (`PrefillDeadlineMode.resolve`) | Prefill-deadline admission on the provider. Read only when `[backend] prefill_deadline_mode` is absent from `provider.toml`; that key takes precedence. | | `DARKBLOOM_TTFT_ADMISSION_FIXES` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`DeadlineAdmissionFixes`) | Deadline-admission estimator corrections: per-batch decode charging, anchored isolated-prefill rate, newest-observation freshness, a probe that re-measures stale isolated-prefill evidence after three refusals it explains. Off restores the previous estimators and turns that probe off too. Forwarded to the launchd provider job. | | `DARKBLOOM_TTFT_NATIVE_PREFILL_EVIDENCE` | `0`, `false`, `off`, `no` disable (trimmed, case-insensitive) | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/AdmissionRateEstimators.swift` (`NativePrefillEvidence`) | GLM-5.3-Flash and native MiMo V2.6 only ([deadlines](../architecture/inference.md#deadlines)): a cold prompt of at most 4,096 tokens may raise the prefill estimate but never lower it, and the smallest prompt-size bucket (up to 1,024 tokens) no longer tightens a prompt. An idle Mac at nominal posture with no calibration cell or longer prompt in the last 120 s is priced at no less than its calibration cell, so once calibrated it takes no short-prompt recovery; a busy Mac or another posture keeps one eighth of the cell as its floor. A slower isolated short sample stays out of the published isolated and observed prefill rates. Off (or `DARKBLOOM_TTFT_ADMISSION_FIXES=0`) restores the previous estimator. Other models, Diffusion Gemma included, are unchanged. Forwarded to the launchd provider job. | -| `DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS` | a positive whole number of seconds; `0`, `false`, `off`, `no` disable (trimmed, case-insensitive); other values keep the default | `1800` | `provider-swift/Sources/ProviderCore/Inference/Performance/DecodeRateIdleAge.swift` (`DecodeRateIdleAge`) | How long an idle slot keeps publishing its decode EWMA as `observed_decode_tps`. Once nothing has run or waited on the slot since a decode sample older than this, the heartbeat omits the rate and the coordinator prices the Mac from its profile or the fleet, as after a reload; the next decode sample is published as measured. Off publishes the last rate however old, as 0.10.17 did. Forwarded to the LaunchAgent. | +| `DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS` | a positive whole number of seconds; `0`, `false`, `off`, `no` disable (trimmed, case-insensitive); other values keep the default | `1800` | `provider-swift/Sources/ProviderCore/Inference/Performance/DecodeRateIdleAge.swift` (`DecodeRateIdleAge`) | How long an idle slot keeps publishing its decode EWMA as `observed_decode_tps`. Once nothing has run or waited on the slot since a decode sample older than this, the heartbeat omits the rate and the coordinator prices the Mac from its profile or the fleet, as after a reload; the next decode sample is published as measured. Off publishes the last rate however old, as 0.10.17 did. Not applied while the connected coordinator advertises `trust_status.coordinator_features` `decode_rate_age_decay`. Forwarded to the LaunchAgent. | | `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_INKLING2_DEPTH_WARMUP` | trimmed, case-insensitive `0`, `false`, `no`, `off` disable | on | `provider-swift/Sources/ProviderCore/Inference/Performance/Inkling2DepthWarmup.swift` (`enabled`) | Inkling 2 Mini only: after its shape warm-up, every draft depth 0 to 7 runs once per load on a private engine with its own scratch paged pool (the `Inkling 2 depth warmup` log line reports cells and time); off skips it and keeps the shape cells. `DARKBLOOM_TTFT_SHAPE_WARMUP=0` skips both. See the [Inkling 2 Mini reference](inkling2-mini-support.md#prompt-contract). Read when a load warms. | +| `DARKBLOOM_INKLING_MTP_MAX_DRAFT` | a whole number, clamped to 1 to 7 (surrounding whitespace ignored); other values keep the default and log a warning | `7` | `provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift` (`maxDraftTokens`) | Inkling 2 Mini only: the most drafts one DSpark round may propose. The adaptive depth policy still picks each round's depth at or below it, down to plain decode, and the verify envelope follows the cap (8 rows × (cap + 1)). Every draft is verified exactly, so tokens are unchanged; only how much a round tries changes. The load warm-up still runs depths 0 to 7. Read when the model loads. Forwarded to the LaunchAgent. | +| `DARKBLOOM_INKLING_MTP_COUPLED` | `1`, `true`, `yes`, `on` enable; `0`, `false`, `no`, `off` disable (trimmed, case-insensitive); other values keep the default | off | `provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift` (`coupledProposals`) | Inkling 2 Mini's served identities only (`Inkling2ModelIdentity.servedModelIDs`): coupled drafting (SDK `CBv2MTPConfig.coupledProposals`). A sampled row under exact acceptance proposes the keyed race its verify draw runs at each output index, instead of the draft's argmax. Output is unchanged, because exact acceptance emits only the target's own draws; only acceptance, and so speed, can move. Greedy rows, rows in a grammar and typical acceptance are unaffected. The `engine_v2: … MTP coupled drafting on` log line reports it. Read when the model loads. 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. | @@ -665,7 +671,7 @@ and rollback are defined in the [provider configuration reference](../provider/c Some switches are read by the SDK itself (`libs/mlx-swift-lm`), which keeps each of them off unless set. The provider decides their defaults (`SDKFeatureDefaults`): a switch the environment (the shell, or the LaunchAgent plist, which forwards each key) sets to a non-empty value is the operator's on every model, so `=0` is the kill switch and restores the 0.10.12 behaviour and `1` turns it on everywhere. A switch left unset or empty follows the release's default, which is on only where it was measured in its ON state: -- **Per build:** `DARKBLOOM_CONSTRAINT_SPANS` and `DARKBLOOM_CBV2_MTP_GRAMMAR` are passed to each engine's MTP configuration by the slot factory, on for the exact model ids in `constraintSpansBuilds` / `grammarMTPBuilds` (never another quantization, a fine-tune or a local path) and off for every other build; grammar MTP's default applies only where constraint spans are on (they were measured together), except on the native builds in `nativeGrammarMTPBuilds` (GLM-5.3-Flash), which have no constraint spans. `DARKBLOOM_NATIVE_REASONING_BUDGET` admits `reasoning.max_tokens` for the families in `reasoningBudgetFamilies` (`NativeReasoningBudget.isEnabled(for:)`). Penalty-row MTP is on for the exact ids in `penaltyRowBuilds` (the catalog Qwen 3.5/3.6 builds and `gemma-4-26b-qat-4bit`); `DARKBLOOM_MTP_PENALTY_ROWS` is a kill switch only (`0` keeps penalty rows target-only as in 0.10.15; `1` cannot widen the builds). Stop-string-row MTP is on for the exact ids in `stopStringRowBuilds` (`gemma-4-26b-qat-4bit`); `DARKBLOOM_MTP_STOP_STRING_ROWS` is likewise a kill switch only. The load log names the per-build switches an engine turned on. +- **Per build:** `DARKBLOOM_CONSTRAINT_SPANS` and `DARKBLOOM_CBV2_MTP_GRAMMAR` are passed to each engine's MTP configuration by the slot factory, on for the exact model ids in `constraintSpansBuilds` / `grammarMTPBuilds` (never another quantization, a fine-tune or a local path) and off for every other build; grammar MTP's default applies only where constraint spans are on (they were measured together), except on the native builds in `nativeGrammarMTPBuilds` (GLM-5.3-Flash), which have no constraint spans. `DARKBLOOM_NATIVE_REASONING_BUDGET` admits `reasoning.max_tokens` for the families in `reasoningBudgetFamilies` (`NativeReasoningBudget.isEnabled(for:)`). Penalty-row MTP is on for the exact ids in `penaltyRowBuilds` (the catalog Qwen 3.5/3.6 builds and `gemma-4-26b-qat-4bit`); `DARKBLOOM_MTP_PENALTY_ROWS` is a kill switch only (`0` keeps penalty rows target-only as in 0.10.15; `1` cannot widen the builds). Repetition-penalty-row MTP is on for the exact ids in `repetitionPenaltyRowBuilds` (the same builds); `DARKBLOOM_MTP_REPETITION_PENALTY_ROWS` is likewise a kill switch only. Stop-string-row MTP is on for the exact ids in `stopStringRowBuilds` (`gemma-4-26b-qat-4bit`); `DARKBLOOM_MTP_STOP_STRING_ROWS` is likewise a kill switch only. Logprob-row MTP is on for the exact ids in `logprobRowBuilds` (Inkling 2 Mini) and needs exact acceptance; `DARKBLOOM_MTP_LOGPROB_ROWS` is likewise a kill switch only. The load log names the per-build switches an engine turned on. - **Process-wide:** switches the SDK reads with no per-model hook (`onByDefault`; with a budget family listed, also `DARKBLOOM_NATIVE_REASONING_BUDGET`, so every engine accepts budget rows) are set by every `darkbloom` process at its entry, before any command or early branch. The process records them in `DARKBLOOM_SDK_DEFAULTS_INJECTED`, which its children inherit, so a `darkbloom` child (the desktop app's workers, a cluster service's parts) does not take them for the operator's; the marker is trusted only for the keys this mechanism injects. A default the provider injected is never written into a service plist, so an installed service follows the running release's defaults, and it does not keep a reviewed deadline profile from applying (profiles are pinned to the provider version). A shell started from a `darkbloom` child inherits the marker: a `KEY=1` exported there still counts as the release's. `darkbloom start` prints `SDK feature defaults on: …` (the switches and the builds or families they cover); `darkbloom benchmark` prints it on stderr. Which switches are on by default in this release: the Default column of each row. Source: `provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift` (`SDKFeatureDefaults`). diff --git a/docs/reference/inkling2-mini-support.md b/docs/reference/inkling2-mini-support.md index 5d1c96b181..cc69f6782a 100644 --- a/docs/reference/inkling2-mini-support.md +++ b/docs/reference/inkling2-mini-support.md @@ -17,7 +17,7 @@ Reference for the provider's side of Thinking Machines' Inkling 2 Mini (`inkling | Prefill geometry | 2,048-token prompt chunks and no solo stripe: with MLX's own prefill products (the SDK default) the engine keeps a fixed chunk grid of the scheduler's chunk and captures a prefix checkpoint only where every prompt range was exactly one grid chunk, so a solo stripe (an operator `DARKBLOOM_CBV2_SOLO_PREFILL_STRIPE` included) is not used for this model; boundaries fall at 2,048, 4,096, 6,144, ... `DARKBLOOM_CBV2_PREFILL_CHUNK` still sets the chunk, and so the grid. The step budget stays the SDK's 2,048 tokens unless `DARKBLOOM_CBV2_STEP_TOKENS` sets it (the grid gives a step's first prompt row its whole chunk past the budget), so one step carries at most one 2,048-token chunk beside its decode rows, as the solo stripe did; paged window rings and step bounds take max(chunk, stripe) = 2,048 as before | `provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+Configuration.swift` (`prefillGeometry`, `inkling2PrefillChunkTokens`) | | Image input | Images in user and tool-result messages. Each image's tower rows replace its run of token 200054 as causal tokens at scalar positions, no position state; only this model's cache bank admits causal media; content parts keep their message order into the template; video and media for a checkpoint without the tower are refused before any decode; media stays out of durable prefix checkpoints (engine rule) | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift` (`buildInkling2Submission`, `validateInkling2Media`); `provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2Factory+Production.swift` | | Prefix cache | On by policy for served identities (the global switch still wins). Complete checkpoints use the SDK's historical recurrent layout, which carries all 48 cache slots: the 8 full-attention slots' K/V for every prompt position, the 40 sliding slots' last 1,024 positions, and every slot's convolution and recurrent state; with the DSpark drafter's rounds on, the drafter's own history too (`native-paged-historical-recurrent-mtp-v1`, otherwise `native-paged-historical-recurrent-v1`). Rows are stored exactly as served: the layout takes no lossy checkpoint profile, so the fleet's default profile leaves them native (the identity records `native`). Checkpoints sit on whole 2,048-token prefill chunks; a follow-up restores the deepest one below its prompt and recomputes the rest. The store, its encryption, cache identity (weights, prompt contract, build, numerics, drafter configuration) and tenant scoping (`cacheSalt`) are the ones every complete-checkpoint model uses; media requests are not captured (engine rule) | `provider-swift/Sources/ProviderCore/Inference/PrefixCache/PrefixCachePolicy+Activation.swift` (`isEnabled`); `provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory+CompletePrefixCache.swift` (`completeCheckpointStorage`); `provider-swift/Sources/ProviderCore/Inference/PrefixCache/CompleteCheckpointStorageIdentity.swift` (`historicalRecurrent`) | -| Drafter | `mtp_config` on the native target declares the DSpark drafter in `mtp.safetensors` beside the target, outside its index. Its header is read with the inline bound; every tensor range must lie in the file; the header digest pins its tensor selection and is revalidated before load. Served on by default: the drafter loads bound to the text model (also when the VLM wrapper serves), with its own engine profile (up to 7 drafts, up to 8 speculating rows, adaptive depth down to plain decode); rows with a presence or frequency penalty or with `stop` strings draft too (`DARKBLOOM_MTP_PENALTY_ROWS`, `DARKBLOOM_MTP_STOP_STRING_ROWS`), while a repetition penalty, logprobs, `logit_bias` or a constraint keeps a row target-only; drafts are accepted exactly (a draft is kept only when it equals the target's own sample, so sampled output keeps the model's distribution) unless `mtp_acceptance` says otherwise; image rows run target-only | `provider-swift/Sources/ProviderCore/SpecDec/SpecDecStore.swift` (`declaresInkling2DSparkMTP`, `inspectInlineArtifact`, `revalidateForLoad`); `provider-swift/Sources/ProviderCore/Inference/MTP/EngineV2MTPAssistant.swift`; `EngineV2SlotFactory.swift` (`Inkling2DSparkDrafter.defaultMTPConfig()`); `provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift` (`penaltyRowBuilds`, `stopStringRowBuilds`); `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift` (`resolve`) | +| Drafter | `mtp_config` on the native target declares the DSpark drafter in `mtp.safetensors` beside the target, outside its index. Its header is read with the inline bound; every tensor range must lie in the file; the header digest pins its tensor selection and is revalidated before load. Served on by default: the drafter loads bound to the text model (also when the VLM wrapper serves), with its own engine profile (up to 7 drafts, up to 8 speculating rows, adaptive depth down to plain decode; `DARKBLOOM_INKLING_MTP_MAX_DRAFT` lowers the draft cap, see the [configuration reference](configuration.md)); rows with a presence, frequency or repetition penalty or with `stop` strings draft too (`DARKBLOOM_MTP_PENALTY_ROWS`, `DARKBLOOM_MTP_REPETITION_PENALTY_ROWS`, `DARKBLOOM_MTP_STOP_STRING_ROWS`), and rows that request `logprobs` / `top_logprobs` draft under exact acceptance, with each token's logprob and top logprobs read from the row-exact verify pass, so they equal the values without speculation (`DARKBLOOM_MTP_LOGPROB_ROWS=0` keeps them target-only; `mtp_acceptance` = `typical` keeps them target-only too), while `logit_bias` or a constraint keeps a row target-only; drafts are accepted exactly (a draft is kept only when it equals the target's own sample, so sampled output keeps the model's distribution) unless `mtp_acceptance` says otherwise; image rows run target-only | `provider-swift/Sources/ProviderCore/SpecDec/SpecDecStore.swift` (`declaresInkling2DSparkMTP`, `inspectInlineArtifact`, `revalidateForLoad`); `provider-swift/Sources/ProviderCore/Inference/MTP/EngineV2MTPAssistant.swift`; `EngineV2SlotFactory.swift` (`Inkling2DSparkDrafter.defaultMTPConfig()`); `provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift` (`penaltyRowBuilds`, `repetitionPenaltyRowBuilds`, `stopStringRowBuilds`); `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift` (`resolve`); `provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift` | ## Cache layout diff --git a/docs/reference/protocol-messages.md b/docs/reference/protocol-messages.md index fdf0500327..a1459ff728 100644 --- a/docs/reference/protocol-messages.md +++ b/docs/reference/protocol-messages.md @@ -587,7 +587,7 @@ routing on them. | `request_limits` | `*SlotRequestLimits` | `SlotRequestLimits?` | opt | The request sizes a cluster pair leader's slot serves; [schema below](#slotsrequest_limits). Omitted by a single Mac's slot and by providers before 0.10.10 | | `active_tokens` | `int64` | `Int64` | req | Σ (prompt + completion) tokens over running requests | | `max_tokens_potential` | `int64` | `Int64` | req | Σ `max_tokens` over running requests | -| `observed_decode_tps` | `float64` | `Double` | opt | EWMA of per-request decode TPS; omitted when unmeasured, and when the slot is idle and its newest decode sample is older than `DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS` (30 minutes by default) | +| `observed_decode_tps` | `float64` | `Double` | opt | EWMA of per-request decode TPS; omitted when unmeasured, and when the slot is idle and its newest decode sample is older than `DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS` (30 minutes by default), unless the connected coordinator advertises `trust_status.coordinator_features` `decode_rate_age_decay` | | `observed_decode_tps_age_ms` | (not read yet) | `Int64?` | opt | Milliseconds since the newest sample that moved `observed_decode_tps` (a reply of at least 32 tokens, or a calibration cell; `EngineV2Bridge.publishedDecodeAt`). Sent only with a published rate. Informational in this release: the provider's rate and the coordinator's ranking are unchanged until the coordinator reads it (`DecodeRateIdleAge.publishedAgeMilliseconds`) | | `observed_prefill_tps` | `float64` | `Double` | opt | Cold-prefill engine-phase EWMA, published at prompt completion; omitted when unmeasured | | `active_token_budget_used`, `active_token_budget_max`, `queued_token_budget` | `int64` | `Int64` | opt | `queued_token_budget` is hard-coded `0` by the v0.8.16 provider (`backendSlotCapacity`, `EngineV2Bridge+Capacity.swift`), so it is always omitted | @@ -1661,7 +1661,18 @@ See [revision lifecycle](../architecture/model-revisions.md). Go `TrustStatusMessage` · Swift `TrustStatus`. `trust_level` ∈ {`none`, `self_signed`, `hardware`}; `status` (`online`, `untrusted`, …); `reason` -(opt in Go, `String` in Swift). Operator diagnostics only. +(opt in Go, `String` in Swift). Operator diagnostics only, except +`coordinator_features`. + +`coordinator_features` (opt, list of strings; Swift `coordinatorFeatures`) +names coordinator behaviours a provider may rely on. Each `trust_status` +replaces the previous list, a disconnect clears it, and absent, malformed or +unknown names leave the provider as it was. `decode_rate_age_decay`: the +coordinator decays a stale `observed_decode_tps` by its +`observed_decode_tps_age_ms`, so the provider stops omitting an idle slot's +rate after `DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS` +(`DecodeRateIdleAge.coordinatorDecays`). Shared cases: +`provider-swift/Tests/ProviderCoreTests/Fixtures/Protocol/coordinator_features_wire.json`. ### `capacity_probe` diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index e7918994a7..10c5a332ee 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit e7918994a7cfb8d59896db03ce5cda925ee93b18 +Subproject commit 10c5a332ee86c6704a4e79502b48be0aaa4750b4 diff --git a/provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift b/provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift index c511ed2453..8bb0e623ec 100644 --- a/provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift +++ b/provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift @@ -16,7 +16,8 @@ import Darwin /// measured in its ON state: /// /// - Per build: the slot factory turns `constraintSpansBuilds`, -/// `grammarMTPBuilds`, `nativeGrammarMTPBuilds`, `penaltyRowBuilds` and `stopStringRowBuilds` on in that engine's +/// `grammarMTPBuilds`, `nativeGrammarMTPBuilds`, `penaltyRowBuilds`, `repetitionPenaltyRowBuilds` and +/// `stopStringRowBuilds` on in that engine's /// `CBv2MTPConfig` (`applyMTPDefaults`); `NativeReasoningBudget.isEnabled(for:)` admits /// budgets for `reasoningBudgetFamilies` only. /// - Process-wide (`onByDefault`, for what the SDK reads with no per-model @@ -50,13 +51,22 @@ public enum SDKFeatureDefaults { /// penalty speculate with exact acceptance on the catalog Qwen 3.5/3.6 /// builds (card default presence 1.5), the catalog Gemma 4 26B QAT /// build and the served Inkling 2 Mini identities (requests that send a - /// penalty). Repetition penalty rows stay target-only on every build. The - /// SDK's process kill switch `DARKBLOOM_MTP_PENALTY_ROWS=0` still wins. + /// penalty). Repetition penalty rows follow `repetitionPenaltyRowBuilds`. + /// The SDK's process kill switch `DARKBLOOM_MTP_PENALTY_ROWS=0` still wins. /// Exact catalog ids (case-sensitive, like `qwen35CardModelTypes`). static let penaltyRowBuilds: Set = Set( [EngineV2SamplingDefaults.qwen35NineBModelID, MTPAcceptancePolicy.gemmaQATModelID] ).union(MTPAcceptancePolicy.qwen35CatalogMoEModelIDs).union(Inkling2ModelIdentity.servedModelIDs) + /// SDK repetition-penalty MTP rows: rows with `repetition_penalty != 1` + /// speculate with exact acceptance on the same builds as presence/frequency + /// rows (every one drafts with target-prefix acceptance). The verifier + /// penalizes each draft position over the last `repetitionContextSize` + /// tokens of prompt, confirmed output and the drafts before it, as ordinary + /// decode does. The SDK's process kill switch + /// `DARKBLOOM_MTP_REPETITION_PENALTY_ROWS=0` still wins. Exact catalog ids. + static let repetitionPenaltyRowBuilds: Set = penaltyRowBuilds + /// SDK stop-string MTP rows: rows with `stop` strings speculate on the /// catalog Gemma 4 26B QAT build and the served Inkling 2 Mini identities; /// the round's finalize confirms committed tokens one at a time through @@ -67,6 +77,14 @@ public enum SDKFeatureDefaults { static let stopStringRowBuilds: Set = Set([MTPAcceptancePolicy.gemmaQATModelID]) .union(Inkling2ModelIdentity.servedModelIDs) + /// SDK logprob MTP rows: rows that request logprobs speculate on Inkling 2 + /// Mini, whose verify windows are row-exact, so each committed token's + /// logprobs (taken from the verify window) equal drafter-off's bit for + /// bit. The SDK applies it only under exact acceptance on a + /// `.rectangularExact` target. The SDK's process kill switch + /// `DARKBLOOM_MTP_LOGPROB_ROWS=0` still wins. Exact served ids. + static let logprobRowBuilds: Set = Inkling2ModelIdentity.servedModelIDs + /// #2099 / SDK #411: `reasoning.max_tokens` budgets, per family. static let reasoningBudgetFamilies: Set = [.nemotronSuper, .mimoV26] @@ -137,7 +155,9 @@ public enum SDKFeatureDefaults { spansBuilds: Set = constraintSpansBuilds, grammarBuilds: Set = grammarMTPBuilds, nativeGrammarBuilds: Set = nativeGrammarMTPBuilds, penaltyBuilds: Set = penaltyRowBuilds, - stopStringBuilds: Set = stopStringRowBuilds + repetitionPenaltyBuilds: Set = repetitionPenaltyRowBuilds, + stopStringBuilds: Set = stopStringRowBuilds, + logprobBuilds: Set = logprobRowBuilds ) -> [String] { func unset(_ key: String) -> Bool { followsDefault(key, in: environment, injected: []) @@ -161,6 +181,13 @@ public enum SDKFeatureDefaults { config.penaltySpeculation = true if CBv2MTPConfig.envPenaltySpeculation { on.append(MTPPenaltyRows.environmentKey) } } + // Same kill-switch-only shape (`CBv2MTPConfig.effectiveRepetitionPenaltySpeculation`). + if repetitionPenaltyBuilds.contains(modelId) { + config.repetitionPenaltySpeculation = true + if CBv2MTPConfig.envRepetitionPenaltySpeculation { + on.append(MTPRepetitionPenaltyRows.environmentKey) + } + } // Same kill-switch-only shape (`CBv2MTPConfig.effectiveStopStringSpeculation`). if stopStringBuilds.contains(modelId) { config.stopStringSpeculation = true @@ -168,9 +195,26 @@ public enum SDKFeatureDefaults { on.append(MTPStopStringRows.environmentKey) } } + // Same kill-switch-only shape (`CBv2MTPConfig.effectiveLogprobSpeculation`). + if logprobBuilds.contains(modelId) { + config.logprobSpeculation = true + if CBv2MTPConfig.envLogprobSpeculation { on.append(MTPLogprobRows.environmentKey) } + } return on } + /// Whether logprob rows draft under `config` as the round driver runs it + /// beside a drafter that requires `drafterMode`, with the mode and + /// acceptance that decide it, for the load log. + static func logprobRowsSummary( + _ config: CBv2MTPConfig, drafterMode: CBv2MTPVerificationMode? + ) -> String { + let running = config.requiring(drafterMode) + let acceptance = running.acceptance == .exact ? "exact" : "typical" + return (running.effectiveLogprobSpeculation ? "on" : "off") + + " (verification \(running.verificationMode.rawValue), acceptance \(acceptance))" + } + /// The keys to set for `environment`: every listed key it leaves unset or /// empty (an empty value is what the LaunchAgent drops, so it means unset). public static func projection( @@ -232,14 +276,19 @@ public enum SDKFeatureDefaults { spansBuilds: constraintSpansBuilds, grammarBuilds: grammarMTPBuilds, nativeGrammarBuilds: nativeGrammarMTPBuilds, penaltyBuilds: CBv2MTPConfig.envPenaltySpeculation ? penaltyRowBuilds : [], - stopStringBuilds: CBv2MTPConfig.envStopStringSpeculation ? stopStringRowBuilds : []) + repetitionPenaltyBuilds: CBv2MTPConfig.envRepetitionPenaltySpeculation + ? repetitionPenaltyRowBuilds : [], + stopStringBuilds: CBv2MTPConfig.envStopStringSpeculation ? stopStringRowBuilds : [], + logprobBuilds: CBv2MTPConfig.envLogprobSpeculation ? logprobRowBuilds : []) } static func summary(environment: [String: String], injected: Set, spansBuilds: Set, grammarBuilds: Set, nativeGrammarBuilds: Set = [], penaltyBuilds: Set = [], - stopStringBuilds: Set = []) -> String? { + repetitionPenaltyBuilds: Set = [], + stopStringBuilds: Set = [], + logprobBuilds: Set = []) -> String? { var on = injected.sorted().map { key in key == NativeReasoningBudget.environmentKey ? "\(key) (\(reasoningBudgetFamilies.map { "\($0)" }.sorted().joined(separator: ", ")))" : key @@ -253,10 +302,17 @@ public enum SDKFeatureDefaults { if !penaltyBuilds.isEmpty { on.append("\(MTPPenaltyRows.environmentKey) (\(penaltyBuilds.sorted().joined(separator: ", ")))") } + if !repetitionPenaltyBuilds.isEmpty { + on.append( + "\(MTPRepetitionPenaltyRows.environmentKey) (\(repetitionPenaltyBuilds.sorted().joined(separator: ", ")))") + } if !stopStringBuilds.isEmpty { on.append( "\(MTPStopStringRows.environmentKey) (\(stopStringBuilds.sorted().joined(separator: ", ")))") } + if !logprobBuilds.isEmpty { + on.append("\(MTPLogprobRows.environmentKey) (\(logprobBuilds.sorted().joined(separator: ", ")))") + } return on.isEmpty ? nil : "SDK feature defaults on: \(on.joined(separator: "; "))" } diff --git a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift index 61bbcab94e..b53192954c 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Connection.swift @@ -40,6 +40,7 @@ extension CoordinatorClient { let end = session.end() let delay = nextMemberAwareReconnectDelay( backoff: TimeInterval.random(in: policy.nextDelayRange(after: end))) + DecodeRateIdleAge.coordinatorDecays.reset() eventContinuation?.yield(.disconnected) let reachable = reachability.isReachable let closeCode = end.closeCode.map { "\($0)" } ?? "none" diff --git a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Inbound.swift b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Inbound.swift index 8ab82e7282..b898c83955 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Inbound.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClient+Inbound.swift @@ -88,6 +88,11 @@ extension CoordinatorClient { // A member that lost trust or runtime verification may not keep an // attachment: its session's native work is cancelled at once. if case .trustStatus(let status) = parsed, ["untrusted", "offline"].contains(status.status) { detachNativePairMember() } + // Only the connected coordinator's latest `trust_status` says whether + // it decays a stale decode rate (`DecodeRateIdleAge.coordinatorDecays`). + if case .trustStatus(let status) = parsed { + DecodeRateIdleAge.coordinatorDecays.update(features: status.coordinatorFeatures) + } if case .runtimeStatus(let status) = parsed, !status.verified || !status.mismatches.isEmpty { detachNativePairMember() } // A coordinator that does not know the member role answers its // registration like any provider's (desired builds, challenges...). diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Capacity.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Capacity.swift index 23bd706620..9b30d42b85 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Capacity.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Capacity.swift @@ -225,7 +225,7 @@ extension EngineV2Bridge { let observedDecodeTps = DecodeRateIdleAge.published(ewma: publishedDecodeTps, newestSampleAge: performanceMeasurements.observationAge("decode", now: now), idle: snapshot.activeRequests == 0 && snapshot.waitingRequests == 0, - maximum: DecodeRateIdleAge.configured) + maximum: DecodeRateIdleAge.effectiveMaximum) return BackendSlotCapacity( model: modelId, state: state, diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift index dd0f6cfe16..27a0d3b51e 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2SamplingDefaults.swift @@ -35,12 +35,14 @@ // * Resolved once at slot construction (like the stop-token set). The // sampler is not part of prompt or cache identity, so prefix-cache and // SSD checkpoint identity are unchanged. It still decides whether a row -// speculates: the engine drafts no row with a repetition penalty, and a -// row with a frequency or presence penalty only on the builds that opt in -// (`SDKFeatureDefaults.penaltyRowBuilds`: these catalog Qwen builds), on a -// drafter with target-prefix acceptance, verified with exact acceptance -// (`EngineLoopV2.mtpPenaltiesEligible`; `DARKBLOOM_MTP_PENALTY_ROWS=0` keeps -// such rows target-only). On an opted-in +// speculates: a row with a frequency or presence penalty drafts only on the +// builds that opt in (`SDKFeatureDefaults.penaltyRowBuilds`: these catalog +// Qwen builds among them), and a row with a repetition penalty only on +// `SDKFeatureDefaults.repetitionPenaltyRowBuilds`, on a drafter with +// target-prefix acceptance, verified with exact acceptance +// (`EngineLoopV2.mtpPenaltiesEligible` / `mtpRepetitionPenaltyEligible`; +// `DARKBLOOM_MTP_PENALTY_ROWS=0` / `DARKBLOOM_MTP_REPETITION_PENALTY_ROWS=0` +// keep such rows target-only). On an opted-in // history-keeping MTP head such a row still stages the resident and SSD // checkpoints a speculating row stages (prefix-cache invariant 9). diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift index 36388c319f..36e89ed285 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift @@ -309,12 +309,33 @@ enum EngineV2SlotFactory { hasBenchmarkVerificationOverride: assemblyOverrides.gemmaMTPVerification != nil), verificationMode: mtpVerification.mode, maxAutomaticRectangularTokens: mtpVerification.automaticRectangularTokens, - acceptance: mtpAcceptance.acceptance) + acceptance: mtpAcceptance.acceptance, + maxDraftPromptTokens: MTPAutomaticVerificationPolicy.maxDraftPromptTokens( + modelID: modelId, + hasBenchmarkVerificationOverride: assemblyOverrides.gemmaMTPVerification != nil)) + if assistantHandle != nil, let limit = mtpConfig.maxDraftPromptTokens { + logInfo("engine_v2: \(modelId) MTP drafts only for prompts of at most \(limit) tokens") + } if assistantHandle?.drafter is Inkling2DSparkDrafter { // The drafter's own engine profile: up to 7 drafts, up to 8 // speculating rows, adaptive depth down to plain decode. The - // operator's acceptance setting still applies. - mtpConfig = Inkling2DSparkDrafter.defaultMTPConfig() + // operator's acceptance setting still applies, + // DARKBLOOM_INKLING_MTP_MAX_DRAFT may lower the cap and + // DARKBLOOM_INKLING_MTP_COUPLED sets coupled drafting. + let maxDraft = Inkling2MTPProfilePolicy.maxDraftTokens(environment: environment) + if let unrecognized = maxDraft.unrecognized { + logWarning( + "engine_v2: unrecognized \(Inkling2MTPProfilePolicy.maxDraftKey) value " + + "\"\(unrecognized)\" for \(modelId) — using \(maxDraft.tokens)") + } else if maxDraft.tokens != Inkling2MTPProfilePolicy.defaultMaxDraftTokens { + logInfo("engine_v2: \(modelId) MTP max draft tokens \(maxDraft.tokens)") + } + let coupled = Inkling2MTPProfilePolicy.coupledProposals( + modelID: modelId, environment: environment) + if coupled { + logInfo("engine_v2: \(modelId) MTP coupled drafting on") + } + mtpConfig = Inkling2MTPProfilePolicy.engineConfig(maxDraft: maxDraft, coupled: coupled) mtpConfig.acceptance = mtpAcceptance.acceptance } // Per-build SDK switches this release turns on where they were measured; @@ -324,6 +345,15 @@ enum EngineV2SlotFactory { if !sdkDefaults.isEmpty, mtpConfig.enabled { logInfo("engine_v2: \(modelId) SDK feature defaults on: \(sdkDefaults.joined(separator: ", "))") } + if mtpConfig.logprobSpeculation, mtpConfig.enabled { + // As the round driver runs it: the drafter's required mode replaces + // the declared one, and the SDK takes the opt-in only on an exact + // verify path (`CBv2MTPConfig.effectiveLogprobSpeculation`). + logInfo( + "engine_v2: \(modelId) MTP logprob rows: " + + SDKFeatureDefaults.logprobRowsSummary( + mtpConfig, drafterMode: assistantHandle?.drafter?.requiredVerificationMode)) + } if let verification = assemblyOverrides.gemmaMTPVerification { mtpConfig = try verification.applying( to: mtpConfig, target: servingModel, drafter: assistantHandle?.drafter) diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index afe32499ef..ed03d5d819 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -1489,7 +1489,10 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { rewriteHarmonyFinalHeaders: HarmonyFinalHeaderFilter.applies(to: request, modelId: modelId, modelType: modelType), nativeInklingChannels: Inkling2PromptContract.applies(modelType: modelType), inklingStreamsCalls: Inkling2PromptContract.applies(modelType: modelType) - && ToolStreamPreparation.streamsInklingCalls(request: request, prepared: prepared) + && ToolStreamPreparation.streamsInklingCalls(request: request, prepared: prepared), + harmonyCallRecovery: GPTOSSToolCallRecovery.make(modelType: modelType, format: toolHandler?.format, + prepared: prepared, loopExit: loopGuard == nil ? nil : exitThinking?.record, + enabled: GPTOSSToolCallRecovery.enabled) ) } @@ -1875,7 +1878,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { withholdReasoning: Bool = false, rewriteHarmonyFinalHeaders: Bool = false, nativeInklingChannels: Bool = false, - inklingStreamsCalls: Bool = false + inklingStreamsCalls: Bool = false, + harmonyCallRecovery: GPTOSSToolCallRecovery? = nil ) async throws -> AsyncThrowingStream { do { try checkFirstContentDeadline() @@ -1908,7 +1912,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { withholdReasoning: withholdReasoning, rewriteHarmonyFinalHeaders: rewriteHarmonyFinalHeaders, nativeInklingChannels: nativeInklingChannels, - inklingStreamsCalls: inklingStreamsCalls) + inklingStreamsCalls: inklingStreamsCalls, + harmonyCallRecovery: harmonyCallRecovery) try checkFirstContentDeadline() return stream } catch { @@ -1950,8 +1955,11 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { withholdReasoning: Bool = false, rewriteHarmonyFinalHeaders: Bool = false, nativeInklingChannels: Bool = false, - inklingStreamsCalls: Bool = false + inklingStreamsCalls: Bool = false, + harmonyCallRecovery: GPTOSSToolCallRecovery? = nil ) throws -> AsyncThrowingStream { + // Read where the stream starts, inside the coordinator path's scope. + let withheldReasoningHeartbeat = InklingWithheldReasoningHeartbeat.enabled // One forwarding implementation preserves all parser/event bytes. The // native path changes only task ownership and cancellation handoff. let forward: @Sendable (AsyncThrowingStream.Continuation, @@ -1983,7 +1991,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { absorbStrayThinkClose: absorbStrayThinkClose, withholdReasoning: withholdReasoning, streamedCalls: prepared, streamsGLMCalls: streamsGLMCalls, - nativeInklingChannels: nativeInklingChannels, inklingStreamsCalls: inklingStreamsCalls) + nativeInklingChannels: nativeInklingChannels, inklingStreamsCalls: inklingStreamsCalls, + withheldReasoningHeartbeat: withheldReasoningHeartbeat) // Withheld reasoning must not return as logprob entry tokens. A // prompt that opens the thought (GLM with thinking on, which // seeds the native channel with an open block) starts inside it. @@ -2000,9 +2009,11 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { // Qwen answer was compiled with. var formatOutput = (answerFormat ?? prepared.responseFormat).map(JSONAnswerOutput.init) var glmAnswer = prepared.glmResponseFormat.map(GLM5NextResponseFormatOutput.init) + // GPT-OSS calls its Harmony parser does not see (`GPTOSSToolCallRecovery`). + var callRecovery = harmonyCallRecovery /// A GLM JSON answer leaves only after it validates; its /// reasoning and every other event stream unchanged. - func emit(_ routed: MLXServerGenerationEvent) { + func send(_ routed: MLXServerGenerationEvent) { formatOutput?.observe(routed) if glmAnswer == nil { continuation.yield(routed) @@ -2013,6 +2024,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { } router.responseStarted = true } + func emit(_ event: MLXServerGenerationEvent) { + for routed in callRecovery?.route(event) ?? [event] { send(routed) } + } startedAt = Date() #if DEBUG @@ -2278,6 +2292,11 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { let settled = try router.finishToolCalls(truncated: stopReason == "length", cutAtLimit: cutAtLimit) for routed in flushed + settled { emit(routed) } + if let recovered = callRecovery?.finish(stopReason: stopReason, cutAtLimit: cutAtLimit, + hasCalls: !router.completedToolCalls.isEmpty) { + for routed in recovered.release { send(routed) } + if let call = recovered.call { for routed in try router.recovered(call) { send(routed) } } + } if !cutAtLimit { try router.checkNativeToolFailure() } // A cut ends `length` (`TokenLimitCutPolicy`): a forced call it left // open is not a missing call, as on the complete-call path. @@ -2350,6 +2369,11 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { if prepared.mode == .auto, let residual, !residual.isEmpty, !router.hasNativeToolFailure { emit(router.visibleEvent(residual)) } + if let recovered = callRecovery?.finish(stopReason: stopReason, cutAtLimit: cutAtLimit, + hasCalls: !toolCalls.isEmpty) { + for routed in recovered.release { send(routed) } + if let call = recovered.call { toolCalls = [call] } + } if prepared.mode == .auto, !cutAtLimit, (toolHandler?.parseFailureCount ?? 0) > 0 { emitToolConstraintTelemetry( operation: "tool_constraint_fallback", @@ -2470,7 +2494,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { rewriteHarmonyFinalHeaders: Bool = false, nativeMiMoChannels: Bool = false, nativeMiMoThinkingEnabled: Bool = true, - withholdReasoning: Bool = false + withholdReasoning: Bool = false, + harmonyCallRecovery: GPTOSSToolCallRecovery? = nil ) throws -> AsyncThrowingStream { try makeEventStream(upstream: upstream, cancelUpstream: cancelUpstream, toolHandler: toolHandler, prepared: prepared, releaseBox: releaseBox, @@ -2481,7 +2506,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { nativeMiMoChannels: nativeMiMoChannels, nativeMiMoThinkingEnabled: nativeMiMoThinkingEnabled, absorbStrayThinkClose: absorbStrayThinkClose, answerStopFilter: answerStopFilter, answerFormat: answerFormat, withholdReasoning: withholdReasoning, - rewriteHarmonyFinalHeaders: rewriteHarmonyFinalHeaders) + rewriteHarmonyFinalHeaders: rewriteHarmonyFinalHeaders, harmonyCallRecovery: harmonyCallRecovery) } #endif diff --git a/provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift b/provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift new file mode 100644 index 0000000000..17c2912c62 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/MTP/Inkling2MTPProfilePolicy.swift @@ -0,0 +1,73 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLLM +import MLXLMCommon + +/// Operator overrides of Inkling 2's DSpark engine profile +/// (`Inkling2DSparkDrafter.defaultMTPConfig`). Tokens are unaffected: every +/// draft is verified exactly, so a cap changes only how much one round tries. +public enum Inkling2MTPProfilePolicy { + /// `DARKBLOOM_INKLING_MTP_MAX_DRAFT`: the most drafts one round may + /// propose. The adaptive depth policy still picks each round's depth at + /// or below it, down to plain decode. + public static let maxDraftKey = "DARKBLOOM_INKLING_MTP_MAX_DRAFT" + /// The drafter's whole block: the shipped cap. + public static let defaultMaxDraftTokens = 7 + + public struct MaxDraft: Equatable, Sendable { + public let tokens: Int + /// The raw value when it was not a whole number (the default applies). + public let unrecognized: String? + } + + /// Unset or blank: 7. A whole number is clamped to 1...7. Anything else + /// keeps 7 and is reported. + public static func maxDraftTokens( + environment: [String: String] = ProcessInfo.processInfo.environment + ) -> MaxDraft { + guard let raw = environment[maxDraftKey]?.trimmingCharacters(in: .whitespacesAndNewlines), + !raw.isEmpty + else { return MaxDraft(tokens: defaultMaxDraftTokens, unrecognized: nil) } + guard let value = Int(raw) else { + return MaxDraft(tokens: defaultMaxDraftTokens, unrecognized: raw) + } + return MaxDraft(tokens: min(max(value, 1), defaultMaxDraftTokens), unrecognized: nil) + } + + /// `DARKBLOOM_INKLING_MTP_COUPLED`: coupled drafting + /// (`CBv2MTPConfig.coupledProposals`) for the served Inkling 2 identities. + /// A sampled row under exact acceptance proposes the keyed race its verify + /// draw runs instead of the draft's argmax; output is unchanged, only + /// acceptance can move. + public static let coupledKey = "DARKBLOOM_INKLING_MTP_COUPLED" + /// The default when the switch is unset. Changes only on measured data. + public static let coupledByDefault = false + + /// On for `1`, `true`, `yes` or `on`; off for `0`, `false`, `no` or `off` + /// (trimmed, any letter case); unset or anything else keeps the default. + /// Never on for an identity outside `Inkling2ModelIdentity.servedModelIDs`. + public static func coupledProposals( + modelID: String, environment: [String: String] = ProcessInfo.processInfo.environment + ) -> Bool { + guard Inkling2ModelIdentity.isServedModelID(modelID) else { return false } + let raw = environment[coupledKey]?.trimmingCharacters(in: .whitespacesAndNewlines) + .lowercased() + switch raw { + case "1", "true", "yes", "on": return true + case "0", "false", "no", "off": return false + default: return coupledByDefault + } + } + + /// Inkling's engine profile with the operator's cap and coupling, through + /// the drafter's own profile (`Inkling2DSparkDrafter.defaultMTPConfig`). + public static func engineConfig( + maxDraft: MaxDraft, coupled: Bool = false, adaptive: Bool = true, + maxSpeculativeRows: Int = 8 + ) -> CBv2MTPConfig { + Inkling2DSparkDrafter.defaultMTPConfig( + maxDraftTokens: maxDraft.tokens, adaptive: adaptive, + maxSpeculativeRows: maxSpeculativeRows, coupledProposals: coupled) + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift b/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift index 8dc318c88d..9085da7a42 100644 --- a/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift @@ -91,6 +91,17 @@ public enum MTPPenaltyRows { public static let environmentKey = "DARKBLOOM_MTP_PENALTY_ROWS" } +/// On the builds in `SDKFeatureDefaults.repetitionPenaltyRowBuilds` (the +/// catalog Qwen 3.5/3.6 builds, Gemma 4 26B QAT and Inkling 2 Mini), rows with +/// a repetition penalty speculate: the engine re-derives the penalty over each +/// verify position's window (prompt, confirmed output, earlier drafts), always +/// with exact acceptance. The SDK reads the switch once per process +/// (`CBv2MTPConfig.envRepetitionPenaltySpeculation`); the LaunchAgent forwards +/// it. `0`, `false`, `no` or `off` keeps such rows target-only. +public enum MTPRepetitionPenaltyRows { + public static let environmentKey = "DARKBLOOM_MTP_REPETITION_PENALTY_ROWS" +} + /// On the builds in `SDKFeatureDefaults.stopStringRowBuilds` (the catalog /// Gemma 4 26B QAT build and Inkling 2 Mini), rows with `stop` strings speculate; the round's /// finalize ends the row at the first match. The SDK reads the switch once @@ -99,3 +110,15 @@ public enum MTPPenaltyRows { public enum MTPStopStringRows { public static let environmentKey = "DARKBLOOM_MTP_STOP_STRING_ROWS" } + +/// On the builds in `SDKFeatureDefaults.logprobRowBuilds` (Inkling 2 Mini, +/// whose verify windows are row-exact), rows that request logprobs +/// speculate; each committed token's logprobs come from the verify window, +/// the values a one-token decode step gives. The SDK takes this only with +/// exact acceptance (`CBv2MTPConfig.effectiveLogprobSpeculation`). It reads +/// the switch once per process (`CBv2MTPConfig.envLogprobSpeculation`); the +/// LaunchAgent forwards it. `0`, `false`, `no` or `off` keeps such rows +/// target-only. +public enum MTPLogprobRows { + public static let environmentKey = "DARKBLOOM_MTP_LOGPROB_ROWS" +} diff --git a/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAutomaticVerificationPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAutomaticVerificationPolicy.swift index 5b2603a4dc..0dd975fad2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAutomaticVerificationPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/MTP/MTPAutomaticVerificationPolicy.swift @@ -74,6 +74,66 @@ public enum MTPAutomaticVerificationPolicy { chipName ?? (try? sysctlString("machdep.cpu.brand_string")) ?? "Unknown" } + /// The operator's Gemma draft prompt-length setting + /// (`DARKBLOOM_GEMMA_MTP_MAX_PROMPT_TOKENS`). + enum GemmaDraftPromptLimit: Equatable { + /// Unset, empty or not a positive integer: the chip's measured limit. + case chipDefault + /// `0`, `off`, `false` or `no`: no limit; every prompt drafts. + case off + /// A positive integer: that limit on the chips that have one. + case tokens(Int) + + init(_ raw: String?) { + let value = raw?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "" + if ["0", "off", "false", "no"].contains(value) { + self = .off + } else if let tokens = Int(value), tokens > 0 { + self = .tokens(tokens) + } else { + self = .chipDefault + } + } + } + + /// `DARKBLOOM_GEMMA_MTP_MAX_PROMPT_TOKENS`: under the two-draft policy on + /// M5 Ultra, a Gemma 4 26B QAT decode step whose speculation-eligible rows + /// all have prompts over the limit runs without drafts + /// (`CBv2MTPConfig.maxDraftPromptTokens`); a row under the limit keeps the + /// chip's table. Unset: `gemmaM5UltraMaxDraftPromptTokens`; + /// `0` (or `off`, `false`, `no`): no limit, the earlier behaviour; a + /// positive integer: that limit. Other chips never get one. Read once per + /// process. + public static let gemmaMaxDraftPromptTokensEnvironmentKey = + "DARKBLOOM_GEMMA_MTP_MAX_PROMPT_TOKENS" + static let gemmaDraftPromptLimit = GemmaDraftPromptLimit( + ProcessInfo.processInfo.environment[gemmaMaxDraftPromptTokensEnvironmentKey]) + /// On a quiet M5 Ultra a lone row's two-draft rounds lose to plain decode + /// above this prompt length. + static let gemmaM5UltraMaxDraftPromptTokens = 16384 + /// Whether an unset `DARKBLOOM_GEMMA_MTP_MAX_PROMPT_TOKENS` applies the + /// chip's limit. False gives every chip no limit unless the operator sets + /// a positive value. + static let gemmaPromptLimitOnByDefault = true + + /// The prompt-length limit for drafting for `modelID` on this chip, or nil + /// for no limit. + static func maxDraftPromptTokens( + modelID: String?, chipName: String? = nil, hasBenchmarkVerificationOverride: Bool = false, + twoDrafts: Bool? = nil, limit: GemmaDraftPromptLimit? = nil, + onByDefault: Bool = gemmaPromptLimitOnByDefault + ) -> Int? { + guard modelID == MTPAcceptancePolicy.gemmaQATModelID, !hasBenchmarkVerificationOverride, + twoDrafts ?? gemmaTwoDraftsEnabled, + case (.m5, .ultra) = parseChipIdentity(resolvedChipName(chipName)) + else { return nil } + switch limit ?? gemmaDraftPromptLimit { + case .chipDefault: return onByDefault ? gemmaM5UltraMaxDraftPromptTokens : nil + case .off: return nil + case .tokens(let tokens): return tokens + } + } + /// The per-row depth table for `modelID` on this chip, or nil. static func fixedDraftTokensByDecodeRows( modelID: String?, chipName: String? = nil, hasBenchmarkVerificationOverride: Bool = false, diff --git a/provider-swift/Sources/ProviderCore/Inference/Performance/DecodeRateIdleAge.swift b/provider-swift/Sources/ProviderCore/Inference/Performance/DecodeRateIdleAge.swift index 51c28d6d8a..77c23cdc1e 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Performance/DecodeRateIdleAge.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Performance/DecodeRateIdleAge.swift @@ -19,6 +19,10 @@ import Foundation /// coordinator's idle measurement age; a positive whole number of seconds sets /// it; `0`, `false`, `no` or `off` (trimmed, case-insensitive) publishes the /// last rate however old, as 0.10.17 did. Any other value keeps the default. +/// +/// A coordinator that decays a stale rate by its age advertises +/// `decode_rate_age_decay` in `trust_status.coordinator_features`; while it +/// does, the heartbeat publishes the rate and its age instead (`effectiveMaximum`). enum DecodeRateIdleAge { static let environmentKey = "DARKBLOOM_DECODE_RATE_IDLE_MAX_AGE_SECONDS" static let defaultMaximum: Duration = .seconds(1_800) @@ -33,6 +37,30 @@ enum DecodeRateIdleAge { return .seconds(seconds) } + /// The `trust_status.coordinator_features` entry of a coordinator that + /// decays a stale published decode rate itself, by its + /// `observed_decode_tps_age_ms`. + static let coordinatorDecayFeature = "decode_rate_age_decay" + + /// Whether the connected coordinator advertised `coordinatorDecayFeature` + /// in its latest `trust_status`. False until it does, and again after a + /// disconnect or a `trust_status` without it. + static let coordinatorDecays = CoordinatorDecayAdvertisement() + + /// Tests set this to price one heartbeat without the process-wide value. + @TaskLocal static var coordinatorDecaysOverride: Bool? + + /// The maximum the heartbeat applies: none while the coordinator decays a + /// stale rate itself (it then sees the rate and its age), else `configured`. + static func effectiveMaximum(configured: Duration?, coordinatorDecays: Bool) -> Duration? { + coordinatorDecays ? nil : configured + } + + static var effectiveMaximum: Duration? { + effectiveMaximum(configured: configured, + coordinatorDecays: coordinatorDecaysOverride ?? coordinatorDecays.value) + } + /// The decode rate the heartbeat publishes: `ewma`, or zero when the slot /// is idle and its newest decode sample is older than `maximum`. static func published(ewma: Double, newestSampleAge: Duration?, idle: Bool, maximum: Duration?) -> Double { @@ -52,3 +80,21 @@ enum DecodeRateIdleAge { return age.components.seconds * 1_000 + age.components.attoseconds / 1_000_000_000_000_000 } } + +/// The connected coordinator's `decode_rate_age_decay` advertisement +/// (`DecodeRateIdleAge.coordinatorDecays`). +final class CoordinatorDecayAdvertisement: @unchecked Sendable { + private let lock = NSLock() + private var advertised = false + + var value: Bool { lock.withLock { advertised } } + + /// From one `trust_status`: nil (an older coordinator) or a list without + /// the feature keeps the provider's idle age. + func update(features: [String]?) { + let decays = features?.contains(DecodeRateIdleAge.coordinatorDecayFeature) ?? false + lock.withLock { advertised = decays } + } + + func reset() { lock.withLock { advertised = false } } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/InklingWithheldReasoningHeartbeat.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/InklingWithheldReasoningHeartbeat.swift new file mode 100644 index 0000000000..eff7c2630e --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/InklingWithheldReasoningHeartbeat.swift @@ -0,0 +1,50 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMServer + +/// One empty answer delta when an Inkling 2 request starts withholding its +/// reasoning (`Inkling2PromptContract.withholdsReasoning`). +/// +/// With reasoning off the model still thinks, and the provider streams +/// nothing until the answer: the only frame before it is the role-only +/// preamble, which the coordinator holds as boilerplate, so a long thought +/// ends at its first-content deadline. When withholding starts, the router +/// emits `event` once; the coordinator serving path rewrites its frame to a +/// plain chunk whose delta is `{"content": ""}` (`frame(rewriting:)`): no +/// `role`, no reasoning field, no finish reason, no usage, and nothing +/// derived from the withheld text. An empty `content` delta is a legal +/// OpenAI streaming chunk that clients append as nothing. +/// +/// Only the coordinator serving path turns it on (`enabled`, set around the +/// stream's start); every other path, every other model and reasoning-on +/// Inkling streams are unchanged. +enum InklingWithheldReasoningHeartbeat { + /// Set by the coordinator serving path while it starts a stream. + @TaskLocal static var enabled = false + + /// The router's event. The SDK's stream encoder writes it as a chunk whose + /// delta holds only the two reasoning fields, both empty, a frame no other + /// event produces (empty reasoning is never emitted). + static let event = MLXServerGenerationEvent.parsed(.init(content: "", reasoningContent: "")) + + /// `frame` with its delta replaced by `{"content": ""}` when it is the + /// encoded `event`, keeping the chunk's id, model and creation time; nil + /// for every other frame. + static func frame(rewriting frame: String) -> String? { + guard frame.contains(#""reasoning_content":"""#), frame.hasPrefix("data: ") else { return nil } + let json = frame.dropFirst("data: ".count).trimmingCharacters(in: .whitespacesAndNewlines) + guard let chunk = try? JSONDecoder().decode(OpenAIChatCompletionChunk.self, from: Data(json.utf8)), + chunk.object == "chat.completion.chunk", chunk.usage == nil, chunk.choices.count == 1, + let choice = chunk.choices.first, choice.finishReason == nil, choice.logprobs == nil, + choice.delta == .init(role: nil, content: nil, reasoningContent: "", toolCalls: nil) + else { return nil } + let heartbeat = OpenAIChatCompletionChunk( + id: chunk.id, model: chunk.model, + choices: [.init(index: choice.index, + delta: .init(role: nil, content: "", reasoningContent: nil, toolCalls: nil), + finishReason: nil)], + usage: nil, created: chunk.created) + return try? ServerSentEventEncoder.encode(heartbeat) + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift index 3fd5e79cdb..57e313c7c7 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift @@ -22,6 +22,10 @@ struct NativeToolStreamRouter { private var rejectedNativeGemmaReasoning = false private let withholdReasoning: Bool private var withheldReasoning = "" + /// Inkling 2: one empty answer delta when withholding starts + /// (`InklingWithheldReasoningHeartbeat`). + private let withheldReasoningHeartbeat: Bool + private var sentWithheldReasoningHeartbeat = false private let tools: [[String: any Sendable]]? /// An `auto` GLM tool suffix that does not parse at EOS is text /// (`GLM5ToolSuffix`). @@ -90,9 +94,11 @@ struct NativeToolStreamRouter { glmUnparsedOutputIsText: Bool = GLM5ToolSuffix.returnsUnparsedOutputAsTextByDefault, harmonyAutoToolGrammar: Bool = GPTOSSAutoToolGrammar.enabled, nativeInklingChannels: Bool = false, inklingStreamsCalls: Bool = false, - inklingUndeclaredCallsAreText: Bool = Inkling2OutputChannels.undeclaredCallsAreTextByDefault) { + inklingUndeclaredCallsAreText: Bool = Inkling2OutputChannels.undeclaredCallsAreTextByDefault, + withheldReasoningHeartbeat: Bool = false) { self.handler = handler self.withholdReasoning = withholdReasoning + self.withheldReasoningHeartbeat = withheldReasoningHeartbeat && withholdReasoning && nativeInklingChannels self.tools = tools self.glmUnparsedOutputIsText = glmUnparsedOutputIsText self.requiresToolCall = requiresToolCall @@ -254,6 +260,13 @@ struct NativeToolStreamRouter { return events } + /// A call recovered at the end of generation (`GPTOSSToolCallRecovery`), + /// exposed and checked as a call never streamed is. + mutating func recovered(_ call: ToolCall) throws -> [MLXServerGenerationEvent] { + guard let prepared = streamedCallPolicy else { return [] } + return try routeToolSegment(.call(call), prepared: prepared) + } + private mutating func recordCut(leftOpen: Bool) { if leftOpen { callsLeftOpenAtCut += 1 } else { callsDroppedAtCut += 1 } } @@ -377,6 +390,10 @@ struct NativeToolStreamRouter { guard !reasoning.isEmpty else { continue } if withholdReasoning { withheldReasoning += reasoning + if withheldReasoningHeartbeat, !sentWithheldReasoningHeartbeat { + sentWithheldReasoningHeartbeat = true + events.append(InklingWithheldReasoningHeartbeat.event) + } } else { events.append(.parsed(.init(content: "", reasoningContent: reasoning))) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/GPTOSSAutoToolConstraint.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/GPTOSSAutoToolConstraint.swift index 0577086cd6..1a0ac6d33d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Tools/GPTOSSAutoToolConstraint.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/GPTOSSAutoToolConstraint.swift @@ -103,7 +103,7 @@ enum GPTOSSAutoToolGrammar { let byName = Dictionary(declared.map { ($0.function.name, $0) }, uniquingKeysWith: { first, _ in first }) return rendered.map { tool in guard let declaration = byName[tool.function.name], !holdsReference(tool) else { return nil } - let resolved = resolvingRefs(declaration) + let resolved = withoutRenderHintTypes(resolvingRefs(declaration)) if let exact = try? ToolConstraintSchemaCompiler.compile(tools: [resolved], mode: .auto).first { return exact } @@ -111,6 +111,62 @@ enum GPTOSSAutoToolGrammar { } } + /// The declaration with each `type` that only names a render hint + /// removed: the type the ingress repair writes beside a union naming one + /// of its branches, a mixed `enum`, a `not` of that type or an + /// `if`/`then`/`else` typed otherwise + /// (`QwenParserLiteralReading.rendersSiblingType`, the rule the call + /// parser and the strict check already read). Compiled as a hard type it + /// held a union's arguments to its first branch (`"-4200"` for `-4200`). + /// Every other node, and a declaration without such a type, is returned + /// unchanged. + static func withoutRenderHintTypes(_ tool: OpenAITool) -> OpenAITool { + guard let parameters = tool.function.parameters else { return tool } + let unhinted = withoutRenderHintTypes(parameters, depth: 0) + guard unhinted != parameters else { return tool } + var copy = tool + copy.function.parameters = unhinted + return copy + } + + /// A hinted node marked `nullable` admits null whatever its type, as the + /// strict check reads it; without the type, its union or `enum` must carry + /// null itself so the grammar admits it too. + private static func admittingNull(_ object: inout [String: MLXLMCommon.JSONValue]) { + for key in ["anyOf", "oneOf"] { + guard case .array(var branches)? = object[key] else { continue } + if !branches.contains(where: isNullBranch) { + branches.append(.object(["type": .string("null")])) + object[key] = .array(branches) + } + } + if case .array(var members)? = object["enum"], !members.contains(.null) { + members.append(.null) + object["enum"] = .array(members) + } + } + + private static func withoutRenderHintTypes(_ schema: MLXLMCommon.JSONValue, depth: Int) -> MLXLMCommon.JSONValue { + guard depth <= ToolConstraintSchemaCompiler.maxDepth, case .object(var object) = schema else { return schema } + if QwenParserLiteralReading.rendersSiblingType(object) { + object.removeValue(forKey: "type") + if object["nullable"] == .bool(true) { admittingNull(&object) } + } + for key in ["anyOf", "oneOf", "allOf", "prefixItems"] { + guard case .array(let branches)? = object[key] else { continue } + object[key] = .array(branches.map { withoutRenderHintTypes($0, depth: depth + 1) }) + } + for key in ["properties", "patternProperties", "$defs", "definitions"] { + guard case .object(let entries)? = object[key] else { continue } + object[key] = .object(entries.mapValues { withoutRenderHintTypes($0, depth: depth + 1) }) + } + for key in ["items", "additionalProperties", "not", "if", "then", "else"] { + guard case .object? = object[key] else { continue } + object[key] = withoutRenderHintTypes(object[key]!, depth: depth + 1) + } + return .object(object) + } + /// A schema outside the subset as written, in the shapes agent clients /// send every day (Pydantic's `anyOf` with `null`, zod's root `$schema`, /// `minimum`, `format`, …): compiled through `ResponseSchemaRewrite` diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/GPTOSSToolCallRecovery.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/GPTOSSToolCallRecovery.swift new file mode 100644 index 0000000000..99e8d38bf1 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/GPTOSSToolCallRecovery.swift @@ -0,0 +1,202 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon +import MLXLMServer + +/// GPT-OSS calls the Harmony parser does not see, for an `auto` request that +/// declares tools. Two shapes, each recovered only when it is a whole, +/// declared and valid call: +/// +/// - **Arguments as the answer.** After the loop guard ended the analysis +/// (`GenerationLoopExitThinking.harmonyAnalysis`), the model sometimes +/// answers in the next message without a recipient: the final (or a +/// recipientless commentary) message is the call's JSON object and nothing +/// else. The answer after the exit is held to the end of generation; when it +/// is a single JSON object that exactly one declared tool admits (every key +/// a declared property, and the caller's schema holds: +/// `ToolConstraintValidation.breaksDeclaration`), it leaves as a call to +/// that tool instead. Anything else leaves as it was written. +/// - **A call frame inside the analysis.** The model sometimes writes its +/// call as text inside an analysis message it never closes, and generation +/// stops right after it. When the open analysis ends with a complete frame, +/// `to=functions.`, its header and `<|message|>`, then one JSON object +/// and nothing else, for a declared function whose schema holds the +/// arguments, it leaves as that call. A partial frame never does. +/// +/// vLLM returns both as text (or nothing). Neither changes a rendered prompt. +/// +/// `DARKBLOOM_GPTOSS_TOOL_CALL_RECOVERY`: unset or any other value keeps it on; +/// `0`, `off`, `false` or `no` turns it off. Read once per process. +struct GPTOSSToolCallRecovery: Sendable { + static let environmentKey = "DARKBLOOM_GPTOSS_TOOL_CALL_RECOVERY" + static let enabled = isEnabled(environment: ProcessInfo.processInfo.environment) + + static func isEnabled(environment: [String: String]) -> Bool { + !ToolOutputLeniencySwitch.isOff(environment[environmentKey]) + } + + /// The most visible text kept for the analysis check: a frame is a header + /// and one argument object. + static let tailLimit = 16_384 + + private static let startMarker = "<|start|>assistant" + private static let analysisOpener = "<|channel|>analysis<|message|>" + private static let messageMarker = "<|message|>" + private static let messageEnds = ["<|end|>", "<|return|>", "<|call|>"] + + private let prepared: ToolChoicePromptPolicy.Prepared + private let loopExit: GenerationLoopExitRecord? + /// The answer after the loop guard's exit, held to the end of generation. + private var held: [MLXServerGenerationEvent] = [] + private var heldText = "" + /// The last `tailLimit` characters of the visible text. + private var tail = "" + /// A call or delta already left: nothing is recovered. + private var sawCall = false + + /// The recovery for a request, or nil where it does not apply: GPT-OSS's + /// Harmony call parser, `auto` with declared tools. + static func make( + modelType: String?, format: ToolCallFormat?, prepared: ToolChoicePromptPolicy.Prepared, + loopExit: GenerationLoopExitRecord?, enabled: Bool = true + ) -> GPTOSSToolCallRecovery? { + guard enabled, modelType == "gpt_oss", format == .harmony, prepared.mode == .auto, + !prepared.allowedToolNames.isEmpty, prepared.tools?.isEmpty == false else { return nil } + return GPTOSSToolCallRecovery(prepared: prepared, loopExit: loopExit) + } + + init(prepared: ToolChoicePromptPolicy.Prepared, loopExit: GenerationLoopExitRecord?) { + self.prepared = prepared + self.loopExit = loopExit + } + + /// The events to send now. Visible text after the loop guard's exit is + /// held; a call releases what is held, in order, before itself. + mutating func route(_ event: MLXServerGenerationEvent) -> [MLXServerGenerationEvent] { + switch event { + case .content(let text): + tail += text + if tail.count > Self.tailLimit { tail = String(tail.suffix(Self.tailLimit)) } + guard !sawCall, loopExit?.requested != nil else { return [event] } + held.append(event) + heldText += text + return [] + case .toolCall, .toolCallDelta: + sawCall = true + defer { held = []; heldText = "" } + return held + [event] + default: + return [event] + } + } + + /// End of generation: the recovered call, or nil with the held events to + /// send as they were. Only an answer that ended with a stop and has no + /// call recovers one. + mutating func finish(stopReason: String, cutAtLimit: Bool, hasCalls: Bool) + -> (call: ToolCall?, release: [MLXServerGenerationEvent]) + { + defer { held = []; heldText = "" } + guard !sawCall, !hasCalls, !cutAtLimit, stopReason == "stop" else { return (nil, held) } + if loopExit?.requested != nil, !heldText.isEmpty { + if let call = Self.answerCall(afterExit: heldText, prepared: prepared) { return (call, []) } + return (nil, held) + } + if let call = Self.analysisCall(tail, prepared: prepared) { return (call, held) } + return (nil, held) + } + + // MARK: - The two shapes + + /// The call an answer after the exit spells: its last message, a `final` + /// or recipientless `commentary` header and a single JSON object, that + /// exactly one declared tool admits. + static func answerCall(afterExit text: String, prepared: ToolChoicePromptPolicy.Prepared) -> ToolCall? { + guard let opener = text.range(of: messageMarker, options: .backwards), + let channel = text[..", options: .backwards) + else { return nil } + // The message starts there: the exit's assistant start precedes its channel. + guard text[.. ToolCall? in + let call = ToolCall(function: .init(name: name, arguments: arguments)) + return admits(call, prepared: prepared) ? call : nil + } + return matches.count == 1 ? matches[0] : nil + } + + /// The call a still-open analysis message ends with: the text after its + /// last recipient, `to=functions.`, is the rest of a call header, + /// `<|message|>` and a single JSON object, for a declared function whose + /// schema holds it. + static func analysisCall(_ text: String, prepared: ToolChoicePromptPolicy.Prepared) -> ToolCall? { + guard let analysis = text.range(of: analysisOpener, options: .backwards) else { return nil } + let body = text[analysis.upperBound...] + // The analysis is still open: no message end and no new message after it. + guard messageEnds.allSatisfy({ !body.contains($0) }), !body.contains("<|start|>") else { return nil } + guard let recipient = body.range(of: "to=functions.", options: .backwards) else { return nil } + let frame = body[recipient.upperBound...] + guard let opener = frame.range(of: messageMarker) else { return nil } + let head = frame[..final` or `<|channel|>commentary`, with no recipient, an + /// optional `json` or `<|constrain|>json` content type. + private static func isAnswerHeader(_ header: Substring) -> Bool { + guard !header.contains("to=") else { return false } + var rest = header.trimmingCharacters(in: .whitespaces) + guard rest.hasPrefix("<|channel|>") else { return false } + rest.removeFirst("<|channel|>".count) + for channel in ["final", "commentary"] where rest.hasPrefix(channel) { + return isContentType(rest.dropFirst(channel.count)) + } + return false + } + + /// What may follow the function name in a call header: an optional + /// `<|channel|>commentary` and an optional content type. + private static func isCallHeaderRest(_ rest: Substring) -> Bool { + var rest = rest.trimmingCharacters(in: .whitespaces) + if rest.hasPrefix("<|channel|>") { + rest.removeFirst("<|channel|>".count) + guard rest.hasPrefix("commentary") else { return false } + rest.removeFirst("commentary".count) + } + return isContentType(Substring(rest)) + } + + private static func isContentType(_ text: Substring) -> Bool { + let type = text.replacingOccurrences(of: "<|constrain|>", with: " ") + .trimmingCharacters(in: .whitespaces) + return type.isEmpty || type == "json" + } + + /// The text as one JSON object and nothing else (surrounding whitespace + /// aside). + private static func jsonObject(_ text: Substring) -> [String: MLXLMCommon.JSONValue]? { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard trimmed.first == "{", trimmed.last == "}" else { return nil } + return try? JSONDecoder().decode([String: MLXLMCommon.JSONValue].self, from: Data(trimmed.utf8)) + } + + /// Every key is a declared property and the caller's schema holds. + private static func admits(_ call: ToolCall, prepared: ToolChoicePromptPolicy.Prepared) -> Bool { + guard let tool = (prepared.declaredTools ?? prepared.tools)? + .first(where: { $0.function.name == call.function.name }) else { return false } + var properties: [String: MLXLMCommon.JSONValue] = [:] + if case .object(let parameters)? = tool.function.parameters, + case .object(let declared)? = parameters["properties"] { + properties = declared + } + guard call.function.arguments.keys.allSatisfy({ properties[$0] != nil }) else { return false } + return !ToolConstraintValidation.breaksDeclaration(call, prepared: prepared) + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/Gemma4ToolSchemaEnforcement.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/Gemma4ToolSchemaEnforcement.swift index d926c99bf6..080c3ffb7c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Tools/Gemma4ToolSchemaEnforcement.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/Gemma4ToolSchemaEnforcement.swift @@ -35,8 +35,14 @@ // 8. A property the caller declared without a type or any other schema // keyword (`{}`: any value) renders an empty type instead of the // `string` the shared normalizer injected, as the served template renders -// a typeless property (`type:<|"|><|"|>`). This needs the declarations as -// sent; without them the injected type stays. +// a typeless property (`type:<|"|><|"|>`). The same holds behind a local +// `$ref`, for an `anyOf`/`oneOf`/`allOf` whose non-null members all accept +// any value, and for a typeless `enum` whose values have more than one +// JSON type (the template prints an enum only under STRING, which quoted +// its numbers). A tuple (`prefixItems` with `items` false or absent) +// renders no `items` block, as the template renders one without a +// mapping `items`, instead of the repair's STRING items. This needs the +// declarations as sent; without them the repair's render stays. // // Mirrors the per-model precedent of `GPTOSSHarmonyTemplateFix.normalizeTools`. @@ -78,7 +84,8 @@ enum Gemma4ToolSchemaEnforcement { let parameters = function["parameters"] as? [String: any Sendable], let declaredRoot = declaredParameters[name] else { return output } - function["parameters"] = renderingDeclaredTypeless(parameters, declared: declaredRoot, changed: &changed) + function["parameters"] = renderingDeclaredTypeless( + parameters, declared: declaredRoot, root: declaredRoot, changed: &changed) output["function"] = function return output } @@ -99,10 +106,90 @@ enum Gemma4ToolSchemaEnforcement { return !schemaKeywords.contains { mapping[$0] != nil } } + /// The node a declaration that is only a local `$ref` (plus annotations) + /// points to in `root`'s `$defs` or `definitions`, followed up to eight + /// hops; any other declaration is returned as is. + static func resolvingLocalReference(_ declared: Any?, root: [String: Any]) -> Any? { + var current = declared + for _ in 0..<8 { + guard let mapping = current as? [String: Any], let reference = mapping["$ref"] as? String, + mapping.keys.allSatisfy({ $0 == "$ref" || !schemaKeywords.contains($0) }) + else { return current } + var target: Any? + for container in ["$defs", "definitions"] where reference.hasPrefix("#/\(container)/") { + let name = String(reference.dropFirst(container.count + 3)) + target = (root[container] as? [String: Any])?[name] + } + guard let target else { return current } + current = target + } + return current + } + + /// Invariant 8: whether a declared property accepts any value, directly + /// (`declaresAnyValue`), behind a local `$ref`, or as a combinator (and + /// nothing else) that does: an `anyOf` with a member that accepts any + /// value, or a `oneOf` / `allOf` whose members all do, a `{"type": "null"}` + /// member of `oneOf` aside (`nullable` carries it). The shared repair folds + /// such an `anyOf` (and an `allOf` of them) to `string`. + static func declaresUntypedValue(_ declared: Any?, root: [String: Any]) -> Bool { + let node = resolvingLocalReference(declared, root: root) + if declaresAnyValue(node) { return true } + guard let mapping = node as? [String: Any] else { return false } + let combinators = ["anyOf", "oneOf", "allOf"].filter { mapping[$0] != nil } + guard combinators.count == 1, let combinator = combinators.first, + let members = mapping[combinator] as? [Any], + mapping.keys.allSatisfy({ $0 == combinator || !schemaKeywords.contains($0) }) + else { return false } + let resolved = members.map { resolvingLocalReference($0, root: root) } + if combinator == "anyOf" { return resolved.contains(where: declaresAnyValue) } + var acceptsAny = false + for member in resolved { + if combinator == "oneOf", let null = member as? [String: Any], null["type"] as? String == "null", + null.keys.allSatisfy({ $0 == "type" || !schemaKeywords.contains($0) }) + { + continue + } + guard declaresAnyValue(member) else { return false } + acceptsAny = true + } + return acceptsAny + } + + /// Invariant 8: whether a declared property is a typeless `enum` (and + /// nothing else) whose non-null values have more than one JSON type. + static func declaresMixedEnum(_ declared: Any?, root: [String: Any]) -> Bool { + guard let mapping = resolvingLocalReference(declared, root: root) as? [String: Any], + let values = mapping["enum"] as? [Any], + mapping.keys.allSatisfy({ $0 == "enum" || !schemaKeywords.contains($0) }) + else { return false } + var kinds = Set() + for value in values { + switch value { + case is Bool: kinds.insert("boolean") + case is Int, is Double: kinds.insert("number") + case is String: kinds.insert("string") + case is [Any]: kinds.insert("array") + case is [String: Any]: kinds.insert("object") + default: continue + } + } + return kinds.count >= 2 + } + + /// Invariant 8: whether a declared node is a tuple, `prefixItems` with + /// `items` false or absent. + static func declaresTuple(_ declared: [String: Any]) -> Bool { + guard declared["prefixItems"] != nil else { return false } + return declared["items"] == nil || declared["items"] as? Bool == false + } + /// Invariant 8 over the nodes the template reaches through `properties` - /// and `items`, walking the caller's declaration alongside. + /// and `items`, walking the caller's declaration alongside. `root` is the + /// declared parameters schema local references resolve in. private static func renderingDeclaredTypeless( - _ node: [String: any Sendable], declared: [String: any Sendable], changed: inout Bool + _ node: [String: any Sendable], declared: [String: any Sendable], root: [String: any Sendable], + changed: inout Bool ) -> [String: any Sendable] { var output = node if var properties = output["properties"] as? [String: any Sendable], @@ -110,13 +197,22 @@ enum Gemma4ToolSchemaEnforcement { { for (key, value) in properties { guard var property = value as? [String: any Sendable] else { continue } - if declaresAnyValue(declaredProperties[key]) { + let declaredProperty = declaredProperties[key] + if declaresUntypedValue(declaredProperty, root: root) + || declaresMixedEnum(declaredProperty, root: root) + { if (property["type"] as? String)?.isEmpty == false { property["type"] = "" changed = true } - } else if let declaredProperty = declaredProperties[key] as? [String: any Sendable] { - property = renderingDeclaredTypeless(property, declared: declaredProperty, changed: &changed) + } else if let resolved = resolvingLocalReference(declaredProperty, root: root) + as? [String: any Sendable] + { + if declaresTuple(resolved), property["items"] != nil { + property.removeValue(forKey: "items") + changed = true + } + property = renderingDeclaredTypeless(property, declared: resolved, root: root, changed: &changed) } properties[key] = property } @@ -125,7 +221,7 @@ enum Gemma4ToolSchemaEnforcement { if let items = output["items"] as? [String: any Sendable], let declaredItems = declared["items"] as? [String: any Sendable] { - output["items"] = renderingDeclaredTypeless(items, declared: declaredItems, changed: &changed) + output["items"] = renderingDeclaredTypeless(items, declared: declaredItems, root: root, changed: &changed) } return output } diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintSchema.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintSchema.swift index 3991ac966b..0df4479e9d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintSchema.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintSchema.swift @@ -272,11 +272,16 @@ enum ToolConstraintSchemaCompiler { // stays unsupported so compilation falls back to raw validation, // which restores the exact allow-all semantics — a compiled string // grammar would wrongly reject schema-valid non-string values. + // Annotations beside the marker (the coordinator keeps a `{}`'s + // `description`) assert nothing and compile the same way. if let marker = object[ToolSchemaNormalization.originalBooleanSchemaKey] { guard allowRenderMetadata, marker == .bool(true), - object.count == 2, - object["type"] == .string("string") + object["type"] == .string("string"), + object.keys.allSatisfy({ + $0 == "type" || $0 == ToolSchemaNormalization.originalBooleanSchemaKey + || ToolConstraintValidation.renderOnlyAnnotationKeys.contains($0) + }) else { throw ToolConstraintSchemaError.unsupported( "\(path) uses reserved schema metadata") diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift index e7dd893610..518544db9a 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift @@ -857,7 +857,7 @@ enum ToolConstraintValidation { return true } - private static let renderOnlyAnnotationKeys: Set = [ + static let renderOnlyAnnotationKeys: Set = [ "$anchor", "$comment", "$id", "$schema", "default", "deprecated", "description", "examples", "readOnly", "title", "writeOnly", ] diff --git a/provider-swift/Sources/ProviderCore/Protocol/Messages.swift b/provider-swift/Sources/ProviderCore/Protocol/Messages.swift index 1ddc3e6f51..60306138cc 100644 --- a/provider-swift/Sources/ProviderCore/Protocol/Messages.swift +++ b/provider-swift/Sources/ProviderCore/Protocol/Messages.swift @@ -1921,12 +1921,18 @@ public enum CoordinatorMessage: Sendable, Equatable { public var status: String public var reason: String public var authorization: ProviderAuthorizationStatus? + /// Optional coordinator behaviours the provider may rely on + /// (`coordinator_features`); nil from a coordinator that sends none. + /// Unknown names are ignored. + public var coordinatorFeatures: [String]? public init(trustLevel: String, status: String, reason: String = "", - authorization: ProviderAuthorizationStatus? = nil) { + authorization: ProviderAuthorizationStatus? = nil, + coordinatorFeatures: [String]? = nil) { self.trustLevel = trustLevel self.status = status self.reason = reason self.authorization = authorization + self.coordinatorFeatures = coordinatorFeatures } } } @@ -1978,6 +1984,7 @@ extension CoordinatorMessage: Codable { case priority case trustLevel = "trust_level" case status, reason, authorization + case coordinatorFeatures = "coordinator_features" case paid case models // CapacityProbe @@ -2088,6 +2095,7 @@ extension CoordinatorMessage: Codable { try container.encode(t.trustLevel, forKey: .trustLevel) try container.encode(t.status, forKey: .status) try container.encodeIfPresent(t.authorization, forKey: .authorization) + try container.encodeIfPresent(t.coordinatorFeatures, forKey: .coordinatorFeatures) if !t.reason.isEmpty { try container.encode(t.reason, forKey: .reason) } @@ -2234,7 +2242,8 @@ extension CoordinatorMessage: Codable { trustLevel: try container.decode(String.self, forKey: .trustLevel), status: try container.decode(String.self, forKey: .status), reason: try container.decodeIfPresent(String.self, forKey: .reason) ?? "", - authorization: try container.decodeIfPresent(ProviderAuthorizationStatus.self, forKey: .authorization) + authorization: try container.decodeIfPresent(ProviderAuthorizationStatus.self, forKey: .authorization), + coordinatorFeatures: try? container.decodeIfPresent([String].self, forKey: .coordinatorFeatures) )) case .clusterMemberAccepted: diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+InferenceHandler.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+InferenceHandler.swift index edd56e45db..991e156596 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+InferenceHandler.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+InferenceHandler.swift @@ -1075,7 +1075,9 @@ extension ProviderLoop { // owner's request can tell whether the engine has admitted this // one (`giveWayToOwner`). frames = try await MeFirstDarkbloomRequest.$id.withValue(requestId) { - try await service.streamChatCompletionFrames(request: streamingRequest) + try await InklingWithheldReasoningHeartbeat.$enabled.withValue(true) { + try await service.streamChatCompletionFrames(request: streamingRequest) + } } if rejectExpiredDeadline() { return } } catch { @@ -1267,7 +1269,23 @@ extension ProviderLoop { var pendingLogprobs: [SSETokenLogprob] = [] var pendingLogprobsDropped = 0 do { - for try await frame in frames { + var sentWithheldReasoningHeartbeat = false + for try await streamed in frames { + // Inkling 2's one empty answer delta while it withholds its + // reasoning (`InklingWithheldReasoningHeartbeat`). + // It is output the coordinator commits to, so it claims + // output first (me first), as a first content frame does. + var frame = streamed + if !sentWithheldReasoningHeartbeat, + let heartbeat = InklingWithheldReasoningHeartbeat.frame(rewriting: streamed) + { + guard token.claimOutput() else { + endAfterGivingWay(framesEmitted, bytesEmitted) + return + } + frame = heartbeat + sentWithheldReasoningHeartbeat = true + } // The iterator suspension is the final pre-content await. // Role/usage boilerplate is not content, so keep enforcing // the same absolute deadline until a real content, diff --git a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift index 7d1b52a563..93554be9c4 100644 --- a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift +++ b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift @@ -508,12 +508,20 @@ public enum LaunchAgent: Sendable { /// `DARKBLOOM_INKLING_UNDECLARED_CALL_TEXT`: an Inkling 2 call frame in the /// answer to an `auto` request that declares no tools is text by default; /// exact `0` restores its refusal. + /// `DARKBLOOM_INKLING_MTP_MAX_DRAFT`: Inkling 2's most drafts per MTP round + /// (1 to 7, default 7); tokens are unaffected. + /// `DARKBLOOM_INKLING_MTP_COUPLED`: Inkling 2's coupled drafting (off by + /// default; `1` turns it on, `0` off); tokens are unaffected. /// `DARKBLOOM_GRAMMAR_ONLY_TOOL_PARSING` (SDK-read, `GrammarOnlyToolParsing`): /// the GLM, Gemma and MiMo parsers return calls that break only their /// schema; `0`, `off`, `false` or `no` restores their refusals. /// `DARKBLOOM_GPTOSS_FORCED_TOOLS`: GPT-OSS forced tool calls are on by /// default; an off word (`off`, `false`, `0`, `none`, `no`, `disabled`) /// refuses them and stops advertising them. + /// `DARKBLOOM_GPTOSS_TOOL_CALL_RECOVERY`: a whole declared GPT-OSS call + /// written as the answer or inside the analysis is returned as a call by + /// default (`GPTOSSToolCallRecovery`); `0`, `off`, `false` or `no` returns + /// it as generated. /// `DARKBLOOM_HARMONY_AUTO_TOOL_GRAMMAR`: GPT-OSS `auto` calls follow a /// declared name and that function's schema in the sampler by default; an /// off word restores calls as generated. @@ -607,6 +615,7 @@ public enum LaunchAgent: Sendable { ToolStreamPreparation.streamForcedToolCallsEnvironmentKey, ToolStreamPreparation.streamForcedQwenToolCallsEnvironmentKey, ToolStreamPreparation.streamForcedGPTOSSToolCallsEnvironmentKey, + GPTOSSToolCallRecovery.environmentKey, ToolStreamPreparation.streamNativeToolCallsEnvironmentKey, ToolStreamPreparation.streamGLMToolCallsEnvironmentKey, JSONAnswerPolicy.familiesEnvironmentKey, @@ -619,16 +628,27 @@ public enum LaunchAgent: Sendable { MTPAutomaticVerificationPolicy.gemmaLoneRowEnvironmentKey, MTPAutomaticVerificationPolicy.gemmaTwoDraftsEnvironmentKey, MTPAutomaticVerificationPolicy.gemmaM5UltraLoneRowEnvironmentKey, + MTPAutomaticVerificationPolicy.gemmaMaxDraftPromptTokensEnvironmentKey, EngineV2KVQuantizationPolicy.gemmaNativeRowsBeforeAssistantEnvironmentKey, "DARKBLOOM_QWEN35_DECODE_COMMAND_BUFFERS", // SDK-read (`CBv2MTPConfig.envPenaltySpeculation`, once per process): rows // with a presence/frequency penalty speculate with exact acceptance; // `0`, `false`, `no` or `off` keeps them target-only (0.10.15). MTPPenaltyRows.environmentKey, + // SDK-read (`CBv2MTPConfig.envRepetitionPenaltySpeculation`, once per process): + // rows with a repetition penalty speculate with exact acceptance on the builds + // that opt in; `0`, `false`, `no` or `off` keeps them target-only. + MTPRepetitionPenaltyRows.environmentKey, // SDK-read (`CBv2MTPConfig.envStopStringSpeculation`, once per process): rows // with `stop` strings speculate on the builds that opt in; `0`, `false`, `no` // or `off` keeps them target-only. MTPStopStringRows.environmentKey, + Inkling2MTPProfilePolicy.maxDraftKey, + Inkling2MTPProfilePolicy.coupledKey, + // SDK-read (`CBv2MTPConfig.envLogprobSpeculation`, once per process): rows + // that request logprobs speculate on the builds that opt in; `0`, `false`, + // `no` or `off` keeps them target-only. + MTPLogprobRows.environmentKey, // SDK-read (`EngineLoopV2.nativeSegmentReleaseEnvironmentKey`): idle seconds // before an issued GLM pool returns its free segments; `0` is the rollback. "DARKBLOOM_NATIVE_SEGMENT_RELEASE", diff --git a/provider-swift/Tests/ProviderCoreTests/Config/MTPConfigTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/MTPConfigTests.swift index 943382bec4..953f9986da 100644 --- a/provider-swift/Tests/ProviderCoreTests/Config/MTPConfigTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Config/MTPConfigTests.swift @@ -151,6 +151,92 @@ struct MTPConfigKeyTests { modelID: gemma, chipName: "Apple M5 Ultra", twoDrafts: true) == (enabled ? [2, 0] : [2, 2, 0])) } + /// Under the two-draft policy on M5 Ultra, a Gemma QAT prompt longer than + /// 16,384 tokens decodes without drafts; `DARKBLOOM_GEMMA_MTP_MAX_PROMPT_TOKENS` + /// moves the limit or, with `0`, removes it. No other chip, model or + /// policy gets a limit, whatever the setting. + @Test func gemmaQATLongPromptsOnM5UltraDecodeWithoutDrafts() { + typealias Limit = MTPAutomaticVerificationPolicy.GemmaDraftPromptLimit + let gemma = MTPAcceptancePolicy.gemmaQATModelID + func limit( + _ chip: String, _ setting: Limit, model: String? = MTPAcceptancePolicy.gemmaQATModelID, + twoDrafts: Bool = true, benchmark: Bool = false, onByDefault: Bool = true + ) -> Int? { + MTPAutomaticVerificationPolicy.maxDraftPromptTokens( + modelID: model, chipName: chip, hasBenchmarkVerificationOverride: benchmark, + twoDrafts: twoDrafts, limit: setting, onByDefault: onByDefault) + } + #expect(MTPAutomaticVerificationPolicy.gemmaM5UltraMaxDraftPromptTokens == 16384) + #expect(limit("Apple M5 Ultra", .chipDefault) == 16384) + #expect(limit("Apple M5 Ultra", .tokens(8192)) == 8192) + #expect(limit("Apple M5 Ultra", .off) == nil) + for setting in [Limit.chipDefault, .off, .tokens(2048)] { + // The two-draft switch off, the benchmark override and other models. + #expect(limit("Apple M5 Ultra", setting, twoDrafts: false) == nil) + #expect(limit("Apple M5 Ultra", setting, benchmark: true) == nil) + for model in ["gemma-4-26b", "gemma-4-26b-8bit", "qwen3.6-35b-a3b-vl-mtp-mxfp8", nil] + as [String?] + { + #expect(limit("Apple M5 Ultra", setting, model: model) == nil) + } + // Every other chip, the other two-draft chips included. + for chip in ["Apple M5 Max", "Apple M3 Ultra", "Apple M5 Pro", "Apple M5", "Apple M4 Max", + "Apple M4 Ultra", "Apple M2 Ultra", "Apple M1 Max", "Unknown"] + { + #expect(limit(chip, setting) == nil, "\(chip)") + } + } + // A call without the setting follows the read-once process value. + #expect(MTPAutomaticVerificationPolicy.maxDraftPromptTokens( + modelID: gemma, chipName: "Apple M5 Ultra", twoDrafts: true) + == limit( + "Apple M5 Ultra", MTPAutomaticVerificationPolicy.gemmaDraftPromptLimit, + onByDefault: MTPAutomaticVerificationPolicy.gemmaPromptLimitOnByDefault)) + } + + /// The build default can be switched off in one line + /// (`gemmaPromptLimitOnByDefault`). Off, an unset setting gives no limit, + /// so the engine runs as it did before the limit existed; an explicit + /// positive setting still applies it, and `0` stays off. + @Test func gemmaPromptLimitDefaultCanBeSwitchedOff() { + func limit(_ setting: MTPAutomaticVerificationPolicy.GemmaDraftPromptLimit, _ onByDefault: Bool) -> Int? { + MTPAutomaticVerificationPolicy.maxDraftPromptTokens( + modelID: MTPAcceptancePolicy.gemmaQATModelID, chipName: "Apple M5 Ultra", + twoDrafts: true, limit: setting, onByDefault: onByDefault) + } + #expect(MTPAutomaticVerificationPolicy.gemmaPromptLimitOnByDefault) + #expect(limit(.chipDefault, true) == 16384) + #expect(limit(.chipDefault, false) == nil) + #expect(limit(.tokens(8192), false) == 8192) + #expect(limit(.off, true) == nil) + #expect(limit(.off, false) == nil) + for chip in ["Apple M5 Max", "Apple M3 Ultra", "Unknown"] { + #expect(MTPAutomaticVerificationPolicy.maxDraftPromptTokens( + modelID: MTPAcceptancePolicy.gemmaQATModelID, chipName: chip, twoDrafts: true, + limit: .chipDefault, onByDefault: true) == nil, "\(chip)") + } + } + + @Test func gemmaDraftPromptLimitParsesTheEnvironment() { + typealias Limit = MTPAutomaticVerificationPolicy.GemmaDraftPromptLimit + for raw in [nil, "", " ", "abc", "-5", "4096.5", "1e4"] as [String?] { + #expect(Limit(raw) == .chipDefault, "\(raw ?? "nil")") + } + for raw in ["0", " 0 ", "OFF", "off", "false", "No"] { + #expect(Limit(raw) == .off, "\(raw)") + } + #expect(Limit("8192") == .tokens(8192)) + #expect(Limit(" 2048 ") == .tokens(2048)) + } + + @Test func gemmaDraftPromptLimitRollbackIsForwarded() { + let key = MTPAutomaticVerificationPolicy.gemmaMaxDraftPromptTokensEnvironmentKey + #expect(key == "DARKBLOOM_GEMMA_MTP_MAX_PROMPT_TOKENS") + #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(key)) + #expect(LaunchAgent.passthroughEnvironment(from: [key: "0"])[key] == "0") + #expect(LaunchAgent.passthroughEnvironment(from: [:])[key] == nil) + } + @Test func gemmaM5UltraLoneRowRollbackIsForwarded() { let key = MTPAutomaticVerificationPolicy.gemmaM5UltraLoneRowEnvironmentKey #expect(key == "DARKBLOOM_GEMMA_MTP_M5_ULTRA_LONE_ROW") diff --git a/provider-swift/Tests/ProviderCoreTests/Config/MTPLogprobRowsSwitchTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/MTPLogprobRowsSwitchTests.swift new file mode 100644 index 0000000000..a804f7f69f --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Config/MTPLogprobRowsSwitchTests.swift @@ -0,0 +1,96 @@ +import MLXLLM +import MLXLMCommon +import ProviderCoreFoundation +import Testing +@testable import ProviderCore + +/// The SDK reads `DARKBLOOM_MTP_LOGPROB_ROWS` once per process +/// (`CBv2MTPConfig.envLogprobSpeculation`): on the builds that opt in, rows +/// that request logprobs speculate unless it is `0`. The rollback must reach a +/// background provider too, so the LaunchAgent forwards the operator's value. +@Suite("MTP logprob-row switch reaches the LaunchAgent") +struct MTPLogprobRowsSwitchTests { + @Test func rollbackIsForwarded() { + let key = MTPLogprobRows.environmentKey + #expect(key == "DARKBLOOM_MTP_LOGPROB_ROWS") + #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(key)) + #expect(LaunchAgent.passthroughEnvironment(from: [key: "0"])[key] == "0") + #expect(LaunchAgent.passthroughEnvironment(from: [:])[key] == nil) + } + + @Test func onlyInklingOptsIn() { + for id in Inkling2ModelIdentity.servedModelIDs { + var config = CBv2MTPConfig(enabled: true) + let on = SDKFeatureDefaults.applyMTPDefaults( + to: &config, modelId: id, environment: [:], processEnvironment: [:]) + #expect(config.logprobSpeculation, "\(id)") + #expect(on.contains(MTPLogprobRows.environmentKey) == CBv2MTPConfig.envLogprobSpeculation) + } + for id in [ + "thinkingmachines/inkling-2-mini", "gemma-4-26b-qat-4bit", "Qwen3.5-9B", "qwen3.5-35b-a3b", + "qwen3.6-35b-a3b-vl-mtp-mxfp8", "EigenLabs/Qwen3.8-27B-4bit-mtp", "glm-5.3-flash", + "nvidia-nemotron-3.5-super", + ] { + var config = CBv2MTPConfig(enabled: true) + SDKFeatureDefaults.applyMTPDefaults( + to: &config, modelId: id, environment: [:], processEnvironment: [:]) + #expect(!config.logprobSpeculation, "\(id)") + } + } + + /// Inkling's configuration as `EngineV2SlotFactory` builds it (the + /// drafter's shipped profile: adaptive depth, declared `.rectangular`; + /// the acceptance `MTPAcceptancePolicy` resolves with nothing + /// configured; then the per-build defaults), run as the round driver + /// runs it beside the loaded drafter (`.rectangularExact`): the opt-in + /// takes effect, at every draft cap. + @Test func theOptInTakesEffectOnInklingsServingConfig() { + let id = Inkling2ModelIdentity.upstreamModelID + for cap in [7, 4, 1] { + var config = Inkling2DSparkDrafter.defaultMTPConfig(maxDraftTokens: cap) + config.acceptance = MTPAcceptancePolicy.resolve( + global: nil, byModel: [:], modelID: id + ).acceptance + SDKFeatureDefaults.applyMTPDefaults( + to: &config, modelId: id, environment: [:], processEnvironment: [:]) + #expect(config.verificationMode == .rectangular) + let running = config.requiring(Inkling2DSparkDrafter.servingVerificationMode) + #expect(running.verificationMode == .rectangularExact) + #expect(running.acceptance == .exact) + #expect( + running.effectiveLogprobSpeculation == CBv2MTPConfig.envLogprobSpeculation, + "cap \(cap)") + #expect( + SDKFeatureDefaults.logprobRowsSummary( + config, drafterMode: Inkling2DSparkDrafter.servingVerificationMode) + == (CBv2MTPConfig.envLogprobSpeculation ? "on" : "off") + + " (verification rectangular_exact, acceptance exact)") + } + } + + /// The SDK takes the opt-in only on an exact verify path under exact + /// acceptance: typical acceptance, or a target that verifies + /// `.rectangular`, keeps logprob rows target-only. + @Test func theOptInNeedsAnExactVerifyPath() { + var config = Inkling2DSparkDrafter.defaultMTPConfig() + SDKFeatureDefaults.applyMTPDefaults( + to: &config, modelId: Inkling2ModelIdentity.upstreamModelID, environment: [:], + processEnvironment: [:]) + #expect(!config.requiring(nil).effectiveLogprobSpeculation) + config.acceptance = .typical(delta: 0.2) + #expect( + !config.requiring(Inkling2DSparkDrafter.servingVerificationMode) + .effectiveLogprobSpeculation) + #expect( + SDKFeatureDefaults.logprobRowsSummary( + config, drafterMode: Inkling2DSparkDrafter.servingVerificationMode) + == "off (verification rectangular_exact, acceptance typical)") + } + + @Test func startupSummaryNamesTheBuild() { + let line = SDKFeatureDefaults.summary(environment: [:], injected: []) + #expect( + line?.contains("DARKBLOOM_MTP_LOGPROB_ROWS (\(Inkling2ModelIdentity.upstreamModelID))") + == CBv2MTPConfig.envLogprobSpeculation) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Config/MTPPenaltyRowsSwitchTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/MTPPenaltyRowsSwitchTests.swift index b7622268c0..fce6e5f5c0 100644 --- a/provider-swift/Tests/ProviderCoreTests/Config/MTPPenaltyRowsSwitchTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Config/MTPPenaltyRowsSwitchTests.swift @@ -40,9 +40,9 @@ struct MTPPenaltyRowsSwitchTests { } /// Inkling's penalty rows draft through the SDK's generic penalty-aware - /// verification; a repetition penalty still keeps a row target-only - /// (`mtpHistoryEligible` requires repetition penalty 1 on every build). - @Test func inklingPenaltyRowsDraftButRepetitionPenaltyStaysRefused() { + /// verification. A repetition penalty is not a presence/frequency penalty: + /// its rows follow their own opt-in (`MTPRepetitionPenaltyRowsSwitchTests`). + @Test func inklingPenaltyRowsDraftThroughTheGenericVerifier() { var config = CBv2MTPConfig(enabled: true) SDKFeatureDefaults.applyMTPDefaults( to: &config, modelId: "thinkingmachines/Inkling-2-Mini", environment: [:], processEnvironment: [:]) diff --git a/provider-swift/Tests/ProviderCoreTests/Config/MTPRepetitionPenaltyRowsSwitchTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/MTPRepetitionPenaltyRowsSwitchTests.swift new file mode 100644 index 0000000000..2539dd51ba --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Config/MTPRepetitionPenaltyRowsSwitchTests.swift @@ -0,0 +1,80 @@ +import MLXLMCommon +import Testing +@testable import ProviderCore + +/// The SDK reads `DARKBLOOM_MTP_REPETITION_PENALTY_ROWS` once per process +/// (`CBv2MTPConfig.envRepetitionPenaltySpeculation`): on the builds that opt +/// in, rows with a repetition penalty speculate unless it is `0`. The rollback +/// must reach a background provider too, so the LaunchAgent forwards the +/// operator's value. +@Suite("MTP repetition-penalty-row switch reaches the LaunchAgent") +struct MTPRepetitionPenaltyRowsSwitchTests { + @Test func rollbackIsForwarded() { + let key = MTPRepetitionPenaltyRows.environmentKey + #expect(key == "DARKBLOOM_MTP_REPETITION_PENALTY_ROWS") + #expect(key != MTPPenaltyRows.environmentKey) + #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(key)) + #expect(LaunchAgent.passthroughEnvironment(from: [key: "0"])[key] == "0") + #expect(LaunchAgent.passthroughEnvironment(from: [:])[key] == nil) + } + + /// The catalog Qwen 3.5/3.6 builds, Gemma 4 26B QAT and Inkling 2 Mini, the + /// presence/frequency builds, all with target-prefix acceptance. Exact ids: + /// no other quantization, casing or family. + @Test func onlyTheCatalogQwenGemmaQATAndInklingBuildsOptIn() { + for id in [ + "Qwen3.5-9B", "qwen3.5-35b-a3b", "qwen3.6-35b-a3b-vl-mtp-mxfp8", "gemma-4-26b-qat-4bit", + "thinkingmachines/Inkling-2-Mini", + ] { + var config = CBv2MTPConfig(enabled: true) + let on = SDKFeatureDefaults.applyMTPDefaults( + to: &config, modelId: id, environment: [:], processEnvironment: [:]) + #expect(config.repetitionPenaltySpeculation, "\(id)") + #expect( + config.effectiveRepetitionPenaltySpeculation + == CBv2MTPConfig.envRepetitionPenaltySpeculation, "\(id)") + #expect( + on.contains(MTPRepetitionPenaltyRows.environmentKey) + == CBv2MTPConfig.envRepetitionPenaltySpeculation, "\(id)") + } + for id in [ + "gemma-4-26b", "gemma-4-26b-8bit", "GEMMA-4-26B-QAT-4BIT", "EigenLabs/Qwen3.8-27B-4bit-mtp", + "mlx-community/Qwen3.5-9B-4bit", "qwen3.5-35b-a3b-8bit", "glm-5.3-flash", "nvidia-nemotron-3.5-super", + "qwen3.5-9b", "QWEN3.6-35B-A3B-VL-MTP-MXFP8", "thinkingmachines/inkling-2-mini", "Inkling-2-Mini", + ] { + var config = CBv2MTPConfig(enabled: true) + let on = SDKFeatureDefaults.applyMTPDefaults( + to: &config, modelId: id, environment: [:], processEnvironment: [:]) + #expect(!config.repetitionPenaltySpeculation, "\(id)") + #expect(!on.contains(MTPRepetitionPenaltyRows.environmentKey), "\(id)") + } + } + + /// The repetition opt-in is its own switch: the presence/frequency opt-in + /// does not imply it, and an operator value cannot widen the builds. + @Test func theOptInIsSeparateAndOnlyTheListCanWidenIt() { + var config = CBv2MTPConfig(enabled: true, penaltySpeculation: true) + SDKFeatureDefaults.applyMTPDefaults( + to: &config, modelId: "gemma-4-26b", environment: [MTPRepetitionPenaltyRows.environmentKey: "1"], + processEnvironment: [MTPRepetitionPenaltyRows.environmentKey: "1"]) + #expect(!config.repetitionPenaltySpeculation) + var listed = CBv2MTPConfig(enabled: true) + SDKFeatureDefaults.applyMTPDefaults( + to: &listed, modelId: "Qwen3.5-9B", environment: [:], processEnvironment: [:], + penaltyBuilds: [], repetitionPenaltyBuilds: ["Qwen3.5-9B"]) + #expect(listed.repetitionPenaltySpeculation && !listed.penaltySpeculation) + #expect(CBv2MTPVerifyPenalties.appliesRepetition(.init(temperature: 0.5, repetitionPenalty: 1.2))) + #expect(!CBv2MTPVerifyPenalties.appliesRepetition(.init(temperature: 0.5, presencePenalty: 1.5))) + } + + @Test func startupSummaryNamesTheBuilds() { + let line = SDKFeatureDefaults.summary(environment: [:], injected: []) + #expect( + line?.contains( + "DARKBLOOM_MTP_REPETITION_PENALTY_ROWS (Qwen3.5-9B, gemma-4-26b-qat-4bit, qwen3.5-35b-a3b, qwen3.6-35b-a3b-vl-mtp-mxfp8, thinkingmachines/Inkling-2-Mini)") + == CBv2MTPConfig.envRepetitionPenaltySpeculation) + let none = SDKFeatureDefaults.summary( + environment: [:], injected: [], spansBuilds: [], grammarBuilds: [], repetitionPenaltyBuilds: []) + #expect(none?.contains(MTPRepetitionPenaltyRows.environmentKey) != true) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Fixtures/Protocol/coordinator_features_wire.json b/provider-swift/Tests/ProviderCoreTests/Fixtures/Protocol/coordinator_features_wire.json new file mode 100644 index 0000000000..0cbbfe8d39 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Fixtures/Protocol/coordinator_features_wire.json @@ -0,0 +1,17 @@ +{ + "feature": "decode_rate_age_decay", + "cases": [ + {"name": "absent", "decays": false, + "message": {"type": "trust_status", "trust_level": "hardware", "status": "online"}}, + {"name": "empty", "decays": false, + "message": {"type": "trust_status", "trust_level": "hardware", "status": "online", "coordinator_features": []}}, + {"name": "other", "decays": false, + "message": {"type": "trust_status", "trust_level": "hardware", "status": "online", "coordinator_features": ["some_later_feature"]}}, + {"name": "advertised", "decays": true, + "message": {"type": "trust_status", "trust_level": "hardware", "status": "online", "coordinator_features": ["decode_rate_age_decay"]}}, + {"name": "advertised_among_others", "decays": true, + "message": {"type": "trust_status", "trust_level": "self_signed", "status": "online", "reason": "qualified", "coordinator_features": ["some_later_feature", "decode_rate_age_decay"]}}, + {"name": "malformed", "decays": false, + "message": {"type": "trust_status", "trust_level": "hardware", "status": "online", "coordinator_features": "decode_rate_age_decay"}} + ] +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Fixtures/ResliceFloorScenario.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Fixtures/ResliceFloorScenario.swift index 12ff78b434..b95f400e61 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Fixtures/ResliceFloorScenario.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Fixtures/ResliceFloorScenario.swift @@ -103,6 +103,10 @@ enum ResliceFloorScenario { /// A real ordinary engine over a contiguous backend holding `grant`, with /// `fixedRequestBytes` of workspace per request at the SDK's default /// watermark: its bridge reports the production floor and serving width. + /// The engine stays idle, so its loop publishes its capacity once and then + /// waits an hour: an idle loop's 1 ms republish can overwrite a re-slice's + /// point update with the capacity it read just before it, and the floor + /// (gauge capacity against ledger admissible) then reads too high. static func makeBridge(modelId: String, fixedRequestBytes: Int, grant: Int, kvBytesPerToken: Int = 0) -> EngineV2Bridge { let fixture = DeadlineAdmissionFixtureModel() @@ -111,6 +115,7 @@ enum ResliceFloorScenario { backend: CBv2ContiguousKVBackend(config: .init(bytesCapacity: grant)), cacheProvider: CBv2LayerCacheBank(layerKinds: fixture.kinds), schedulerConfig: .init(maxConcurrentRequests: 4, enablePrefixCache: false), + loopConfig: CBv2EngineLoopConfig(idleRecheckInterval: 3_600), admissionConfig: admission) return EngineV2Bridge(engine: engine, modelId: modelId, tokenizer: TokenizerHandle(StubBridgeTokenizer()), eosTokenIds: [], diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/MTP/Inkling2MTPCoupledSwitchTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/MTP/Inkling2MTPCoupledSwitchTests.swift new file mode 100644 index 0000000000..10a1ac49bf --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/MTP/Inkling2MTPCoupledSwitchTests.swift @@ -0,0 +1,64 @@ +import MLXLLM +import MLXLMCommon +import Testing +@testable import ProviderCore + +/// `DARKBLOOM_INKLING_MTP_COUPLED` turns coupled drafting +/// (`CBv2MTPConfig.coupledProposals`) on for the served Inkling 2 identities +/// (`Inkling2MTPProfilePolicy.coupledProposals`). Off by default; never on for +/// another identity. Output is unchanged either way (the SDK's exact +/// acceptance); only acceptance can move. +@Suite("Inkling 2 MTP coupled drafting switch") +struct Inkling2MTPCoupledSwitchTests { + private let key = Inkling2MTPProfilePolicy.coupledKey + private var served: String { Inkling2ModelIdentity.upstreamModelID } + + @Test func offByDefault() { + #expect(key == "DARKBLOOM_INKLING_MTP_COUPLED") + #expect(!Inkling2MTPProfilePolicy.coupledByDefault) + #expect(Inkling2ModelIdentity.isServedModelID(served)) + for environment in [[:], [key: ""], [key: "maybe"]] { + #expect(!Inkling2MTPProfilePolicy.coupledProposals(modelID: served, environment: environment)) + } + let config = Inkling2MTPProfilePolicy.engineConfig( + maxDraft: Inkling2MTPProfilePolicy.maxDraftTokens(environment: [:])) + #expect(!config.coupledProposals) + } + + @Test(arguments: ["1", "true", "YES", " on "]) + func onWordsTurnItOnForTheServedModel(raw: String) { + #expect(Inkling2MTPProfilePolicy.coupledProposals(modelID: served, environment: [key: raw])) + } + + @Test(arguments: ["0", "false", "no", "OFF"]) + func offWordsKeepItOff(raw: String) { + #expect(!Inkling2MTPProfilePolicy.coupledProposals(modelID: served, environment: [key: raw])) + } + + @Test(arguments: ["gemma-4-26b-qat-4bit", "glm-5.3-flash", "Qwen3.5-9B", "thinkingmachines/inkling-2-mini"]) + func otherModelsNeverCouple(modelID: String) { + #expect(!Inkling2MTPProfilePolicy.coupledProposals(modelID: modelID, environment: [key: "1"])) + } + + @Test func theProfileCarriesTheSwitchAndNothingElseMoves() { + let cap = Inkling2MTPProfilePolicy.maxDraftTokens(environment: [:]) + let on = Inkling2MTPProfilePolicy.engineConfig(maxDraft: cap, coupled: true) + let off = Inkling2DSparkDrafter.defaultMTPConfig() + #expect(on.coupledProposals) + #expect(on.maxDraftTokens == off.maxDraftTokens) + #expect(on.maxSpeculativeBatch == off.maxSpeculativeBatch) + #expect(on.fixedDraftTokens == off.fixedDraftTokens) + #expect(on.maxAutomaticRectangularTokens == off.maxAutomaticRectangularTokens) + #expect(on.costCurveDepthSelection == off.costCurveDepthSelection) + let capped = Inkling2MTPProfilePolicy.engineConfig( + maxDraft: Inkling2MTPProfilePolicy.maxDraftTokens(environment: [Inkling2MTPProfilePolicy.maxDraftKey: "3"]), + coupled: true) + #expect(capped.coupledProposals && capped.maxDraftTokens == 3) + } + + @Test func theSwitchReachesABackgroundProvider() { + #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(key)) + #expect(LaunchAgent.passthroughEnvironment(from: [key: "1"])[key] == "1") + #expect(LaunchAgent.passthroughEnvironment(from: [:])[key] == nil) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/MTP/Inkling2MTPMaxDraftTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/MTP/Inkling2MTPMaxDraftTests.swift new file mode 100644 index 0000000000..dabe84c7c2 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/MTP/Inkling2MTPMaxDraftTests.swift @@ -0,0 +1,58 @@ +import MLXLLM +import MLXLMCommon +import Testing +@testable import ProviderCore + +/// `DARKBLOOM_INKLING_MTP_MAX_DRAFT` caps Inkling 2's drafts per MTP round +/// (`Inkling2MTPProfilePolicy`): unset keeps the drafter's whole block (7), a +/// whole number is clamped to 1...7, anything else keeps 7 and is reported. +@Suite("Inkling 2 MTP max draft override") +struct Inkling2MTPMaxDraftTests { + private let key = Inkling2MTPProfilePolicy.maxDraftKey + + @Test func unsetOrBlankKeepsTheShippedProfile() { + #expect(key == "DARKBLOOM_INKLING_MTP_MAX_DRAFT") + for environment in [[:], [key: ""], [key: " "]] { + let cap = Inkling2MTPProfilePolicy.maxDraftTokens(environment: environment) + #expect(cap == .init(tokens: 7, unrecognized: nil)) + let config = Inkling2MTPProfilePolicy.engineConfig(maxDraft: cap) + let shipped = Inkling2DSparkDrafter.defaultMTPConfig() + #expect(config.maxDraftTokens == shipped.maxDraftTokens) + #expect(config.maxAutomaticRectangularTokens == shipped.maxAutomaticRectangularTokens) + #expect(config.fixedDraftTokens == nil) + #expect(config.costCurveDepthSelection) + } + } + + @Test(arguments: [("4", 4), ("3", 3), ("2", 2), (" 5 ", 5), ("7", 7), ("1", 1)]) + func aWholeNumberSetsTheCap(raw: String, tokens: Int) { + let cap = Inkling2MTPProfilePolicy.maxDraftTokens(environment: [key: raw]) + #expect(cap == .init(tokens: tokens, unrecognized: nil)) + let config = Inkling2MTPProfilePolicy.engineConfig(maxDraft: cap) + #expect(config.enabled) + #expect(config.maxDraftTokens == tokens) + // Still adaptive below the cap, with the verify envelope of that depth. + #expect(config.fixedDraftTokens == nil) + #expect(config.maxAutomaticRectangularTokens == 8 * (tokens + 1)) + #expect(config.maxSpeculativeBatch == 8) + } + + @Test(arguments: [("0", 1), ("-3", 1), ("8", 7), ("64", 7)]) + func outOfRangeValuesAreClamped(raw: String, tokens: Int) { + let cap = Inkling2MTPProfilePolicy.maxDraftTokens(environment: [key: raw]) + #expect(cap == .init(tokens: tokens, unrecognized: nil)) + #expect(Inkling2MTPProfilePolicy.engineConfig(maxDraft: cap).maxDraftTokens == tokens) + } + + @Test(arguments: ["four", "4.5", "3x", "on"]) + func otherValuesKeepSevenAndAreReported(raw: String) { + let cap = Inkling2MTPProfilePolicy.maxDraftTokens(environment: [key: raw]) + #expect(cap == .init(tokens: 7, unrecognized: raw)) + } + + @Test func theOverrideReachesABackgroundProvider() { + #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(key)) + #expect(LaunchAgent.passthroughEnvironment(from: [key: "3"])[key] == "3") + #expect(LaunchAgent.passthroughEnvironment(from: [:])[key] == nil) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Performance/CoordinatorDecodeRateDecayTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Performance/CoordinatorDecodeRateDecayTests.swift new file mode 100644 index 0000000000..913159770c --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Performance/CoordinatorDecodeRateDecayTests.swift @@ -0,0 +1,137 @@ +import Foundation +import MLXLMCommon +import Testing +@testable import ProviderCore + +/// `trust_status.coordinator_features`: the provider stops idle-zeroing its +/// published decode rate only while the coordinator advertises +/// `decode_rate_age_decay`. Without it the heartbeat is what it was. Synthetic +/// observations and a scripted engine; no model or GPU is involved. Nothing here +/// changes the process-wide advertisement: heartbeats take a task-local value. +@Suite("Coordinator decode rate decay") +struct CoordinatorDecodeRateDecayTests { + private func decode(_ tps: Double, at: ContinuousClock.Instant) -> EngineRateObservation { + EngineRateObservation(phase: "decode", tps: tps, prompt: 1_024, context: 1_024, cache: "cold", + overlap: .init(contended: true, peakRequests: 4), at: at, postureEpoch: nil, aggregate: true, + decodeShape: .init(batchRows: 4)) + } + + private struct Fixture: Decodable { + struct Case: Decodable { + let name: String + let decays: Bool + let message: JSONValue + } + let feature: String + let cases: [Case] + } + + /// Any JSON value, re-encoded byte for byte enough to feed the decoder. + private enum JSONValue: Decodable, Encodable { + case object([String: JSONValue]), array([JSONValue]), string(String), number(Double), bool(Bool), null + init(from decoder: Decoder) throws { + let c = try decoder.singleValueContainer() + if c.decodeNil() { self = .null } + else if let v = try? c.decode(Bool.self) { self = .bool(v) } + else if let v = try? c.decode(Double.self) { self = .number(v) } + else if let v = try? c.decode(String.self) { self = .string(v) } + else if let v = try? c.decode([JSONValue].self) { self = .array(v) } + else { self = .object(try c.decode([String: JSONValue].self)) } + } + func encode(to encoder: Encoder) throws { + var c = encoder.singleValueContainer() + switch self { + case .object(let v): try c.encode(v) + case .array(let v): try c.encode(v) + case .string(let v): try c.encode(v) + case .number(let v): try c.encode(v) + case .bool(let v): try c.encode(v) + case .null: try c.encodeNil() + } + } + } + + @Test("every fixture trust_status decodes, and only an advertised feature turns the provider's idle age off") + func sharedFixture() throws { + let url = try #require(Bundle.module.url( + forResource: "coordinator_features_wire", withExtension: "json", subdirectory: "Fixtures/Protocol")) + let fixture = try JSONDecoder().decode(Fixture.self, from: Data(contentsOf: url)) + #expect(fixture.feature == DecodeRateIdleAge.coordinatorDecayFeature) + #expect(fixture.cases.count == 6) + for item in fixture.cases { + let data = try JSONEncoder().encode(item.message) + guard case .trustStatus(let status) = try ProviderProtocolCodec.decodeCoordinatorMessage(from: data) else { + Issue.record("\(item.name): expected trust status"); continue + } + let advertisement = CoordinatorDecayAdvertisement() + advertisement.update(features: status.coordinatorFeatures) + #expect(advertisement.value == item.decays, "\(item.name)") + #expect(DecodeRateIdleAge.effectiveMaximum(configured: .seconds(1_800), + coordinatorDecays: advertisement.value) == (item.decays ? nil : .seconds(1_800)), "\(item.name)") + } + } + + @Test("a trust_status without the field re-encodes without it; with it, the list round-trips") + func wireShape() throws { + let legacy = Data(#"{"type":"trust_status","trust_level":"hardware","status":"online"}"#.utf8) + guard case .trustStatus(let old) = try ProviderProtocolCodec.decodeCoordinatorMessage(from: legacy) else { + Issue.record("expected trust status"); return + } + #expect(old.coordinatorFeatures == nil) + let reencoded = try #require(try JSONSerialization.jsonObject( + with: JSONEncoder().encode(CoordinatorMessage.trustStatus(old))) as? [String: Any]) + #expect(reencoded["coordinator_features"] == nil) + let current = CoordinatorMessage.TrustStatus(trustLevel: "hardware", status: "online", + coordinatorFeatures: [DecodeRateIdleAge.coordinatorDecayFeature]) + let encoded = try JSONEncoder().encode(CoordinatorMessage.trustStatus(current)) + #expect(try JSONDecoder().decode(CoordinatorMessage.self, from: encoded) == .trustStatus(current)) + let object = try #require(try JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + #expect(object["coordinator_features"] as? [String] == ["decode_rate_age_decay"]) + } + + @Test("the advertisement follows each trust_status and clears on reset") + func advertisementLifecycle() { + let advertisement = CoordinatorDecayAdvertisement() + #expect(!advertisement.value) + advertisement.update(features: ["decode_rate_age_decay"]) + #expect(advertisement.value) + advertisement.update(features: nil) + #expect(!advertisement.value, "a later trust_status without the field restores the idle age") + advertisement.update(features: ["decode_rate_age_decay"]) + advertisement.reset() + #expect(!advertisement.value, "a disconnect restores the idle age") + #expect(DecodeRateIdleAge.effectiveMaximum(configured: nil, coordinatorDecays: false) == nil) + #expect(DecodeRateIdleAge.effectiveMaximum(configured: .seconds(900), coordinatorDecays: false) == .seconds(900)) + } + + @Test("without the feature an idle stale slot's heartbeat is byte for byte what it was; with it the rate and its age stay") + func heartbeatBytes() async throws { + let bridge = EngineV2Bridge(engine: PrefillScriptEngine(), modelId: "gemma-4-26b-qat-4bit", + tokenizer: TokenizerHandle(PrefillStubTokenizer()), eosTokenIds: [], admissionFixes: true) + let start = ContinuousClock.now + await bridge.applyRateObservation(decode(16, at: start), requestID: "stacked", calibration: false) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + for offset in [60, 1_801, 7_200] { + let now = start + .seconds(offset) + // The process-wide value is false in tests: no coordinator is connected. + let process = try encoder.encode(await bridge.backendSlotCapacity(now: now)) + let absent = try await DecodeRateIdleAge.$coordinatorDecaysOverride.withValue(false) { + try encoder.encode(await bridge.backendSlotCapacity(now: now)) + } + #expect(process == absent, "offset \(offset)") + let advertised = try await DecodeRateIdleAge.$coordinatorDecaysOverride.withValue(true) { + await bridge.backendSlotCapacity(now: now) + } + let without = try JSONDecoder().decode(BackendSlotCapacity.self, from: absent) + #expect(advertised.observedDecodeTps == 16, "offset \(offset)") + #expect(advertised.observedDecodeTpsAgeMs == Int64(offset) * 1_000, "offset \(offset)") + if offset > 1_800 { + #expect(without.observedDecodeTps == 0 && without.observedDecodeTpsAgeMs == nil) + } else { + #expect(try encoder.encode(advertised) == absent, "a fresh rate is the same either way") + } + } + await bridge.shutdown() + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/Inkling2OutputChannelsTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/Inkling2OutputChannelsTests.swift index 83c7bcbc68..b147fa8242 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/Inkling2OutputChannelsTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/Inkling2OutputChannelsTests.swift @@ -173,6 +173,36 @@ struct Inkling2OutputChannelsTests { } } + /// The same frame as a parallel call after a native one: a text message + /// that opens with `NAME<|content_invoke_tool_json|>` after a completed + /// call is the second call, at any split (vLLM reads `TOOL_START` from + /// `CONTENT` after a call too). + @Test func callFrameOpeningAnAnswerAfterANativeCallIsTheNextCall() { + let native = Self.call("set_note", #"{"name":"set_note","args":{"note":"twice"}}"#) + let body = #"{"name":"set_thermostat_offset","args":{"offset":-2.5,"zone":"hall"}}"# + let wrapped = "set_thermostat_offset<|content_invoke_tool_json|>" + body + Self.end + for opener in [Self.answer, "<|content_text|>"] { + let output = Self.thought + "Two calls." + Self.end + native + opener + wrapped + Self.eos + let characters = Array(output) + for width in [1, 3, 4096] { + let chunks = stride(from: 0, to: characters.count, by: width).map { + String(characters[$0.." + body) + } + } + /// The name before the marker is the call's header, held to the body's name. @Test func callFrameOpeningAnAnswerKeepsTheHeaderRule() { let (reading, lexer) = Self.read( diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/Inkling2ToolStreamRouterTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/Inkling2ToolStreamRouterTests.swift index cd702d292f..87944f34c6 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/Inkling2ToolStreamRouterTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/Inkling2ToolStreamRouterTests.swift @@ -111,6 +111,29 @@ struct Inkling2ToolStreamRouterTests { } } + /// A call written as an answer message after a native call is the second + /// call, held to the end or streamed when its frame closes. + @Test func callWrittenAsAnAnswerMessageAfterANativeCallIsTheNextCall() throws { + let wrapped = #"<|message_model|><|content_text|>write_file<|content_invoke_tool_json|>{"name":"write_file","args":{"path":"a.txt","content":"hi"}}<|end_message|>"# + let output = Self.thought + Self.call + wrapped + for width in [1, 3, 4096] { + let (_, prepared) = try Self.prepared(clientStreams: false) + var held = Self.router(prepared, streams: false) + let routed = Routed(try Self.feed(&held, output, width: width)) + #expect(routed.content.isEmpty) + let finished = try held.finishCompleteCalls(truncated: false) + #expect(finished.calls.map(\.function.name) == ["get_weather", "write_file"], "\(width)") + #expect(finished.calls.last?.function.arguments == ["path": .string("a.txt"), "content": .string("hi")]) + + let (_, streamedPrepared) = try Self.prepared() + var streamed = Self.router(streamedPrepared, streams: true) + let events = Routed(try Self.feed(&streamed, output, width: width)) + #expect(events.content.isEmpty) + #expect(try streamed.finishToolCalls(truncated: false).isEmpty) + #expect(streamed.completedToolCalls.map(\.function.name) == ["get_weather", "write_file"], "\(width)") + } + } + /// To a client that streams, each call leaves complete when its frame closes. @Test func callsLeaveWhenTheirFrameCloses() throws { let (request, prepared) = try Self.prepared() diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/InklingWithheldReasoningHeartbeatTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/InklingWithheldReasoningHeartbeatTests.swift new file mode 100644 index 0000000000..cfd76e000e --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/InklingWithheldReasoningHeartbeatTests.swift @@ -0,0 +1,163 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon +import MLXLMServer +import Testing + +@testable import ProviderCore + +/// Inkling 2 with reasoning withheld: one empty answer delta when withholding +/// starts (`InklingWithheldReasoningHeartbeat`), and nothing else changes. +@Suite("Inkling withheld-reasoning heartbeat") +struct InklingWithheldReasoningHeartbeatTests { + static let thought = "<|message_model|><|content_thinking|>The user wants a short greeting. Think it over.<|end_message|>" + static let answer = "<|message_model|><|content_text|>Hello there.<|end_message|><|content_model_end_sampling|>" + static let call = #"<|message_model|>get_weather<|content_invoke_tool_json|>{"name":"get_weather","args":{"location":"Paris"}}<|end_message|>"# + + static func router(withhold: Bool, heartbeat: Bool, inkling: Bool = true, + prepared: ToolChoicePromptPolicy.Prepared? = nil) -> NativeToolStreamRouter { + NativeToolStreamRouter(handler: nil, requiresToolCall: false, nativePrefix: inkling ? nil : "", + tools: prepared?.tools?.map { $0.toolSpec() }, withholdReasoning: withhold, streamedCalls: prepared, + nativeInklingChannels: inkling, inklingStreamsCalls: false, withheldReasoningHeartbeat: heartbeat) + } + + static func feed(_ router: inout NativeToolStreamRouter, _ text: String, width: Int) throws + -> [MLXServerGenerationEvent] + { + let characters = Array(text) + var events: [MLXServerGenerationEvent] = [] + for start in stride(from: 0, to: characters.count, by: width) { + events += try router.process(String(characters[start.. String { + try ServerSentEventEncoder.encode(OpenAIChatCompletionChunk( + id: "chatcmpl-1", model: "thinkingmachines/Inkling-2-Mini", + choices: [.init(index: 0, delta: .init(role: role, content: content, reasoningContent: reasoning, + toolCalls: nil), finishReason: finish)], + usage: usage, created: 1_795_550_000)) + } + + @Test func theFrameIsAPlainEmptyContentChunk() throws { + let rewritten = try #require(InklingWithheldReasoningHeartbeat.frame( + rewriting: try Self.encoded(content: nil, reasoning: ""))) + #expect(rewritten == #"data: {"choices":[{"delta":{"content":""},"index":0}],"created":1795550000,"# + + #""id":"chatcmpl-1","model":"thinkingmachines/Inkling-2-Mini","object":"chat.completion.chunk"}"# + + "\n\n") + // The coordinator holds a chunk only when its line says "role". + #expect(!rewritten.contains("role")) + #expect(!rewritten.contains("reasoning")) + #expect(!rewritten.contains("usage")) + #expect(!rewritten.contains("finish_reason")) + } + + @Test func everyOtherFrameIsLeftAlone() throws { + for frame in [ + try Self.encoded(content: nil, reasoning: "a thought"), + try Self.encoded(content: "Hello", reasoning: nil), + try Self.encoded(content: "", reasoning: nil, role: "assistant"), + try Self.encoded(content: nil, reasoning: "", finish: "stop"), + try Self.encoded(content: nil, reasoning: "", usage: .init(promptTokens: 1, completionTokens: 1)), + ServerSentEventEncoder.done, + ] { + #expect(InklingWithheldReasoningHeartbeat.frame(rewriting: frame) == nil, "\(frame)") + } + } + + // MARK: - Through the SDK's stream encoder + + private struct Fixture: MLXServerEngine { + func availableModels() async throws -> [MLXServerModel] { [.init(id: "fixture")] } + func streamChatCompletion(request: OpenAIChatCompletionRequest) async throws + -> AsyncThrowingStream + { + AsyncThrowingStream { continuation in + continuation.yield(InklingWithheldReasoningHeartbeat.event) + continuation.yield(.parsed(.init(content: "Hello there.", reasoningContent: nil))) + continuation.finish() + } + } + func tokenize(_ request: TokenizeRequest) async throws -> TokenizeResponse { .init(tokens: [1]) } + func detokenize(_ request: DetokenizeRequest) async throws -> DetokenizeResponse { .init(text: "ok") } + func applyTemplate(_ request: ApplyTemplateRequest) async throws -> TokenizeResponse { .init(tokens: [1]) } + } + + @Test func theSDKStreamCarriesExactlyOneHeartbeatFrame() async throws { + let request = OpenAIChatCompletionRequest( + model: "fixture", messages: [.init(role: .user, content: .text("Hi"))], stream: true) + var frames: [String] = [] + for try await frame in try await MLXOpenAIService(engine: Fixture()).streamChatCompletionFrames(request: request) { + frames.append(frame) + } + let rewritten = frames.compactMap(InklingWithheldReasoningHeartbeat.frame(rewriting:)) + #expect(rewritten.count == 1) + #expect(rewritten.allSatisfy { !$0.contains("role") && $0.contains(#""delta":{"content":""}"#) }) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/GPTOSSAutoToolRenderHintTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/GPTOSSAutoToolRenderHintTests.swift new file mode 100644 index 0000000000..0bf13fdc71 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/GPTOSSAutoToolRenderHintTests.swift @@ -0,0 +1,140 @@ +import Foundation +import MLXLMCommon +import MLXLMServer +import Testing + +@testable import ProviderCore + +/// The type the ingress repair writes beside a union, a mixed `enum`, a `not` +/// or an `if` is a render hint (`QwenParserLiteralReading.rendersSiblingType`). +/// GPT-OSS's `auto` grammar compiles the declaration without it, so a union's +/// arguments are no longer held to its first branch. +@Suite("GPT-OSS auto tool grammar render hints") +struct GPTOSSAutoToolRenderHintTests { + private typealias A = GPTOSSAutoFixture + private typealias F = GPTOSSForcedFixture + private typealias T = HarmonyByteTestTokenizer + + private static func tool(_ name: String, _ schema: [String: Any]) -> [String: Any] { + A.tool(name, ["type": "object", "properties": ["v": schema], "required": ["v"]]) + } + + /// Declarations as the coordinator forwards them today: the union kept, + /// the repair's render type beside it. + private static var hinted: [String: [String: Any]] { + [ + "adjust": tool("adjust", [ + "anyOf": [["type": "string"], ["type": "integer"]], "type": "string", + ]), + "pick": tool("pick", [ + "oneOf": [["type": "string"], ["type": "integer"]], "type": "string", + ]), + "mode": tool("mode", [ + "enum": ["default", "inherit", -1] as [Any], "type": "string", + ]), + ] + } + + private static func accepts(_ constraint: GPTOSSAutoToolConstraint, _ name: String, _ value: String) -> Bool { + guard let header = A.walk(F.analysis("x") + F.call(name, ""), constraint), + let state = A.walk("{\"v\":\(value)}", constraint, from: header) + else { return false } + return constraint.nextState(state: state, tokenID: T.call) == -1 + } + + @Test("a union with the repair's render type admits each of its branches") + func hintedUnionsAdmitEveryBranch() throws { + let tools = Self.hinted + let constraint = try A.constraint(tools: [tools["adjust"]!, tools["pick"]!]) + for name in ["adjust", "pick"] { + #expect(Self.accepts(constraint, name, "-4200"), "\(name)") + #expect(Self.accepts(constraint, name, "\"-4200\""), "\(name)") + } + } + + @Test("a mixed enum with the repair's render type admits its non-string member") + func hintedEnumAdmitsItsMembers() throws { + let constraint = try A.constraint(tools: [Self.hinted["mode"]!]) + #expect(Self.accepts(constraint, "mode", "-1")) + #expect(Self.accepts(constraint, "mode", "\"inherit\"")) + } + + @Test("an enum the render type contradicts admits its members") + func contradictedEnumAdmitsItsMembers() throws { + let constraint = try A.constraint(tools: [Self.tool("level", ["enum": [1, 2, 3], "type": "string"])]) + #expect(Self.accepts(constraint, "level", "2")) + } + + @Test("a not of the render type admits values of every other type") + func notOfTheRenderTypeAdmitsOtherTypes() throws { + let constraint = try A.constraint(tools: [Self.tool("other", ["not": ["type": "string"], "type": "string"])]) + #expect(Self.accepts(constraint, "other", "5")) + #expect(Self.accepts(constraint, "other", "true")) + } + + @Test("a hinted node marked nullable admits null, as the strict check reads it") + func hintedNullableNodesAdmitNull() throws { + let tools = [ + Self.tool("adjust", [ + "anyOf": [["type": "string"], ["type": "integer"]], "type": "string", "nullable": true, + ]), + Self.tool("pick", ["oneOf": [["type": "integer"]], "type": "integer", "nullable": true]), + Self.tool("mode", ["enum": ["default", "inherit", -1] as [Any], "type": "string", "nullable": true]), + ] + let constraint = try A.constraint(tools: tools) + for name in ["adjust", "pick", "mode"] { + #expect(Self.accepts(constraint, name, "null"), "\(name)") + } + #expect(Self.accepts(constraint, "adjust", "-4200")) + #expect(Self.accepts(constraint, "pick", "7")) + #expect(Self.accepts(constraint, "mode", "-1")) + } + + /// Declarations without a render hint, which the pre-pass returns as + /// they are, and Pydantic's nullable unions, whose render type the + /// widening already drops (`withoutUnionRepair`): their compiled + /// arguments are exactly those before. + private static var unchanged: [(tool: [String: Any], identical: Bool)] { + [ + (F.weather, true), (F.time, true), (A.readZod, true), (A.bookInlined, true), (A.search, true), + (tool("plain", ["type": "integer"]), true), + (tool("nullable", ["type": ["integer", "null"]]), true), + (tool("consistent", [ + "type": "object", "properties": ["a": ["type": "string"]], + "anyOf": [["required": ["a"]], ["properties": ["a": ["minLength": 1]]]] as [Any], + ]), true), + (A.createIssueRouted, false), + ] + } + + @Test("a declaration without a render hint compiles exactly as before") + func unhintedDeclarationsCompileAsBefore() throws { + for (raw, identical) in Self.unchanged { + let declared = try A.declared([raw]) + let tool = try #require(declared.first) + let resolved = GPTOSSAutoToolGrammar.resolvingRefs(tool) + let before: CompiledToolSchema? = + (try? ToolConstraintSchemaCompiler.compile(tools: [resolved], mode: .auto).first) + ?? GPTOSSAutoToolGrammar.widenedArguments(resolved) + let prepared = try A.prepared(tools: [raw]) + let after = GPTOSSAutoToolGrammar.compiledArguments( + declared: declared, rendered: try #require(prepared.tools)) + let name = tool.function.name + if identical { + #expect(GPTOSSAutoToolGrammar.withoutRenderHintTypes(resolved) == resolved, "\(name)") + } + #expect(String(reflecting: after.first ?? nil) == String(reflecting: before), "\(name)") + } + } + + @Test("forced choices compile the request's tools as before") + func forcedChoicesAreUnchanged() throws { + let tools = Self.hinted + for raw in [tools["adjust"]!, tools["mode"]!] { + let request = try F.request(choice: "required", tools: [raw]) + let prepared = try? ToolChoicePromptPolicy.prepare(request, modelType: "gpt_oss") + let direct = try? ToolConstraintSchemaCompiler.compile(tools: request.tools ?? [], mode: .required) + #expect(String(reflecting: prepared?.compiledTools) == String(reflecting: direct)) + } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/GPTOSSToolCallRecoveryTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/GPTOSSToolCallRecoveryTests.swift new file mode 100644 index 0000000000..6760da8c66 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/GPTOSSToolCallRecoveryTests.swift @@ -0,0 +1,277 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon +import MLXLMServer +import Testing + +@testable import ProviderCore + +/// GPT-OSS calls its Harmony parser does not see (`GPTOSSToolCallRecovery`). +/// The fixtures are OpenRouter's tool-call fuzz cases as the coordinator +/// forwards them (`realistic:*:anyOf[string,null]@null`, +/// `oneOf[string,null]@string`, `oneOf[integer,string]@string`), with the +/// Harmony text GPT-OSS 20B wrote for them at T 0. +@Suite("GPT-OSS tool call recovery") +struct GPTOSSToolCallRecoveryTests { + static let giftTool = #"{"type":"function","function":{"name":"set_order_gift_message","strict":true,"parameters":{"# + + #""additionalProperties":false,"properties":{"gift_message":{"anyOf":[{"description":"Text to print on the gift card","type":"string"},"# + + #"{"description":"Remove the gift message","type":"null"}],"description":"The gift message for the order, or null to clear it","# + + #""nullable":true,"type":"string"}},"required":["gift_message"],"type":"object"}}}"# + static let noteTool = #"{"type":"function","function":{"name":"create_note","parameters":{"additionalProperties":false,"# + + #""properties":{"content":{"description":"Text body of the new note, or null for a blank note.","nullable":true,"# + + #""oneOf":[{"type":"string"},{"type":"null"}],"type":"string"}},"required":["content"],"type":"object"}}}"# + static let productsTool = #"{"type":"function","function":{"name":"list_products","parameters":{"additionalProperties":false,"# + + #""properties":{"category":{"description":"Numeric category ID or category name. Use an empty string for no category filter.","# + + #""oneOf":[{"type":"integer"},{"type":"string"}],"type":"integer"}},"required":["category"],"type":"object"}}}"# + /// A second tool that admits the same `{"content": …}` object. + static let memoTool = #"{"type":"function","function":{"name":"create_memo","parameters":{"type":"object","# + + #""properties":{"content":{"type":["string","null"]}},"required":["content"]}}}"# + + static let exit = "<|end|><|start|>assistant" + + static func prepared(_ tools: [String], choice: String? = nil) throws -> ToolChoicePromptPolicy.Prepared { + let body = #"{"model":"gpt-oss-20b","messages":[{"role":"user","content":"Call it again."}],"tools":["# + + tools.joined(separator: ",") + "]" + (choice.map { #","tool_choice":"# + $0 } ?? "") + "}" + let request = try ProviderLoop.decodeOpenAIRequest(Data(body.utf8)) + return try ToolChoicePromptPolicy.prepare(request, modelType: "gpt_oss") + } + + static func exited() -> GenerationLoopExitRecord { + let record = GenerationLoopExitRecord() + record.requestExit(.init(period: 19, span: 2_048, generatedTokens: 4_096)) + return record + } + + /// Routes `pieces` as visible text, then finishes with `stop`. + static func run(_ recovery: GPTOSSToolCallRecovery, _ pieces: [String], stopReason: String = "stop", + cutAtLimit: Bool = false) -> (sent: [MLXServerGenerationEvent], call: ToolCall?) { + var recovery = recovery + var sent: [MLXServerGenerationEvent] = [] + for piece in pieces { sent += recovery.route(.content(piece)) } + let finished = recovery.finish(stopReason: stopReason, cutAtLimit: cutAtLimit, hasCalls: false) + return (sent + finished.release, finished.call) + } + + static func text(_ events: [MLXServerGenerationEvent]) -> String { + events.map { if case .content(let text) = $0 { text } else { "" } }.joined() + } + + // MARK: - Arguments as the answer, after the loop guard's exit + + @Test(arguments: [ + (giftTool, #"{"gift_message":null}"#, "set_order_gift_message", ["gift_message": MLXLMCommon.JSONValue.null]), + (noteTool, #"{"content":"Pick up dry cleaning before 6pm on Thursday."}"#, "create_note", + ["content": .string("Pick up dry cleaning before 6pm on Thursday.")]), + ]) + func anAnswerThatIsOneToolsArgumentsLeavesAsThatCall( + tool: String, answer: String, name: String, arguments: [String: MLXLMCommon.JSONValue] + ) throws { + let recovery = try #require(GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: .harmony, + prepared: Self.prepared([tool]), loopExit: Self.exited())) + let (sent, call) = Self.run(recovery, [ + "But we need to produce a", Self.exit, "<|channel|>final<|message|>", answer, + ]) + #expect(call?.function.name == name) + #expect(call?.function.arguments == arguments) + #expect(Self.text(sent).isEmpty, "the held answer does not leave as text") + } + + @Test func aRecipientlessCommentaryAnswerAlsoLeavesAsTheCall() throws { + let recovery = try #require(GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: .harmony, + prepared: Self.prepared([Self.giftTool]), loopExit: Self.exited())) + let (_, call) = Self.run(recovery, [Self.exit + #"<|channel|>commentary json<|message|>{"gift_message":"Hi"}"#]) + #expect(call?.function.arguments == ["gift_message": .string("Hi")]) + } + + /// Every other answer after the exit leaves as it was written, in order. + @Test(arguments: [ + // Two declared tools admit it. + ([noteTool, memoTool], #"<|channel|>final<|message|>{"content":"x"}"#), + // Other text beside the object. + ([noteTool], #"<|channel|>final<|message|>Here: {"content":"x"}"#), + ([noteTool], "<|channel|>final<|message|>```json\n{\"content\":\"x\"}\n```"), + // Not one object. + ([noteTool], #"<|channel|>final<|message|>[{"content":"x"}]"#), + ([noteTool], #"<|channel|>final<|message|>{"content":"x"} {"content":"y"}"#), + ([noteTool], "<|channel|>final<|message|>{}"), + // An undeclared key, a value the schema refuses. + ([noteTool], #"<|channel|>final<|message|>{"content":"x","tag":1}"#), + ([giftTool], #"<|channel|>final<|message|>{"gift_message":5}"#), + // A plain answer. + ([noteTool], "<|channel|>final<|message|>Done: the note is created."), + ]) + func anyOtherAnswerLeavesAsWritten(tools: [String], answer: String) throws { + let recovery = try #require(GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: .harmony, + prepared: Self.prepared(tools), loopExit: Self.exited())) + let (sent, call) = Self.run(recovery, ["thinking", Self.exit, answer]) + #expect(call == nil) + #expect(Self.text(sent) == "thinking" + Self.exit + answer) + } + + @Test func withoutTheLoopGuardsExitTheAnswerIsNeverHeldOrRead() throws { + for exit in [nil, GenerationLoopExitRecord()] { + let recovery = try #require(GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: .harmony, + prepared: Self.prepared([Self.giftTool]), loopExit: exit)) + var held = recovery + let piece = #"<|start|>assistant<|channel|>final<|message|>{"gift_message":null}"# + #expect(held.route(.content(piece)) == [.content(piece)]) + #expect(Self.run(recovery, [piece]).call == nil) + } + } + + @Test func anAnswerCutAtTheLimitOrWithACallIsNotRead() throws { + let recovery = try #require(GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: .harmony, + prepared: Self.prepared([Self.giftTool]), loopExit: Self.exited())) + let answer = [Self.exit, #"<|channel|>final<|message|>{"gift_message":null}"#] + #expect(Self.run(recovery, answer, stopReason: "length").call == nil) + #expect(Self.run(recovery, answer, cutAtLimit: true).call == nil) + var withCall = recovery + _ = withCall.route(.content(answer[0])) + let call = ToolCall(function: .init(name: "set_order_gift_message", arguments: ["gift_message": .null])) + // A call releases what was held, before itself. + #expect(withCall.route(.toolCall(call)) == [.content(answer[0]), .toolCall(call)]) + #expect(withCall.finish(stopReason: "stop", cutAtLimit: false, hasCalls: true).call == nil) + } + + @Test func onlyAnAutoGPTOSSRequestWithToolsTakesIt() throws { + // A schema a forced choice also serves (`required` refuses `anyOf`). + let tools = [#"{"type":"function","function":{"name":"ping","parameters":{"type":"object","# + + #""properties":{"n":{"type":"integer"}},"required":["n"]}}}"#] + #expect(GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: .harmony, + prepared: try Self.prepared(tools), loopExit: nil) != nil) + #expect(GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: .harmony, + prepared: try Self.prepared(tools, choice: #""none""#), loopExit: nil) == nil) + #expect(GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: .harmony, + prepared: try Self.prepared(tools, choice: #""required""#), loopExit: nil) == nil) + #expect(GPTOSSToolCallRecovery.make(modelType: "qwen3_5", format: .harmony, + prepared: try Self.prepared(tools), loopExit: nil) == nil) + #expect(GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: .harmony, + prepared: try Self.prepared(tools), loopExit: nil, enabled: false) == nil) + #expect(GPTOSSToolCallRecovery.environmentKey == "DARKBLOOM_GPTOSS_TOOL_CALL_RECOVERY") + } + + @Test("`DARKBLOOM_GPTOSS_TOOL_CALL_RECOVERY` off turns it off; it reaches the launchd daemon") + func theSwitchReachesTheDaemon() { + let key = GPTOSSToolCallRecovery.environmentKey + for value in ["0", "off", "false", "no", " OFF "] { + #expect(!GPTOSSToolCallRecovery.isEnabled(environment: [key: value]), "\(value)") + } + for value in ["", "1", "on", "true"] { + #expect(GPTOSSToolCallRecovery.isEnabled(environment: [key: value]), "\(value)") + } + #expect(GPTOSSToolCallRecovery.isEnabled(environment: [:])) + #expect(LaunchAgent.inferencePassthroughEnvKeys.contains(key)) + #expect(LaunchAgent.passthroughEnvironment(from: [key: "0"])[key] == "0") + } + + // MARK: - A complete call frame ending an open analysis + + static let analysis = "<|channel|>analysis<|message|>The user wants us to call the list_products tool again. " + + "The previous calls used that format. So we should produce:\n\n```\n" + static let frame = #"assistant<|channel|>commentary to=functions.list_products<|channel|>commentary json"# + + #"<|message|>{"category":"Garden Tools"}"# + + @Test func aCompleteFrameEndingTheOpenAnalysisLeavesAsTheCall() throws { + let recovery = try #require(GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: .harmony, + prepared: Self.prepared([Self.productsTool]), loopExit: nil)) + let (sent, call) = Self.run(recovery, [Self.analysis, Self.frame]) + #expect(call?.function.name == "list_products") + #expect(call?.function.arguments == ["category": .string("Garden Tools")]) + // The analysis itself leaves unchanged. + #expect(Self.text(sent) == Self.analysis + Self.frame) + } + + @Test(arguments: [ + // Partial frames. + #"assistant<|channel|>commentary to=functions.list_products<|channel|>commentary json<|message|>{"category":"Gard"#, + #"assistant<|channel|>commentary to=functions.list_products<|channel|>commentary json"#, + // Text after the object. + #"to=functions.list_products<|channel|>commentary json<|message|>{"category":"Garden Tools"}"# + + "\n```\nThat is the call.", + // An undeclared function, a refused value, an unknown header word. + #"to=functions.delete_products<|channel|>commentary json<|message|>{"category":"Garden Tools"}"#, + #"to=functions.list_products<|channel|>commentary json<|message|>{"category":[1]}"#, + #"to=functions.list_products<|channel|>commentary yaml<|message|>{"category":"Garden Tools"}"#, + ]) + func anIncompleteOrUndeclaredFrameIsNotACall(frame: String) throws { + let recovery = try #require(GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: .harmony, + prepared: Self.prepared([Self.productsTool]), loopExit: nil)) + #expect(Self.run(recovery, [Self.analysis, frame]).call == nil) + } + + @Test func aFrameInAClosedAnalysisOrBeforeAnAnswerIsNotACall() throws { + let recovery = try #require(GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: .harmony, + prepared: Self.prepared([Self.productsTool]), loopExit: nil)) + #expect(Self.run(recovery, [Self.analysis, Self.frame, "<|end|>"]).call == nil) + #expect(Self.run(recovery, [Self.analysis, Self.frame, "<|end|><|start|>assistant<|channel|>final<|message|>Ok"]) + .call == nil) + #expect(Self.run(recovery, [Self.analysis, Self.frame], stopReason: "length").call == nil) + // No analysis at all. + #expect(Self.run(recovery, [Self.frame]).call == nil) + } + + // MARK: - Through the scheduler's event stream + + #if DEBUG + /// The engine output as the scheduler forwards it, with GPT-OSS's Harmony + /// call parser; streamed and complete-call clients alike. + static func serve(_ tool: String, output: [String], exited: Bool, streamed: Bool) async throws + -> [MLXServerGenerationEvent] + { + var request = try ProviderLoop.decodeOpenAIRequest(Data((#"{"model":"gpt-oss-20b","stream":true,"# + + #""messages":[{"role":"user","content":"Call it again."}],"tools":["# + tool + "]}").utf8)) + request.streamToolCallDeltas = streamed + let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "gpt_oss") + let handler = try ToolStreamPreparation.makeHandler(request: request, prepared: prepared, + modelType: "gpt_oss", streamToolCalls: streamed) + let upstream = AsyncStream.makeStream() + for chunk in output { upstream.continuation.yield(.chunk(chunk)) } + upstream.continuation.yield(.info(promptTokens: 9, completionTokens: 30, tokensPerSecond: 0, + finishReason: "stop")) + upstream.continuation.finish() + let recovery = GPTOSSToolCallRecovery.make(modelType: "gpt_oss", format: handler?.format, + prepared: prepared, loopExit: exited ? Self.exited() : GenerationLoopExitRecord()) + var events: [MLXServerGenerationEvent] = [] + for try await event in try MultiModelBatchSchedulerEngine(registryProvider: { [:] })._testMakeEventStream( + upstream: upstream.stream, cancelUpstream: {}, prepared: prepared, + releaseBox: OneShotRelease(release: { _ in }, modelId: request.model), + toolHandler: handler, harmonyCallRecovery: recovery) { + events.append(event) + } + return events + } + + static func calls(_ events: [MLXServerGenerationEvent]) -> [ToolCall] { + events.compactMap { + switch $0 { + case .toolCall(let call): call + case .toolCallDelta(let delta): delta.completed + default: nil + } + } + } + + @Test(arguments: [false, true]) + func theSchedulerReturnsTheRecoveredCalls(streamed: Bool) async throws { + let answer = ["<|channel|>analysis<|message|>I'm stuck.", Self.exit, + #"<|channel|>final<|message|>{"gift_message":null}"#] + let events = try await Self.serve(Self.giftTool, output: answer, exited: true, streamed: streamed) + #expect(Self.calls(events).map(\.function.name) == ["set_order_gift_message"]) + #expect(!Self.text(events).contains("gift_message")) + + let frame = try await Self.serve(Self.productsTool, output: [Self.analysis, Self.frame], exited: false, + streamed: streamed) + #expect(Self.calls(frame).map(\.function.arguments) == [["category": .string("Garden Tools")]]) + } + + @Test(arguments: [false, true]) + func theSchedulerLeavesAPlainAnswerAsText(streamed: Bool) async throws { + let answer = ["<|channel|>analysis<|message|>I'm stuck.", Self.exit, + "<|channel|>final<|message|>The gift message is cleared."] + let events = try await Self.serve(Self.giftTool, output: answer, exited: true, streamed: streamed) + #expect(Self.calls(events).isEmpty) + #expect(Self.text(events).hasSuffix("The gift message is cleared.")) + } + #endif +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/GemmaToolTypelessWalkTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/GemmaToolTypelessWalkTests.swift new file mode 100644 index 0000000000..7a742e544d --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/GemmaToolTypelessWalkTests.swift @@ -0,0 +1,125 @@ +import Foundation +import Jinja +import MLXLMServer +import Testing + +@testable import ProviderCore + +/// Invariant 8 beyond a bare `{}` property: a property that accepts any value +/// behind a local `$ref`, as an `anyOf`/`oneOf`/`allOf` of such members, or +/// as a typeless enum of mixed JSON types renders an empty type for Gemma, and +/// a tuple renders no STRING `items`, as the served template renders the +/// caller's own schema. Each needs the declarations as sent; such a +/// coordinator request is served without the prompt cache. +@Suite("Gemma typeless render positions") +struct GemmaToolTypelessWalkTests { + /// A request whose tool `f` declares `value` as `schema`, with `root` + /// merged into the parameters schema (for `$defs` / `definitions`). + private static func body(_ schema: [String: Any], root: [String: Any] = [:]) throws -> Data { + var parameters: [String: Any] = ["type": "object", "properties": ["value": schema], "required": ["value"]] + parameters.merge(root) { _, new in new } + return try JSONSerialization.data(withJSONObject: [ + "model": "gemma-4-26b-qat-4bit", + "messages": [["role": "user", "content": "Go."]], + "tools": [["type": "function", "function": ["name": "f", "description": "d", "parameters": parameters]]], + ] as [String: Any]) + } + + /// The template input for `value` (render type, nullable, items present) + /// and whether the served-cold rule fires, with and without the + /// declarations as sent. + private struct Render: Equatable { + let type: String + let nullable: Bool + let hasItems: Bool + let servedCold: Bool + } + + private static func render( + _ schema: [String: Any], root: [String: Any] = [:], withDeclarations: Bool = true + ) throws -> Render { + let data = try body(schema, root: root) + let request = try ProviderLoop.decodeOpenAIRequest(data) + let declared = withDeclarations ? ProviderLoop.extractChatTemplateControls(from: data).declaredTools : nil + let tools = ChatTemplateFixes.normalizeTools( + request.tools?.map { $0.toolSpec() }, context: .init(modelType: "gemma4"), declared: declared) + let parameters = (tools?.first?["function"] as? [String: any Sendable])?["parameters"] as? [String: any Sendable] + let value = try #require((parameters?["properties"] as? [String: any Sendable])?["value"] as? [String: any Sendable]) + return Render( + type: value["type"] as? String ?? "", + nullable: value["nullable"] as? Bool == true, + hasItems: value["items"] != nil, + servedCold: GemmaToolUnionTypeCache.changesRender(request, modelType: "gemma4", declared: declared)) + } + + @Test("a local $ref to a schema without a type renders an empty type") + func referenceToTypelessSchema() throws { + for container in ["$defs", "definitions"] { + let root: [String: Any] = [container: ["Cents": ["description": "Signed cents"]]] + let schema: [String: Any] = ["$ref": "#/\(container)/Cents"] + let rendered = try Self.render(schema, root: root) + #expect(rendered == Render(type: "", nullable: false, hasItems: false, servedCold: true), + "\(container): \(rendered)") + #expect(try Self.render(schema, root: root, withDeclarations: false).type == "string", "\(container)") + } + // A reference to a typed schema keeps its type. + let typed: [String: Any] = ["$defs": ["Cents": ["type": "integer"]]] + let kept = try Self.render(["$ref": "#/$defs/Cents"], root: typed) + #expect(kept.type != "" && !kept.servedCold, "\(kept)") + } + + /// The shared repair folds an `anyOf` with an any-value member (null or + /// not, typed members or not) to `string` and keeps no `nullable`, as such + /// an `anyOf` accepts every value; a `oneOf` of an any-value member and + /// null keeps its members and gains `nullable`. + @Test("an anyOf with an any-value member, or a oneOf of one and null, renders an empty type") + func nullableAnyValue() throws { + let cases: [([String: Any], Bool)] = [ + (["anyOf": [[:] as [String: Any], ["type": "null"]], "description": "Content or null"], false), + (["anyOf": [["type": "null"], [:] as [String: Any]]], false), + (["anyOf": [["type": "integer"], [:] as [String: Any]]], false), + (["oneOf": [[:] as [String: Any], ["type": "null"]]], true), + ] + for (schema, nullable) in cases { + let rendered = try Self.render(schema) + #expect(rendered == Render(type: "", nullable: nullable, hasItems: false, servedCold: true), + "\(schema): \(rendered)") + let repaired = try Self.render(schema, withDeclarations: false) + #expect(repaired.type == "string" && !repaired.servedCold, "\(schema): \(repaired)") + } + // Without an any-value member the union keeps its render type. + let typed = try Self.render(["anyOf": [["type": "integer"], ["type": "null"]]]) + #expect(typed == Render(type: "integer", nullable: true, hasItems: false, servedCold: false), "\(typed)") + } + + @Test("an allOf of any-value members renders an empty type") + func allOfAnyValue() throws { + let schema: [String: Any] = ["description": "Note text", "allOf": [[:] as [String: Any]]] + let rendered = try Self.render(schema) + #expect(rendered == Render(type: "", nullable: false, hasItems: false, servedCold: true), "\(rendered)") + #expect(try Self.render(schema, withDeclarations: false).type == "string") + } + + @Test("a typeless enum of mixed JSON types renders an empty type; a single-type enum keeps STRING") + func mixedEnum() throws { + let mixed: [String: Any] = ["enum": ["default", "inherit", "archive", -1]] + let rendered = try Self.render(mixed) + #expect(rendered == Render(type: "", nullable: false, hasItems: false, servedCold: true), "\(rendered)") + #expect(try Self.render(mixed, withDeclarations: false).type == "string") + let strings = try Self.render(["enum": ["a", "b"]]) + #expect(strings.type == "string" && !strings.servedCold, "\(strings)") + } + + @Test("a tuple renders no items block; an array with item schemas keeps its items") + func tupleItems() throws { + let tuple: [String: Any] = [ + "type": "array", "items": false, + "prefixItems": [["type": "string"], ["type": "integer"], ["type": "boolean"]], + ] + let rendered = try Self.render(tuple) + #expect(rendered == Render(type: "array", nullable: false, hasItems: false, servedCold: true), "\(rendered)") + #expect(try Self.render(tuple, withDeclarations: false).hasItems) + let list = try Self.render(["type": "array", "items": ["type": "integer"]]) + #expect(list.hasItems && !list.servedCold, "\(list)") + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenStrictToolGrammarTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenStrictToolGrammarTests.swift index 6d50d26b98..2d4392adfe 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenStrictToolGrammarTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenStrictToolGrammarTests.swift @@ -259,10 +259,10 @@ struct QwenStrictToolGrammarTests { + #""list":{"type":"array","items":{"type":"string","\#(marker)":true}}},"# + #""required":["any"],"additionalProperties":false}}}]"# if choice != nil { - // A forced choice compiles the declared tools, where a marked node - // compiles only as exactly `{type: string, : true}` - // (`ToolConstraintSchema`, unchanged here): an annotated or `false` - // marker is refused before any argument reading, as before. + // A forced choice compiles the declared tools, where a `false` + // marker (`none`) is refused before any argument reading + // (`ToolConstraintSchema`); the annotated `true` marker (`any`) + // compiles as free text (`annotatedRenderMarkersCompileUnderAForcedChoice`). #expect(throws: (any Error).self) { try F.prepared(F.body(tools: tools, choice: choice)) } return } @@ -290,6 +290,53 @@ struct QwenStrictToolGrammarTests { constraint, after: "\n\n")) } + /// A forced choice compiles a render-marked `{}` that keeps its + /// annotations (as the coordinator forwards `{"description": …}` and + /// `nullable/{}`) as it compiles the bare marker: free text. A marker + /// beside an assertion, or a `false` marker, is still refused. + @Test func annotatedRenderMarkersCompileUnderAForcedChoice() throws { + let marker = ToolSchemaNormalization.originalBooleanSchemaKey + func tools(_ node: String) -> [OpenAITool]? { + try? JSONDecoder().decode([OpenAITool].self, from: Data((#"[{"type":"function","function":{"name":"probe","# + + #""parameters":{"type":"object","properties":{"p":"# + node + #"},"required":["p"]}}}]"#).utf8)) + } + for node in [ + #"{"type":"string","\#(marker)":true}"#, + #"{"type":"string","\#(marker)":true,"description":"The content, or null for an empty placeholder."}"#, + #"{"type":"string","\#(marker)":true,"title":"P","default":null,"examples":[1]}"#, + ] { + for mode in [ToolConstraintMode.required, .named("probe")] { + let compiled = try ToolConstraintSchemaCompiler.compile(tools: tools(node), mode: mode) + guard case .object(let properties, _, _)? = compiled.first?.parameters, + case .string(let values, let nullable)? = properties.first?.schema, + values == nil, !nullable else { + Issue.record("\(node) did not compile as free text"); continue + } + } + } + for node in [ + #"{"type":"string","\#(marker)":true,"minLength":1}"#, + #"{"type":"string","\#(marker)":false}"#, + #"{"type":"string","\#(marker)":false,"description":"nothing"}"#, + #"{"type":"integer","\#(marker)":true}"#, + ] { + #expect(throws: (any Error).self, "\(node)") { + try ToolConstraintSchemaCompiler.compile(tools: tools(node), mode: .required) + } + } + // Auto keeps falling back to raw validation for every marker. + #expect(throws: (any Error).self) { + try ToolConstraintSchemaCompiler.compile( + tools: tools(#"{"type":"string","\#(marker)":true,"description":"x"}"#), mode: .auto) + } + // Served end to end under tool_choice required: the call constrains. + let body = F.body(tools: #"[{"type":"function","function":{"name":"probe","strict":true,"parameters":{"# + + #""type":"object","properties":{"p":{"type":"string","\#(marker)":true,"description":"anything"}},"# + + #""required":["p"],"additionalProperties":false}}}]"#, choice: #""required""#) + let (_, prepared) = try F.prepared(body) + #expect(prepared.compiledTools?.count == 1) + } + /// An optional string (`["string","null"]`, `anyOf` string or null) keeps /// its text constraint although the parser reads its `null` text as null: /// that literal is one the declaration admits. diff --git a/provider-swift/Tests/test_protocol_fixture_resources.py b/provider-swift/Tests/test_protocol_fixture_resources.py index b212240ac6..212c071ed9 100644 --- a/provider-swift/Tests/test_protocol_fixture_resources.py +++ b/provider-swift/Tests/test_protocol_fixture_resources.py @@ -13,6 +13,7 @@ # Digests captured from the original shared fixtures before platform removal. SHA256 = { "calibrated_capacity_wire_fixture": "c73d1be2972540dbe48e8cc5b3871a15f44dcbafb4f8c51f6ee27e88b01c2e41", + "coordinator_features_wire": "aaefb0b56ac4c16415cbcfea86c61625fa9c0d0c97e6db76ff8eeceba9bb7021", "calibrated_deadline_decisions": "079a387c50070d2742e95dee1c6a8115ba49d10934eacc219574adb8c4ac6650", "deadline_coverage_confidence": "3a96307ff7cdb2e3949c039313549d1f2e0142b8f49fc2d23b20882704d760eb", "deadline_unbounded_reasons": "547b9cdf473f19d120e9f2e5db5dd47d3211796f8b1b85d685c7dce748aa1d4c", @@ -30,6 +31,7 @@ "Inference/Performance/Deadline/DeadlineCoverageConfidenceTests.swift": ["deadline_coverage_confidence"], "Inference/Performance/Deadline/DeadlineDecisionFixtureTests.swift": ["calibrated_deadline_decisions"], "Inference/Memory/ProcessMemoryTelemetryTests.swift": ["process_memory_wire"], + "Inference/Performance/CoordinatorDecodeRateDecayTests.swift": ["coordinator_features_wire"], }