Repository navigation
Stream auto tool calls while they are generated and seed content for plain Qwen prompt tails - #1549
Conversation
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>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Threat model review — advisoryReviewed head Review not completed for this head. Previous findings are superseded, not confirmed resolved. Scan incomplete: 1 file(s) could not be fully read as text. Binary, Git LFS and submodule changes require manual review. Models: budgeted Sonnet / selective Opus / selective Sol 6.1. Findings require human validation; this review never requests changes or blocks merging. Failure diagnostics: 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>
There was a problem hiding this comment.
💡 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".
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>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
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>
…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 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>
Summary
Provider TTFT is measured from dispatch to the first content-bearing frame
(
firstContentElapsedMsinProviderLoop+InferenceHandler.swift). Tool callswere released only after the engine terminal (
toolHandler?.finish()inMultiModelBatchSchedulerEngine), 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:
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_callsfragments:index,id,typeandfunction.nameassoon as the name resolves to a declared tool, then
function.argumentsfragments.
NativeToolStreamRouteradmitsparallel_tool_callscardinalityat a call's first fragment, validates name and schema
(
ToolConstraintValidation) when its frame closes, and re-validates the wholeset at the terminal. A call cut off by
max_tokensends withfinish_reason: "length", including when the end-of-generation parse of itspartial 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 (
formatOutputobserve/validate,
checkNativeToolFailure, and feat(flint): OpenRouter parameter compatibility (reasoning controls, stop, JSON response_format, logprobs) #1552's matched-answer-stopoverride, now in
yieldTerminalInfo).already counted a
tool_callsframe as content; streaming moves that frame tothe call's first fragment, so a call that is already visible is never
discarded. The response hash adds one
tool_callmarker per fragment (acomplete 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.
ReasoningPromptProbestarts a Qwen3-VL (
qwen3_vl_moe,plainTailContentModelTypes) request onthe
qwen3parser in content state when the rendered prompt tail has nothink 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_nextstay undecided so their reasoning is notexposed as answer text.
libs/mlx-swift-lmfrommaster's889fe3ccto SDKmainf77b384c, which is889fe3ccplus Stream auto tool calls as OpenAI tool_calls fragments and find end tags in appended text mlx-swift-lm#332 (this change's SDKside), 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 whosebidirectionalMediaPrefillChunkCeilingdefaults to nil and is never set bythe 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) andlibs/mlx(ad4745a2) stay atmaster'spins, so this PR changes no Metal source.
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 achangelog.dfragment.Commits
Branch
ttft/stream-auto-tool-calls, merged withmaster8f6958689:102835bcf3dc0e968965af6e213a062dfb01tool_callsfragments ininference_response_chunkbb313ec3cexposesCallsWhileGeneratedprivate, correct comments07c1233cblibs/mlx-swift-lmto the merged SDK change (118ffb0a)bfcbd7192master(#1552 Flint OpenRouter conflicts in the router and engine forwarder)4b372c5cflibs/mlx-swift-lmto SDKmainf77b384c(SDK test build fix)e5c2c6834d696e1736max_tokenswithlength, even if divergedda617fc765deb03903Before
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 checkAfter
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 sameflowchart 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 sameLegend: 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 thecoordinator's
reasoning_parserin each request (gemma4,qwen3withenable_thinking: false,harmony). Medians of 5 requests per arm. "Firstcontent 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.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
argumentsparsed as JSON, andcompletion 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_fileprompt,max_tokens2048, 2 requests per arm, same hold). Table:
$LOGS/m3u-final/summary-long.md, JSON:$LOGS/m3u-final/final/long/.max_tokens: raw<tool_call>markup as contentmax_tokens: partial call,finish_reason: lengthGemma'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
ToolCallProcessorper 4-character chunk of onewrite_filecall(release
swiftc -O -wmooverLibraries/MLXLMCommon/Tool, best of 3, on theM5 Ultra while other builds ran; load average in the log). Log:
$LOGS/cpubench.logmain4 / 16 / 64 KB (µs per chunk)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
autochatstreams). 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 toolresult, with and without tools,
enable_thinkingunset, true and false): Qwen3.5-9B, Qwen3.5-35B-A3B, Qwen3.6-35B-A3B andQwen3.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\nin 12 of 12,which previously left the
qwen3parser 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.jsonandprobe_tails_qwen36.jsonbeside 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
masterbinary, 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.logmaster, first tool fragment (s)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
9d8bfc89on the old base (mastereaaf5e615,libs/mlx-swift81f58d79,libs/mlx71271f08). They were not re-measured after the refactor pass, themastermerges, the SDK re-pins (f77b384c), the Qwen3-VL-only seednarrowing or the truncation fix. None of those later changes touches the
measured paths: the seed change affects only
qwen3_vl_moeplain tails, andthe truncation fix affects only a call cut off by
max_tokenswhose partialframe fails or diverges at end of generation.
Platform protocol review
The
inference_response_chunkenvelope and every WebSocket field areunchanged, but the chat chunk JSON inside
datachanges shape for streamedautocalls: one call now spans severalchoices[].delta.tool_callsentriesthat share
index(the first withid,type,function.nameand emptyarguments; later ones with onlyindexand anargumentsfragment).Read-only review of darkbloom-platform
master67b120bbe. Verdict:compatible, no platform code change needed.
coordinator/api/inference/response/tool_call_accumulator.go(
toolCallAccumulator.apply): id-less fragments continue the active call atthe same index;
id/type/namecome from the first fragment; argumentsare concatenated;
finalizeis index-ordered. Non-streaming chat/Responsesaggregation uses it in
stream_message.go(
ExtractMessageWithReasoningPolicy), and the Messages stream uses it ingeneric_endpoint_stream.go(messagesStreamEmitter.HandleChunk/Finish).responses_stream.go(ResponsesStreamEmitter.appendToolCall) opens thefunction_callitem on the first fragment (name), emitsresponse.function_call_arguments.deltaper fragment and closes calls incloseFunctionCalls.internal/inference/sse/sse_normalize.go(NormalizeSSEChunk) onlyrewrites null fields.
response/sse_events.go(IsBoilerplateChunk) treats any non-emptytool_callsas content, so dispatch and the first-content clock commit atthe name fragment (
internal/inference/firstcontent/first_content_policy.go),and
observation/request_outcome_egress.go(GeneratedContentJSON) alsocounts
tool_calls.internal/inference/responsepolicy/finish_policy.go(
EffectiveFinishReason) keeps a providerlength, so a truncated streamedcall is not rewritten to
tool_calls.generic_endpoint_response.go(
messagesToolUseBlock) falls back to input{}for partial JSON.inference_complete, andresponse_hashis forwarded opaquely (
api/inference/provider_inference.go,pr.ResponseHash = msg.ResponseHash); the consumer verification contractalready forbids recomputing it from re-serialized output.
tool_choiceonly on the request(
request/tool_constraints.go) and enforces nothing on the response; aprovider 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:
inference_response_chunkparagraph in the platform copy of
docs/reference/protocol-messages.md.(the call was withheld until the terminal) and was refunded. Its fragments
are now visible, so
StreamedGenerationUsage.cancelledUsageInfosettles itas
inference_completewith the delivered-text floor(
max(deliveredCompletionTokenFloor, contentFrameCount)when engine usage ismissing), the same as a cancelled content stream.
Review follow-ups
Fixed in this round:
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)118ffb0adid not compileServerSurfaceTests4b372c5cf(pin SDKmainf77b384c, with Layr-Labs/mlx-swift-lm#333)master(#1552) inNativeToolStreamRouterand the engine forwarder; the streamed terminal branch skipped #1552's terminal checksbfcbd7192(both router features kept; streamed branch runsformatOutputobserve/validate,checkNativeToolFailureand the answer-stop override throughyieldTerminalInfo;.toolCallDeltahandled inFlintResponseFormatOutput.observe)inference.mdda617fc76,5deb03903da617fc76(protocol-messages.md; the other two pages carry 2026-10-22 frommasterand this round's edits)max_tokenswhose partial arguments contain}ended in atool_choiceviolation instead oflengthd696e1736(regression case intruncatedCallEndsQuietlyOnlyAtTheTokenLimit)5deb03903756432c807c1233cb; nowf77b384cDeferred (not merge-blocking):
frame's lenient end-of-generation parse happens to agree with the exposed
prefix, the SDK reports
.callCompleted, and a missing required propertystill throws a
tool_choiceviolation instead of ending withlength.master's complete-call path rejected the same call inToolConstraintValidation, so this is not a regression. Possible follow-up:treat a failed validation of an EOS completion as truncation when
truncatedis true (
NativeToolStreamRouter.finishToolCalls).stopsequence matched inside a streamed call reportsstop, notlength, so the open call ends in a violation. Edge case; could be treatedas a quiet truncation.
deliveredTextinProviderLoop+InferenceHandler.swiftis inline in the frame loop; covering itneeds an extraction or a handler-level harness.
long_filedecode outlier (one of two streamed requests at 98.8tok/s): rerun with more requests on the final binary.
Validation
This round, on the M3 Ultra, in the branch worktree (provider tests with
isolated
DARKBLOOM_STATE_FILE/DARKBLOOM_LOADED_MODELS_FILE, as inscripts/run-provider-tests.sh). Full CI runs on the pushed head5deb03903.cd provider-swift && swift build --build-tests -j 8, thenscripts/stage-test-metallib.shswift test --skip-build --no-parallel --filterforStreamedToolCallTests,ReasoningPromptProbeTests,NativeToolStreamRouterTests,EngineV2RequestRoutingTests(inEngineV2ProductionWiringTests.swift),EngineV2SlotBuildTests,EngineV2ReslicingWiringTests,EngineV2RuntimeGuardTests,NativeLocalConsumerOwnershipTests,GLM5ToolFailureTests, the Flint answer-stop/response-format/policy/protocol suites,MiMoV26StreamContractTests,NemotronSuperLocalOutputTests,ThinkStreamingLatencyTests,ReasoningParserSelectionTests,LocalChatRequestTestsand theProviderLoopstream-chunk tests (MiMo prompt fixtures fromscripts/prepare-mimo-prompt-fixtures.py)5deb03903, a 20-term filter over the same areashasPrefix("qwen")and truncation back to.callFailed(.unterminated)EngineV2ProductionWiringTests.swift:1362,plainPromptTailKeepsCloseOnlyQwenUndecided,plainTailWithoutSeedand the}case oftruncatedCallEndsQuietlyOnlyAtTheTokenLimit; passes again after restoringcd libs/mlx-swift-lm && swift build --build-tests -j 8atf77b384c, then../../scripts/run-nested-suite.shServerSurfaceTests,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.sh190 file(s) OKDOCS_IMPACT_BASE=origin/master python3 scripts/docs-impact-check.py23 changed file(s), canonical documentation coverage OKpython3 scripts/changelog.py check45 valid fragment(s)git log --show-signatureon the six new commitsEarlier rounds, before the rebase, also built the release binary measured
above and checked that its
mlx.metallibmatched the production metallib(
fb1ba8f9…); see Evidence.Kill switch
Both default on; exact
0restores the previous behavior, and both areforwarded to the LaunchAgent (
LaunchAgent.inferencePassthroughEnvKeys):0restoresDARKBLOOM_TTFT_STREAM_TOOL_CALLStool_callsentry eachDARKBLOOM_TTFT_THINK_CONTENT_SEEDqwen3parsing for Qwen3-VL (qwen3_vl_moe) prompt tails without a think markerThe SDK's linear end-tag scan is not switchable; its differential test shows the
same calls and text as the whole-frame path.
Limitations
exposed prefix or violates its schema ends the stream with a typed
tool_choiceviolation (unless the call was cut off bymax_tokens). Before,an
autocall that failed to parse fell back to visible text withfinish_reason: "stop"; the kill switch restores that. Worth a release notefor agent integrators.
other than Gemma, Qwen 3.5, Harmony and framed JSON, and
required/namedtool choices, are unchanged.
was already early (reasoning); the gain is in the first tool fragment.
max_tokensnow arrives as a partial call withfinish_reason: "length"(OpenAI stream semantics) where the complete-callpath returned the raw call markup as content (Qwen
long_filerows above).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).
MLXOpenAIService.streamChatCompletionFramesand router path as coordinatorrequests (with the coordinator's
reasoning_parserset in the request), notthrough a live coordinator. The A/B binary predates the rebase (see
provenance above) and was not compared with the current production
masterbinary.
and template-tail rendering only (evidence above); Qwen3-VL is not a local
model, so it has no GPU measurement.
(
GemmaToolCallLiveTests,Qwen36ProductionCanaryTests,ModelContainerEngineFinishReasonTests,GenerateTaskToolFilterTests). CIruns the provider and SDK lanes on the pushed head.
Landing order
libs/mlx-swift-lmpins SDKmainf77b384c(libs/mlx-swiftandlibs/mlxstay atmaster's pins).5deb03903.line. Resolve by pinning the newest SDK
mainthat contains every mergedSDK PR.
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
bb313ec3chere and in the SDK side ofLayr-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,ToolCallProcessorwrite-backs through the optional
callStream) and makesGemmaArgumentValueParser.parseValueprivate again; the provider makesToolStreamPreparation.exposesCallsWhileGeneratedprivate and corrects thestreamingOptionsandReasoningPromptProbecomments and the changelog's CPUexample. 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
.toolCallDeltabranches inMLXOpenAIServicerepeat the whole-call handlingfor a case those surfaces never request; they exist for exhaustiveness.
Round 2, this round: done. An independent reviewer checked the
mastermerge 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: theDARKBLOOM_TTFT_THINK_CONTENT_SEEDdoc comment names theplainTailContentModelTypesscope,inference.mdsays "request" instead of"stream" (the probe also seeds collected requests), the
max_tokensrow of thestreamed-call table covers a partial frame that fails or diverges, and the
FlintResponseFormatOutputTestscollector counts a.toolCallDeltaonly whenit completes a call. The remaining edge cases are under Review follow-ups.
🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need.