diff --git a/.github/workflows/provider-tests.yml b/.github/workflows/provider-tests.yml index a7602b7527..bbabc590d3 100644 --- a/.github/workflows/provider-tests.yml +++ b/.github/workflows/provider-tests.yml @@ -456,6 +456,14 @@ jobs: --output-dir "$RUNNER_TEMP/provider-test-diagnostics" \ --diagnostic-after-seconds 900 --timeout-seconds 1800 \ -- ../scripts/run-provider-tests.sh + - name: Test Gemma quoted numeric argument conformance switches + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.test-products.outcome == 'success' }} + working-directory: provider-swift + timeout-minutes: 5 + run: | + for enabled in 0 1; do + env DARKBLOOM_GEMMA_SCHEMA_COERCION="$enabled" ../scripts/run-nested-suite.sh GemmaQuotedArgumentConformanceTests --no-parallel + done - name: Upload provider test diagnostics if: ${{ !cancelled() && steps.provider-unit-tests.outcome != 'skipped' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 diff --git a/changelog.d/gemma-quoted-numeric-arguments.md b/changelog.d/gemma-quoted-numeric-arguments.md new file mode 100644 index 0000000000..80c05bc9f4 --- /dev/null +++ b/changelog.d/gemma-quoted-numeric-arguments.md @@ -0,0 +1,3 @@ +### Gemma quoted numeric tool arguments + +Adopt the opt-in SDK parser fix. `DARKBLOOM_GEMMA_SCHEMA_COERCION=1` enables it (the LaunchAgent forwards the switch to the installed service); unset or `0` retains current behavior. Numeric marker strings become numbers at frame close only when the parameter schema unambiguously requests a numeric type. Potentially converted values stay withheld from argument deltas until the completed parse; unsupported or ambiguous schemas preserve their quoted text. The provider still validates strict calls. diff --git a/changelog.d/grammar-aware-mtp.md b/changelog.d/grammar-aware-mtp.md new file mode 100644 index 0000000000..e617eabf11 --- /dev/null +++ b/changelog.d/grammar-aware-mtp.md @@ -0,0 +1,3 @@ +### Grammar-aware MTP + +- Adopt SDK #409: with `DARKBLOOM_CBV2_MTP_GRAMMAR=1` (forwarded by the LaunchAgent), constrained rows draft with MTP and every committed position is verified under the row's grammar; unset or `0` keeps 0.10.12's target-only constrained rows. Default per `docs/reference/configuration.md` (SDK feature defaults). diff --git a/changelog.d/native-reasoning-budget.md b/changelog.d/native-reasoning-budget.md new file mode 100644 index 0000000000..32b7903a3a --- /dev/null +++ b/changelog.d/native-reasoning-budget.md @@ -0,0 +1,3 @@ +### Changed + +- Add native reasoning budgets for supported local Nemotron Super and MiMo routes. Positive `reasoning.max_tokens` now reaches the SDK sampler, closes the thought at its token limit and continues the answer within the original total output ceiling. Unsupported routes and conflicting thinking-off controls remain refused. On by default since 0.10.13 for Nemotron 3.5 Super and MiMo V2.6 (each measured in its ON state); `DARKBLOOM_NATIVE_REASONING_BUDGET=0` restores 0.10.12 for every family. A Super cluster pair cannot hold a budget: there the request is refused at the engine bridge (unsupported output control) instead of by the prompt contract. diff --git a/changelog.d/qwen-constraint-spans.md b/changelog.d/qwen-constraint-spans.md new file mode 100644 index 0000000000..467384d6e1 --- /dev/null +++ b/changelog.d/qwen-constraint-spans.md @@ -0,0 +1,4 @@ +### Qwen constraint spans + +- Add default-off `DARKBLOOM_CONSTRAINT_SPANS` support for eligible Qwen strict-auto tool requests and JSON reasoning. Ordinary reasoning and content may draft; tool framing/arguments and JSON values remain protected. Text after a completed call may draft again. +- Forward the flag into the installed provider service. Preserve existing grammar admission, masks, engine eligibility and off behavior. No full-model speedup is claimed. diff --git a/changelog.d/sdk-feature-defaults.md b/changelog.d/sdk-feature-defaults.md new file mode 100644 index 0000000000..acb83f03af --- /dev/null +++ b/changelog.d/sdk-feature-defaults.md @@ -0,0 +1,3 @@ +### SDK feature defaults + +- Add provider defaults for feature switches the SDK reads (`SDKFeatureDefaults`). An unset switch follows the release's default, which is on only where it was measured in its ON state: per exact model id for constraint spans and grammar-aware MTP (grammar only where spans are on), per family for native reasoning budgets, process-wide for the Gemma parser switch. An operator value always wins; `=0` restores 0.10.12 on every model. Injected defaults are recorded in `DARKBLOOM_SDK_DEFAULTS_INJECTED` and never written into a service plist, so an installed service follows the running release. `darkbloom start` (and `benchmark`, on stderr) prints `SDK feature defaults on: …`. Nothing is on by default unless its switch is listed. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index 7a7432c946..1ec8a15e66 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -17,6 +17,11 @@ The native [cross-stream fence ordering](inference.md#cross-stream-fence-orderin uses the same memory reservations and command-buffer limits. Its component tests do not change a model's hardware qualification or usable-memory grant. +[Native reasoning token budgets](inference.md#native-reasoning-token-budgets) +use the existing model admission and native retirement owners. They add no +hardware eligibility or memory grant; target-only budget rows can reduce mixed +batch chaining, so the feature carries no throughput qualification. + ## Context Automatic local cluster batching prices each lane's full registered request @@ -1203,6 +1208,10 @@ Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Metadata/GLM5NextImageBudget.swift`, and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Metadata/GLM5NextServingMetadata.swift`. +### Gemma o4 parser qualification + +The [Gemma quoted numeric tool arguments change](inference.md#gemma-quoted-numeric-tool-arguments) operates on CPU text and schema values. Parser tests do not establish full-model numerical, memory, throughput or concurrency qualification. This parser switch does not change hardware admission or model memory allowances. + ### Gemma batch arithmetic evidence boundary The ordinary Gemma stage decode scope preserves per-request projection, value diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 3aee017f86..a1235ab8f3 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3757,6 +3757,10 @@ Sources: `provider-swift/Sources/ProviderCore/Inference/Tools/GemmaJSONAnswerPol `provider-swift/Sources/ProviderCore/Inference/GemmaJSONAnswerConstraint.swift`, `provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift`. +### Gemma quoted numeric tool arguments + +The SDK parser behind `DARKBLOOM_GEMMA_SCHEMA_COERCION` is adopted through the `libs/mlx-swift-lm` gitlink. Numeric marker strings become numbers at frame close only when the parameter schema unambiguously requests a numeric type. Potentially converted values stay withheld from argument deltas until the completed parse; unsupported or ambiguous schemas preserve their quoted text. The provider still validates strict calls. See the [process switch](../reference/configuration.md#engine-and-scheduler). Source: `libs/mlx-swift-lm/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift` (`GemmaFunctionParser`). + ### Constrained Qwen JSON answers Qwen, Bonsai 2 27B and Nemotron 3.5 Lightning share this machinery. @@ -4280,6 +4284,42 @@ Which requests render this way: re-encodes the bodies it forwards sorted; darkbloom-platform#919 keeps the caller's order for the builds it names). +### Native reasoning token budgets + +Supported local Super and MiMo requests can opt into a thought-token ceiling +through [the default-off switch](../reference/configuration.md#native-reasoning-budgets). +`NemotronSuperPromptContract` and `MiMoV26RawControlEvidence` retain validated +`reasoning.max_tokens`; explicit thinking-off conflicts with the budget. MiMo +retains the value across both Chat and Responses decoding. Super uses its bound +Chat owner; this change does not register a Super Responses route. + +`NativeReasoningBudget` is an internal sidecar excluded from +`ChatCompletionRequest` wire coding. Family owners set the initial thought +state: Super's rendered prompt opens the thought, while MiMo waits for an open +marker. `EngineV2Bridge.submitTokenized` checks its actual engine capability and +validates atomic marker encode/decode round trips with the loaded tokenizer +before admission. Distributed or unsupported engines refuse the control. + +The SDK default sampler counts confirmed thought payload tokens, permits an +early natural close and forces the close at N before continuing the same +request's answer. Markers do not spend N, later opens cannot reset it, and the +original total output ceiling and stops still win. The close counts toward +completion usage; logprobs remain the raw model probabilities. Budget rows use +ordinary target decoding for their full lifetime; they do not chain or draft. +Other rows keep their sampling semantics, but a mixed batch may lose chaining. +A generic token constraint or cancel/resubmit thought-exit continuation cannot +be combined with this first budget contract. + +Text and supported native image paths carry the same sidecar. Native media +seals, admission, cancellation and retirement remain owned by the existing +engine lifecycle. This capability changes no model memory limit or hardware +qualification and makes no throughput or full-model quality claim. + +Sources: `provider-swift/Sources/ProviderCore/Inference/Prompting/NativeReasoningBudget.swift` +(`resolved`), `provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift` +(`submitTokenized`), and `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/ReasoningBudgetV2.swift` +(`CBv2ReasoningBudget`). + ### Reasoning effort Every model that reasons takes each effort a client names (`none`, @@ -4375,6 +4415,36 @@ the owner's go. ### Strict tool-call grammar +When the [constraint-span setting](../reference/configuration.md#engine-and-scheduler) +(`DARKBLOOM_CONSTRAINT_SPANS`) enables speculation, `QwenStrictToolConstraint` +exposes ordinary reasoning and content as free spans through +`CBv2FreeSpanTokenConstraint`. Its pure preview accepts only tokens that stay +in the same state without touching a marker prefix. Call openings, framing, +arguments and partial markers remain protected; text after a closed call can +become free again. `QwenJSONAnswerConstraint` (the Qwen-family +`JSONAnswerConstraint` that `JSONAnswerPolicy` builds) exposes only Qwen +reasoning before the answer: the JSON value, string bodies and trailing +whitespace stay protected. Other JSON families build the plain +`JSONAnswerConstraint`, which does not conform to `CBv2FreeSpanTokenConstraint`, +so they neither draft nor keep MTP history and retain target-only decoding. +Neither constraint mutates its interned states while previewing a speculative +token. + +Disabling the setting retains request-wide target-only constrained decoding. +Existing grammar admission, masks and sampler/model/lifecycle eligibility remain +authoritative. Required/named calls acquire no new strict-auto grammar. An +eligible native Qwen assistant retains committed history through protected +spans, but starts no draft there. Engines with native completion tracking remain +ineligible. The LaunchAgent forwards the flag at installation; the SDK snapshots +it at engine construction. + +`QwenConstraintSpanServingTests` checks streamed content, reasoning, calls and +accounting through the scheduler, bridge and engine. Coverage includes multiple +calls, thinking on/off, short budgets, cancellation and refusal recovery. Tiny +native Qwen target/assistant fixtures check committed history across protected +entry and return to free text. These are bounded integration fixtures, not +full-model throughput or production qualification. + A `strict` `auto` call is checked against the caller's schema only when its frame closes ([streamed auto tool calls](#streamed-auto-tool-calls)), after the answer has started, so on the Qwen 3.5 template family (`qwen3_5`, diff --git a/docs/developer/build.md b/docs/developer/build.md index c7c4b6f6fa..94b708f801 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build The Provider And Landing -> Last updated: 2026-11-12 +> Last updated: 2026-11-13 Build the provider, its source-matched native resources, and the independent landing site from this repository. Backend, sidecar, console and admin builds @@ -1134,3 +1134,7 @@ Qwen27 TP batch prefix capture/restore changes the Runtime target only; it reuses the pinned SDK owned-state APIs. Rebuild the worker and planner together because the same complete LOAD budget prices the additional snapshot banks. See [warm-prefix validation](test.md#qwen27-tp-warm-prefix-checks). + +### Gemma o4 dependency adoption + +The Gemma quoted numeric tool arguments conformance suite consumes the exact `libs/mlx-swift-lm` gitlink, including its parser tests. Use the normal recursive dependency checkout and test-product build; the [isolated conformance runs](test.md#gemma-o4-conformance) reuse those products without a second build. Native MLX and nested core pins are unchanged. diff --git a/docs/developer/test.md b/docs/developer/test.md index 4d37c252d8..54e911710b 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -123,6 +123,21 @@ No model weights or live provider state are needed. ## Provider And SDK +`QwenConstraintSpanServingTests` sends strict-auto and JSON requests through +the public scheduler, bridge and real `EngineV2`. Deterministic native targets +supply literal reasoning, content and call arguments; an unconstrained control +proves drafting works. Tests require drafting around protected calls, unchanged +off/on output and accounting, multiple calls, thinking on/off and JSON that +never returns to a free span after its value starts. Tiny Qwen target/inline +assistant fixtures also verify committed history through protected entry and +return to text, cancellation with request-ID reuse, short output budgets, and +bridge refusal recovery. `QwenJSONFreeSpanTests` checks preview purity, partial +markers, scalar/string answers, exhaustion and non-Qwen fallback. + +Run these with the normal source-matched provider test products and isolated +runner below. Tiny fixtures do not qualify full-model throughput, production +resource use or native completion-tracked engines. + From the repository root, use the [MiMo regression fixture recipe](#mimo-regression-fixtures) to prepare the inputs and run `make provider-test`. @@ -3687,3 +3702,7 @@ one-line explanation and that request lengths still come from every build; read and the router's build-keyed setup. `swift test --filter DistributedAutomaticBatchPlannerTests` and `--filter ClusterObservabilityTests` from `provider-swift` cover replacement calibration and the recorded builds. + +### Gemma o4 conformance + +`GemmaQuotedArgumentConformanceTests` exercises the adopted SDK through provider-facing types without loading a model. CI reuses the compiled test products and runs this suite in separate processes with `DARKBLOOM_GEMMA_SCHEMA_COERCION=0` and `=1`; the ordinary suite checks the SDK's own default (off); the provider's default is `SDKFeatureDefaults`'s, covered by its own tests (test processes never run `apply()`). In an authorized CPU test lane, from `provider-swift`, use `DARKBLOOM_GEMMA_SCHEMA_COERCION=1 ../scripts/run-nested-suite.sh GemmaQuotedArgumentConformanceTests --no-parallel` after building the exact pinned composition. GPU qualification remains separate. diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 656d56b148..db3e8df58d 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -4099,8 +4099,16 @@ Positive Gemma caps retain the 128-token floor; `0` defers prefill while decodin Pure-prefill stripes are unchanged. These variables are not forwarded to a LaunchAgent; see the [scheduler environment reference](../reference/configuration.md#engine-and-scheduler). +### Gemma o4 parser switch + +`DARKBLOOM_GEMMA_SCHEMA_COERCION` is read once when the process starts; the LaunchAgent forwards an operator value to the installed service (`0` turns it off, `1` on). The [configuration reference](../reference/configuration.md#engine-and-scheduler) gives its default ([SDK feature defaults](../reference/configuration.md#sdk-feature-defaults)) and rollback. + ## LaunchAgent environment passthrough +`DARKBLOOM_NATIVE_REASONING_BUDGET` is forwarded to the service when the operator +sets it (`0` turns budgets off for every family, `1` on); see [native reasoning budgets](../reference/configuration.md#native-reasoning-budgets) +for its default, values and supported request behavior. + The SDK's [Gemma row-mapped NAX route](../reference/configuration.md#gemma-4-row-mapped-nax) is enabled by default within its hardware and model guards. The provider forwards `DARKBLOOM_GEMMA4_NAX_ROW_MAP` verbatim, including an explicit empty value, when diff --git a/docs/provider/hardware-requirements.md b/docs/provider/hardware-requirements.md index 49284a6022..7bab395d2a 100644 --- a/docs/provider/hardware-requirements.md +++ b/docs/provider/hardware-requirements.md @@ -1,6 +1,6 @@ # Provider hardware requirements -> Last updated: 2026-11-07 +> Last updated: 2026-11-13 Reference for what a Mac needs to run the `darkbloom` provider: the minimum requirements, the chip families the provider distinguishes, which catalog @@ -93,6 +93,9 @@ period. `doctor` does not name the reason. Follow the [authenticated registration steps](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/docs/consumer/authentication.md#6-register-hardware-interest). Registration is an opt-in record; email delivery is a separate operation. +[Native reasoning budgets](../architecture/inference.md#native-reasoning-token-budgets) +do not widen model eligibility, memory limits or hardware qualification. + ## Minimum requirements New network providers require macOS 27 or later and current qualified App Attest diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index b22056c4e2..7907f82358 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -560,7 +560,9 @@ and rollback are defined in the [provider configuration reference](../provider/c | `DARKBLOOM_NEMOTRON_SUPER_VIDEO_PRUNING` | number in [0, 1) (surrounding spaces ignored) | `0.5` (`NemotronSuperVideoPreprocessing.defaultPruningRate`) | `provider-swift/Sources/ProviderCore/Inference/Vision/NemotronSuperVideoFeatures.swift` (`validatedPruningRate`) | EVS pruning rate `q` of Super video requests, in the managed slot and the qualification hook: a video of `T` tubelets of `N` visual rows keeps `max(N, int(T * N * (1 - q)))` rows; `0` keeps every row. Any other value fails the load before its LOAD claim and installation. A value below `0.5` keeps more rows, so a video's prompt has more tokens than the coordinator estimates for it, since that estimate assumes `0.5`. Not forwarded to LaunchAgents. | | `DARKBLOOM_MTP_VERIFICATION_MODE` | `rectangular`, `serial`, `serial_target`, `automatic` | `automatic` | `provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift` | MTP verification strategy (benchmark session). | | `DARKBLOOM_MTP_ACCEPTANCE` | `exact`, `typical`, `typical:` (finite positive delta) | `exact` | `provider-swift/Sources/ProviderBenchmark/MTPProductionSession.swift`; `provider-swift/Sources/ProviderCore/Inference/MTP/MTPAcceptancePolicy.swift` (`benchmarkOverride`) | MTP draft acceptance rule (benchmark session only). An unrecognized value uses `exact`. Serving reads no environment variable for this rule; it reads `[backend] mtp_acceptance` and `mtp_acceptance_by_model` in [`provider.toml`](../provider/cli-reference.md#providertoml-keys-read-by-the-cli). | -| `DARKBLOOM_STRICT_TOOL_GRAMMAR` | unset: 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. While a constrained answer decodes, no answer on that Mac drafts with MTP. See [strict tool-call grammar](../architecture/inference.md#strict-tool-call-grammar). Forwarded to the LaunchAgent. | +| `DARKBLOOM_CONSTRAINT_SPANS` | trimmed, case-insensitive `1`, `true`, `on`, `yes`; other values disable | off | `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_CBV2_MTP_GRAMMAR` | case-insensitive `1`, `true`, `on`, `yes`; other values disable | off | `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. 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_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. | @@ -578,6 +580,27 @@ and rollback are defined in the [provider configuration reference](../provider/c | `DARKBLOOM_TTFT_THINK_CONTENT_SEED` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningPromptProbe.swift` (`seedsPlainTailContentByDefault`) | Qwen3-VL (`qwen3_vl_moe`, `plainTailContentModelTypes`) requests on the `qwen3` reasoning parser whose prompt tail has no think marker start in content state, so the answer streams instead of waiting for a tag or the end of generation. Other model types, including close-only Qwen reasoners, keep undecided parsing. `0` restores undecided parsing. Forwarded to the LaunchAgent. | | `DARKBLOOM_JSON_ANSWER_GRAMMAR` | `qwen`, `0`, `off`, `false`, `no`, `none` (trimmed, case-insensitive) narrow; any other value or unset admits every family | every admitted family | `provider-swift/Sources/ProviderCore/Inference/Tools/JSONAnswerPolicy.swift` (`JSONAnswerPolicy.Families`) | Which families sample a tool-free JSON `response_format` answer under the grammar ([constrained Qwen JSON answers](../architecture/inference.md#constrained-qwen-json-answers)): Qwen 3.5/3.6/3.8, and for answer-first prompts on a single Mac Bonsai 2 27B and Nemotron 3.5 Lightning. The narrowing values keep it to the Qwen types, as before Bonsai and Lightning were admitted; the others then keep prompt-only steering. Read once per process. Forwarded to the LaunchAgent. | | `DARKBLOOM_QWEN_JSON_SCHEMA_REWRITE` | `off`, `0`, `false`, `no` (trimmed, case-insensitive) disable; unset or any other value enables | on | `provider-swift/Sources/ProviderCore/Inference/Tools/QwenJSONSchemaRewrite.swift` (`QwenJSONSchemaRewrite.enabled`) | Qwen JSON answers constrain a `json_schema` outside the subset: rewritten exactly (Pydantic, OpenAI strict, zod), else without its value assertions (`minimum`, `pattern`, `format`, …; never refused for those values), else, for an object root, as a JSON object ([constrained Qwen JSON answers](../architecture/inference.md#constrained-qwen-json-answers)). The off words restore today's prompt-only decline for them. Read once per process. Forwarded to the LaunchAgent. | +| `DARKBLOOM_GEMMA_SCHEMA_COERCION` | exact `1` enables; any other non-empty value is off | unset (off); `0` keeps legacy behavior | `libs/mlx-swift-lm/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift` (`GemmaFunctionParser`) | Gemma quoted numeric tool arguments: a marker-quoted number for an integer/number parameter is typed by the tool's schema at frame close ([parser behavior](../architecture/inference.md#gemma-quoted-numeric-tool-arguments)). Read once per process; set it before starting the provider (reinstall for the service), `0` and a restart roll back. Forwarded by the LaunchAgent. | + +### SDK feature defaults + +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). `DARKBLOOM_NATIVE_REASONING_BUDGET` admits `reasoning.max_tokens` for the families in `reasoningBudgetFamilies` (`NativeReasoningBudget.isEnabled(for:)`). 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`). + +### Native reasoning budgets + +| Variable | Values | Default | Source | Effect | +|---|---|---|---|---| +| `DARKBLOOM_NATIVE_REASONING_BUDGET` | `1`, `true`, `yes`, `on` (case-insensitive) enable for every family; every other non-empty value disables | **on for Nemotron 3.5 Super and MiMo V2.6** (provider default since 0.10.13, `SDKFeatureDefaults`); `0` restores 0.10.12 for every family | `provider-swift/Sources/ProviderCore/Inference/Prompting/NativeReasoningBudget.swift` (`isEnabled(for:)`); SDK `CBv2ReasoningBudget.enabled` | Enables validated `reasoning.max_tokens` on supported local Super/MiMo routes. Set before engine construction; forwarded to the daemon. | + +The request budget is a positive JSON integer no greater than 2,147,483,647; +an explicit thinking-off setting conflicts with it. The total output ceiling +remains separate. See [native reasoning token budgets](../architecture/inference.md#native-reasoning-token-budgets) +for supported routes, exact token accounting and refusal behavior. ### Managed Nemotron Super slot diff --git a/docs/reference/protocol-messages.md b/docs/reference/protocol-messages.md index e06a6c9ad8..d66f437845 100644 --- a/docs/reference/protocol-messages.md +++ b/docs/reference/protocol-messages.md @@ -1337,6 +1337,14 @@ the part type and the service-validated cut-off (`handleInferenceRequest`), `provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift` (`mapInferenceErrorToStatus`). +#### Native reasoning budgets + +The existing `reasoning.max_tokens` body field can be admitted by supported +local Super/MiMo family routes under the [native budget contract](../architecture/inference.md#native-reasoning-token-budgets). +The provider carries it internally to the SDK; no WebSocket field or serialized +internal-budget field is added. Unsupported routes refuse it. The default-off +switch preserves the previous family refusal. + #### History reasoning under another name A decrypted Chat body's message with no `reasoning_content` (absent or null) but a `thinking` or `reasoning` string diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 859f641529..f41a5f9af3 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 859f641529adc2f8fd011b8df295ee214d673060 +Subproject commit f41a5f9af30761833960ff6e76a4fff52e8d1554 diff --git a/provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift b/provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift new file mode 100644 index 0000000000..18df9988cb --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Config/SDKFeatureDefaults.swift @@ -0,0 +1,203 @@ +import Foundation +import MLXLMCommon +#if canImport(Darwin) +import Darwin +#endif + +/// Provider defaults for feature switches the SDK reads from the process +/// environment (`libs/mlx-swift-lm` keeps every one of them opt-in). +/// +/// An operator value always wins: a switch the environment (the shell, or the +/// LaunchAgent plist, which forwards each key) sets to a non-empty value is the +/// SDK's to read, so `=0` is the kill switch and restores 0.10.12's +/// behaviour on every model, and `1` turns a switch on for every model. A switch +/// left unset (or empty) follows this release's evidence, on only where it was +/// measured in its ON state: +/// +/// - Per build: the slot factory turns `constraintSpansBuilds` and +/// `grammarMTPBuilds` 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 +/// hook): set in every `darkbloom` process at the `main.swift` entry, before +/// any command runs. A key a `darkbloom` process injected, including a +/// parent's (`injectedMarkerKey`), is never the operator's: it is not written +/// into a service plist (`LaunchAgent.passthroughEnvironment`), so an +/// installed service follows the running release's defaults. +public enum SDKFeatureDefaults { + /// #2090 / SDK #408: Gemma quoted numeric tool arguments typed by the + /// schema. One process-wide parser switch (`GemmaFunctionParser`). + static let gemmaQuotedNumbers: [String] = [] + + /// #2101 / SDK #413: MTP drafting through free Qwen reasoning and text + /// spans. A build is an exact model id, lowercased (`matches`). + static let constraintSpansBuilds: Set = [] + + /// SDK #409: grammar-aware MTP verification of constrained rows, on a + /// listed build only where constraint spans are on (measured together). + static let grammarMTPBuilds: Set = [] + + /// #2099 / SDK #411: `reasoning.max_tokens` budgets, per family. + static let reasoningBudgetFamilies: Set = [.nemotronSuper, .mimoV26] + + /// The process-wide switches. With a budget family listed, the budget + /// switch is set too, so every engine accepts budget rows; only + /// `NativeReasoningBudget.isEnabled(for:)` admits a request's budget. + public static let onByDefault: [String] = + gemmaQuotedNumbers + (reasoningBudgetFamilies.isEmpty ? [] : [NativeReasoningBudget.environmentKey]) + + static let constraintSpansKey = "DARKBLOOM_CONSTRAINT_SPANS" + static let grammarMTPKey = "DARKBLOOM_CBV2_MTP_GRAMMAR" + + /// Inherited by child processes and never forwarded to a plist: the keys a + /// `darkbloom` process injected, so a `darkbloom` child (the desktop app's + /// workers, a cluster service's parts) does not take them for the operator's. + public static let injectedMarkerKey = "DARKBLOOM_SDK_DEFAULTS_INJECTED" + + /// Every key this mechanism may set process-wide, whatever a release + /// lists; a marker naming any other key is not trusted. + static let injectableKeys: Set = ["DARKBLOOM_GEMMA_SCHEMA_COERCION", NativeReasoningBudget.environmentKey] + + /// The keys a parent `darkbloom` injected: named in `environment`'s marker, + /// injectable, with the value still `1`. + static func inherited(_ environment: [String: String]) -> Set { + Set((environment[injectedMarkerKey] ?? "").split(separator: ",").map(String.init)) + .filter { injectableKeys.contains($0) && environment[$0] == "1" } + } + + /// Whether `key`'s value is the release's (this process's, or a parent's + /// per the marker, so a process that never ran `apply` knows too), not the + /// operator's. + static func isInjected(_ key: String, in environment: [String: String], + injected: Set = injectedKeys) -> Bool { + injected.contains(key) || inherited(environment).contains(key) + } + + /// Whether `key` follows this release's default: unset, empty (what the + /// LaunchAgent drops, so foreground and service agree) or injected. + static func followsDefault(_ key: String, in environment: [String: String], + injected: Set = injectedKeys) -> Bool { + (environment[key]?.isEmpty ?? true) || isInjected(key, in: environment, injected: injected) + } + + /// Whether `modelId` is exactly one of `builds` (lowercased model ids): a + /// default never reaches another quantization, a fine-tune or a local path. + static func matches(_ builds: Set, modelId: String) -> Bool { + builds.contains(modelId.lowercased()) + } + + /// The per-build MTP defaults for one engine. `config` holds the SDK's + /// reading of the environment (the operator's value; off when unset); a + /// switch left unset, in the slot's environment and in the process's (what + /// the SDK read), is turned on for the listed builds only, grammar MTP only + /// where constraint spans are on (measured together). Returns the switches + /// it turned on, for the load log. + @discardableResult + static func applyMTPDefaults( + to config: inout CBv2MTPConfig, modelId: String, environment: [String: String], + processEnvironment: [String: String] = ProcessInfo.processInfo.environment, + spansBuilds: Set = constraintSpansBuilds, grammarBuilds: Set = grammarMTPBuilds + ) -> [String] { + func unset(_ key: String) -> Bool { + followsDefault(key, in: environment, injected: []) + && followsDefault(key, in: processEnvironment, injected: []) + } + var on: [String] = [] + if unset(constraintSpansKey), matches(spansBuilds, modelId: modelId) { + config.freeSpanSpeculation = true + on.append(constraintSpansKey) + } + if unset(grammarMTPKey), config.freeSpanSpeculation, matches(grammarBuilds, modelId: modelId) { + config.constrainedSpeculation = true + on.append(grammarMTPKey) + } + return on + } + + /// 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( + onByDefault: [String] = onByDefault, environment: [String: String] + ) -> [String: String] { + onByDefault.reduce(into: [:]) { out, key in + if environment[key]?.isEmpty ?? true { out[key] = "1" } + } + } + + /// What `apply` changes in a process environment. + struct Plan: Equatable { + var set: [String: String] = [:] + var unset: [String] = [] + /// The switches this release turned on, not the operator; sorted. + var injected: [String] = [] + } + + /// A key a parent `darkbloom` injected (named in its marker, value still + /// `1`) counts as unset, so this release's list decides it again: re-set + /// and recorded as injected if listed, unset if not. Every listed key the + /// environment leaves unset or empty is turned on; the marker names them. + static func plan(onByDefault: [String] = onByDefault, environment: [String: String]) -> Plan { + let fromParent = inherited(environment) + var operatorEnvironment = environment + for key in fromParent { operatorEnvironment[key] = nil } + var changes = Plan(set: projection(onByDefault: onByDefault, environment: operatorEnvironment)) + changes.injected = changes.set.keys.sorted() + changes.unset = fromParent.subtracting(changes.injected).sorted() + if !changes.injected.isEmpty { + changes.set[injectedMarkerKey] = changes.injected.joined(separator: ",") + } else if environment[injectedMarkerKey] != nil { + changes.unset.append(injectedMarkerKey) + } + return changes + } + + /// Apply the plan to this process and remember what it injected. + /// Returns the keys it turned on. + @discardableResult + public static func apply( + onByDefault: [String] = onByDefault, + environment: [String: String] = ProcessInfo.processInfo.environment + ) -> [String] { + let changes = plan(onByDefault: onByDefault, environment: environment) + for (key, value) in changes.set { setenv(key, value, 1) } + for key in changes.unset { unsetenv(key) } + injected.add(changes.injected) + return changes.injected + } + + /// The `start` / `benchmark` line naming what is on by default (and for + /// which builds or families); nil if nothing. + public static func summary( + environment: [String: String] = ProcessInfo.processInfo.environment, + injected: Set = injectedKeys + ) -> String? { + summary(environment: environment, injected: injected, + spansBuilds: constraintSpansBuilds, grammarBuilds: grammarMTPBuilds) + } + + static func summary(environment: [String: String], injected: Set, + spansBuilds: Set, grammarBuilds: Set) -> String? { + var on = injected.sorted().map { key in + key == NativeReasoningBudget.environmentKey + ? "\(key) (\(reasoningBudgetFamilies.map { "\($0)" }.sorted().joined(separator: ", ")))" : key + } + for (key, builds, scope) in [(constraintSpansKey, spansBuilds, ""), + (grammarMTPKey, grammarBuilds, ", where constraint spans are on")] + where !builds.isEmpty && followsDefault(key, in: environment, injected: []) { + on.append("\(key) (\(builds.sorted().joined(separator: ", "))\(scope))") + } + return on.isEmpty ? nil : "SDK feature defaults on: \(on.joined(separator: "; "))" + } + + /// Keys this process set itself (not the operator's): never persisted. + public static var injectedKeys: Set { injected.all } + + private static let injected = InjectedKeys() + + private final class InjectedKeys: @unchecked Sendable { + private let lock = NSLock() + private var keys: Set = [] + func add(_ new: some Sequence) { lock.lock(); keys.formUnion(new); lock.unlock() } + var all: Set { lock.lock(); defer { lock.unlock() }; return keys } + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift index 3bf6e5937b..478015f68f 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift @@ -168,6 +168,18 @@ extension EngineV2Bridge { /// (`GenerationLoopGuardPolicy`); nil leaves it unguarded. loopGuard: GenerationLoopGuard? = nil ) async throws -> AsyncStream { + let reasoningBudget: CBv2ReasoningBudget? + do { + if let budget = request.nativeReasoningBudget { + guard supportsNativeReasoningBudgets, tokenConstraint == nil, loopGuard?.exitThinking == nil else { + throw NativeReasoningBudget.refusal("this engine route cannot preserve a reasoning budget") + } + reasoningBudget = try budget.resolved(tokenizer: tokenizer.inner) + } else { reasoningBudget = nil } + } catch { + usageSignal?.finalizeLookup(failure: .policy, fallbackTier: prefixCacheFallbackTier) + throw error + } let tokenConstraint = Self.admittedConstraint(tokenConstraint, servesDistributedPair: servesDistributedPair, tracksNativeShutdown: tracksNativeShutdown) if let clusterStillImages { @@ -385,6 +397,7 @@ extension EngineV2Bridge { cbv2Request.clusterQwenMedia = clusterQwenMedia cbv2Request.positionState = positionState ?? multimodal?.positionState cbv2Request.hybridPrefixIdentity = hybridPrefixIdentity + cbv2Request.reasoningBudget = reasoningBudget if let minP = request.min_p { cbv2Request.sampling.minP = minP } let checkpointScope = cbv2Request.checkpointCacheSalt ?? "" try await checkFirstContentDeadline( diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift index 6966e26169..4e596b9163 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge.swift @@ -67,6 +67,9 @@ public actor EngineV2Bridge { var glm5NextStepSetupBytes = 0 /// GLM requests between the capacity gate and `active`. var glm5NextGateReservations: [String: Int] = [:] + var supportsNativeReasoningBudgets: Bool { + !servesDistributedPair && ownedEngine?.supportsReasoningBudgets == true + } var tracksNativeShutdown: Bool { (ownedEngine as? EngineV2)?.nativeShutdownExecutionContractID != nil } diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding+Output.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding+Output.swift index c3415d76ac..47652ed2bf 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding+Output.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/NemotronSuperLocalBinding+Output.swift @@ -19,7 +19,7 @@ extension NemotronSuperLocalBinding { // translate deliberately strips wire output controls; this route owns // them through the pinned rendered prompt and withheld validation. let translated = MultiModelBatchSchedulerEngine.translate(openAIRequest: plan.request, - defaultMaxTokens: defaultMaxTokens) + defaultMaxTokens: defaultMaxTokens, nativeReasoningBudget: plan.nativeReasoningBudget) try await run(request: translated, promptTokens: tokens) { event in await collector.accept(event) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift index 41db0e0949..7bc222a29b 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift @@ -307,6 +307,13 @@ enum EngineV2SlotFactory { verificationMode: mtpVerification.mode, maxAutomaticRectangularTokens: mtpVerification.automaticRectangularTokens, acceptance: mtpAcceptance.acceptance) + // Per-build SDK switches this release turns on where they were measured; + // the operator's value (read above by the SDK) wins. + let sdkDefaults = SDKFeatureDefaults.applyMTPDefaults( + to: &mtpConfig, modelId: modelId, environment: environment) + if !sdkDefaults.isEmpty, mtpConfig.enabled { + logInfo("engine_v2: \(modelId) SDK feature defaults on: \(sdkDefaults.joined(separator: ", "))") + } 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+Translation.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine+Translation.swift index 2d4c20d6c5..41797ef91c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine+Translation.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine+Translation.swift @@ -256,13 +256,14 @@ extension MultiModelBatchSchedulerEngine { topLogprobs: Int? = nil, logitBias: [String: Float]? = nil, seed: UInt64? = nil, - engineStopStrings: Bool = true + engineStopStrings: Bool = true, + nativeReasoningBudget: NativeReasoningBudget? = nil ) -> ChatCompletionRequest { let stop: StopSequences? = { guard engineStopStrings, let stops = request.stop, !stops.isEmpty else { return nil } return .multiple(stops) }() - return ChatCompletionRequest( + var translated = ChatCompletionRequest( model: request.model, messages: request.messages.map { msg in ChatMessage(role: msg.role.rawValue, content: msg.content.text) @@ -286,6 +287,8 @@ extension MultiModelBatchSchedulerEngine { top_logprobs: topLogprobs, min_p: request.minP ) + translated.nativeReasoningBudget = nativeReasoningBudget + return translated } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index 2ddcd889f2..7b38df545b 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -507,6 +507,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { ? (nativeLocalCacheScope ?? cacheScope) : cacheScope let prepared: ToolChoicePromptPolicy.Prepared let nativeMiMoThinkingEnabled: Bool + let nativeReasoningBudget: NativeReasoningBudget? // A GLM request on a cluster pair (`Prepared.glm5PairPostValidation`). let glm5PairPostValidation = GLM5NextPromptPolicy.applies(modelType: modelType) ? await engineV2Bridge?.servesDistributedPair == true : false @@ -520,7 +521,13 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { try MiMoV26TemplateFix.validateRequest(request) nativeMiMoThinkingEnabled = try MiMoV26TemplateFix.effectiveThinkingEnabled( request: request, controls: templateControls) - } else { nativeMiMoThinkingEnabled = true } + nativeReasoningBudget = templateControls.rawMiMoControls.reasoningBudgetTokens.map { + .init(maximumTokens: $0, family: .mimoV26) + } + if nativeReasoningBudget != nil, await engineV2Bridge?.supportsNativeReasoningBudgets != true { + throw NativeReasoningBudget.refusal("this MiMo route cannot preserve a reasoning budget") + } + } else { nativeMiMoThinkingEnabled = true; nativeReasoningBudget = nil } try ReasoningEffortPolicy.validate(request, controls: templateControls, modelType: modelType) var policy = try ToolChoicePromptPolicy.prepare( request, @@ -630,7 +637,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { do { return try await prepareNativeMiMoMedia(request:request,templateControls:templateControls, requestUsage:requestUsage,prepared:prepared,toolHandler:toolHandler, - thinkingEnabled:nativeMiMoThinkingEnabled,acquired:consume acquired) + thinkingEnabled:nativeMiMoThinkingEnabled,reasoningBudget:nativeReasoningBudget,acquired:consume acquired) } catch { await releaseBox.fire() throw MiMoV26EncodedMediaIngress.outwardFailure(error) @@ -1142,6 +1149,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { logprobs: engineV2Logprobs != nil, declaresTools: prepared.tools?.isEmpty == false, setting: exitThinkingSetting, finalExit: gptossFinalExit) if exitThinking != nil, await engineV2Bridge?.servesDistributedPair != false { exitThinking = nil } + if nativeReasoningBudget != nil { exitThinking = nil } let loopGuard = GenerationLoopGuardPolicy.resolve( modelType: modelType, request: request, prepared: prepared, tokenConstraint: tokenConstraint, exitThinking: exitThinking) @@ -1180,7 +1188,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { logitBias: engineV2Sampling?.logitBias, seed: engineV2Sampling?.seed, // Exact Flint matches stops on its answer channel only. - engineStopStrings: modelType != "flint"), + engineStopStrings: modelType != "flint", nativeReasoningBudget: nativeReasoningBudget), requestId: requestId, // Same per-tenant scope the legacy submit threads into the // checkpoint cache; the bridge maps it to CBv2Request.cacheSalt @@ -1586,11 +1594,14 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { private func prepareNativeMiMoMedia(request: OpenAIChatCompletionRequest, templateControls: ChatTemplateControls, requestUsage: EngineV2RequestUsageSignal, prepared: ToolChoicePromptPolicy.Prepared, toolHandler: BatchedToolStreamHandler?, - thinkingEnabled: Bool, acquired: consuming AcquiredModel + thinkingEnabled: Bool, reasoningBudget: NativeReasoningBudget?, acquired: consuming AcquiredModel ) async throws -> AsyncThrowingStream { try checkFirstContentDeadline() try templateControls.rawMiMoControls.validateMedia(modelType:acquired.modelType) if let bridge = acquired.engineV2Bridge, let binding = try await bridge.draftMiMoImageIngress() { + guard reasoningBudget == nil else { + throw NativeReasoningBudget.refusal("MiMo cluster media does not support reasoning budgets") + } guard engineV2Logprobs == nil,request.responseFormat?.requiresJSONOutput != true else { throw MultiModelBatchSchedulerEngineError.multimodalRejected("MiMo cluster media output controls") } @@ -1667,7 +1678,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { let id = "req-" + UUID().uuidString let upstream = try await bridge.submitTokenized(promptTokens:native.request.promptTokens, request:Self.translate(openAIRequest:request,defaultMaxTokens:maximumOutput, - logitBias:engineV2Sampling?.logitBias,seed:engineV2Sampling?.seed), + logitBias:engineV2Sampling?.logitBias,seed:engineV2Sampling?.seed, + nativeReasoningBudget:reasoningBudget), requestId:id,cacheScope:cacheScope,cacheEnabled:false,usageSignal:requestUsage, multimodal:native.request.multimodal, stopStringScope:ReasoningStopScope.scope(reasoningParser:request.reasoningParser,reasoningPrefix:nil,parsesToolCalls:toolHandler != nil), diff --git a/provider-swift/Sources/ProviderCore/Inference/JSONAnswerConstraint.swift b/provider-swift/Sources/ProviderCore/Inference/JSONAnswerConstraint.swift index 4f48c293e5..ca1a85ef83 100644 --- a/provider-swift/Sources/ProviderCore/Inference/JSONAnswerConstraint.swift +++ b/provider-swift/Sources/ProviderCore/Inference/JSONAnswerConstraint.swift @@ -56,7 +56,7 @@ struct JSONAnswerBoundary: Hashable { /// once the value is complete. Per-request and host-only: as in /// `FlintNativeProtocolConstraint`, interning collapses free text to bounded /// framing states, and it never forces a value or repairs a truncated one. -final class JSONAnswerConstraint: CBv2TokenConstraint, @unchecked Sendable { +class JSONAnswerConstraint: CBv2TokenConstraint, @unchecked Sendable { let mode = CBv2TokenConstraintMode.auto let maxTokens: Int let initialState = 0 @@ -145,6 +145,31 @@ final class JSONAnswerConstraint: CBv2TokenConstraint, @unchecked Sendable { /// step ahead and redraw it when the confirmed token changes the state. var allowsChainedDecode: Bool { true } + func isFreeSpan(state: Int) -> Bool { + lock.lock(); defer { lock.unlock() } + return !resourceExhausted && states.indices.contains(state) && isFree(states[state]) + } + + /// Preview never interns a state. Even a token that returns to reasoning + /// is protected if any byte enters a marker prefix along the way. + func isFreeSpanContinuation(state: Int, tokenID: Int) -> Bool { + lock.lock(); defer { lock.unlock() } + guard !resourceExhausted, states.indices.contains(state), isFree(states[state]), + vocabulary.pieces.indices.contains(tokenID), + !vocabulary.stopTokenIDs.contains(tokenID), !vocabulary.pieces[tokenID].isEmpty else { + return false + } + var next = states[state] + for byte in vocabulary.pieces[tokenID] { + guard next.consume(byte, profile: profile, grammar: format.grammar), isFree(next) else { return false } + } + return next == states[state] + } + + private func isFree(_ boundary: JSONAnswerBoundary) -> Bool { + profile.family == "Qwen" && boundary.phase == .reasoning && boundary.window.isEmpty + } + func nextState(state: Int, tokenID: Int) -> Int? { lock.lock(); defer { lock.unlock() } guard !resourceExhausted, states.indices.contains(state), vocabulary.pieces.indices.contains(tokenID) else { @@ -188,3 +213,9 @@ final class JSONAnswerConstraint: CBv2TokenConstraint, @unchecked Sendable { return next } } + +/// The Qwen answers whose reasoning can hold a free span. The SDK makes a row +/// MTP history-eligible by `CBv2FreeSpanTokenConstraint` conformance alone, so +/// only this subclass conforms (`JSONAnswerPolicy` builds it for the Qwen +/// family); other families' JSON answers keep ordinary chained decode. +final class QwenJSONAnswerConstraint: JSONAnswerConstraint, CBv2FreeSpanTokenConstraint, @unchecked Sendable {} diff --git a/provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/DeadlineRuntimeEnvironment.swift b/provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/DeadlineRuntimeEnvironment.swift index 797bc05ca5..433149db2b 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/DeadlineRuntimeEnvironment.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Performance/Deadline/DeadlineRuntimeEnvironment.swift @@ -15,15 +15,21 @@ enum DeadlineRuntimeEnvironment { "DARKBLOOM_STATE_FILE", "DARKBLOOM_VERIFIED_WEIGHTS_FILE", "DARKBLOOM_WATCHDOG_STATE", + SDKFeatureDefaults.injectedMarkerKey, ] static func permitsQualification(_ environment: [String: String], - cacheIsolation: DeadlineQualificationCacheIsolation? = nil) -> Bool { + cacheIsolation: DeadlineQualificationCacheIsolation? = nil, + injected: Set = SDKFeatureDefaults.injectedKeys) -> Bool { if let cacheIsolation { do { try cacheIsolation.validate(environment: environment) } catch { return false } } return !environment.keys.contains { key in + // The release's own defaults (`SDKFeatureDefaults`) are part of every + // darkbloom process, the qualification runner's included; profiles + // are pinned to the provider version. An operator value is not. + if SDKFeatureDefaults.isInjected(key, in: environment, injected: injected) { return false } if key == EngineV2KVQuantizationPolicy.environmentKey { // Existing bounds describe native execution only. The factory // publishes this resolved key even without an env override. diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatRequest.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatRequest.swift index a98ae7f27a..8159619359 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatRequest.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatRequest.swift @@ -3,6 +3,16 @@ import Foundation // MARK: - Request Types public struct ChatCompletionRequest: Codable, Sendable { + /// Trusted family control assigned after raw request validation; never a wire field. + var nativeReasoningBudget: NativeReasoningBudget? = nil + + private enum CodingKeys: String, CodingKey { + case model, messages, temperature, top_p, top_k, max_tokens + case repetition_penalty, presence_penalty, frequency_penalty, stream, stop, seed + case tools, tool_choice, response_format, user, prompt_cache_key + case logit_bias, logprobs, top_logprobs, min_p + } + public let model: String public let messages: [ChatMessage] public let temperature: Float? diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/MiMo/MiMoV26TemplateFix.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/MiMo/MiMoV26TemplateFix.swift index 16c1411c7e..c7cafa4a61 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/MiMo/MiMoV26TemplateFix.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/MiMo/MiMoV26TemplateFix.swift @@ -18,6 +18,7 @@ struct MiMoV26RawControlEvidence: Sendable, Equatable, Decodable { var responseEnableThinking: Bool? /// The thinking switch a Responses body's top-level effort implies. var responseEffortThinking: Bool? + var reasoningBudgetTokens: Int? private struct Key: CodingKey { let stringValue: String @@ -95,7 +96,17 @@ struct MiMoV26RawControlEvidence: Sendable, Equatable, Decodable { } if root.contains(Key("reasoning")), try !root.decodeNil(forKey: Key("reasoning")) { let nested = try root.nestedContainer(keyedBy: Key.self, forKey: Key("reasoning")) - let allowed = surface == .chat ? ["enabled", "effort"] : ["effort"] + var allowed = surface == .chat ? ["enabled", "effort"] : ["effort"] + let budgets = NativeReasoningBudget.isEnabled(for: .mimoV26) + if budgets { allowed.append("max_tokens") } + // Off, `max_tokens` is only an unknown key (0.10.12); a value that + // is not an integer must never skip the effort check below. + if budgets, nested.contains(Key("max_tokens")) { + if let maximum = try? nested.decode(Int.self, forKey: Key("max_tokens")), + NativeReasoningBudget.acceptsMaximumTokens(maximum) { + evidence.reasoningBudgetTokens = maximum + } else { evidence.invalid = true } + } if nested.allKeys.contains(where: { !allowed.contains($0.stringValue) }) { evidence.invalid = true } _ = try boolean(nested, "enabled") _ = try effort(nested, "effort", .reasoningObject) @@ -215,9 +226,14 @@ enum MiMoV26TemplateFix { } let rawEffort = try controls.reasoningEffort.map { try thinkingFromEffort($0, .reasoningEffort) } let nestedEffort = try request.reasoning?.effort.map { try thinkingFromEffort($0, .reasoningObject) } - return request.reasoning?.enabled ?? controls.rawMiMoControls.responseEnableThinking + let enabled = request.reasoning?.enabled ?? controls.rawMiMoControls.responseEnableThinking ?? controls.enableThinking ?? controls.rawMiMoControls.templateThinkingAlias ?? nestedEffort ?? controls.rawMiMoControls.responseEffortThinking ?? rawEffort + if controls.rawMiMoControls.reasoningBudgetTokens != nil { + guard enabled != false else { throw invalid("reasoning budget conflicts with disabled thinking") } + return true + } + return enabled } private static func thinkingFromEffort(_ effort: String, _ field: ReasoningEffortField) throws -> Bool { diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/NativeReasoningBudget.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/NativeReasoningBudget.swift new file mode 100644 index 0000000000..35775fdabc --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/NativeReasoningBudget.swift @@ -0,0 +1,45 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon + +/// A validated family control, carried separately from the client's wire request. +struct NativeReasoningBudget: Sendable, Equatable { + enum Family: Sendable { case nemotronSuper, mimoV26 } + let maximumTokens: Int + let family: Family + + func resolved(tokenizer: any MLXLMCommon.Tokenizer) throws -> CBv2ReasoningBudget { + let open = tokenizer.encode(text: "", addSpecialTokens: false) + let close = tokenizer.encode(text: "", addSpecialTokens: false) + guard Self.acceptsMaximumTokens(maximumTokens), open.count == 1, close.count == 1, + open != close, tokenizer.convertTokenToId("") == open.first, + tokenizer.convertTokenToId("") == close.first, + tokenizer.decode(tokenIds: open, skipSpecialTokens: false) == "", + tokenizer.decode(tokenIds: close, skipSpecialTokens: false) == "" else { + throw Self.refusal("reasoning budget requires validated atomic thought markers") + } + return try CBv2ReasoningBudget(maximumTokens: maximumTokens, openTokenID: open[0], + closeTokenID: close[0], startsInsideThought: family == .nemotronSuper) + } + + static func refusal(_ message: String) -> MultiModelBatchSchedulerEngineError { + .unsupportedOutputControl("\(EngineV2Translation.unsupportedOutputControlPrefix): \(message)") + } + + static let environmentKey = "DARKBLOOM_NATIVE_REASONING_BUDGET" + /// Whether `family` admits `reasoning.max_tokens`: the operator's value + /// (shell or LaunchAgent) for every family, else this release's default + /// (`SDKFeatureDefaults.reasoningBudgetFamilies`). The provider's own + /// injected `1` (set so engines accept budget rows) is not the operator's. + static func isEnabled( + for family: Family, + environment: [String: String] = ProcessInfo.processInfo.environment, + families: Set = SDKFeatureDefaults.reasoningBudgetFamilies, + injected: Set = SDKFeatureDefaults.injectedKeys + ) -> Bool { + SDKFeatureDefaults.followsDefault(environmentKey, in: environment, injected: injected) + ? families.contains(family) : CBv2ReasoningBudget.enabled(environment: environment) + } + static func acceptsMaximumTokens(_ value: Int) -> Bool { value > 0 && value <= Int(Int32.max) } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperPromptContract.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperPromptContract.swift index 208ad9d577..22bb761c58 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperPromptContract.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperPromptContract.swift @@ -32,6 +32,7 @@ enum NemotronSuperPromptContract { var mediumEffort = false var truncateHistoryThinking = true var forceNonemptyContent = false + var reasoningBudgetTokens: Int? = nil } /// Verified pinned template, prepared for swift-jinja: comment whitespace @@ -52,13 +53,14 @@ enum NemotronSuperPromptContract { let effort: String? let nestedEnabled: Bool? let nestedEffort: String? + let budget: Int? enum Keys: String, CodingKey { case enabled = "enable_thinking", medium = "medium_effort" case truncate = "truncate_history_thinking", effort = "reasoning_effort" case forceContent = "force_nonempty_content", thinking case kwargs = "chat_template_kwargs", reasoning, preserve = "preserve_thinking" } - enum ReasoningKeys: String, CodingKey { case enabled, effort } + enum ReasoningKeys: String, CodingKey { case enabled, effort; case maxTokens = "max_tokens" } /// The kwargs this contract reads: the template's switches, OpenRouter's /// `thinking` spelling of `enable_thinking`, and the parser's /// `force_nonempty_content`. Any other kwarg would be dropped by the template. @@ -88,6 +90,12 @@ enum NemotronSuperPromptContract { let reasoning = try values.nestedOptionalContainer(keyedBy: ReasoningKeys.self, forKey: .reasoning) nestedEnabled = try reasoning?.decodeIfPresent(Bool.self, forKey: .enabled) nestedEffort = try reasoning?.decodeIfPresent(String.self, forKey: .effort) + budget = try reasoning?.decodeIfPresent(Int.self, forKey: .maxTokens) + if let budget { + guard NativeReasoningBudget.isEnabled(for: .nemotronSuper), + NativeReasoningBudget.acceptsMaximumTokens(budget) + else { throw Failure.unsupportedControl } + } } /// Fields the pinned template cannot honor are refused, never dropped: @@ -153,10 +161,10 @@ enum NemotronSuperPromptContract { let effortMedium = effort?.nemotronSuperMediumEffort if let medium = raw.medium, let effortMedium, medium != effortMedium { throw Failure.conflictingControls } let medium = raw.medium ?? effortMedium ?? false - guard !(medium && !enabled) else { throw Failure.conflictingControls } + guard !(medium && !enabled), raw.budget == nil || enabled else { throw Failure.conflictingControls } return Controls(enableThinking: enabled, mediumEffort: medium, truncateHistoryThinking: raw.truncate ?? true, - forceNonemptyContent: raw.forceContent ?? false) + forceNonemptyContent: raw.forceContent ?? false, reasoningBudgetTokens: raw.budget) } static func additionalContext(body: Data) throws -> [String: any Sendable] { diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperRequestPlan.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperRequestPlan.swift index 33b878ff7a..3aabe80027 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperRequestPlan.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperRequestPlan.swift @@ -78,7 +78,7 @@ struct NemotronSuperRequestPlan: Sendable { promptTokens: [Int], tokenizer: any MLXLMCommon.Tokenizer, setting: GenerationLoopExitThinkingPolicy.Setting = GenerationLoopExitThinkingPolicy.current ) -> GenerationLoopExitThinking? { - guard !hasMedia else { return nil } + guard !hasMedia, nativeReasoningBudget == nil else { return nil } return GenerationLoopExitThinkingPolicy.resolve(modelType: Self.modelType, tokenizer: tokenizer, promptTokens: promptTokens, logprobs: topLogprobs > 0, setting: setting) } @@ -87,9 +87,14 @@ struct NemotronSuperRequestPlan: Sendable { /// keeps the request's `max_tokens` (nil: the bridge default) and drops /// tools and the response format: they are prompt instructions here, and /// `NemotronSuperLocalOutput` validates the answer. + var nativeReasoningBudget: NativeReasoningBudget? { + controls.reasoningBudgetTokens.map { .init(maximumTokens: $0, family: .nemotronSuper) } + } + var bridgeRequest: ChatCompletionRequest { MultiModelBatchSchedulerEngine.translate(openAIRequest: request, defaultMaxTokens: 1, - logprobs: topLogprobs > 0 ? true : nil, topLogprobs: topLogprobs > 0 ? topLogprobs : nil) + logprobs: topLogprobs > 0 ? true : nil, topLogprobs: topLogprobs > 0 ? topLogprobs : nil, + nativeReasoningBudget: nativeReasoningBudget) } /// Reference prompt for a text request. Media requests are rendered by diff --git a/provider-swift/Sources/ProviderCore/Inference/QwenStrictToolConstraint.swift b/provider-swift/Sources/ProviderCore/Inference/QwenStrictToolConstraint.swift index c304ed1cd3..075e03f328 100644 --- a/provider-swift/Sources/ProviderCore/Inference/QwenStrictToolConstraint.swift +++ b/provider-swift/Sources/ProviderCore/Inference/QwenStrictToolConstraint.swift @@ -116,6 +116,15 @@ struct QwenStrictToolBoundary: Hashable { } } + /// Draft only ordinary text, never a partial marker or a call opening. + var isFreeSpan: Bool { + guard window.isEmpty else { return false } + switch step { + case .reasoning, .content: return true + default: return false + } + } + /// Free spans whose bytes can only be refused by completing a marker: /// reasoning, text, text values (every marker ends in `>`). var isOpaqueSpan: Bool { @@ -296,7 +305,7 @@ struct QwenStrictToolBoundary: Hashable { /// Should the interned states ever run out, the constraint releases the rest /// of the answer to free sampling (as before the grammar) instead of failing /// it. -final class QwenStrictToolConstraint: CBv2TokenConstraint, @unchecked Sendable { +final class QwenStrictToolConstraint: CBv2FreeSpanTokenConstraint, @unchecked Sendable { let mode = CBv2TokenConstraintMode.auto let maxTokens: Int let initialState = 0 @@ -404,6 +413,29 @@ final class QwenStrictToolConstraint: CBv2TokenConstraint, @unchecked Sendable { /// `nextState` interns only host-confirmed tokens. var allowsChainedDecode: Bool { true } + func isFreeSpan(state: Int) -> Bool { + lock.lock(); defer { lock.unlock() } + return states.indices.contains(state) && states[state].isFreeSpan + } + + /// Preview a copy: discarded proposals must not intern states or release + /// the grammar. A token touching a marker is protected even when its final + /// bytes return to the same free state. + func isFreeSpanContinuation(state: Int, tokenID: Int) -> Bool { + lock.lock(); defer { lock.unlock() } + guard states.indices.contains(state), states[state].isFreeSpan, + vocabulary.pieces.indices.contains(tokenID), + !vocabulary.stopTokenIDs.contains(tokenID) else { return false } + let piece = vocabulary.pieces[tokenID] + guard !piece.isEmpty else { return false } + let boundary = states[state] + var next = boundary + for byte in piece { + guard next.consume(byte, schema: schema, markers: markers), next.isFreeSpan else { return false } + } + return next == boundary + } + func nextState(state: Int, tokenID: Int) -> Int? { lock.lock(); defer { lock.unlock() } guard vocabulary.pieces.indices.contains(tokenID) else { return nil } diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/JSONAnswerPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/JSONAnswerPolicy.swift index dd253b5762..11318651c7 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Tools/JSONAnswerPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/JSONAnswerPolicy.swift @@ -95,9 +95,15 @@ enum JSONAnswerPolicy { stopTokenIDs: stopTokenIDs) else { return declined(profile, "tokenizer does not match the pinned vocabulary") } - guard let constraint = try? JSONAnswerConstraint(format: answer, profile: profile, vocabulary: vocabulary, - initialPhase: phase, - maxTokens: request.maxTokens ?? defaultMaxTokens) else { + // Only Qwen answers can hold a free span; only they may conform to + // CBv2FreeSpanTokenConstraint (QwenJSONAnswerConstraint). + let maxTokens = request.maxTokens ?? defaultMaxTokens + let built: JSONAnswerConstraint? = profile.family == "Qwen" + ? try? QwenJSONAnswerConstraint(format: answer, profile: profile, vocabulary: vocabulary, + initialPhase: phase, maxTokens: maxTokens) as JSONAnswerConstraint + : try? JSONAnswerConstraint(format: answer, profile: profile, vocabulary: vocabulary, + initialPhase: phase, maxTokens: maxTokens) + guard let constraint = built else { return declined(profile, "no positive output budget") } if let widening { logger.info("\(profile.family) json_schema outside the constrained subset: \(widening.note)") } diff --git a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift index b516e50933..24bde9e48b 100644 --- a/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift +++ b/provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift @@ -343,6 +343,10 @@ public enum LaunchAgent: Sendable { /// rectangular cap override is the operator's lever to REDUCE speculative /// verification work short of disabling MTP entirely; it must survive /// install/restart like the kill switches. + /// `DARKBLOOM_CONSTRAINT_SPANS`: opt-in drafting through free Qwen + /// reasoning/text spans; the SDK snapshots it when constructing an engine. + /// `DARKBLOOM_CBV2_MTP_GRAMMAR`: grammar-aware MTP verification of + /// constrained rows (SDK-read, per engine); `0` keeps them target-only. /// `DARKBLOOM_KV_BACKEND_GUARD`: the crash-loop guard's record-path /// override (`KVBackendGuardStore.pathEnvKey`). The guard has one writer /// (the launchd watchdog — same key in `WatchdogAgent.passthroughEnvKeys`) @@ -494,6 +498,10 @@ public enum LaunchAgent: Sendable { // SDK-read (`EngineLoopV2.nativeSegmentReleaseEnvironmentKey`): idle seconds // before an issued GLM pool returns its free segments; `0` is the rollback. "DARKBLOOM_NATIVE_SEGMENT_RELEASE", + NativeReasoningBudget.environmentKey, + // SDK-read (`GemmaFunctionParser.schemaCoercionEnabled`): quoted Gemma + // numbers typed by the tool's schema at frame close; `0` keeps strings. + "DARKBLOOM_GEMMA_SCHEMA_COERCION", GenerationLoopGuardPolicy.environmentKey, GenerationLoopExitThinkingPolicy.environmentKey, GenerationLoopExitThinkingPolicy.finalExitEnvironmentKey, @@ -512,6 +520,7 @@ public enum LaunchAgent: Sendable { "DARKBLOOM_CBV2_KV_QUANTIZATION", "DARKBLOOM_CBV2_CHECKPOINT_QUANTIZATION", "DARKBLOOM_CBV2_MTP", "DARKBLOOM_MTP_MAX_RECTANGULAR_TOKENS", + "DARKBLOOM_CONSTRAINT_SPANS", "DARKBLOOM_CBV2_MTP_GRAMMAR", "DARKBLOOM_KV_BACKEND_GUARD", "DARKBLOOM_MLX_CACHE_LIMIT_GB", "DARKBLOOM_MLX_MEMORY_RESERVE_GB", "DARKBLOOM_R2_CDN_URL", @@ -530,10 +539,16 @@ public enum LaunchAgent: Sendable { /// would collapse a drain export back to `trust`. Config-backed `0` / /// `trust` remain excluded — `provider.toml` stays authoritative for /// whether the route runs, and `trust` is the default whenever it does. - static func passthroughEnvironment(from environment: [String: String]) -> [String: String] { + /// Keys `SDKFeatureDefaults` injected into this process are not the + /// operator's: they are left out, so the installed service applies the + /// running release's own defaults (`injected`). + static func passthroughEnvironment( + from environment: [String: String], + injected: Set = SDKFeatureDefaults.injectedKeys + ) -> [String: String] { var out = GemmaOptimizationEnvironment.daemonDrainPassthrough( from: environment) - for key in passthroughEnvKeys { + for key in passthroughEnvKeys where !SDKFeatureDefaults.isInjected(key, in: environment, injected: injected) { if let value = environment[key], !value.isEmpty { out[key] = value } diff --git a/provider-swift/Sources/darkbloom/BenchmarkCommand.swift b/provider-swift/Sources/darkbloom/BenchmarkCommand.swift index bfb9f9bcff..8150acbec0 100644 --- a/provider-swift/Sources/darkbloom/BenchmarkCommand.swift +++ b/provider-swift/Sources/darkbloom/BenchmarkCommand.swift @@ -260,6 +260,10 @@ struct Benchmark: AsyncParsableCommand { """) throw ExitCode.failure } + // SDK feature defaults (main.swift and per engine); record them (stderr). + if let sdkDefaults = SDKFeatureDefaults.summary() { + FileHandle.standardError.write(Data("\(sdkDefaults)\n".utf8)) + } do { try ServeRuntimePreparer.prepareRuntime(settings: gemmaSettings) } catch { diff --git a/provider-swift/Sources/darkbloom/Start/StartCommand.swift b/provider-swift/Sources/darkbloom/Start/StartCommand.swift index b542437f12..6fe2821a50 100644 --- a/provider-swift/Sources/darkbloom/Start/StartCommand.swift +++ b/provider-swift/Sources/darkbloom/Start/StartCommand.swift @@ -530,6 +530,9 @@ struct Start: AsyncParsableCommand { } } + // Applied in main.swift (process-wide) and per engine; name what is on. + if let sdkDefaults = SDKFeatureDefaults.summary() { print(sdkDefaults) } + // These controls are process-start latches in MLX/MLXLM. Project the // authoritative TOML, bind the immutable default runtime metallib, and // only then let requireMetal() perform the first MLX touch. diff --git a/provider-swift/Sources/darkbloom/main.swift b/provider-swift/Sources/darkbloom/main.swift index 81a1ba0ed5..7dc0e92c9f 100644 --- a/provider-swift/Sources/darkbloom/main.swift +++ b/provider-swift/Sources/darkbloom/main.swift @@ -13,6 +13,13 @@ import ProviderCore let rawArgs = Array(CommandLine.arguments.dropFirst()) +// First: the process-wide SDK switches this release turns on by default, so +// every command and early branch (serving, the native serving qualification, +// pair members, workers, benchmarks) sees them before any engine or parser +// reads them. An operator value (shell or LaunchAgent) wins, `0` = 0.10.12; +// injected keys are never written into a service plist (`SDKFeatureDefaults`). +SDKFeatureDefaults.apply() + // A worker never enters AppKit, CLI lifecycle, inference or update startup. if rawArgs.first == AppAttestWorkerHost.argument { await AppAttestWorkerCommand.runIfRequested(rawArgs) diff --git a/provider-swift/Tests/DarkbloomCLITests/SDKFeatureDefaultsEntryTests.swift b/provider-swift/Tests/DarkbloomCLITests/SDKFeatureDefaultsEntryTests.swift new file mode 100644 index 0000000000..d34f346aa5 --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/SDKFeatureDefaultsEntryTests.swift @@ -0,0 +1,22 @@ +import Foundation +import Testing + +/// review prov-2109-d2 SF2: `SDKFeatureDefaults.apply()` runs first in +/// `main.swift`, before every early branch (the native serving qualification +/// loads a model and serves; it must qualify the defaults it ships with). +@Suite struct SDKFeatureDefaultsEntryTests { + @Test func defaultsApplyBeforeAnyCommandOrEarlyBranch() throws { + let main = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // DarkbloomCLITests + .deletingLastPathComponent() // Tests + .deletingLastPathComponent() // provider-swift + .appendingPathComponent("Sources/darkbloom/main.swift") + let code = try String(contentsOf: main, encoding: .utf8) + .split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty && !$0.hasPrefix("//") && !$0.hasPrefix("import ") } + let apply = try #require(code.firstIndex(of: "SDKFeatureDefaults.apply()")) + let firstBranch = try #require(code.firstIndex { $0.hasPrefix("if ") }) + #expect(apply < firstBranch) + #expect(code.filter { $0.contains("SDKFeatureDefaults.apply(") }.count == 1) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Config/SDKDefaultReasoningBudgetsTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/SDKDefaultReasoningBudgetsTests.swift new file mode 100644 index 0000000000..4e7aaf9ef3 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Config/SDKDefaultReasoningBudgetsTests.swift @@ -0,0 +1,23 @@ +import Testing +@testable import ProviderCore + +/// 0.10.13 default flip, scoped to its evidence: `reasoning.max_tokens` budgets +/// are admitted for Nemotron 3.5 Super and MiMo V2.6 unless the operator sets +/// `DARKBLOOM_NATIVE_REASONING_BUDGET` (`0` = 0.10.12 for every family). +@Suite("SDK default: DARKBLOOM_NATIVE_REASONING_BUDGET") +struct SDKDefaultReasoningBudgetsTests { + @Test func isOnByDefaultForSuperAndMiMoAndKillable() { + let key = "DARKBLOOM_NATIVE_REASONING_BUDGET" + #expect(SDKFeatureDefaults.reasoningBudgetFamilies == [.nemotronSuper, .mimoV26]) + #expect(NativeReasoningBudget.isEnabled(for: .nemotronSuper, environment: [:], injected: [])) + #expect(NativeReasoningBudget.isEnabled(for: .mimoV26, environment: [:], injected: [])) + // The release's own `1` follows the family list; the operator's `0` kills every family. + #expect(SDKFeatureDefaults.onByDefault.contains(key)) + #expect(NativeReasoningBudget.isEnabled(for: .mimoV26, environment: [key: "1"], injected: [key])) + #expect(!NativeReasoningBudget.isEnabled(for: .nemotronSuper, environment: [key: "0"], injected: [])) + #expect(!NativeReasoningBudget.isEnabled(for: .mimoV26, environment: [key: "0"], injected: [])) + #expect(LaunchAgent.passthroughEnvKeys.contains(key)) + #expect(SDKFeatureDefaults.summary(environment: [:], injected: [key])? + .contains("\(key) (mimoV26, nemotronSuper)") == true) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Config/SDKFeatureDefaultsTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/SDKFeatureDefaultsTests.swift new file mode 100644 index 0000000000..62997ee066 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Config/SDKFeatureDefaultsTests.swift @@ -0,0 +1,225 @@ +import Foundation +import MLXLMCommon +import Testing +@testable import ProviderCore + +@Suite("SDK feature defaults") +struct SDKFeatureDefaultsTests { + @Test func listedSwitchesTurnOnOnlyWhereTheOperatorSetNothing() { + let keys = ["DARKBLOOM_A", "DARKBLOOM_B", "DARKBLOOM_C"] + // The operator's non-empty value always wins: `0` is the kill switch, + // and any explicit spelling is left exactly as given. + let projection = SDKFeatureDefaults.projection( + onByDefault: keys, environment: ["DARKBLOOM_B": "0", "DARKBLOOM_C": "off", "UNRELATED": "x"]) + #expect(projection == ["DARKBLOOM_A": "1"]) + // Empty means unset, as for the LaunchAgent, which drops empty values: + // foreground and installed service agree. + #expect(SDKFeatureDefaults.projection(onByDefault: keys, environment: ["DARKBLOOM_A": ""]).keys.sorted() + == keys) + #expect(SDKFeatureDefaults.projection(onByDefault: [], environment: [:]).isEmpty) + } + + @Test func injectedDefaultsAreNeverWrittenIntoAServicePlist() { + // review prov-2109 SF1: an installing `darkbloom` process carries its own + // injected defaults; persisting them would pin today's default into the + // plist, so a later release could not change it without a reinstall. + let key = "DARKBLOOM_GEMMA_SCHEMA_COERCION" + #expect(LaunchAgent.passthroughEnvironment(from: [key: "1"], injected: [key]).isEmpty) + // The operator's own value (not injected) is still forwarded, `0` included. + #expect(LaunchAgent.passthroughEnvironment(from: [key: "0"], injected: []) == [key: "0"]) + #expect(LaunchAgent.passthroughEnvironment(from: [key: "1"], injected: []) == [key: "1"]) + } + + @Test func everyDefaultOnSwitchReachesTheInstalledService() { + // A default-ON switch is only a kill switch if the LaunchAgent forwards it. + let perBuild = [SDKFeatureDefaults.constraintSpansKey, SDKFeatureDefaults.grammarMTPKey, + NativeReasoningBudget.environmentKey] + for key in SDKFeatureDefaults.onByDefault + perBuild { + #expect(LaunchAgent.passthroughEnvKeys.contains(key), "\(key)") + } + // The per-build MTP switches are never set process-wide: the SDK's + // `CBv2MTPConfig` would read an injected `1` on every model. + #expect(!SDKFeatureDefaults.onByDefault.contains(SDKFeatureDefaults.constraintSpansKey)) + #expect(!SDKFeatureDefaults.onByDefault.contains(SDKFeatureDefaults.grammarMTPKey)) + } + + /// The environment a `darkbloom` child inherits after its parent's `apply`. + private func inherited(_ environment: [String: String], _ plan: SDKFeatureDefaults.Plan) -> [String: String] { + var child = environment.merging(plan.set) { $1 } + for key in plan.unset { child[key] = nil } + return child + } + + @Test func aDarkbloomChildNeverPersistsItsParentsInjectedDefaults() { + // review prov-2109-d2 MUST-FIX 1: `darkbloom desktop serve` injects a + // default, its DesktopWorker child (`start`, `desktop start-local`) + // inherits KEY=1 and installs the provider plist. The child must still + // know KEY=1 is the release's, not the operator's. + let key = "DARKBLOOM_GEMMA_SCHEMA_COERCION" + let marker = SDKFeatureDefaults.injectedMarkerKey + let operatorEnvironment = ["HOME": "/Users/op", "DARKBLOOM_OTHER": "x"] + let parent = SDKFeatureDefaults.plan(onByDefault: [key], environment: operatorEnvironment) + #expect(parent.injected == [key]) + let childEnvironment = inherited(operatorEnvironment, parent) + #expect(childEnvironment[key] == "1") + let child = SDKFeatureDefaults.plan(onByDefault: [key], environment: childEnvironment) + #expect(child.injected == [key]) + let childAfter = inherited(childEnvironment, child) + let plist = LaunchAgent.passthroughEnvironment(from: childAfter, injected: Set(child.injected)) + #expect(plist[key] == nil) + #expect(plist[marker] == nil) + // A grandchild still knows. + let grandchild = SDKFeatureDefaults.plan(onByDefault: [key], environment: childAfter) + #expect(grandchild.injected == [key]) + } + + @Test func aChildFollowsItsOwnReleaseAndTheOperator() { + let key = "DARKBLOOM_GEMMA_SCHEMA_COERCION" + let marker = SDKFeatureDefaults.injectedMarkerKey + // A child of a newer release that no longer lists the key restores the + // SDK default instead of keeping its parent's injection. + let dropped = SDKFeatureDefaults.plan(onByDefault: [], environment: [key: "1", marker: key]) + #expect(dropped.injected.isEmpty) + #expect(Set(dropped.unset) == [key, marker]) + // The operator's value in the child's own environment wins (`0` kills), + // even beside a stale marker. + let killed = SDKFeatureDefaults.plan(onByDefault: [key], environment: [key: "0", marker: key]) + #expect(killed.injected.isEmpty) + #expect(killed.set[key] == nil) + #expect(LaunchAgent.passthroughEnvironment(from: [key: "0", marker: key], injected: [])[key] == "0") + } + + @Test func theStartLineNamesWhatIsOnAndWhere() { + // review prov-2109-d5 NIT 1: grammar MTP's default rides on constraint + // spans, and the line says so (a grammar-only fold is a no-op there). + let id: Set = ["eigenlabs/qwen3.8-27b-4bit-mtp"] + #expect(SDKFeatureDefaults.summary(environment: [:], injected: [], spansBuilds: [], grammarBuilds: []) == nil) + #expect(SDKFeatureDefaults.summary(environment: [:], injected: [], spansBuilds: id, grammarBuilds: id) == + "SDK feature defaults on: DARKBLOOM_CONSTRAINT_SPANS (eigenlabs/qwen3.8-27b-4bit-mtp); " + + "DARKBLOOM_CBV2_MTP_GRAMMAR (eigenlabs/qwen3.8-27b-4bit-mtp, where constraint spans are on)") + #expect(SDKFeatureDefaults.summary(environment: [SDKFeatureDefaults.grammarMTPKey: "0"], injected: [], + spansBuilds: [], grammarBuilds: id) == nil) + } + + @Test func aChildsPlistSkipsMarkedDefaultsEvenBeforeItRecordsThem() { + // review prov-2109-d5 NIT 4: the plist writer knows the release's value + // from the marker alone, like every other consumer. + let key = "DARKBLOOM_GEMMA_SCHEMA_COERCION", marker = SDKFeatureDefaults.injectedMarkerKey + #expect(LaunchAgent.passthroughEnvironment(from: [key: "1", marker: key], injected: [])[key] == nil) + #expect(LaunchAgent.passthroughEnvironment(from: [key: "0", marker: key], injected: [])[key] == "0") + } + + @Test func theMarkerIsNeverForwarded() { + let marker = SDKFeatureDefaults.injectedMarkerKey + #expect(!LaunchAgent.passthroughEnvKeys.contains(marker)) + #expect(LaunchAgent.passthroughEnvironment(from: [marker: "DARKBLOOM_X"], injected: [])[marker] == nil) + } + + @Test func mtpDefaultsTurnOnOnlyForListedBuildsAndOnlyWhenUnset() { + // review prov-2109-d2 SF3 / d4 SF1: a default is on only for the exact + // build it was measured on. + let builds: Set = ["eigenlabs/qwen3.8-27b-4bit-mtp"] + func config(spans: Bool = false, grammar: Bool = false, modelId: String, + environment: [String: String] = [:]) -> CBv2MTPConfig { + var config = CBv2MTPConfig(enabled: true, constrainedSpeculation: grammar, freeSpanSpeculation: spans) + SDKFeatureDefaults.applyMTPDefaults(to: &config, modelId: modelId, environment: environment, + processEnvironment: [:], spansBuilds: builds, grammarBuilds: builds) + return config + } + let qwen38 = config(modelId: "EigenLabs/Qwen3.8-27B-4bit-mtp") + #expect(qwen38.freeSpanSpeculation && qwen38.constrainedSpeculation) + for id in ["gemma-4-26b-qat-4bit", "mlx-community/Qwen3.6-35B-A3B-4bit", "mlx-community/Qwen3.5-9B-MLX-4bit", + "mlx-community/Qwen3.8-27B-8bit-mtp", "EigenLabs/Qwen3.8-27B-4bit", + "EigenLabs/Qwen3.8-27B-4bit-mtp-dpo", "/Users/op/models/EigenLabs/Qwen3.8-27B-4bit-mtp"] { + let other = config(modelId: id) + #expect(!other.freeSpanSpeculation && !other.constrainedSpeculation, "\(id)") + } + // The operator's value is the SDK's reading (here: the config as built): + // `0` keeps the listed build off, `1` turns any build on. + let killed = config(modelId: "EigenLabs/Qwen3.8-27B-4bit-mtp", + environment: [SDKFeatureDefaults.constraintSpansKey: "0", SDKFeatureDefaults.grammarMTPKey: "off"]) + #expect(!killed.freeSpanSpeculation && !killed.constrainedSpeculation) + let optedIn = config(spans: true, grammar: true, modelId: "gemma-4-26b-qat-4bit", + environment: [SDKFeatureDefaults.constraintSpansKey: "1", SDKFeatureDefaults.grammarMTPKey: "1"]) + #expect(optedIn.freeSpanSpeculation && optedIn.constrainedSpeculation) + // Empty is unset, as everywhere else. + let empty = config(modelId: "EigenLabs/Qwen3.8-27B-4bit-mtp", + environment: [SDKFeatureDefaults.constraintSpansKey: "", SDKFeatureDefaults.grammarMTPKey: ""]) + #expect(empty.freeSpanSpeculation && empty.constrainedSpeculation) + } + + @Test func grammarMTPsDefaultRidesOnlyOnConstraintSpans() { + // review prov-2109-d4 SF2: grammar MTP was measured with spans on; with + // spans off every constrained position takes the grammar path instead. + let id = "EigenLabs/Qwen3.8-27B-4bit-mtp", builds: Set = ["eigenlabs/qwen3.8-27b-4bit-mtp"] + var spansKilled = CBv2MTPConfig(enabled: true, constrainedSpeculation: false, freeSpanSpeculation: false) + SDKFeatureDefaults.applyMTPDefaults(to: &spansKilled, modelId: id, + environment: [SDKFeatureDefaults.constraintSpansKey: "0"], processEnvironment: [:], + spansBuilds: builds, grammarBuilds: builds) + #expect(!spansKilled.freeSpanSpeculation && !spansKilled.constrainedSpeculation) + var spansUnlisted = CBv2MTPConfig(enabled: true, constrainedSpeculation: false, freeSpanSpeculation: false) + SDKFeatureDefaults.applyMTPDefaults(to: &spansUnlisted, modelId: id, environment: [:], + processEnvironment: [:], spansBuilds: [], grammarBuilds: builds) + #expect(!spansUnlisted.constrainedSpeculation) + var spansByOperator = CBv2MTPConfig(enabled: true, freeSpanSpeculation: true) + SDKFeatureDefaults.applyMTPDefaults(to: &spansByOperator, modelId: id, + environment: [SDKFeatureDefaults.constraintSpansKey: "1"], processEnvironment: [:], + spansBuilds: [], grammarBuilds: builds) + #expect(spansByOperator.constrainedSpeculation) + // An operator value in the process environment wins over a slot + // environment that lacks it (review prov-2109-d4 NIT 7). + var scrubbed = CBv2MTPConfig(enabled: true, constrainedSpeculation: false, freeSpanSpeculation: false) + SDKFeatureDefaults.applyMTPDefaults(to: &scrubbed, modelId: id, environment: [:], + processEnvironment: [SDKFeatureDefaults.constraintSpansKey: "0", SDKFeatureDefaults.grammarMTPKey: "0"], + spansBuilds: builds, grammarBuilds: builds) + #expect(!scrubbed.freeSpanSpeculation && !scrubbed.constrainedSpeculation) + } + + @Test func aMarkerIsTrustedOnlyForKeysTheProviderInjects() { + // review prov-2109-d4 NIT 5/6: a stale or foreign marker never unsets an + // operator's value of another key; the marker alone identifies the + // release's own value (a process that never ran `apply`). + let marker = SDKFeatureDefaults.injectedMarkerKey + let foreign = SDKFeatureDefaults.plan(onByDefault: [], + environment: ["DARKBLOOM_CBV2_MTP": "1", marker: "DARKBLOOM_CBV2_MTP"]) + #expect(!foreign.unset.contains("DARKBLOOM_CBV2_MTP")) + let key = NativeReasoningBudget.environmentKey + #expect(!NativeReasoningBudget.isEnabled(for: .mimoV26, environment: [key: "1", marker: key], + families: [.nemotronSuper], injected: [])) + #expect(NativeReasoningBudget.isEnabled(for: .mimoV26, environment: [key: "1", marker: "DARKBLOOM_OTHER"], + families: [.nemotronSuper], injected: [])) + } + + @Test func reasoningBudgetsFollowTheFamilyDefaultUnlessTheOperatorSetsThem() { + let key = NativeReasoningBudget.environmentKey + func on(_ family: NativeReasoningBudget.Family, _ environment: [String: String], + injected: Set = []) -> Bool { + NativeReasoningBudget.isEnabled(for: family, environment: environment, + families: [.nemotronSuper], injected: injected) + } + #expect(on(.nemotronSuper, [:])) + #expect(!on(.mimoV26, [:])) + // The release's own `1` (injected so engines accept budget rows) is not + // the operator's: MiMo stays off. + #expect(!on(.mimoV26, [key: "1"], injected: [key])) + #expect(on(.nemotronSuper, [key: "1"], injected: [key])) + // The operator's value applies to every family. + #expect(on(.mimoV26, [key: "1"])) + #expect(!on(.nemotronSuper, [key: "0"])) + #expect(on(.nemotronSuper, [key: ""])) + } + + @Test func theSlotFactoryAppliesThePerBuildDefaults() throws { + let source = try String(contentsOf: Self.sources.appendingPathComponent( + "ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory.swift"), encoding: .utf8) + .filter { !$0.isWhitespace } + #expect(source.contains("SDKFeatureDefaults.applyMTPDefaults(to:&mtpConfig,modelId:modelId,environment:environment")) + } + + static let sources = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // Config + .deletingLastPathComponent() // ProviderCoreTests + .deletingLastPathComponent() // Tests + .deletingLastPathComponent() // provider-swift + .appendingPathComponent("Sources") +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/BudgetOnlyReasoningConformanceTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/BudgetOnlyReasoningConformanceTests.swift new file mode 100644 index 0000000000..27ec716169 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/BudgetOnlyReasoningConformanceTests.swift @@ -0,0 +1,94 @@ +import Foundation +import MLXLMServer +import XCTest +@testable import ProviderCore + +final class BudgetOnlyReasoningConformanceTests: XCTestCase { + private let flag = "DARKBLOOM_NATIVE_REASONING_BUDGET" + private var previous: String? + override func setUp() { + super.setUp() + previous = ProcessInfo.processInfo.environment[flag] + setenv(flag, "1", 1) + } + override func tearDown() { + if let previous { setenv(flag, previous, 1) } else { unsetenv(flag) } + super.tearDown() + } + + private func body(_ budget: String) -> Data { + Data(""" + {"model":"mimo-v2.6-flash-mopd","messages":[{"role":"user","content":"Hello"}], + "reasoning":{"max_tokens":\(budget)}} + """.utf8) + } + + func testSuperBudgetOnlyEnablesThinking() throws { + let data = body("512") + let controls = try NemotronSuperPromptContract.controls(body: data) + XCTAssertTrue(controls.enableThinking) + XCTAssertEqual(try JSONDecoder().decode(ChatTemplateControls.self, from: data).reasoningBudgetTokens, 512) + } + + func testMiMoBudgetOnlyIsAcceptedAndRetainsBudget() throws { + let data = body("512") + try MiMoV26TemplateFix.validateRawControls(data) + let request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: data) + let controls = try JSONDecoder().decode(ChatTemplateControls.self, from: data) + XCTAssertTrue(try MiMoV26TemplateFix.effectiveThinkingEnabled(request: request, controls: controls)) + XCTAssertEqual(controls.reasoningBudgetTokens, 512) + } + + func testInvalidBudgetsAreStillRefused() { + for value in ["0", "-1", "2147483648", "9223372036854775807", "2.5", #""512""#, "true", "{}", "[]"] { + XCTAssertThrowsError(try NemotronSuperPromptContract.controls(body: body(value))) + XCTAssertThrowsError(try MiMoV26TemplateFix.validateRawControls(body(value))) + } + } + + func testPositiveBudgetConflictsWithExplicitThinkingOff() throws { + for controls in [#""reasoning":{"enabled":false,"max_tokens":2}"#, + #""reasoning":{"effort":"none","max_tokens":2}"#, + #""enable_thinking":false,"reasoning":{"max_tokens":2}"#] { + let data = Data(""" + {"model":"mimo-v2.6-flash-mopd","messages":[{"role":"user","content":"Hello"}],\(controls)} + """.utf8) + XCTAssertThrowsError(try NemotronSuperPromptContract.controls(body: data)) + let request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: data) + let template = try JSONDecoder().decode(ChatTemplateControls.self, from: data) + XCTAssertThrowsError(try MiMoV26TemplateFix.effectiveThinkingEnabled(request: request, controls: template)) + } + } + + /// Off must be 0.10.12 byte for byte, including which refusal a client + /// gets: an unusable `max_tokens` beside an unknown effort is still the + /// effort refusal (`unsupported_reasoning_control`), not a payload error. + func testOffKeepsTodaysRefusalClassForUnusableBudgetBesideUnknownEffort() { + for budget in ["null", #""512""#, "2.5", "true"] { + let data = Data(""" + {"model":"mimo-v2.6-flash-mopd","messages":[{"role":"user","content":"Hello"}], + "reasoning":{"max_tokens":\(budget),"effort":"bogus"}} + """.utf8) + for value in ["0", nil] as [String?] { + if let value { setenv(flag, value, 1) } else { unsetenv(flag) } + XCTAssertThrowsError(try MiMoV26TemplateFix.validateRawControls(data)) { + XCTAssertEqual( + $0 as? MultiModelBatchSchedulerEngineError, + .unsupportedReasoningEffort(.reasoningObject), "max_tokens \(budget), flag \(value ?? "unset")") + } + } + } + } + + func testOffKeepsTodaysRefusalAndAbsentFollowsTheReleaseDefault() throws { + for value in ["0", "off", "false", "no"] { + setenv(flag, value, 1) + XCTAssertThrowsError(try NemotronSuperPromptContract.controls(body: body("512"))) + XCTAssertThrowsError(try MiMoV26TemplateFix.validateRawControls(body("512"))) + } + // Unset: on for Super and MiMo since 0.10.13 (`SDKFeatureDefaults`). + unsetenv(flag) + XCTAssertEqual(try NemotronSuperPromptContract.controls(body: body("512")).reasoningBudgetTokens, 512) + XCTAssertNoThrow(try MiMoV26TemplateFix.validateRawControls(body("512"))) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeReasoningBudgetBridgeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeReasoningBudgetBridgeTests.swift new file mode 100644 index 0000000000..d634f38678 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/NativeReasoningBudgetBridgeTests.swift @@ -0,0 +1,274 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import Hummingbird +import HummingbirdTesting +import MLX +import MLXLMCommon +import MLXLMServer +import NIOCore +import NIOFoundationCompat +import Testing +import XCTest +@testable import ProviderCore + +private struct BudgetBridgeTokenizer: MLXLMCommon.Tokenizer { + var promptToken = 0 + var splitsClose = false + func encode(text: String, addSpecialTokens: Bool) -> [Int] { + switch text { + case "": return [14] + case "": return splitsClose ? [7, 8] : [8] + default: return [promptToken] + } + } + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + tokenIds.map { convertIdToToken($0)! }.joined() + } + func convertTokenToId(_ token: String) -> Int? { + switch token { case "": return 14; case "": return 8; default: return nil } + } + func convertIdToToken(_ id: Int) -> String? { + switch id { case 14: return ""; case 8: return ""; default: return "t\(id)" } + } + var bosToken: String? { nil } + var eosToken: String? { nil } + var unknownToken: String? { nil } + func applyChatTemplate(messages: [[String: any Sendable]], tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]?) throws -> [Int] { [promptToken] } +} + +/// XCTest runs separately from Swift Testing. The raw-ingress flag is restored +/// after each case; the native engine's capability is explicit and immutable. +final class NativeReasoningBudgetIngressTests: XCTestCase { + private final class LookupReceipts: @unchecked Sendable { + private let lock = NSLock() + private var values: [PrefixCacheLookupResult] = [] + func append(_ value: PrefixCacheLookupResult) { lock.withLock { values.append(value) } } + var snapshot: [PrefixCacheLookupResult] { lock.withLock { values } } + } + + private let flag = "DARKBLOOM_NATIVE_REASONING_BUDGET" + private var previous: String? + + override func setUp() { + super.setUp() + previous = ProcessInfo.processInfo.environment[flag] + setenv(flag, "1", 1) + } + + override func tearDown() { + if let previous { setenv(flag, previous, 1) } else { unsetenv(flag) } + super.tearDown() + } + + private func bridge(model: String, tokenizer: BudgetBridgeTokenizer, + enabled: Bool = true) -> EngineV2Bridge { + let kinds = [CBv2LayerKind(attention: .full, headDim: 64, kvHeads: 1, queryHeads: 1)] + let engine = EngineV2(model: BudgetBridgeModel(), layerKinds: kinds, + backend: CBv2ContiguousKVBackend(config: .init(bytesCapacity: 1 << 20)), + cacheProvider: CBv2LayerCacheBank(layerKinds: kinds), + detokenizerFactory: CBv2TextDetokenizerFactory(tokenizer: tokenizer), + reasoningBudgetsEnabled: enabled) + return EngineV2Bridge(engine: engine, modelId: model, + tokenizer: TokenizerHandle(tokenizer), eosTokenIds: [], extraEOSTokens: [], + defaultMaxTokens: 6, maxConcurrentRequests: 2) + } + + private func collect(_ stream: AsyncStream) async + -> (text: String, completion: Int?, errors: [String]) { + var result = (text: "", completion: Optional.none, errors: [String]()) + for await event in stream { + switch event { + case .chunk(let text): result.text += text + case .info(_, let count, _, _): result.completion = count + case .error(let message): result.errors.append(message) + case .terminal: result.errors.append("unexpected abort") + case .logprobs: break + } + } + return result + } + + func testSuperRawBudgetControlsTheActualGeneratedTokens() async throws { + let model = NemotronSuperLocalBinding.modelID + let bridge = bridge(model: model, tokenizer: .init()) + for (budget, expected) in [(1, "t1t9t10t11t12"), + (2, "t1t2t9t10t11"), + (3, "t1t2t3t9t10")] { + let body = Data(""" + {"model":"\(model)","messages":[{"role":"user","content":"Hello"}], + "reasoning":{"max_tokens":\(budget)},"max_tokens":6,"temperature":0} + """.utf8) + let plan = try NemotronSuperRequestPlan(body: body) + let result = await collect(await bridge.submitTokenized(promptTokens: [0], + request: plan.bridgeRequest, cacheEnabled: false)) + XCTAssertTrue(result.errors.isEmpty) + XCTAssertEqual(result.text, expected) + XCTAssertEqual(result.completion, 6) + } + await bridge.shutdown() + } + + func testMiMoHTTPChatAndResponsesPreserveNThroughTheRealScheduler() async throws { + // The ON prompt ends outside thought. The deterministic model emits + // opener14, payload15/0, forced close8, then answer9/10: six tokens. + let tokenizer = BudgetBridgeTokenizer(promptToken: 13) + let bridge = bridge(model: "budget-mimo", tokenizer: tokenizer) + let app = makeLocalInferenceApplication( + config: .init(host: "127.0.0.1", port: 0, authToken: "budget-fixture"), + defaultMaxTokens: 6, + acquire: { model in + .init(tokenizer: TokenizerHandle(tokenizer), + releaseToken: .init(release: { _ in }, modelId: model), + modelType: "mimo_v2", engineV2Bridge: bridge) + }, + tokenizerProvider: { _ in .init(tokenizer: TokenizerHandle(tokenizer), modelType: "mimo_v2") }, + availableModels: { ["budget-mimo"] }, mtpSlots: { [] }) + try await app.test(.router) { client in + for responses in [false, true] { + for (budget, expectedThought, expectedAnswer) in [ + (1, "t15", "t9t10t11"), (2, "t15t0", "t9t10"), (3, "t15t0t1", "t9") + ] { + let input = responses ? #""input":"Hello","max_output_tokens":6"# + : #""messages":[{"role":"user","content":"Hello"}],"max_tokens":6"# + let body = Data(""" + {"model":"budget-mimo",\(input),"reasoning":{"max_tokens":\(budget)},"temperature":0} + """.utf8) + try await client.execute(uri: responses ? "/v1/responses" : "/v1/chat/completions", + method: .post, headers: [.contentType: "application/json", .authorization: "Bearer budget-fixture"], + body: ByteBuffer(bytes: body)) { result in + XCTAssertEqual(result.status, .ok, String(buffer: result.body)) + let bytes = Data(buffer: result.body) + let object = try XCTUnwrap(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + let usage = try XCTUnwrap(object["usage"] as? [String: Any]) + XCTAssertEqual(usage[responses ? "output_tokens" : "completion_tokens"] as? Int, 6) + if responses { + let response = try JSONDecoder().decode(OpenAIResponse.self, from: bytes) + XCTAssertEqual(response.outputText, expectedAnswer) + XCTAssertEqual(response.output.filter { $0.type == "reasoning" } + .flatMap { $0.summary ?? [] }.map(\.text).joined(), expectedThought) + } else { + let response = try JSONDecoder().decode(OpenAIChatCompletionResponse.self, from: bytes) + let message = try XCTUnwrap(response.choices.first?.message) + XCTAssertEqual(message.content.text, expectedAnswer) + XCTAssertEqual(message.reasoningContent, expectedThought) + } + } + } + } + } + await bridge.shutdown() + } + + func testUnsupportedEngineAndSplitMarkerRefuseBeforeOutput() async throws { + for (enabled, tokenizer) in [(false, BudgetBridgeTokenizer()), + (true, BudgetBridgeTokenizer(splitsClose: true))] { + let bridge = bridge(model: "budget-refusal", tokenizer: tokenizer, enabled: enabled) + var request = ChatCompletionRequest(model: "budget-refusal", messages: [], temperature: 0, max_tokens: 6) + request.nativeReasoningBudget = .init(maximumTokens: 2, family: .nemotronSuper) + let result = await collect(await bridge.submitTokenized(promptTokens: [0], request: request, cacheEnabled: false)) + XCTAssertEqual(result.text, "") + XCTAssertFalse(result.errors.isEmpty) + XCTAssertNil(result.completion) + await bridge.shutdown() + } + } + + func testUntrustedWireCannotSetOrRoundTripTheInternalBudget() throws { + let data = Data(#"{"model":"fixture","messages":[],"max_tokens":7,"seed":23,"min_p":0.2,"nativeReasoningBudget":{"maximumTokens":2,"family":"nemotronSuper"}}"#.utf8) + var decoded = try JSONDecoder().decode(ChatCompletionRequest.self, from: data) + XCTAssertNil(decoded.nativeReasoningBudget) + decoded.nativeReasoningBudget = .init(maximumTokens: 2, family: .nemotronSuper) + let encoded = try JSONEncoder().encode(decoded) + let object = try XCTUnwrap(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + XCTAssertNil(object["nativeReasoningBudget"]) + let roundTrip = try JSONDecoder().decode(ChatCompletionRequest.self, from: encoded) + XCTAssertEqual(roundTrip.max_tokens, 7) + XCTAssertEqual(roundTrip.seed, 23) + XCTAssertEqual(roundTrip.min_p, 0.2) + XCTAssertNil(roundTrip.nativeReasoningBudget) + } + + func testBudgetRefusalFinalizesPolicyLookupExactlyOnceForBothSubmissionAPIs() async throws { + for throwsOnRefusal in [false, true] { + for (enabled, tokenizer) in [(false, BudgetBridgeTokenizer()), + (true, BudgetBridgeTokenizer(splitsClose: true))] { + let bridge = bridge(model: "budget-receipt", tokenizer: tokenizer, enabled: enabled) + var request = ChatCompletionRequest(model: "budget-receipt", messages: [], temperature: 0, max_tokens: 6) + request.nativeReasoningBudget = .init(maximumTokens: 2, family: .nemotronSuper) + let receipts = LookupReceipts() + let signal = EngineV2RequestUsageSignal(onLookupResolved: receipts.append) + if throwsOnRefusal { + do { + _ = try await bridge.submitTokenized(promptTokens: [0], request: request, + usageSignal: signal, firstContentDeadline: nil) + XCTFail("Unsupported budget must throw before generation") + } catch let error as MultiModelBatchSchedulerEngineError { + guard case .unsupportedOutputControl = error else { throw error } + } + } else { + let result = await collect(await bridge.submitTokenized(promptTokens: [0], + request: request, usageSignal: signal)) + XCTAssertEqual(result.text, "") + XCTAssertFalse(result.errors.isEmpty) + XCTAssertNil(result.completion) + } + XCTAssertEqual(signal.lookupResult?.outcome, .skippedPolicy) + XCTAssertEqual(receipts.snapshot.count, 1) + XCTAssertEqual(receipts.snapshot.first?.outcome, .skippedPolicy) + await bridge.shutdown() + XCTAssertEqual(receipts.snapshot.count, 1) + } + } + } +} + +private final class BudgetBridgeModel: CBv2SteppableModel { + let transitions = MLXArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]) + func forward(tokens: MLXArray, caches: [CBv2AttendingLayerCache]) -> MLXArray { + let kv = broadcast(tokens.asType(.float32).reshaped([tokens.dim(0), 1, tokens.dim(1), 1]), + to: [tokens.dim(0), 1, tokens.dim(1), 64]) + for cache in caches { + _ = cache.updateAndAttend(queries: kv, keys: kv, values: kv, scale: 1, sinks: nil) + } + return take(eye(16), take(transitions, tokens, axis: 0), axis: 0) + } +} + +@Suite("Native reasoning budget through the provider bridge", .serialized) +struct NativeReasoningBudgetBridgeTests { + @Test("The real bridge closes at N and continues the same native request") + func closesAtBudget() async throws { + let kinds = [CBv2LayerKind(attention: .full, headDim: 64, kvHeads: 1, queryHeads: 1)] + let tokenizer = BudgetBridgeTokenizer() + let engine = EngineV2(model: BudgetBridgeModel(), layerKinds: kinds, + backend: CBv2ContiguousKVBackend(config: .init(bytesCapacity: 1 << 20)), + cacheProvider: CBv2LayerCacheBank(layerKinds: kinds), + detokenizerFactory: CBv2TextDetokenizerFactory(tokenizer: tokenizer), + reasoningBudgetsEnabled: true) + let bridge = EngineV2Bridge(engine: engine, modelId: "super-budget-fixture", + tokenizer: TokenizerHandle(tokenizer), eosTokenIds: [], extraEOSTokens: [], + defaultMaxTokens: 6, maxConcurrentRequests: 2) + var request = ChatCompletionRequest(model: "super-budget-fixture", messages: [], + temperature: 0, max_tokens: 6) + request.nativeReasoningBudget = NativeReasoningBudget(maximumTokens: 2, family: .nemotronSuper) + let stream = await bridge.submitTokenized(promptTokens: [0], request: request, cacheEnabled: false) + var text = "" + var completion: Int? + var errors: [String] = [] + for await event in stream { + switch event { + case .chunk(let value): text += value + case .info(_, let count, _, _): completion = count + case .error(let message): errors.append(message) + case .terminal: errors.append("unexpected abort") + case .logprobs: break + } + } + await bridge.shutdown() + #expect(errors.isEmpty) + #expect(text == "t1t2t9t10t11") + #expect(completion == 6) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Performance/Deadline/DeadlineRuntimeEnvironmentTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Performance/Deadline/DeadlineRuntimeEnvironmentTests.swift index 5d138dec80..9e9e2e8695 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Performance/Deadline/DeadlineRuntimeEnvironmentTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Performance/Deadline/DeadlineRuntimeEnvironmentTests.swift @@ -19,6 +19,19 @@ import Testing } } +@Test func deadlineQualificationAcceptsTheReleasesOwnSDKDefaults() { + // review prov-2109-d4 SF3: every darkbloom process (serving and the + // qualification runner) carries the release's injected defaults and the + // marker; profiles are pinned to the provider version, so these describe + // the measured environment. An operator value still fails closed. + let key = "DARKBLOOM_GEMMA_SCHEMA_COERCION", marker = SDKFeatureDefaults.injectedMarkerKey + #expect(DeadlineRuntimeEnvironment.permitsQualification([key: "1", marker: key], injected: [key])) + #expect(DeadlineRuntimeEnvironment.permitsQualification([key: "1", marker: key], injected: [])) + #expect(DeadlineRuntimeEnvironment.permitsQualification([marker: key], injected: [])) + #expect(!DeadlineRuntimeEnvironment.permitsQualification([key: "1"], injected: [])) + #expect(!DeadlineRuntimeEnvironment.permitsQualification([key: "0", marker: key], injected: [])) +} + @Test func deadlineProfileRejectsUnmeasuredRuntimeOverrides() { let profile = deadlineCalibrationProfileFixture() let hardware = HardwareInfo(machineModel: "test", chipName: profile.chipName, diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GemmaQuotedArgumentConformanceTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GemmaQuotedArgumentConformanceTests.swift new file mode 100644 index 0000000000..77c8e83567 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/GemmaQuotedArgumentConformanceTests.swift @@ -0,0 +1,123 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon +import MLXLMServer +import Testing + +@testable import ProviderCore + +@Suite("Gemma quoted numeric argument conformance") +struct GemmaQuotedArgumentConformanceTests { + private let enabled = ProcessInfo.processInfo.environment["DARKBLOOM_GEMMA_SCHEMA_COERCION"] == "1" + + @Test("strict validation sees the completed numeric conversion", arguments: [false, true]) + func validatesCompletedCall(stream: Bool) throws { + let (prepared, handler) = try setup(schema: #"{"type":"integer"}"#, stream: stream) + let frame = #"<|tool_call>call:count_items{count:<|"|>3<|"|>}"# + func streamedCalls() throws -> [ToolCall] { + var router = NativeToolStreamRouter(handler: handler, requiresToolCall: false, nativePrefix: nil, + streamedCalls: prepared) + var events: [MLXServerGenerationEvent] = [] + for character in frame { events += try router.process(String(character)) } + events += try router.finishText() + events += try router.finishToolCalls(truncated: false) + let deltas = events.compactMap { if case .toolCallDelta(let delta) = $0 { delta } else { nil } } + let completed = try #require(deltas.last?.completed) + let json = Data(deltas.map(\.arguments).joined().utf8) + #expect(try JSONDecoder().decode([String: MLXLMCommon.JSONValue].self, from: json) + == completed.function.arguments) + return router.completedToolCalls + } + if stream && !enabled { + #expect(throws: MultiModelBatchSchedulerEngineError.toolChoiceViolation(ToolNoncomplianceCheck.schemaViolation)) { + _ = try streamedCalls() + } + return + } + let calls: [ToolCall] + if stream { + calls = try streamedCalls() + } else { + _ = handler.processChunk(frame) + calls = handler.finish() + } + #expect(calls.count == 1) + #expect(calls.first?.function.arguments["count"] == (enabled ? .int(3) : .string("3"))) + if enabled { + try ToolConstraintValidation.validate(calls, prepared: prepared) + } else { + #expect(throws: MultiModelBatchSchedulerEngineError.toolChoiceViolation(ToolNoncomplianceCheck.schemaViolation)) { + try ToolConstraintValidation.validate(calls, prepared: prepared) + } + } + } + + @Test("render types do not erase caller-admitted strings", arguments: [false, true]) + func unionStrings(stream: Bool) throws { + for schema in [ + #"{"anyOf":[{"type":"integer"},{"type":"string"}]}"#, + #"{"anyOf":[{"type":"string"},{"type":"integer"}]}"#, + #"{"type":["integer","string"]}"#, + #"{"type":["string","integer"]}"#, + #"{"anyOf":[{"type":["integer","string"]},{"type":"null"}]}"#, + #"{"allOf":[{"anyOf":[{"type":"integer"},{"type":"string"}]}]}"#, + ] { + let (prepared, handler) = try setup(schema: schema, stream: stream) + let frame = #"<|tool_call>call:count_items{count:<|"|>003<|"|>}"# + let calls: [ToolCall] + if stream { + var router = NativeToolStreamRouter(handler: handler, requiresToolCall: false, nativePrefix: nil, + streamedCalls: prepared) + for character in frame { _ = try router.process(String(character)) } + _ = try router.finishText() + _ = try router.finishToolCalls(truncated: false) + calls = router.completedToolCalls + } else { + _ = handler.processChunk(frame) + calls = handler.finish() + } + #expect(calls.count == 1) + #expect(calls.first?.function.arguments["count"] == .string("003")) + try ToolConstraintValidation.validate(calls, prepared: prepared) + } + } + + @Test("invalid numeric text fails before completed-call exposure") + func rejectsFractionBeforeResponseStarts() throws { + let (prepared, handler) = try setup(schema: #"{"type":"integer"}"#, stream: true) + var router = NativeToolStreamRouter(handler: handler, requiresToolCall: false, nativePrefix: nil, + streamedCalls: prepared) + // Deliberately leave responseStarted false: post-start leniency is a separate policy. + let before = try router.process(#"<|tool_call>call:count_items{count:<|"|>3.5<|"|>}"#) + for event in before { + if case .toolCallDelta(let delta) = event { + #expect(delta.completed == nil) + if enabled { #expect(delta.arguments.isEmpty) } + } + } + #expect(throws: MultiModelBatchSchedulerEngineError.toolChoiceViolation(ToolNoncomplianceCheck.schemaViolation)) { + _ = try router.process("") + } + #expect(router.completedToolCalls.isEmpty) + } + + private func setup(schema: String, stream: Bool) throws + -> (ToolChoicePromptPolicy.Prepared, BatchedToolStreamHandler) { + let body = Data(""" + {"model":"gemma-4-26b-qat-4bit","messages":[{"role":"user","content":"Count it."}],"stream":true, + "tools":[{"type":"function","function":{"name":"count_items","strict":true,"parameters":{ + "type":"object","properties":{"count":\(schema)},"required":["count"],"additionalProperties":false}}}]} + """.utf8) + let inbound = try ProviderLoop.decodeInboundChatRequest(body) + var request = inbound.request + request.streamToolCallDeltas = stream + var prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "gemma4") + // Mirror the scheduler: validate against caller declarations, not the + // normalized render types passed to the Gemma parser/template. + prepared.declaredTools = try #require(inbound.extensions.templateControls.declaredTools) + let handler = try #require(try ToolStreamPreparation.makeHandler( + request: request, prepared: prepared, modelType: "gemma4", streamToolCalls: stream)) + return (prepared, handler) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenConstraintSpanNativeFixture.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenConstraintSpanNativeFixture.swift new file mode 100644 index 0000000000..683935ba73 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenConstraintSpanNativeFixture.swift @@ -0,0 +1,222 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN +import Testing +@testable import ProviderCore + +// Observe the public assistant contract while forwarding every operation to +// the real native head. Array values are read only after the stream finishes. +final class ProviderObservedQwenAssistant: CBv2MTPRequestStatefulDrafter { + let native: Qwen35InlineMTPAssistant + private(set) var starts: [(token: MLXArray, history: Int)] = [] + private var rounds: Set = [] + + init(_ native: Qwen35InlineMTPAssistant) { self.native = native } + var mtpTargetIdentity: ObjectIdentifier? { native.mtpTargetIdentity } + var requiredVerificationMode: CBv2MTPVerificationMode? { native.requiredVerificationMode } + var maximumDraftTokens: Int? { native.maximumDraftTokens } + var maximumSpeculativeBatch: Int? { native.maximumSpeculativeBatch } + var supportsTargetPrefixAcceptance: Bool { native.supportsTargetPrefixAcceptance } + var supportsEarlyDraftSubmission: Bool { native.supportsEarlyDraftSubmission } + var prefersBatchedRectangularAttention: Bool { native.prefersBatchedRectangularAttention } + var commitsAcceptedPrefixPerRow: Bool { native.commitsAcceptedPrefixPerRow } + var supportsOrdinaryDecodeHistory: Bool { native.supportsOrdinaryDecodeHistory } + var requiresCommittedObservationFence: Bool { native.requiresCommittedObservationFence } + var draftShortlistSize: Int? { native.draftShortlistSize } + var submitsEveryDraftStepEarly: Bool { native.submitsEveryDraftStepEarly } + var requestStateBytesPerToken: Int { native.requestStateBytesPerToken } + var requestStateTokenGranularity: Int { native.requestStateTokenGranularity } + var requestStateTokenAllocationPadding: Int { native.requestStateTokenAllocationPadding } + var requestStateAllocationSpecs: [CBv2AuxiliaryAllocationSpec]? { + native.requestStateAllocationSpecs + } + + func prepare(rows: [CBv2MTPRowCapture]) -> CBv2MTPPreparedCapture { + native.prepare(rows: rows) + } + + func draftStep(tokens: MLXArray, hidden: MLXArray, prepared: CBv2MTPPreparedCapture) + -> (tokens: MLXArray, hidden: MLXArray) + { + native.draftStep(tokens: tokens, hidden: hidden, prepared: prepared) + } + + func makeRequestState() -> any CBv2MTPRequestState { native.makeRequestState() } + func configureRequestState(_ state: any CBv2MTPRequestState, maximumSequenceLength: Int) + throws + { + try native.configureRequestState(state, maximumSequenceLength: maximumSequenceLength) + } + + func observeCommittedTarget( + _ observation: CBv2MTPCommittedTargetObservation, requestState: any CBv2MTPRequestState + ) { + native.observeCommittedTarget(observation, requestState: requestState) + } + + func draftStep( + tokens: MLXArray, hidden: MLXArray, shortlist: MLXArray?, + requestState: any CBv2MTPRequestState + ) -> (tokens: MLXArray, hidden: MLXArray) { + if rounds.insert(ObjectIdentifier(requestState)).inserted { + starts.append((tokens, requestState.committedInputCount)) + } + return native.draftStep( + tokens: tokens, hidden: hidden, shortlist: shortlist, requestState: requestState) + } + + func evaluationTargets(for state: any CBv2MTPRequestState) -> [MLXArray] { + native.evaluationTargets(for: state) + } + + func requestStateDidFinishEvaluation(_ state: any CBv2MTPRequestState) throws { + try native.requestStateDidFinishEvaluation(state) + } + + func finalizeRound( + requestState: any CBv2MTPRequestState, confirmedInputTokens: Int, + committedDraftTokens: MLXArray, committedTargetHidden: MLXArray + ) { + native.finalizeRound( + requestState: requestState, confirmedInputTokens: confirmedInputTokens, + committedDraftTokens: committedDraftTokens, committedTargetHidden: committedTargetHidden + ) + rounds.remove(ObjectIdentifier(requestState)) + } + + func discardRound(requestState: any CBv2MTPRequestState) { + native.discardRound(requestState: requestState) + rounds.remove(ObjectIdentifier(requestState)) + } + + func releaseRequestState(_ state: any CBv2MTPRequestState) { + native.releaseRequestState(state) + rounds.remove(ObjectIdentifier(state)) + } +} + +// Shared deterministic input for the two native model fixtures, not an output +// oracle. Stream expectations remain independent literal strings and token IDs. +func providerSpanSuccessorWeights(path: [Int], repeating tokenToRepeat: Int? = nil) + -> (embedding: [Float], head: [Float]) { + let width = 64, vocabularySize = 248320 + precondition(path.count < 64 && path.allSatisfy { (0.. (Qwen35TextModel, Qwen35InlineMTPAssistant) { + let json = Data( + #""" + {"model_type":"qwen3_5_moe", + "mtplx_mtp":{"included":true,"prefix":"mtp.","block_size":3}, + "mtplx_mtp_quantization":{}, + "text_config":{"model_type":"qwen3_5_moe_text","hidden_size":64, + "num_hidden_layers":4,"intermediate_size":64,"num_attention_heads":2, + "num_key_value_heads":1,"head_dim":64,"linear_num_value_heads":1, + "linear_num_key_heads":1,"linear_key_head_dim":64,"linear_value_head_dim":64, + "linear_conv_kernel_dim":4,"full_attention_interval":2,"vocab_size":248320, + "num_experts":0,"num_experts_per_tok":0,"moe_intermediate_size":32, + "shared_expert_intermediate_size":32,"norm_topk_prob":true, + "mtp_num_hidden_layers":1,"tie_word_embeddings":false}} + """#.utf8) + let object = try JSONSerialization.jsonObject(with: json) as! [String: Any] + let configuration = try JSONDecoder().decode( + Qwen35TextConfiguration.self, + from: JSONSerialization.data(withJSONObject: object["text_config"]!)) + let target = Qwen35TextModel(configuration) + let path = [promptToken] + outputTokens + [stopToken] + precondition(!repeatsSingleToken || outputTokens.count == 1) + let (code, head) = providerSpanSuccessorWeights(path: path, + repeating: repeatsSingleToken ? outputTokens[0] : nil) + var parameters = Dictionary(uniqueKeysWithValues: target.parameters().flattened()) + for (key, value) in parameters { + parameters[key] = value.asType(.bfloat16) + if key.hasSuffix(".self_attn.o_proj.weight") + || key.hasSuffix(".linear_attn.out_proj.weight") + || key.hasSuffix(".mlp.down_proj.weight") + { + parameters[key] = MLXArray.zeros(value.shape, dtype: .bfloat16) + } + } + parameters["model.embed_tokens.weight"] = MLXArray(code, [248320, 64]).asType(.bfloat16) + parameters["lm_head.weight"] = MLXArray(head, [248320, 64]).asType(.bfloat16) + target.update(parameters: ModuleParameters.unflattened(parameters)) + + // The head's full-attention block shares the public checkpoint layout. + var weights: [String: MLXArray] = Dictionary( + uniqueKeysWithValues: parameters.compactMap { key, value in + key.hasPrefix("model.layers.1.") + ? ("mtp.layers.0." + String(key.dropFirst("model.layers.1.".count)), value) : nil + }) + for key in ["pre_fc_norm_hidden", "pre_fc_norm_embedding", "norm"] { + weights["mtp.\(key).weight"] = MLXArray.ones([64], dtype: .bfloat16) + } + var fusion = [Float](repeating: 0, count: 64 * 128) + for index in 0 ..< 64 { fusion[index * 128 + index] = 1 } + weights["mtp.fc.weight"] = MLXArray(fusion, [64, 128]).asType(.bfloat16) + quantize(model: target, groupSize: 32, bits: 4) { _, module in module is Embedding } + eval(target) + + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("provider-qwen-span-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + try json.write(to: directory.appendingPathComponent("config.json")) + let shard = "model-00001-of-00001.safetensors" + try save(arrays: weights, url: directory.appendingPathComponent(shard)) + try JSONSerialization.data(withJSONObject: [ + "weight_map": Dictionary(uniqueKeysWithValues: weights.keys.map { ($0, shard) }) + ]).write(to: directory.appendingPathComponent("model.safetensors.index.json")) + let assistant = try Qwen35InlineMTPAssistant.load( + from: directory, target: target, verificationMode: .serialTarget) + return (target, assistant) +} + + +func makeProviderQwenSpanEngine(target: Qwen35TextModel, native: Qwen35InlineMTPAssistant, + tokenizer: any MLXLMCommon.Tokenizer, enabled: Bool) + throws -> (EngineV2, ProviderObservedQwenAssistant) { + let assistant = ProviderObservedQwenAssistant(native) + let kinds = target.cbv2LayerKinds + let adapter = CBv2SteppableLanguageModelAdapter(target) + let observed = try CBv2NativeKVTypeProbe.run(model: adapter, layerKinds: kinds, + caches: target.newCacheV2 { CBv2LayerCache(layerIndex: $0, kind: $1) }) + let backend = try PagedKVBackend(layerKinds: kinds, + config: .init(capacityBytes: 64 << 20, maxPrefillChunk: 32, + nominalMaxSequenceLength: 8192, segmentSizeBytes: 64 << 10, + layerDTypes: observed.layerDTypes)) + let storage = backend.makeLayerCaches() + let indices = Dictionary(uniqueKeysWithValues: kinds.enumerated().map { + ($0.element.modelLayerIndex ?? $0.offset, $0.offset) + }) + let engine = EngineV2(model: adapter, layerKinds: kinds, backend: backend, + cacheProvider: CBv2LayerCacheBank(caches: target.newCacheV2 { index, _ in storage[indices[index]!] }), + detokenizerFactory: CBv2TextDetokenizerFactory(tokenizer: tokenizer), + schedulerConfig: .init(maxConcurrentRequests: 1, maxBatchedTokensPerStep: 32, + prefillChunkSize: 32, maxWaiting: 4, enablePrefixCache: false), + admissionConfig: .init(watermarkFraction: 0), mtpDrafter: assistant, + mtpConfig: .init(enabled: true, maxDraftTokens: 2, fixedDraftTokens: 2, + verificationMode: .serialTarget, freeSpanSpeculation: enabled)) + return (engine, assistant) +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenConstraintSpanServingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenConstraintSpanServingTests.swift new file mode 100644 index 0000000000..ed49ea482b --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenConstraintSpanServingTests.swift @@ -0,0 +1,571 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXLMServer +import MLXNN +import Testing +@testable import ProviderCore + +/// Qwen's verified vocabulary shape with distinct pieces for a literal stream. +/// The real provider still compiles its ordinary strict-tool constraint. +private struct SpanStreamTokenizer: MLXLMCommon.Tokenizer { + static let promptID = 900 + static let firstPiece = 1000 + let pieces: [String] + var thinking = true + private let bytes = QwenByteTestTokenizer() + + func encode(text: String, addSpecialTokens: Bool) -> [Int] { + bytes.encode(text: text, addSpecialTokens: addSpecialTokens) + } + + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + tokenIds.map { id in + if id == Self.promptID { return QwenByteTestTokenizer.prompt(thinking: thinking) } + if pieces.indices.contains(id - Self.firstPiece) { return pieces[id - Self.firstPiece] } + return bytes.decode(tokenIds: [id], skipSpecialTokens: skipSpecialTokens) + }.joined() + } + + func convertTokenToId(_ token: String) -> Int? { bytes.convertTokenToId(token) } + func convertIdToToken(_ id: Int) -> String? { + let piece: String + if id == Self.promptID { + piece = QwenByteTestTokenizer.prompt(thinking: thinking) + } else if pieces.indices.contains(id - Self.firstPiece) { + piece = pieces[id - Self.firstPiece] + } else { + return bytes.convertIdToToken(id) + } + return piece.utf8.map { bytes.convertIdToToken(Int($0))! }.joined() + } + var bosToken: String? { nil } + var eosToken: String? { bytes.eosToken } + var unknownToken: String? { nil } + func applyChatTemplate(messages: [[String: any Sendable]], tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]?) throws -> [Int] { + #expect((additionalContext?["enable_thinking"] as? Bool ?? true) == thinking) + return [Self.promptID] + } +} + +private final class SpanStreamCursor: CBv2MTPPreparedCapture { + let offsets: [Int] + var step = 0 + init(_ offsets: [Int]) { self.offsets = offsets } +} + +/// The target is native; this transparent proposer makes draft boundaries +/// observable without claiming to qualify Qwen's persistent assistant history. +private final class SpanStreamDrafter: CBv2MTPDrafter { + let mtpTargetIdentity: ObjectIdentifier? + private let tokens: [Int] + private let lock = NSLock() + private var offsets: [Int] = [] + var starts: [Int] { lock.withLock { offsets } } + + init(target: Gemma4TextModel, tokens: [Int]) { + mtpTargetIdentity = ObjectIdentifier(target) + self.tokens = tokens + } + + func prepare(rows: [CBv2MTPRowCapture]) -> CBv2MTPPreparedCapture { + // One prompt token: anchor is the next output index after the seed. + let starts = rows.map(\.anchor) + lock.withLock { offsets += starts } + return SpanStreamCursor(starts) + } + + func draftStep(tokens: MLXArray, hidden: MLXArray, prepared: CBv2MTPPreparedCapture) + -> (tokens: MLXArray, hidden: MLXArray) { + let cursor = prepared as! SpanStreamCursor + let next = cursor.offsets.map { index in + Int32(self.tokens[min(index + cursor.step, self.tokens.count - 1)]) + } + cursor.step += 1 + return (MLXArray(next), hidden) + } +} + +private struct SpanStreamOutcome { + var content = "" + var reasoning = "" + var deltas: [ServerToolCallDelta] = [] + var info: ServerGenerationInfo? + var terminals = 0 + private var parser = StreamingReasoningParser(format: .qwen3) + + mutating func record(_ event: MLXServerGenerationEvent) { + switch event { + case .content(let text): parser.parse(text).forEach { apply($0) } + case .parsed(let value): apply(value) + case .toolCallDelta(let delta): deltas.append(delta) + case .info(let value): info = value; terminals += 1 + case .toolCall, .logprobs: break + } + } + mutating func finish() { parser.finish().forEach { apply($0) } } + private mutating func apply(_ value: ParsedReasoning) { + content += value.content + reasoning += value.reasoningContent ?? "" + } +} + +@Suite("Qwen constraint spans through native serving", .serialized) +struct QwenConstraintSpanServingTests { + private static let pieces = [ + "Let", " me", " check", " the", " time", ".", "", + "One", " moment", ",", " please", ".", " ", + "\n", "\n", "\n", + "Ro", "me", "\n\n", "\n", "", + "All", " done", ",", " thank", " you", ".", + ] + private static let tools = #""" + [{"type":"function","function":{"name":"get_time","strict":true, + "parameters":{"type":"object","properties":{"city":{"type":"string"}}, + "required":["city"],"additionalProperties":false}}}] + """# + + /// A small real Gemma target carries a fixed token code through native + /// layers and KV updates. This qualifies provider/engine wiring, not a + /// full Qwen model or the production Qwen assistant's history ownership. + private func target(pieces: [String] = Self.pieces) throws -> Gemma4TextModel { + let configuration = #""" + {"model_type":"gemma4_text","hidden_size":64,"num_hidden_layers":6, + "intermediate_size":128,"num_attention_heads":2,"head_dim":32, + "global_head_dim":32,"num_key_value_heads":1,"num_kv_shared_layers":2, + "layer_types":["sliding_attention","full_attention","full_attention", + "sliding_attention","sliding_attention","full_attention"], + "sliding_window":16,"final_logit_softcapping":30.0, + "tie_word_embeddings":false,"vocab_size":248320,"vocab_size_per_layer_input":248320, + "rms_norm_eps":1e-6,"hidden_size_per_layer_input":0,"use_double_wide_mlp":false} + """# + let model = Gemma4TextModel(try JSONDecoder().decode( + Gemma4TextConfiguration.self, from: Data(configuration.utf8))) + let path = [SpanStreamTokenizer.promptID] + + Array(SpanStreamTokenizer.firstPiece ..< SpanStreamTokenizer.firstPiece + pieces.count) + + [StrictToolFixture.imEnd] + let width = 64 + let (embedding, head) = providerSpanSuccessorWeights(path: path) + var replacements: [String: MLXArray] = [ + "model.embed_tokens.weight": MLXArray(embedding, [248320, width]), + "lm_head.weight": MLXArray(head, [248320, width]), + ] + for (name, value) in model.parameters().flattened() { + if name.hasSuffix(".self_attn.o_proj.weight") || name.hasSuffix(".mlp.down_proj.weight") { + replacements[name] = MLXArray.zeros(value.shape, dtype: value.dtype) + } else if name.hasSuffix(".layer_scalar") || name == "model.norm.weight" { + replacements[name] = MLXArray.ones(value.shape, dtype: value.dtype) + } + } + model.update(parameters: ModuleParameters.unflattened(replacements)) + eval(model) + return model + } + + private func engine(_ target: Gemma4TextModel, enabled: Bool, + pieces: [String] = Self.pieces, thinking: Bool = true) + -> (EngineV2, SpanStreamDrafter, SpanStreamTokenizer) { + let tokenizer = SpanStreamTokenizer(pieces: pieces, thinking: thinking) + let tokens = Array(SpanStreamTokenizer.firstPiece ..< SpanStreamTokenizer.firstPiece + pieces.count) + + [StrictToolFixture.imEnd] + let drafter = SpanStreamDrafter(target: target, tokens: tokens) + let kinds = target.cbv2LayerKinds + let engine = EngineV2(model: CBv2SteppableLanguageModelAdapter(target), layerKinds: kinds, + backend: CBv2ContiguousKVBackend(config: .init(bytesCapacity: 1 << 26)), + cacheProvider: CBv2LayerCacheBank(layerKinds: kinds), + detokenizerFactory: CBv2TextDetokenizerFactory(tokenizer: tokenizer), + mtpDrafter: drafter, + mtpConfig: .init(enabled: true, maxDraftTokens: 3, fixedDraftTokens: 3, + verificationMode: .serialTarget, freeSpanSpeculation: enabled)) + return (engine, drafter, tokenizer) + } + + @Test(.timeLimit(.minutes(3))) + func strictAutoStreamDraftsAroundTheProtectedCall() async throws { + let target = try target() + // Prove this fixture actually supports MTP before the constrained red. + let (unconstrained, _, _) = engine(target, enabled: true) + do { + var raw = "" + for await event in try unconstrained.submit(.init(id: .init(1), + promptTokens: [SpanStreamTokenizer.promptID], sampling: .init(temperature: 0), + maxTokens: Self.pieces.count + 2, stopTokens: StrictToolFixture.stops)) { + if case .delta(let text, _, _) = event { raw += text } + } + let control = try #require(unconstrained.mtpMetricsSnapshot()) + #expect(raw == Self.pieces.joined()) + #expect(control.acceptedTokens > 0) + await unconstrained.shutdown() + } catch { + await unconstrained.shutdown() + throw error + } + + var baseline: SpanStreamOutcome? + for enabled in [false, true] { + let (native, drafter, tokenizer) = engine(target, enabled: enabled) + let outcome = try await stream(native, tokenizer: tokenizer, thinking: true, + extra: #""tools":\#(Self.tools)"#, prompt: "time") + let metrics = try #require(native.mtpMetricsSnapshot()) + #expect(outcome.reasoning == "Let me check the time.") + #expect(outcome.content == "One moment, please. All done, thank you.") + let calls = outcome.deltas.compactMap(\.completed) + #expect(calls.count == 1) + #expect(calls.first?.function.name == "get_time") + #expect(calls.first?.function.arguments == ["city": .string("Rome")]) + #expect(outcome.deltas.count > 2 && outcome.deltas.first?.name == "get_time") + #expect(outcome.terminals == 1) + if enabled { + #expect(metrics.acceptedTokens > 0) + #expect(drafter.starts.contains { $0 < 6 }) + #expect(drafter.starts.contains { $0 >= 21 }) + #expect(!drafter.starts.contains { (14..<21).contains($0) }) + #expect(outcome.info?.completionTokens == baseline?.info?.completionTokens) + #expect(outcome.info?.stopReason == baseline?.info?.stopReason) + } else { + #expect(metrics.rounds == 0 && drafter.starts.isEmpty) + baseline = outcome + } + } + } + + @Test(.timeLimit(.minutes(3)), arguments: [false, true]) + func multipleCallsReturnToFreeTextWithThinkingOnOrOff(thinking: Bool) async throws { + var pieces = thinking ? ["Let", " me", " check", " both", " clocks", ".", ""] : [] + let before = pieces.count + pieces += ["First", " city", " is", " next", ".", " "] + let firstCall = pieces.count + pieces += ["\n", "\n", "\n", + "Ro", "me", "\n\n\n"] + let between = pieces.count + pieces += ["One", " more", " city", " to", " check", ".", " "] + let secondCall = pieces.count + pieces += ["\n\n\n", + "Pa", "ris", "\n\n", "\n", ""] + let after = pieces.count + pieces += ["All", " done", ",", " thank", " you", "."] + let target = try target(pieces: pieces) + var baseline: SpanStreamOutcome? + for enabled in [false, true] { + let (native, drafter, tokenizer) = engine(target, enabled: enabled, pieces: pieces, thinking: thinking) + let outcome = try await stream(native, tokenizer: tokenizer, thinking: thinking, + extra: #""tools":\#(Self.tools)"#) + let metrics = try #require(native.mtpMetricsSnapshot()) + #expect(outcome.reasoning == (thinking ? "Let me check both clocks." : "")) + #expect(outcome.content == "First city is next. One more city to check. All done, thank you.") + let calls = outcome.deltas.compactMap(\.completed) + #expect(calls.map(\.function.name) == ["get_time", "get_time"]) + #expect(calls.map(\.function.arguments) == [["city": .string("Rome")], ["city": .string("Paris")]]) + #expect(outcome.deltas.count > 4 && outcome.terminals == 1) + if enabled { + #expect(metrics.acceptedTokens > 0) + #expect(drafter.starts.contains { (before..= after }) + #expect(!drafter.starts.contains { + ((firstCall + 1).."] : [] + let answerStart = pieces.count + pieces += ["{", "\"city\"", ":", "\"", "Ro", "me", "\"", "}", " ", "\n", " "] + let target = try target(pieces: pieces) + var baseline: SpanStreamOutcome? + for enabled in [false, true] { + let (native, drafter, tokenizer) = engine(target, enabled: enabled, pieces: pieces, thinking: thinking) + let outcome = try await stream(native, tokenizer: tokenizer, thinking: thinking, + extra: #""response_format":{"type":"json_object"}"#) + let metrics = try #require(native.mtpMetricsSnapshot()) + #expect(outcome.reasoning == (thinking ? "Let me check the value." : "")) + #expect(outcome.content == "{\"city\":\"Rome\"} \n ") + #expect(outcome.deltas.isEmpty && outcome.terminals == 1) + #expect(!drafter.starts.contains { $0 >= answerStart }) + if enabled && thinking { + #expect(metrics.acceptedTokens > 0) + #expect(!drafter.starts.isEmpty) + } else { + #expect(metrics.rounds == 0 && drafter.starts.isEmpty) + } + if let baseline { + #expect(outcome.info?.completionTokens == baseline.info?.completionTokens) + #expect(outcome.info?.stopReason == baseline.info?.stopReason) + } else { baseline = outcome } + } + } + + @Test func strictPreviewDoesNotInternDiscardedBoundaries() throws { + let pieces = ["ordinary", "<", "\n\n\nRome\n\n\n", + "\n\n\n", "Rome"] + let (request, prepared) = try StrictToolFixture.prepared(StrictToolFixture.body(tools: Self.tools)) + let tokenizer = TokenizerHandle(SpanStreamTokenizer(pieces: pieces, thinking: false)) + let constraint = try #require(QwenStrictToolGrammar.constraint( + prepared: prepared, request: request, parser: .qwen35, tokenizer: tokenizer, + modelType: "qwen3_5", defaultMaxTokens: 64, stopTokenIDs: StrictToolFixture.stops, + promptTokens: [SpanStreamTokenizer.promptID], runsTokenConstraints: true)) + let state = constraint.initialState + let count = constraint.cachedStateCount + #expect(constraint.isFreeSpan(state: state)) + for _ in 0..<10 { + #expect(constraint.isFreeSpanContinuation(state: state, tokenID: 1000)) + for token in [1001, 1002, 1003, 1004, StrictToolFixture.imEnd, 248300, -1] { + #expect(!constraint.isFreeSpanContinuation(state: state, tokenID: token)) + } + #expect(!constraint.isFreeSpan(state: QwenStrictToolConstraint.releasedState)) + #expect(!constraint.isFreeSpan(state: -1)) + } + #expect(constraint.cachedStateCount == count) + #expect(constraint.nextState(state: state, tokenID: 1000) == state) + // This token ends in the original state but transiently touched '<'. + #expect(constraint.nextState(state: state, tokenID: 1002) == state) + let partial = try #require(constraint.nextState(state: state, tokenID: 1001)) + let argument = try #require(constraint.nextState(state: state, tokenID: 1004)) + #expect(!constraint.isFreeSpan(state: partial)) + #expect(!constraint.isFreeSpan(state: argument)) + #expect(!constraint.isFreeSpanContinuation(state: argument, tokenID: 1005)) + let complete = try #require(constraint.nextState(state: state, tokenID: 1003)) + #expect(constraint.isFreeSpan(state: complete)) + #expect(constraint.allowedTokenIDs(state: complete, remainingTokens: 1) + == constraint.allowedTokenIDs(state: complete, remainingTokens: 100)) + } + + @Test func installedProviderReceivesTheExplicitSpanSwitch() throws { + for value: String? in [nil, "0", "1", "false", " true "] { + let key = "DARKBLOOM_CONSTRAINT_SPANS" + var environment = ["UNRELATED_SECRET": "excluded"] + environment[key] = value + let plist = LaunchAgent.makeServicePlist(label: LaunchAgent.label, + programArguments: ["/test/darkbloom", "start", "--foreground"], + logPath: "/test/provider.log", environment: environment) + let encoded = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0) + let decoded = try #require(try PropertyListSerialization.propertyList(from: encoded, format: nil) + as? [String: Any]) + let forwarded = decoded["EnvironmentVariables"] as? [String: String] + #expect(forwarded?[key] == value) + #expect(forwarded?["UNRELATED_SECRET"] == nil) + } + } + + @Test(.timeLimit(.minutes(3)), arguments: [false, true], [false, true]) + func nativeQwenKeepsHistoryAcrossProviderSpans(thinking: Bool, json: Bool) async throws { + let pieces: [String] + if json { + pieces = (thinking ? ["Let", " me", " check", " the", " value", ".", ""] : []) + + ["{", "\"city\"", ":", "\"", "Ro", "me", "\"", "}", " ", "\n", " "] + } else { + // No-thinking begins immediately with a protected call, then returns to text. + pieces = thinking ? Self.pieces : Array(Self.pieces.dropFirst(13)) + } + let tokenizer = SpanStreamTokenizer(pieces: pieces, thinking: thinking) + let tokens = Array(SpanStreamTokenizer.firstPiece ..< SpanStreamTokenizer.firstPiece + pieces.count) + for enabled in [false, true] { + let (target, assistant) = try makeProviderQwenSpanFixture(outputTokens: tokens, + promptToken: SpanStreamTokenizer.promptID, stopToken: StrictToolFixture.imEnd) + let (native, observed) = try makeProviderQwenSpanEngine(target: target, native: assistant, + tokenizer: tokenizer, enabled: enabled) + let outcome = try await stream(native, tokenizer: tokenizer, thinking: thinking, + extra: json ? #""response_format":{"type":"json_object"}"# : #""tools":\#(Self.tools)"#) + #expect(outcome.reasoning == (thinking + ? (json ? "Let me check the value." : "Let me check the time.") : "")) + #expect(outcome.content == (json ? "{\"city\":\"Rome\"} \n " + : (thinking ? "One moment, please. All done, thank you." : "All done, thank you."))) + #expect(outcome.terminals == 1 && outcome.info?.stopReason == "stop") + #expect(outcome.info?.completionTokens == (json ? (thinking ? 19 : 12) : (thinking ? 28 : 15))) + let calls = outcome.deltas.compactMap(\.completed) + #expect(calls.count == (json ? 0 : 1)) + if !json { #expect(calls.first?.function.arguments == ["city": .string("Rome")]) } + let metrics = try #require(native.mtpMetricsSnapshot()) + if enabled && (thinking || !json) { + #expect(metrics.acceptedTokens > 0 && !observed.starts.isEmpty) + var indices: [Int] = [] + for start in observed.starts { + let seed = Int(start.token.item(Int32.self)) + let index = try #require(tokens.firstIndex(of: seed)) + indices.append(index) + #expect(start.history == index, "seed \(seed) has \(start.history) trusted transitions") + } + if json { + #expect(indices.allSatisfy { $0 < 6 }) + } else { + let firstCall = thinking ? 13 : 0 + let lastClose = thinking ? 20 : 7 + if thinking { #expect(indices.contains { $0 < firstCall }) } + #expect(indices.contains { $0 >= lastClose }) + #expect(!indices.contains { (firstCall.. QwenStrictToolConstraint { + let (request, prepared) = try StrictToolFixture.prepared( + StrictToolFixture.body(tools: Self.tools, maxTokens: maxTokens)) + return try #require(QwenStrictToolGrammar.constraint(prepared: prepared, request: request, + parser: .qwen35, tokenizer: TokenizerHandle(tokenizer), modelType: "qwen3_5", + defaultMaxTokens: maxTokens, stopTokenIDs: StrictToolFixture.stops, + promptTokens: [SpanStreamTokenizer.promptID], runsTokenConstraints: true)) + } + + @Test(.timeLimit(.minutes(3)), arguments: [false, true]) + func cancelledNativeQwenReleasesHistoryAndReusesTheRequestID(enabled: Bool) async throws { + let tokenizer = SpanStreamTokenizer(pieces: [" word"], thinking: false) + let (target, assistant) = try makeProviderQwenSpanFixture(outputTokens: [SpanStreamTokenizer.firstPiece], + promptToken: SpanStreamTokenizer.promptID, stopToken: StrictToolFixture.imEnd, repeatsSingleToken: true) + let (native, _) = try makeProviderQwenSpanEngine(target: target, native: assistant, + tokenizer: tokenizer, enabled: enabled) + do { + let id = CBv2RequestID(99) + let constraint = try strictConstraint(tokenizer: tokenizer, maxTokens: 4096) + var count = 0, terminals = 0 + var requested = false + for await event in try native.submit(.init(id: id, promptTokens: [SpanStreamTokenizer.promptID], + sampling: .init(temperature: 0), maxTokens: 4096, stopTokens: StrictToolFixture.stops, + tokenConstraint: constraint)) { + switch event { + case .delta(_, let tokens, _): + count += tokens.count + if !requested { native.cancel(id); requested = true } + case .finished(let reason, let usage): + terminals += 1 + #expect(reason == .cancelled) + #expect(usage.completionTokens == count && usage.promptTokens == 1) + } + } + #expect(requested && count > 0 && count < 4096 && terminals == 1) + var reused: [Int] = [] + terminals = 0 + for await event in try native.submit(.init(id: id, promptTokens: [SpanStreamTokenizer.promptID], + sampling: .init(temperature: 0), maxTokens: 3, stopTokens: StrictToolFixture.stops, + tokenConstraint: strictConstraint(tokenizer: tokenizer, maxTokens: 3))) { + switch event { + case .delta(_, let tokens, _): reused += tokens + case .finished(let reason, let usage): + terminals += 1 + #expect(reason == .length && usage.completionTokens == 3) + } + } + #expect(reused == [1000, 1000, 1000] && terminals == 1) + await native.shutdown() + } catch { + await native.shutdown() + throw error + } + } + + + @Test(.timeLimit(.minutes(3)), arguments: [1, 2, 4, 7, 17]) + func shortOutputBudgetsPreserveTheStreamAndUsage(limit: Int) async throws { + let target = try target() + let expectedReasoning = [1: "Let", 2: "Let me", 4: "Let me check the", + 7: "Let me check the time.", 17: "Let me check the time."] + var baseline: SpanStreamOutcome? + for enabled in [false, true] { + let (native, _, tokenizer) = engine(target, enabled: enabled) + let outcome = try await stream(native, tokenizer: tokenizer, thinking: true, + extra: #""tools":\#(Self.tools)"#, maxTokens: limit) + #expect(outcome.reasoning == expectedReasoning[limit]) + #expect(outcome.terminals == 1 && outcome.info?.stopReason == "length") + #expect(outcome.info?.completionTokens == limit) + #expect(outcome.deltas.compactMap(\.completed).isEmpty) + if let baseline { + #expect(outcome.content == baseline.content) + #expect(outcome.deltas.map(\.arguments).joined() == baseline.deltas.map(\.arguments).joined()) + #expect(outcome.deltas.compactMap(\.name) == baseline.deltas.compactMap(\.name)) + } else { baseline = outcome } + } + } + + @Test(.timeLimit(.minutes(3))) + func bridgeErrorDoesNotPublishSuccessOrPoisonTheNextRequest() async throws { + let target = try target() + var baselineError: [String]? + for enabled in [false, true] { + let (native, _, tokenizer) = engine(target, enabled: enabled) + let bridge = EngineV2Bridge(engine: native, modelId: StrictToolFixture.model, + tokenizer: TokenizerHandle(tokenizer), eosTokenIds: StrictToolFixture.stops, + defaultMaxTokens: 64, maxConcurrentRequests: 1) + do { + let constraint = try strictConstraint(tokenizer: tokenizer, maxTokens: 4) + var errors: [String] = [], text = "" + var terminals = 0 + for await event in await bridge.submitTokenized(promptTokens: [SpanStreamTokenizer.promptID], + request: ChatCompletionRequest(model: StrictToolFixture.model, messages: [], temperature: 0, max_tokens: 3), + requestId: "reused-after-refusal", cacheEnabled: false, tokenConstraint: constraint) { + switch event { + case .error(let message): errors.append(message) + case .info: terminals += 1 + case .chunk(let value): text += value + case .terminal, .logprobs: Issue.record("unexpected error-path event") + } + } + #expect(errors.count == 1 && terminals == 0 && text.isEmpty) + if let baselineError { #expect(errors == baselineError) } else { baselineError = errors } + errors = [] + let nextConstraint = try strictConstraint(tokenizer: tokenizer, maxTokens: 4) + for await event in await bridge.submitTokenized(promptTokens: [SpanStreamTokenizer.promptID], + request: ChatCompletionRequest(model: StrictToolFixture.model, messages: [], temperature: 0, max_tokens: 4), + requestId: "reused-after-refusal", cacheEnabled: false, + tokenConstraint: nextConstraint) { + switch event { + case .chunk(let value): text += value + case .info(_, let count, _, let reason): + terminals += 1 + #expect(count == 4 && reason == "length") + case .error(let message): errors.append(message) + case .terminal, .logprobs: Issue.record("unexpected success-path event") + } + } + #expect(errors.isEmpty && terminals == 1 && text == "Let me check the") + await bridge.shutdown() + } catch { + await bridge.shutdown() + throw error + } + } + } + + /// Owns the engine until the bridge drains, including request opening failures. + private func stream(_ native: EngineV2, tokenizer: SpanStreamTokenizer, + thinking: Bool, extra: String, maxTokens: Int = 64, + prompt: String = "check") async throws -> SpanStreamOutcome { + let handle = TokenizerHandle(tokenizer) + let id = StrictToolFixture.model + let bridge = EngineV2Bridge(engine: native, modelId: id, tokenizer: handle, + eosTokenIds: StrictToolFixture.stops, defaultMaxTokens: 64, maxConcurrentRequests: 1) + do { + let scheduler = MultiModelBatchSchedulerEngine(registryProvider: { + [id: .init(tokenizer: handle, modelType: "qwen3_5", engineV2Bridge: bridge)] + }) + let body = #"{"model":"\#(id)","messages":[{"role":"user","content":"\#(prompt)"}],"# + + #""temperature":0,"reasoning":{"enabled":\#(thinking)},"reasoning_parser":"qwen3","# + + #""max_tokens":\#(maxTokens),\#(extra)}"# + var request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: Data(body.utf8)) + request.stream = true + request.streamToolCallDeltas = true + var outcome = SpanStreamOutcome() + for try await event in try await scheduler.streamChatCompletion(request: request) { outcome.record(event) } + outcome.finish() + await bridge.shutdown() + return outcome + } catch { + await bridge.shutdown() + throw error + } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONFreeSpanTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONFreeSpanTests.swift new file mode 100644 index 0000000000..3163939f55 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/QwenJSONFreeSpanTests.swift @@ -0,0 +1,87 @@ +// Copyright © 2026 Eigen Labs. + +import MLXLMCommon +import Testing +@testable import ProviderCore + +@Suite("Qwen JSON free-span boundaries", .serialized) +struct QwenJSONFreeSpanTests { + @Test func jsonPreviewIsPureAndTheAnswerNeverBecomesFree() throws { + typealias F = QwenAnswerFixture + let constraint = try F.constraint(F.jsonObject, phase: .reasoning, + extra: ["ordinary", "{\"a\":1}", "{\"a\":1}", constraint)) + let trailing = try #require(F.walk(" \n ", constraint, from: complete)) + for state in [complete, trailing, -1, Int.max] { + #expect(!constraint.isFreeSpan(state: state)) + #expect(!constraint.isFreeSpanContinuation(state: state, tokenID: 256)) + } + for (schema, answer) in [(#"{"type":"integer"}"#, "42"), (#"{"type":"string"}"#, "\"Rome\"")] { + let scalar = try F.constraint(F.schemaFormat(schema)) + #expect(!scalar.isFreeSpan(state: 0)) + if answer.hasPrefix("\"") { + let inside = try #require(F.walk("\"Ro", scalar)) + #expect(!scalar.isFreeSpan(state: inside)) + #expect(!scalar.isFreeSpanContinuation(state: inside, tokenID: 109)) + } + let done = try #require(F.walk(answer, scalar)) + #expect(!scalar.isFreeSpan(state: done)) + #expect(!scalar.isFreeSpanContinuation(state: done, tokenID: 32)) + } + + // Exhaustion invalidates even the initial reasoning state; speculative + // preview must never restore a released or impossible grammar. + var exhausted = false + for path in 0..<(1 << 13) { + let text = "{\"a\":" + (0..<13).map { (path >> $0) & 1 == 0 ? "[" : #"{"k":"# }.joined() + guard F.walk(text, constraint) != nil else { exhausted = true; break } + } + #expect(exhausted && constraint.cachedStateCount == JSONAnswerConstraint.maximumStates) + #expect(!constraint.isFreeSpan(state: 0)) + #expect(!constraint.isFreeSpanContinuation(state: 0, tokenID: 256)) + } + + @Test func otherJSONFamiliesDoNotAcquireFreeSpanSupport() throws { + typealias F = QwenAnswerFixture + let profile = JSONAnswerProfile.bonsai2 + let format = try JSONAnswerFormat(try #require(try F.request(format: F.jsonObject).responseFormat), + forbidding: profile.contentMarkers, family: profile.family) + let vocabulary = try JSONAnswerVocabulary(pieces: F.vocabulary().pieces, + profile: profile, stopTokenIDs: F.stops) + let constraint = try JSONAnswerConstraint(format: format, profile: profile, vocabulary: vocabulary, + initialPhase: .reasoning, maxTokens: 64) + #expect(!constraint.isFreeSpan(state: 0)) + #expect(!constraint.isFreeSpanContinuation(state: 0, tokenID: 65)) + } + + /// review prov-2101 SF1: the SDK makes a row MTP history-eligible by the + /// constraint's free-span conformance alone (`mtpSpanConstraint`), so a + /// non-Qwen JSON answer (Nemotron Lightning, Bonsai, GPT-OSS arguments) + /// that conformed would seed MTP history every step with the switch on. + /// Only the Qwen answers that can hold a free span may conform. + @Test func onlyQwenJSONAnswersOfferFreeSpansToTheEngine() throws { + typealias F = QwenAnswerFixture + for profile in [JSONAnswerProfile.bonsai2] { + let format = try JSONAnswerFormat(try #require(try F.request(format: F.jsonObject).responseFormat), + forbidding: profile.contentMarkers, family: profile.family) + let vocabulary = try JSONAnswerVocabulary(pieces: F.vocabulary().pieces, + profile: profile, stopTokenIDs: F.stops) + let constraint: any CBv2TokenConstraint = try JSONAnswerConstraint(format: format, profile: profile, + vocabulary: vocabulary, initialPhase: .reasoning, maxTokens: 64) + #expect(!(constraint is any CBv2FreeSpanTokenConstraint), "\(profile.family)") + } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/NemotronSuperPromptContractTests.swift b/provider-swift/Tests/ProviderCoreTests/NemotronSuperPromptContractTests.swift index a228dbe3b3..887116bdeb 100644 --- a/provider-swift/Tests/ProviderCoreTests/NemotronSuperPromptContractTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/NemotronSuperPromptContractTests.swift @@ -132,7 +132,6 @@ final class NemotronSuperPromptContractTests: XCTestCase { for body in [#"{"chat_template_kwargs":{"reasoning_effort":"low"}}"#, #"{"chat_template_kwargs":{"preserve_thinking":true}}"#, #"{"chat_template_kwargs":{"unknown":null}}"#, - #"{"reasoning":{"max_tokens":64}}"#, #"{"reasoning":{"exclude":true}}"#, #"{"reasoning":{"exclude":0}}"#, #"{"reasoning":{"exclude":"false"}}"#, @@ -148,6 +147,20 @@ final class NemotronSuperPromptContractTests: XCTestCase { for body in [#"{"reasoning":"on"}"#, #"{"chat_template_kwargs":[]}"#] { XCTAssertThrowsError(try NemotronSuperPromptContract.controls(body: Data(body.utf8)), body) } + // `reasoning.max_tokens` is a native budget for Super since 0.10.13 + // (`SDKFeatureDefaults`, unset switch), refused as before with `0`. + let budget = Data(#"{"reasoning":{"max_tokens":64}}"#.utf8) + let flag = NativeReasoningBudget.environmentKey + let previous = ProcessInfo.processInfo.environment[flag] + defer { if let previous { setenv(flag, previous, 1) } else { unsetenv(flag) } } + unsetenv(flag) + XCTAssertEqual(try NemotronSuperPromptContract.controls(body: budget).reasoningBudgetTokens, 64) + setenv(flag, "0", 1) + XCTAssertThrowsError(try NemotronSuperPromptContract.controls(body: budget)) { error in + guard case .unsupportedControl = error as? NemotronSuperPromptContract.Failure else { + return XCTFail("budget with the switch off: \(error)") + } + } let plain = try NemotronSuperPromptContract.controls(body: Data("{}".utf8)) for body in [#"{"reasoning":{"exclude":false}}"#, #"{"reasoning":{"max_tokens":null,"exclude":null}}"#, #"{"reasoning":null,"chat_template_kwargs":null}"#, diff --git a/provider-swift/Tests/ProviderCoreTests/Service/LaunchAgentRestartTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/LaunchAgentRestartTests.swift index cb0fc41de4..6f9b4c4ea2 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/LaunchAgentRestartTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/LaunchAgentRestartTests.swift @@ -275,6 +275,28 @@ struct LaunchAgentEnvironmentTests { #expect(LaunchAgent.passthroughEnvironment(from: [:])[key] == nil) } + @Test func forwardsSDKFeatureSwitchesToProviderJob() { + // 0.10.13 phase D: the SDK reads these switches itself (grammar-aware + // MTP, Gemma quoted numeric arguments). Whatever their default, the + // operator's value (`0` = 0.10.12's behaviour) only reaches the launchd + // provider job if the plist carries it. The watchdog never runs inference. + for key in ["DARKBLOOM_CBV2_MTP_GRAMMAR", "DARKBLOOM_GEMMA_SCHEMA_COERCION"] { + #expect(LaunchAgent.passthroughEnvKeys.contains(key)) + #expect(!WatchdogAgent.passthroughEnvKeys.contains(key)) + for value in ["0", "1"] { + let out = LaunchAgent.passthroughEnvironment(from: [key: value, "UNRELATED_SECRET": "excluded"]) + #expect(out == [key: value]) + let plist = LaunchAgent.makeServicePlist( + label: "io.darkbloom.provider", + programArguments: ["/usr/local/bin/darkbloom", "start", "--foreground"], + logPath: "/tmp/p.log", + environment: out) + #expect(plist["EnvironmentVariables"] as? [String: String] == [key: value]) + } + #expect(LaunchAgent.passthroughEnvironment(from: [:])[key] == nil) + } + } + @Test func forwardsMiMoResidencyRollbackToProviderJob() { // Standing MiMo residency is the default; the operator's rollback is // only effective if it reaches the launchd-managed provider process. diff --git a/scripts/test-provider-ci-workflow.py b/scripts/test-provider-ci-workflow.py index f3aa1b4d0f..60dc1a357d 100644 --- a/scripts/test-provider-ci-workflow.py +++ b/scripts/test-provider-ci-workflow.py @@ -480,6 +480,9 @@ def test_provider_entrypoint_and_resource_installer_checks_are_retained(self): MIMO_HTTP_PREPARE, MIMO_PROVIDER_PREPARE, PROVIDER_TEST_COMMAND, + "for enabled in 0 1; do\n" + ' env DARKBLOOM_GEMMA_SCHEMA_COERCION="$enabled" ../scripts/run-nested-suite.sh GemmaQuotedArgumentConformanceTests --no-parallel\n' + "done", "python3 scripts/test-desktop-api.py provider-swift/.build/debug/darkbloom", *MIMO_NATIVE_COMMANDS.values(), 'python3 scripts/prepare-mimo-audio-fixtures.py --cache /private/tmp/dinf-ci/mimo-audio-source --output "$RUNNER_TEMP/mimo-audio-fixtures" --github-env "$GITHUB_ENV"',