Skip to content

Stream auto tool calls while they are generated and seed content for plain Qwen prompt tails - #1549

Merged
Gajesh2007 merged 12 commits into
masterfrom
ttft/stream-auto-tool-calls
Oct 22, 2026
Merged

Gajesh2007 merged 12 commits into
masterfrom
ttft/stream-auto-tool-calls

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Paired SDK changes are merged on Layr-Labs/mlx-swift-lm main: Layr-Labs/mlx-swift-lm#332 (streamed tool-call fragments, squash 118ffb0a) and Layr-Labs/mlx-swift-lm#333 (the ServerSurfaceTests build fix, squash f77b384c). libs/mlx-swift-lm pins f77b384c (4b372c5).

Summary

Provider TTFT is measured from dispatch to the first content-bearing frame
(firstContentElapsedMs in ProviderLoop+InferenceHandler.swift). Tool calls
were released only after the engine terminal (toolHandler?.finish() in
MultiModelBatchSchedulerEngine), so an answer that starts with a tool call
(Gemma 4 with thinking off, Qwen without thinking, GPT-OSS after its analysis)
reported prefill plus the whole call decode. The frame loop's pre-content deadline
check could also discard a fully generated call and reroute the request.

This PR:

  1. Streams tool_choice: "auto" calls while they are generated for the Gemma,
    Qwen 3.5 (3.5, 3.6, 3.8 templates), Harmony (GPT-OSS) and framed-JSON formats,
    as OpenAI tool_calls fragments: index, id, type and function.name as
    soon as the name resolves to a declared tool, then function.arguments
    fragments. NativeToolStreamRouter admits parallel_tool_calls cardinality
    at a call's first fragment, validates name and schema
    (ToolConstraintValidation) when its frame closes, and re-validates the whole
    set at the terminal. A call cut off by max_tokens ends with
    finish_reason: "length", including when the end-of-generation parse of its
    partial frame fails or diverges. Required and named tool choices,
    native-channel families, other formats and non-chat surfaces keep
    validate-then-expose at the engine terminal. The streamed terminal branch runs
    the same terminal checks as the complete-call path (formatOutput
    observe/validate, checkNativeToolFailure, and feat(flint): OpenRouter parameter compatibility (reasoning controls, stop, JSON response_format, logprobs) #1552's matched-answer-stop
    override, now in yieldTerminalInfo).
  2. Ends the pre-content deadline at the first tool fragment: the frame loop
    already counted a tool_calls frame as content; streaming moves that frame to
    the call's first fragment, so a call that is already visible is never
    discarded. The response hash adds one tool_call marker per fragment (a
    complete call hashes exactly as before), and the cancelled-stream billing
    floor now counts only delivered text (content, reasoning, tool names and
    argument text) instead of the hash markers.
  3. Seeds content state for plain Qwen3-VL prompt tails: ReasoningPromptProbe
    starts a Qwen3-VL (qwen3_vl_moe, plainTailContentModelTypes) request on
    the qwen3 parser in content state when the rendered prompt tail has no
    think marker (Qwen3-VL Instruct). The undecided think parser otherwise held
    the whole answer until a tag or EOS. Other Qwen types are unchanged: the
    Qwen 3.5, 3.6 and 3.8 templates already end in a marker, and close-only
    reasoners such as qwen3_next stay undecided so their reasoning is not
    exposed as answer text.
  4. Moves the SDK pin: libs/mlx-swift-lm from master's 889fe3cc to SDK
    main f77b384c, which is 889fe3cc plus Stream auto tool calls as OpenAI tool_calls fragments and find end tags in appended text mlx-swift-lm#332 (this change's SDK
    side), Add an opt-in plain-chunk ceiling for bidirectional media requests mlx-swift-lm#331 (c8dce97d, an opt-in plain-chunk ceiling for bidirectional media whose
    bidirectionalMediaPrefillChunkCeiling defaults to nil and is never set by
    the provider, so scheduling is unchanged) and Fix the MLXLMServerTests build after the OpenAIToolCallDelta change mlx-swift-lm#333 (SDK
    test build fix).
    libs/mlx-swift (67dc7528) and libs/mlx (ad4745a2) stay at master's
    pins, so this PR changes no Metal source.
  5. Documents the fragment shape in docs/reference/protocol-messages.md
    (inference_response_chunk), docs/architecture/inference.md
    (streamed auto tool calls, plain-tail seed) and both switches in
    docs/reference/configuration.md, with a changelog.d fragment.

Commits

Branch ttft/stream-auto-tool-calls, merged with master 8f6958689:

Commit Change
102835bcf Stream auto tool calls and seed content for plain Qwen prompt tails
3dc0e9689 Stream only Gemma marker strings early and scan end tags linearly
65af6e213 Test a streamed Gemma call that leaves the strict grammar
a062dfb01 Document streamed tool_calls fragments in inference_response_chunk
bb313ec3c Refactor pass: pin the SDK streamer cleanup, make exposesCallsWhileGenerated private, correct comments
07c1233cb Re-pin libs/mlx-swift-lm to the merged SDK change (118ffb0a)
bfcbd7192 Merge master (#1552 Flint OpenRouter conflicts in the router and engine forwarder)
4b372c5cf Re-pin libs/mlx-swift-lm to SDK main f77b384c (SDK test build fix)
e5c2c6834 Seed content for plain prompt tails only on Qwen3-VL
d696e1736 End a streamed call cut off by max_tokens with length, even if diverged
da617fc76 Describe the Qwen3-VL-only plain-tail seed and restamp changed docs
5deb03903 Review cleanup: seed and truncation wording; count completed Flint calls in a test collector

Before

flowchart TB
  subgraph PB1["Before: behavior (answer starts with a tool call)"]
    direction LR
    q1(["dispatch"]) --> pf1["prefill"]
    pf1 --> dc1["decode the whole call<br/>(no frame sent)"]
    dc1 --> eos1["engine terminal"]
    eos1 --> fr1(["FIRST content frame =<br/>complete call"])
    dc1 -. "pre-content deadline" .-> rr1(["finished call discarded,<br/>request rerouted"])
  end
  subgraph PB2["Before: code flow"]
    direction LR
    h1["toolHandler.processChunk<br/>withholds call text"] --> f1["toolHandler.finish()<br/>at terminal"]
    f1 --> v1["checkNativeToolFailure,<br/>ToolConstraintValidation,<br/>formatOutput.validate"]
    v1 --> y1[".toolCall events"]
    y1 --> i1["inline .info<br/>(answer-stop override)"]
    i1 --> l1(["ProviderLoop:<br/>contentFrameCount 0 until here"])
  end
  PB1 ~~~ PB2
  classDef slow fill:#fdecea,stroke:#c62828,color:#1b1b1b
  classDef same fill:#e3f2fd,stroke:#1565c0,color:#1b1b1b
  classDef check fill:#fff8e1,stroke:#f9a825,color:#1b1b1b
  class dc1,eos1,fr1,rr1,h1,f1,l1 slow
  class q1,pf1,y1,i1 same
  class v1 check
Loading

After

flowchart TB
  subgraph PA1["After: behavior (tool_choice auto; Gemma, Qwen 3.5, Harmony, framed JSON)"]
    direction LR
    q2(["dispatch"]) --> pf2["prefill"]
    pf2 --> nm2(["FIRST content frame:<br/>index, id, type, name"])
    nm2 --> ar2(["arguments fragments<br/>while decoding"])
    ar2 --> cl2{"frame closes:<br/>name + schema valid?"}
    cl2 -- yes --> ok2(["finish_reason tool_calls"])
    cl2 -- no --> er2(["typed tool_choice<br/>violation"])
    ar2 -. "max_tokens reached inside the call<br/>(EOS parse unterminated, failed<br/>or diverged)" .-> ln2(["partial call,<br/>finish_reason length"])
  end
  subgraph PA2["After: code flow"]
    direction LR
    tp2["ToolStreamPreparation<br/>.makeHandler<br/>(auto + chat stream +<br/>kill switch on)"] --> rt2["NativeToolStreamRouter<br/>.routeToolSegment"]
    rt2 --> ad2["admitCall:<br/>parallel_tool_calls"]
    rt2 --> vl2["validate at<br/>frame close"]
    rt2 --> fn2["engine terminal:<br/>finishToolCalls(truncated:)"]
    fn2 --> tc2["formatOutput.observe,<br/>checkNativeToolFailure,<br/>re-validate the set,<br/>formatOutput.validate"]
    tc2 --> yi2["yieldTerminalInfo<br/>(answer-stop override,<br/>shared with the<br/>complete-call path)"]
    rt2 --> lp2(["ProviderLoop: first fragment<br/>is the first content frame"])
  end
  PA1 ~~~ PA2
  classDef fast fill:#e8f5e9,stroke:#2e7d32,color:#1b1b1b
  classDef check fill:#fff8e1,stroke:#f9a825,color:#1b1b1b
  classDef same fill:#e3f2fd,stroke:#1565c0,color:#1b1b1b
  class nm2,ar2,ok2,ln2,rt2,lp2,tp2 fast
  class cl2,er2,ad2,vl2,fn2,tc2 check
  class q2,pf2,yi2 same
Loading
flowchart LR
  t(["qwen3 parser, prompt tail<br/>has no think marker"]) --> b{{"ReasoningPromptProbe<br/>.streamingPrefix"}}
  b -- "Before: nil (every model type)" --> u(["parser undecided:<br/>whole answer held<br/>until a tag or EOS"])
  b -- "After, qwen3_vl_moe<br/>(Qwen3-VL Instruct):<br/>empty closed block" --> c(["content state:<br/>answer streams; a think tag<br/>from the model still<br/>opens reasoning"])
  b -- "After, other types<br/>(qwen3_next, qwen3_5, ...): nil" --> k(["unchanged: undecided,<br/>close-only reasoning<br/>stays reasoning"])
  classDef slow fill:#fdecea,stroke:#c62828,color:#1b1b1b
  classDef fast fill:#e8f5e9,stroke:#2e7d32,color:#1b1b1b
  classDef same fill:#e3f2fd,stroke:#1565c0,color:#1b1b1b
  class u slow
  class c fast
  class t,b,k same
Loading

Legend: red = latency removed by this PR, green = new path, amber = validation,
blue = unchanged.

Evidence

Logs below are on the lead's M5 Ultra under $LOGS = /private/tmp/claude-501/-Users-gaj-Documents-Builds-Darkbloom/8eacbef9-e1dd-444e-98a8-972bc1d30258/scratchpad/pr/tool-stream/work/logs;
refactor-pass re-runs are under $RLOGS = /private/tmp/claude-501/-Users-gaj-Documents-Builds-Darkbloom/8eacbef9-e1dd-444e-98a8-972bc1d30258/scratchpad/refactor-tool-stream;
post-rebase re-runs are under $BLOGS = /private/tmp/claude-501/-Users-gaj-Documents-Builds-Darkbloom/8eacbef9-e1dd-444e-98a8-972bc1d30258/scratchpad/rebase-logs.

M3 Ultra (fleet-representative, non-NAX), one exclusive GPU hold. The PR
binary runs as two resident servers per model, DARKBLOOM_TTFT_STREAM_TOOL_CALLS=0
(off) and default (on), with requests interleaved in rotating order,
temperature 0, prefix cache off, the bench provider.toml, and the
coordinator's reasoning_parser in each request (gemma4, qwen3 with
enable_thinking: false, harmony). Medians of 5 requests per arm. "First
content frame" is the first SSE delta carrying content, reasoning or
tool_calls, which is what provider TTFT counts. Log: $LOGS/m3u-final/final.log,
JSON: $LOGS/m3u-final/final/std/, table: $LOGS/m3u-final/summary-std.md.

Model Prompt First content frame, off → on (s) First tool fragment, off → on (s) Total, off → on (s) Same calls and text
Gemma 4 26B QAT weather call 0.322 → 0.179 0.322 → 0.179 0.322 → 0.322 yes
Gemma 4 26B QAT write_file call (158 tokens) 1.563 → 0.200 1.563 → 0.200 1.563 → 1.563 yes
Gemma 4 26B QAT two calls 0.535 → 0.189 0.535 → 0.189 0.535 → 0.528 yes
Gemma 4 26B QAT plain answer, no call 0.127 → 0.127 — 0.196 → 0.196 yes
Qwen3.5-9B weather call 0.559 → 0.382 0.559 → 0.382 0.559 → 0.567 yes
Qwen3.5-9B write_file call (180 tokens) 1.498 → 0.392 1.498 → 0.392 1.498 → 1.524 yes
Qwen3.5-9B two calls 0.541 → 0.359 0.766 → 0.359 0.766 → 0.759 yes
Qwen3.5-9B plain answer, no call 0.318 → 0.318 — 0.379 → 0.382 yes
GPT-OSS 20B weather call 0.165 → 0.174 0.435 → 0.317 0.435 → 0.446 yes
GPT-OSS 20B write_file call (213 tokens) 0.155 → 0.167 1.828 → 0.383 1.828 → 1.842 yes
GPT-OSS 20B two calls (one call made) 0.171 → 0.172 4.564 → 4.435 4.564 → 4.565 yes
GPT-OSS 20B plain answer, no call 0.165 → 0.164 — 1.843 → 1.848 yes

First content frame on the write_file call: Gemma 7.8x earlier, Qwen 3.8x;
GPT-OSS already streamed its analysis first, and its first tool fragment arrives
4.8x earlier. Every call's reconstructed arguments parsed as JSON, and
completion tokens were identical across arms. Median totals moved by -1.3% to
+2.5%: the largest are GPT-OSS weather 0.435 → 0.446 s (minima 0.419 / 0.417 s)
and Qwen write_file 1.498 → 1.524 s (minima 1.493 / 1.508 s). The no-call
prompts, whose path is identical in both arms, moved by up to +0.9% between the
two server processes.

Decode under one long streamed call (long_file prompt, max_tokens
2048, 2 requests per arm, same hold). Table: $LOGS/m3u-final/summary-long.md, JSON:
$LOGS/m3u-final/final/long/.

Model Arm Completion tokens First content frame (s) Total (s) Tokens / total (tok/s) Output
Gemma 4 26B QAT off 1692 / 1570 15.166 / 13.985 15.166 / 13.985 111.6 / 112.3 complete call, one frame
Gemma 4 26B QAT on 1773 / 1771 0.290 / 0.188 17.938 / 15.946 98.8 / 111.1 complete call, 1513 / 958 fragments
Qwen3.5-9B off 2048 / 2048 11.825 / 11.779 11.826 / 11.779 173.2 / 173.9 cut by max_tokens: raw <tool_call> markup as content
Qwen3.5-9B on 2048 / 2048 0.414 / 0.406 11.945 / 11.801 171.4 / 173.5 cut by max_tokens: partial call, finish_reason: length
GPT-OSS 20B off 2048 / 2048 0.231 / 0.173 16.707 / 16.603 122.6 / 123.3 analysis only (identical in both arms)
GPT-OSS 20B on 2048 / 2048 0.184 / 0.158 16.557 / 16.549 123.7 / 123.8 analysis only

Gemma's long outputs differed between requests within each arm at temperature 0,
so its long runs are not paired. One of the two streamed Gemma requests ran at
98.8 tok/s against 111–112 tok/s for the other three. Replaying that exact call
through the streamed parser costs 4.4 ms of CPU in total ($LOGS/cpubench-replay.log),
so parsing does not explain its 2 s; two requests are too few to separate it from
run-to-run variance (see limitations).

SDK parse cost behind the long-call numbers:

CPU time of ToolCallProcessor per 4-character chunk of one write_file call
(release swiftc -O -wmo over Libraries/MLXLMCommon/Tool, best of 3, on the
M5 Ultra while other builds ran; load average in the log). Log:
$LOGS/cpubench.log

Format main 4 / 16 / 64 KB (µs per chunk) This PR, complete-frame path This PR, streamed path
Gemma 56.07 / 229.44 / 1217.43 2.59 / 1.91 / 2.48 3.15 / 2.93 / 6.36
Harmony 93.00 / 522.34 / 2509.96 2.56 / 2.63 / 2.51 3.89 / 3.86 / 3.49
Framed JSON 35.16 / 321.05 / 523.32 1.02 / 1.03 / 1.12 1.87 / 1.85 / 2.09
Qwen 3.5 XML 2.33 / 2.29 / 2.37 2.25 / 2.29 / 3.14 3.19 / 4.27 / 3.72

A 64 KB Gemma call is 16,406 chunks: about 20 s of parser CPU on main
(16,406 × 1217.43 µs) and, with this PR, about 0.04 s on the complete-frame
path (× 2.48 µs) or 0.1 s streamed (× 6.36 µs, the default for auto chat
streams). The refactor-pass sources re-run on a less loaded machine cost the
same as the PR-head binary run beside them (Gemma 64 KB streamed 2.83 vs 2.81
/ 2.89 µs; $RLOGS/cpubench-refactor.log).

Template tails for the plain-tail seed, rendered with each local model's
chat_template (12 renders per model: a user turn and a turn after a tool
result, with and without tools, enable_thinking unset, true and false): Qwen3.5-9B, Qwen3.5-35B-A3B, Qwen3.6-35B-A3B and
Qwen3.8-27B end in <think> (8) or <think></think> (4) and are unchanged;
the Hugging Face Qwen3-VL-30B-A3B-Instruct chat template (template only; the
model is not local) ends in a plain <|im_start|>assistant\n in 12 of 12,
which previously left the qwen3 parser undecided. Logs:
/private/tmp/claude-501/-Users-gaj-Documents-Builds-Darkbloom/8eacbef9-e1dd-444e-98a8-972bc1d30258/scratchpad/tool-stream/probe_tails_summary.json,
probe_tails.json and probe_tails_qwen36.json beside it.

Earlier M5 Ultra paired run (implementation binary on the production gitlinks, before the Gemma marker-only and linear-scan commits; shared GPU)

Same harness with a third arm running the production master binary, n=6
(Gemma, Qwen) or 8 (GPT-OSS); the shared GPU makes totals noisy. Log:
/private/tmp/claude-501/-Users-gaj-Documents-Builds-Darkbloom/8eacbef9-e1dd-444e-98a8-972bc1d30258/scratchpad/tool-stream/r3/ab1.log

Model Prompt First content frame, off → on (s) First tool fragment, off → on (s) Production master, first tool fragment (s)
Gemma 4 26B QAT write_file 1.413 → 0.218 1.413 → 0.218 1.449
Qwen3.5-9B write_file 1.148 → 0.173 1.148 → 0.173 1.014
GPT-OSS 20B write_file 0.165 → 0.168 1.659 → 0.354 1.707

Measured binary provenance. The A/B and CPU numbers above come from a
binary built before the rebase, from the PR's first four commits with SDK
9d8bfc89 on the old base (master eaaf5e615, libs/mlx-swift 81f58d79,
libs/mlx 71271f08). They were not re-measured after the refactor pass, the
master merges, the SDK re-pins (f77b384c), the Qwen3-VL-only seed
narrowing or the truncation fix. None of those later changes touches the
measured paths: the seed change affects only qwen3_vl_moe plain tails, and
the truncation fix affects only a call cut off by max_tokens whose partial
frame fails or diverges at end of generation.

Platform protocol review

The inference_response_chunk envelope and every WebSocket field are
unchanged, but the chat chunk JSON inside data changes shape for streamed
auto calls: one call now spans several choices[].delta.tool_calls entries
that share index (the first with id, type, function.name and empty
arguments; later ones with only index and an arguments fragment).

Read-only review of darkbloom-platform master 67b120bbe. Verdict:
compatible, no platform code change needed.

  1. coordinator/api/inference/response/tool_call_accumulator.go
    (toolCallAccumulator.apply): id-less fragments continue the active call at
    the same index; id/type/name come from the first fragment; arguments
    are concatenated; finalize is index-ordered. Non-streaming chat/Responses
    aggregation uses it in stream_message.go
    (ExtractMessageWithReasoningPolicy), and the Messages stream uses it in
    generic_endpoint_stream.go (messagesStreamEmitter.HandleChunk/Finish).
  2. responses_stream.go (ResponsesStreamEmitter.appendToolCall) opens the
    function_call item on the first fragment (name), emits
    response.function_call_arguments.delta per fragment and closes calls in
    closeFunctionCalls.
  3. The consumer chat stream relays fragments verbatim;
    internal/inference/sse/sse_normalize.go (NormalizeSSEChunk) only
    rewrites null fields.
  4. response/sse_events.go (IsBoilerplateChunk) treats any non-empty
    tool_calls as content, so dispatch and the first-content clock commit at
    the name fragment (internal/inference/firstcontent/first_content_policy.go),
    and observation/request_outcome_egress.go (GeneratedContentJSON) also
    counts tool_calls.
  5. internal/inference/responsepolicy/finish_policy.go
    (EffectiveFinishReason) keeps a provider length, so a truncated streamed
    call is not rewritten to tool_calls. generic_endpoint_response.go
    (messagesToolUseBlock) falls back to input {} for partial JSON.
  6. Billing uses provider usage from inference_complete, and response_hash
    is forwarded opaquely (api/inference/provider_inference.go,
    pr.ResponseHash = msg.ResponseHash); the consumer verification contract
    already forbids recomputing it from re-serialized output.
  7. The coordinator validates tool_choice only on the request
    (request/tool_constraints.go) and enforces nothing on the response; a
    provider violation after a committed fragment surfaces as an in-band error
    with no failover.

This was a source reading, not an end-to-end run against a coordinator.

Platform-owner acknowledgement still requested for two points:

  • The fragment shape above, and a mirror of the new inference_response_chunk
    paragraph in the platform copy of docs/reference/protocol-messages.md.
  • Settlement for a stream cancelled mid-call: it used to have no visible output
    (the call was withheld until the terminal) and was refunded. Its fragments
    are now visible, so StreamedGenerationUsage.cancelledUsageInfo settles it
    as inference_complete with the delivered-text floor
    (max(deliveredCompletionTokenFloor, contentFrameCount) when engine usage is
    missing), the same as a cancelled content stream.

Review follow-ups

Fixed in this round:

Finding Commit
CI Provider Unit Tests, codex P1: the plain-tail seed matched every qwen* type, so close-only Qwen reasoning (qwen3_next) would stream as answer text (EngineV2ProductionWiringTests.swift:1362) e5c2c6834 (Qwen3-VL only, new probe and wiring tests), 5deb03903 (doc comment)
CI Provider SDK Tests: SDK 118ffb0a did not compile ServerSurfaceTests 4b372c5cf (pin SDK main f77b384c, with Layr-Labs/mlx-swift-lm#333)
Merge conflict with master (#1552) in NativeToolStreamRouter and the engine forwarder; the streamed terminal branch skipped #1552's terminal checks bfcbd7192 (both router features kept; streamed branch runs formatOutput observe/validate, checkNativeToolFailure and the answer-stop override through yieldTerminalInfo; .toolCallDelta handled in FlintResponseFormatOutput.observe)
codex P1: contradictory unknown-tail statement in inference.md da617fc76, 5deb03903
codex P1: stale freshness stamps da617fc76 (protocol-messages.md; the other two pages carry 2026-10-22 from master and this round's edits)
Review: a Gemma call cut off by max_tokens whose partial arguments contain } ended in a tool_choice violation instead of length d696e1736 (regression case in truncatedCallEndsQuietlyOnlyAtTheTokenLimit)
Review: a merge-added Flint test collector counted every fragment as a call 5deb03903
codex P1: pin pointed at the unmerged SDK PR head 756432c8 already fixed by 07c1233cb; now f77b384c

Deferred (not merge-blocking):

  • EOS completion that fails validation at the token limit. If a cut-off
    frame's lenient end-of-generation parse happens to agree with the exposed
    prefix, the SDK reports .callCompleted, and a missing required property
    still throws a tool_choice violation instead of ending with length.
    master's complete-call path rejected the same call in
    ToolConstraintValidation, so this is not a regression. Possible follow-up:
    treat a failed validation of an EOS completion as truncation when truncated
    is true (NativeToolStreamRouter.finishToolCalls).
  • Consumer stop sequence matched inside a streamed call reports stop, not
    length, so the open call ends in a violation. Edge case; could be treated
    as a quiet truncation.
  • Billing-floor change has no dedicated regression test. deliveredText in
    ProviderLoop+InferenceHandler.swift is inline in the frame loop; covering it
    needs an extraction or a handler-level harness.
  • Gemma long_file decode outlier (one of two streamed requests at 98.8
    tok/s): rerun with more requests on the final binary.
  • Platform acknowledgement and docs mirror (section above).

Validation

This round, on the M3 Ultra, in the branch worktree (provider tests with
isolated DARKBLOOM_STATE_FILE/DARKBLOOM_LOADED_MODELS_FILE, as in
scripts/run-provider-tests.sh). Full CI runs on the pushed head 5deb03903.

Command Outcome
cd provider-swift && swift build --build-tests -j 8, then scripts/stage-test-metallib.sh Build complete after each change
swift test --skip-build --no-parallel --filter for StreamedToolCallTests, ReasoningPromptProbeTests, NativeToolStreamRouterTests, EngineV2RequestRoutingTests (in EngineV2ProductionWiringTests.swift), EngineV2SlotBuildTests, EngineV2ReslicingWiringTests, EngineV2RuntimeGuardTests, NativeLocalConsumerOwnershipTests, GLM5ToolFailureTests, the Flint answer-stop/response-format/policy/protocol suites, MiMoV26StreamContractTests, NemotronSuperLocalOutputTests, ThinkStreamingLatencyTests, ReasoningParserSelectionTests, LocalChatRequestTests and the ProviderLoop stream-chunk tests (MiMo prompt fixtures from scripts/prepare-mimo-prompt-fixtures.py) Swift Testing 222 tests in 27 suites passed (live/GPU-only cases skip); XCTest 59 executed, 9 skipped (opt-in native MiMo media), 0 failures
Same build after the review cleanup 5deb03903, a 20-term filter over the same areas Swift Testing 157 tests in 16 suites passed; XCTest 37 executed, 0 failures
Mutation: seed scope back to hasPrefix("qwen") and truncation back to .callFailed(.unterminated) Fails as expected (45 tests, 10 issues), including EngineV2ProductionWiringTests.swift:1362, plainPromptTailKeepsCloseOnlyQwenUndecided, plainTailWithoutSeed and the } case of truncatedCallEndsQuietlyOnlyAtTheTokenLimit; passes again after restoring
cd libs/mlx-swift-lm && swift build --build-tests -j 8 at f77b384c, then ../../scripts/run-nested-suite.sh Build complete; ServerSurfaceTests, ToolCallStreamingTests, ToolCallStreamingDifferentialTests, ToolCallDeltaStreamingTests, BidirectionalMediaChunkCeilingTests: 18 tests passed; server streaming/Harmony suites: 317 tests in 47 suites passed; tool suites (ToolCallProcessorStreamingTests, FlintToolTests, ...): 92 tests in 11 suites passed
./scripts/docs-check.sh 190 file(s) OK
DOCS_IMPACT_BASE=origin/master python3 scripts/docs-impact-check.py 23 changed file(s), canonical documentation coverage OK
python3 scripts/changelog.py check 45 valid fragment(s)
git log --show-signature on the six new commits all signed (ED25519 SSH)

Earlier rounds, before the rebase, also built the release binary measured
above and checked that its mlx.metallib matched the production metallib
(fb1ba8f9…); see Evidence.

Kill switch

Both default on; exact 0 restores the previous behavior, and both are
forwarded to the LaunchAgent (LaunchAgent.inferencePassthroughEnvKeys):

Variable 0 restores
DARKBLOOM_TTFT_STREAM_TOOL_CALLS Complete calls released at the engine terminal after validation, one tool_calls entry each
DARKBLOOM_TTFT_THINK_CONTENT_SEED Undecided qwen3 parsing for Qwen3-VL (qwen3_vl_moe) prompt tails without a think marker

The SDK's linear end-tag scan is not switchable; its differential test shows the
same calls and text as the whole-frame path.

Limitations

  • After a call's name is visible, a frame that fails to parse, diverges from the
    exposed prefix or violates its schema ends the stream with a typed
    tool_choice violation (unless the call was cut off by max_tokens). Before,
    an auto call that failed to parse fell back to visible text with
    finish_reason: "stop"; the kill switch restores that. Worth a release note
    for agent integrators.
  • Gemma exposes non-string argument values only when the frame closes. Formats
    other than Gemma, Qwen 3.5, Harmony and framed JSON, and required/named
    tool choices, are unchanged.
  • GPT-OSS emits its analysis channel before a call, so its first content frame
    was already early (reasoning); the gain is in the first tool fragment.
  • A call cut off by max_tokens now arrives as a partial call with
    finish_reason: "length" (OpenAI stream semantics) where the complete-call
    path returned the raw call markup as content (Qwen long_file rows above).
  • Decode under long streamed calls rests on two requests per arm. Qwen and
    GPT-OSS tokens per second stay within 1.5% (Qwen 173.2 / 173.9 off, 171.4 /
    173.5 on; GPT-OSS 122.6 / 123.3 off, 123.7 / 123.8 on). One of two streamed
    Gemma requests ran at 98.8 tok/s against 111–112 tok/s for the other three,
    which parser CPU (4.4 ms for the whole call) does not explain. On short
    calls, median totals moved by -1.3% to +2.5% (table above).
  • TTFT was measured on the standalone local server, which runs the same
    MLXOpenAIService.streamChatCompletionFrames and router path as coordinator
    requests (with the coordinator's reasoning_parser set in the request), not
    through a live coordinator. The A/B binary predates the rebase (see
    provenance above) and was not compared with the current production master
    binary.
  • The Qwen3-VL plain-tail seed is covered by unit and production-wiring tests
    and template-tail rendering only (evidence above); Qwen3-VL is not a local
    model, so it has no GPU measurement.
  • Not run locally: the full provider suite and the live-model suites
    (GemmaToolCallLiveTests, Qwen36ProductionCanaryTests,
    ModelContainerEngineFinishReasonTests, GenerateTaskToolFilterTests). CI
    runs the provider and SDK lanes on the pushed head.

Landing order

  1. Done: Stream auto tool calls as OpenAI tool_calls fragments and find end tags in appended text mlx-swift-lm#332 and Fix the MLXLMServerTests build after the OpenAIToolCallDelta change mlx-swift-lm#333 are merged, and libs/mlx-swift-lm pins SDK main
    f77b384c (libs/mlx-swift and libs/mlx stay at master's pins).
  2. Green Provider Unit, Provider SDK and Provider Tests lanes on 5deb03903.
  3. Sibling TTFT PRs move the same gitlink; they may conflict only on that
    line. Resolve by pinning the newest SDK main that contains every merged
    SDK PR.
  4. Platform-owner acknowledgement (Platform protocol review above) and the
    protocol-reference mirror.

Refactor pass

Round 1, before the rebase: done. An independent refactor subagent reviewed
the first implementation (d-inference AGENTS.md, Required Refactor Pass).
Behavior-preserving cleanups landed in bb313ec3c here and in the SDK side of
Layr-Labs/mlx-swift-lm#332: the SDK drops streamer state nothing read (the Gemma marker-string and
Qwen 3.5 string-parameter phase key, a Harmony dead store, ToolCallProcessor
write-backs through the optional callStream) and makes
GemmaArgumentValueParser.parseValue private again; the provider makes
ToolStreamPreparation.exposesCallsWhileGenerated private and corrects the
streamingOptions and ReasoningPromptProbe comments and the changelog's CPU
example. Checked with no change needed: naming and comment density, tests
driving real components (production prompt policy, parser resolution and
forwarder, with only the engine row scripted), docs matching code, and every
benchmark number matching its log. Left as is: the collected-chat and Responses
.toolCallDelta branches in MLXOpenAIService repeat the whole-call handling
for a case those surfaces never request; they exist for exhaustiveness.

Round 2, this round: done. An independent reviewer checked the master
merge with git show --remerge-diff (both sides of every conflict kept;
reasoning is still classified or withheld before any tool segment is routed;
#1552's complete-call terminal order is unchanged), the SDK re-pin, the seed
narrowing and the truncation fix, and repeated the mutation check. It found no
blocking defects and added one behavior-preserving cleanup, 5deb03903: the
DARKBLOOM_TTFT_THINK_CONTENT_SEED doc comment names the
plainTailContentModelTypes scope, inference.md says "request" instead of
"stream" (the probe also seeds collected requests), the max_tokens row of the
streamed-call table covers a partial frame that fails or diverges, and the
FlintResponseFormatOutputTests collector counts a .toolCallDelta only when
it completes a call. The remaining edge cases are under Review follow-ups.

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

Gajesh2007 and others added 5 commits October 21, 2026 18:04
Provider TTFT is measured to the first content-bearing frame, and tool
calls were released only after the engine terminal. A response that
began with a tool call (Gemma 4 with thinking off, Qwen without
thinking, Qwen3-VL) therefore reported prefill plus the whole call
decode, and the frame loop's pre-content deadline could discard a fully
generated call.

For tool_choice auto, chat streams now pass calls through as OpenAI
tool_calls fragments while they are generated (Gemma, Qwen 3.5, Harmony
and framed-JSON formats). NativeToolStreamRouter admits
parallel_tool_calls cardinality at a call's first fragment and validates
the declared name and schema when its frame closes; a call cut off by
max_tokens ends with finish_reason length. Required and named tool
choices, native-channel families and other formats keep
validate-then-expose at the engine terminal. The response hash adds one
marker per fragment (a complete call hashes as before), and the
cancelled-stream billing floor counts only delivered text.

ReasoningPromptProbe also starts Qwen-family streams in content state
when the rendered prompt tail carries no think marker (Qwen3-VL
Instruct); the undecided think parser otherwise buffered the whole
answer until end of generation. The local Qwen 3.5, 3.6 and 3.8
templates already end in a marker and are unchanged.

Bumps libs/mlx-swift-lm to 9496f677 (the pinned SDK 19634dd8 plus a
format-only commit and the streamed tool-call fragments).

Rollbacks, both forwarded to the LaunchAgent:
DARKBLOOM_TTFT_STREAM_TOOL_CALLS=0, DARKBLOOM_TTFT_THINK_CONTENT_SEED=0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Bumps libs/mlx-swift-lm to 9d8bfc89:

- A Gemma frame that leaves the strict grammar anywhere is read by the
  complete parser's fallback, which turns bare scalars and Gemma-syntax
  composites into raw strings. Typed members a streamed call had already
  exposed then disagreed with the parse, and a valid call failed as a
  tool_choice violation. Gemma now streams only marker strings; other
  values arrive with the closing frame. A seeded differential test over
  template-rendered calls in token-like chunks found it.
- Every format except Qwen 3.5, MiMo and strict Gemma searched the whole
  growing buffer for its end tags on every chunk. Gemma, Harmony and
  framed-JSON calls cost CPU time quadratic in their length (1.2 ms per
  chunk at 64 KB, about 20 s for one 64 KB Gemma file write); they now
  cost 1-3 us per chunk at every size (2-6 us when streamed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A typed Gemma value followed by one that drops its string markers makes
the complete parse read every value as a raw string. Before Gemma
streamed only marker strings, the router exposed the typed value first
and then refused the valid call as diverged; it now completes with the
parse's arguments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The inference_response_chunk envelope is unchanged, but the chat chunk
it carries now splits a streamed auto tool call across several
tool_calls entries that share one index: id, type and function.name
first, then function.arguments fragments. The coordinator parses these
chunks, so the protocol reference states the shape and links the
mechanism; the platform keeps a mirror of this page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Moves libs/mlx-swift-lm to 4fceb806, a behavior-preserving SDK commit
that drops dead state from the streamed tool-call renderers.

- ToolStreamPreparation.exposesCallsWhileGenerated is private; only
  makeHandler uses it. The streamingOptions comment now says what
  happens to a call that is not exposed: it is validated before it is
  shown, unless the parser rejects the frame and returns it as text.
- The ReasoningPromptProbe comment no longer says that every
  unrecognized prompt tail keeps its old behavior; plain Qwen tails are
  the documented exception.
- The changelog fragment names the 64 KB example as a Gemma call and
  gives its logged cost with this change (about 0.1 s streamed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-22T08:06:58.320512Z 5deb039 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Threat model review — advisory

Reviewed head 5deb03903c08 against base 8f695868950d.

Review not completed for this head. Previous findings are superseded, not confirmed resolved.
Bedrock request allowance reached; no fallback around the limit

Scan incomplete: 1 file(s) could not be fully read as text. Binary, Git LFS and submodule changes require manual review.
Affected files: libs/mlx-swift-lm

Models: budgeted Sonnet / selective Opus / selective Sol 6.1. Findings require human validation; this review never requests changes or blocks merging.

Failure diagnostics: BEDROCK_CALL_LIMIT

Coverage: 120/130 source units; cross-file integration pending. 0 selected depth batch(es) pending. All threat definitions indexed; relevant full definitions selected. Unchanged callers are not scanned.

Cost this run: $0.0000 reported, $0.0000 reserved with unknown cost; 0 paid request(s), 0 reused batch(es), 0 provider cache-hit tokens.

Saved findings and earlier report · Historical findings are not confirmed resolved.

Bedrock: 30 request(s), 1465969 uncached + 0 cache-read + 0 cache-write input / 22993 output tokens; 0 request(s) with unknown usage. OpenRouter backup used 0 time(s). Dollar amounts above cover OpenRouter only; AWS billing is reconciled separately.

Layr-Labs/mlx-swift-lm#332 squash-merged as 118ffb0a ("Stream auto tool calls as OpenAI tool_calls fragments and find end tags in appended text (#332)").
Move the gitlink from the PR branch head 756432c8 to that commit on SDK main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bb313ec3cd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread libs/mlx-swift-lm Resolved
Comment thread docs/architecture/inference.md Resolved
Comment thread docs/architecture/inference.md Resolved
Gajesh2007 and others added 5 commits October 22, 2026 00:31
Resolve the conflicts with #1552 (Flint OpenRouter compatibility):

- NativeToolStreamRouter keeps both #1552's withheld-reasoning state and
  this branch's streamed-call policy; withheld reasoning is classified
  before any tool segment is routed, as before.
- The engine forwarder builds the router with withholdReasoning and
  streamedCalls. The streamed-call terminal branch now runs the same
  checks as the complete-call path: finished fragments feed the
  response-format observer, the native tool failure and response-format
  checks run, and the matched answer-stop override moved into
  yieldTerminalInfo so both terminal paths apply it.
- The SDK's new .toolCallDelta event case is handled in master's
  exhaustive switches (FlintResponseFormatOutput and two Flint test
  collectors).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
f77b384c is SDK main: 118ffb0a (#332) plus #331 (an opt-in plain-chunk
ceiling for bidirectional media requests, CBv2Contracts and
SchedulerV2) and #333, which fixes the MLXLMServerTests build after the
OpenAIToolCallDelta change. With 118ffb0a the SDK test targets did not
compile, so the Provider SDK Tests lane failed. #331 is opt-in and the
provider does not enable it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The plain-tail content seed matched every qwen* model type. A
close-only reasoner such as qwen3_next writes its reasoning before a
bare </think>, so after a plain prompt tail the seed exposed that
reasoning as answer content (plainPromptTailDoesNotInject failed).

Seed only qwen3_vl_moe: Qwen3-VL Instruct renders a bare
"<|im_start|>assistant\n" and never reasons, and Qwen3-VL Thinking
opens <think> in the prompt, which the tail check handles first. Qwen
3.5, 3.6 and 3.8 templates always end in a marker, so they keep the
tail-derived prefix and an unmarked tail stays undecided.

Tests: the probe table moves to ReasoningPromptProbeTests and covers
qwen3_vl_moe (plain and think tails) against close-only and other
types; production wiring tests cover a plain qwen3_vl_moe tail and
plain qwen3_5/qwen3_5_moe tails. Reverting the scope check fails 3
tests (8 issues).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
finishToolCalls dropped only .callFailed(.unterminated) when the engine
stopped at the token limit. Gemma's lenient EOS parse slices from the
first "{" to the last "}", so a truncated frame whose partial arguments
contain a "}" (common in written code) parses to a garbled call, the
SDK reports .callFailed(.diverged), and the stream ended in a
tool_choice violation instead of the documented finish_reason length.

At the token limit every EOS failure of the open exposed call is now
truncation. A frame that ends without the limit still fails.

Regression test: truncatedCallEndsQuietlyOnlyAtTheTokenLimit gains a
partial with a "}" inside the open string; it fails without the fix
with toolChoiceViolation("streamed tool call output was diverged").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
inference.md had two contradictory statements about prompt tails with
no think marker: a garbled sentence after the new seed paragraph and
the original "unrecognized prompt tails receive no prefix" sentence.
Replace both with one paragraph that matches the narrowed seed
(qwen3_vl_moe only, why other Qwen types are excluded, the kill switch)
followed by the remaining no-prefix cases.

The DARKBLOOM_TTFT_THINK_CONTENT_SEED configuration row and the
changelog fragment now name Qwen3-VL instead of every Qwen-family
stream. protocol-messages.md gained the streamed tool_calls paragraph
on 2026-10-22 UTC but kept its 2026-10-21 stamp; restamp it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… calls

Review cleanup with no behavior change:

- The DARKBLOOM_TTFT_THINK_CONTENT_SEED comment now names the
  plainTailContentModelTypes scope instead of every unmarked prompt.
- inference.md says "request" for the Qwen3-VL seed, because the probe
  also seeds collected requests. The max_tokens row of the streamed-call
  table now states that a partial frame whose end-of-generation parse
  fails or diverges still ends with finish_reason length, matching
  NativeToolStreamRouter.finishToolCalls.
- The Flint response_format output collector counts a .toolCallDelta
  only when it completes a call, like the Flint answer-stop collector,
  so argument fragments are never counted as separate calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
d-inference Ready Ready Preview Oct 22, 2026 8:04am UTC
d-inference-console-ui-dev Ready Ready Preview Oct 22, 2026 8:04am UTC
d-inference-landing Ready Ready Preview Oct 22, 2026 8:04am UTC
darkbloom-status Ready Ready Preview Oct 22, 2026 8:04am UTC
eigen-homepages-darkbloom Ready Ready Preview Oct 22, 2026 8:04am UTC

Request Review

Gajesh2007 added a commit that referenced this pull request Oct 22, 2026
The previous pin, c8dce97d (#331), also carries SDK #332: chunk deltas now
carry [OpenAIToolCallDelta] and MLXServerGenerationEvent gains
.toolCallDelta, so ProviderLoop+SSEParser.swift no longer compiled. Pin
f77b384c, the merged SDK main commit that adds #333's MLXLMServerTests
build fix on top of #331 (same library tree).

The SSE parser and the six test-file hunks are copied byte for byte from
#1549 (ttft/stream-auto-tool-calls), so whichever of the two lands second
merges cleanly. They change types only; this branch does not request
streamed fragments, so complete calls hash and encode as before.

Flint response-format code added by master's #1552 also switches over
MLXServerGenerationEvent; it ignores .toolCallDelta like .toolCall, and
its tests count a completed delta as a call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007 added a commit that referenced this pull request Oct 22, 2026
…1549 does

FlintResponseFormatTests counted every .toolCallDelta event as a call, so
it disagreed with FlintAnswerStopTests and with #1549
(ttft/stream-auto-tool-calls), which count a delta only when it completes
a call. Both helpers now match #1549's files byte for byte, so this branch
and #1549 merge without conflicts in either file. Behavior is unchanged:
this branch does not request streamed fragments, so its engines emit only
whole .toolCall events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Gajesh2007
Gajesh2007 merged commit 7d10154 into master Oct 22, 2026
51 checks passed
@Gajesh2007
Gajesh2007 deleted the ttft/stream-auto-tool-calls branch October 22, 2026 21:01
Gajesh2007 added a commit that referenced this pull request Oct 22, 2026
* Raise CBv2 mixed-step prefill geometry for GPT-OSS, dense Qwen and Gemma 4

With one partial prefill a busy engine prefills only its plain chunk beside
decode rows, so production fed every mixed step 512 prompt tokens. GPT-OSS,
dense Qwen3.5/3.8 and Gemma 4 now default to a 2,048-token plain chunk and
a 4,096-token step budget (EngineV2Factory.prefillGeometry). The chunk
replaces the 2,048-token GPT-OSS and Gemma stripes and stays below dense
Qwen's 4,096-token stripe, so paged ring sizes, KV charges and load
quotations are unchanged. Other families keep 512 / 2,048.

Gemma 4 image and video requests keep 512-token chunks through the SDK's
new bidirectionalMediaPrefillChunkCeiling (libs/mlx-swift-lm moves to the
commit that adds it): a paged span-bearing chunk attends in one unblocked
call, so its score tensor grows with the chunk length times the history.

DARKBLOOM_CBV2_PREFILL_CHUNK and DARKBLOOM_CBV2_STEP_TOKENS override the
geometry for every family and reach the launchd provider job; 512 / 2048
rolls back. Scheduler-prefill receipts record the geometry (schema 5), the
decision live runner pins its simulated geometry, and fixtures that pin a
stripe also pin the SDK chunk. Docs, a dated measurement report and a
changelog fragment record the load, inter-token latency and activation
evidence and its limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Document the Gemma 4 block ring bound and tighten geometry comments

Behavior-preserving refactor-pass follow-up to the prompt geometry change.

- inference.md invariant 9: a Gemma 4 block chunk stays within the
  2,048-token ring because Gemma4Processor delimits every image and video
  frame, not because submit validation bounds blocks, which now admits them
  up to the 4,096-token step.
- configuration.md: a solo stripe that does not exceed the plain chunk,
  including an equal one, is disabled.
- productionSchedulerConfig: the media ceiling comment names bidirectional
  media, which is all the ceiling applies to.
- SegmentedFleetGeometry: window rings follow the largest schedulable
  chunk, which for GPT-OSS and Gemma is now the plain chunk, not a stripe.
- libs/mlx-swift-lm moves to the SDK commit that files the ceiling tests
  under Unit/Scheduling, matching SDK main; no library change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Record why the Gemma benchmark wrapper schema stays at 6

Raw scheduler-prefill schema 5 adds the plain chunk and step budget. Like the
raw sweep 8 / arrival 6 note, say why the wrapper schema does not move: the
default workload's prompts each fit one chunk and no step exceeds 2,048
tokens, so the Gemma 4 geometry change does not alter its chunking; longer
prompts beside decode rows do not compare across the change. Comment only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: untangle the recurrent-bank paragraph after the master merge

The merge kept both sides of the conflicting prefix-cache.md paragraph, which
repeated two sentences. Keep this branch's 2,048-token plain chunk and master's
Nemotron Super alignment sentence once each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Re-pin libs/mlx-swift-lm to the merged SDK change (#331)

Layr-Labs/mlx-swift-lm#331 squash-merged as c8dce97d ("Add an opt-in plain-chunk ceiling for bidirectional media requests (#331)").
Move the gitlink from the PR branch head 204771c4 to that commit on SDK main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Re-pin the SDK to f77b384c and adapt to its tool-call delta type

The previous pin, c8dce97d (#331), also carries SDK #332: chunk deltas now
carry [OpenAIToolCallDelta] and MLXServerGenerationEvent gains
.toolCallDelta, so ProviderLoop+SSEParser.swift no longer compiled. Pin
f77b384c, the merged SDK main commit that adds #333's MLXLMServerTests
build fix on top of #331 (same library tree).

The SSE parser and the six test-file hunks are copied byte for byte from
#1549 (ttft/stream-auto-tool-calls), so whichever of the two lands second
merges cleanly. They change types only; this branch does not request
streamed fragments, so complete calls hash and encode as before.

Flint response-format code added by master's #1552 also switches over
MLXServerGenerationEvent; it ignores .toolCallDelta like .toolCall, and
its tests count a completed delta as a call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fill the schema-5 geometry in the merged prompt-mode receipt test

Master's #1535 added SchedulerPrefillPromptTests against schema 4. After
the merge its receipt fixture omitted this branch's new required
prefillChunkTokens and maxBatchedTokensPerStep and expected schema 4 from a
current-version report, so the test target failed to compile. The fixture
now records the SDK geometry and expects the current schema; the legacy
case decodes a faithful schema-4 payload without the geometry fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Carry the schema-5 prompt geometry into gptoss_profile summaries

summarize_cell copied only soloPrefillStripeTokens from a scheduler-prefill
receipt. Under the wide plain chunk a nil stripe no longer means 512-token
chunks, so derived summaries could not tell a default run from an explicit
chunk or step-budget arm. Prefill rows now also keep prefillChunkTokens and
maxBatchedTokensPerStep (None for schema-4 receipts, which lack them).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep the wide prompt geometry default for Gemma 4 only

The PR's own KV-subtracted activation probe at eight rows of 32,768-token
prompts, inside the floors' measurement range of eight rows at 4k tokens or
more, shows 2,048 / 4,096 pushing GPT-OSS from its 3.5 GiB floor to 3.62 GiB
and Qwen3.5-9B from 5.73 to 6.03 GiB against the 5.5 GiB default. No margin
absorbs that: UnifiedMemoryCap.liveKVHeadroomBytes grants KV until MLX usage
plus the reserve reaches the cap, so activation above the reserve lands past
the cap once the KV budget is full. Floors are measured constants that move
only with platform admission, so they stay unchanged here.

usesWidePrefillChunk now selects Gemma 4 alone (3.73 GiB at 32k against
5.5). GPT-OSS and dense Qwen3.5/3.8, including the unmeasured Qwen3.8-27B,
keep 512 / 2,048 and their stripes; DARKBLOOM_CBV2_PREFILL_CHUNK=2048 with
DARKBLOOM_CBV2_STEP_TOKENS=4096 still opts them in for measurement.

Tests pin GPT-OSS and dense Qwen to the SDK geometry and drive the GPT-OSS
busy-engine and pool-lockstep cases through the opt-in. The GPT-OSS and
Qwen live checkpoint fixtures no longer need to pin the SDK geometry and
return to master's form; prefix-cache.md returns to master because no
recurrent family takes the wide chunk by default. The report gains a
default-scope section with the per-cell margins and names the SDK revision
the probes ran on (cef662176, before SDK #326's GPT-OSS bf16 activations).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Raise undersized Gemma 4 chunk overrides to cover a whole media block

A Gemma 4 chunk that starts at a bidirectional media block extends over
the whole block, and submit validation bounds blocks only by the step
budget, but the paged window rings hold max(chunk, stripe) tokens. With
DARKBLOOM_CBV2_PREFILL_CHUNK=256 and DARKBLOOM_CBV2_SOLO_PREFILL_STRIPE=0
the rings held 256 tokens and a 280-token image block tripped the
PagedSequenceKV precondition, killing the provider.

prefillGeometry now raises a Gemma 4 chunk to 1,120 tokens, the vision
family's largest image budget, whenever the override leaves
max(chunk, stripe) below it. The default 2,048-token chunk, the documented
512 / 2,048 rollback (its 2,048-token stripe re-arms) and other families
are unchanged.

A geometry test pins the raised values; an engine test prefills a
300-token block beside decode under chunk 256 with the stripe off. With
the guard disabled the first fails and the second stops on "windowed
update of 300 tokens exceeds maxPrefillChunk 256".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Record the prompt geometry the built engines actually ran in receipts

The scheduler-prefill receipt took prefillChunkTokens,
maxBatchedTokensPerStep and soloPrefillStripeTokens from
EngineV2Factory.prefillGeometry before production applied later policy:
glm5NextServingScheduler (2,048 / 2,048, stripe off), the calibrated
Nemotron clamp and any dedicated scheduler policy. A GLM or Nemotron run
could therefore be attributed to the generic geometry.

ProductionBuild now carries prefillGeometry, taken from the scheduler
configuration assembleProductionBuild hands the engine. The benchmark
records the warm-up engine's value and fails the run if a measured engine
was built with different geometry, so one report-level field never
describes samples it does not cover.

A test builds a tiny paged GPT-OSS engine with and without a scheduler
policy that narrows the chunk, step and stripe, and checks the build
reports the narrowed geometry rather than prefillGeometry(model:).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Count only completed tool-call deltas in the Flint test helpers, as #1549 does

FlintResponseFormatTests counted every .toolCallDelta event as a call, so
it disagreed with FlintAnswerStopTests and with #1549
(ttft/stream-auto-tool-calls), which count a delta only when it completes
a call. Both helpers now match #1549's files byte for byte, so this branch
and #1549 merge without conflicts in either file. Behavior is unchanged:
this branch does not request streamed fragments, so its engines emit only
whole .toolCall events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Raise undersized Gemma 4 step budgets to cover a whole media block

e19f138 kept the windowed rings at least one Gemma 4 media block wide,
but submit validation also refuses a block longer than the step budget
(CBv2MultimodalPlan.validate). With a chunk below the block, a stripe
that already covers it and an explicit step budget equal to the small
chunk (for example 256 / 1,120 / 256), the ring guard did not fire and
every image request failed with spanTooLong although the rings could
hold the block.

prefillGeometry now raises a Gemma 4 step budget below 1,120 tokens
(gemma4MaximumMediaBlockTokens) to 1,120. Defaults, the 512 / 2,048
rollback and other families are unchanged.

A geometry test pins the raised budget and that other families keep
theirs. A real paged Gemma 4 engine test submits a 300-token block under
chunk 256, stripe 1,120 and step 256. With the clamp removed, the
geometry test fails and the engine test catches
.spanTooLong(blockTokens: 300, maxBatchedTokensPerStep: 256).
inference.md invariant 9 records the budget bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Name the families whose policy replaces the prompt geometry overrides

The prompt-geometry docs said an explicit DARKBLOOM_CBV2_PREFILL_CHUNK
applies to every family. Three later policies replace or cap it:
glm5NextServingScheduler sets GLM5Next's own 2,048-token chunk and step;
NemotronSuperLocalPrefill.Policy.apply sets Nemotron Super local
serving's chunk (DARKBLOOM_NEMOTRON_SUPER_PREFILL_CHUNK) and step; and
calibratedPrefillTokenLimit caps calibrated Nemotron chunks.
inference.md and the configuration rows now name these exceptions, and
point to the receipts' built geometry. The STEP_TOKENS row also records
the Gemma 4 media-block budget raise.

The changelog said solo prefill is unchanged. Solo chunking is, but the
2,048-token Gemma stripe used to shrink to 512 tokens once when KV could
not be reserved, and a plain chunk does not. On contiguous KV (Gemma 4
artifacts other than the catalog's paged gemma-4-26b-qat-4bit, or with
paging disabled), such a prompt now waits or is preempted. The fragment
now says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Place prefill-geometry passthrough test apart from sibling PRs' insertions

Move forwardsPrefillGeometryRollbackToProviderJob up beside
forwardsPrefillOperationalControlsUnchanged, mirroring the key order in
inferencePassthroughEnvKeys, so it no longer shares an insertion point
with the serving-stalls test after the deadline-admission test. Pure move;
the test body is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch was successfully deployed

5 active deployments
Preview – d-inference — 5deb0390 Deployed Oct 22, 2026 by vercel[bot]
Preview – d-inference-landing — 5deb0390 Deployed Oct 22, 2026 by vercel[bot]
Preview – eigen-homepages-darkbloom — 5deb0390 Deployed Oct 22, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 5deb0390 Deployed Oct 22, 2026 by vercel[bot]
Preview – darkbloom-status — 5deb0390 Deployed Oct 22, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants