Repository navigation
Studio: stop rescanning the whole answer on every streamed token - #8428
danielhanchen wants to merge 12 commits into
Conversation
3db4286 to
b18e172
Compare
60dd3fe to
9a14fc3
Compare
9a14fc3 to
bc84a6e
Compare
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3fa0f1c8ab
ℹ️ 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".
| "<tool_call", # Qwen/Hermes open + GLM, and the <tool_call|> Gemma closer | ||
| "<|tool_call", # Gemma open, Kimi <|tool_call_begin|> / <|tool_calls_section_begin|> | ||
| "<function", # Qwen3.5 <function=name> and <function name="..."> | ||
| "[TOOL_CALLS]", # Mistral array + name forms |
There was a problem hiding this comment.
Include the bare Mistral closer in the sentinel scan
When a streamed response contains a standalone Mistral v11 [/TOOL_CALLS] closer, none of these sentinels is present, so the fast path returns the markup unchanged. The reference scan deliberately removes this token via the bare-closer pattern in core/tool_healing.py, meaning this change can expose a control marker that was previously hidden; include the closer in the sentinel set so such responses still reach the full stripper.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked this one against the code rather than the description, and the premise does not hold for this path.
The [/TOOL_CALLS] arm is in core/tool_healing.py's pattern list, not the parser's. strip_segment applies the parser's _TOOL_ALL_PATS / _TOOL_CLOSED_PATS, and those have never carried that arm, at 19abc08bb or now:
parser has [/TOOL_CALLS] arm: False (merge base: False)
healer has [/TOOL_CALLS] arm: True
So the reference scan this class is measured against does not remove the token either. Both agree:
merge-base strip_tool_markup("Here is the answer.[/TOOL_CALLS]", final = True) -> "Here is the answer.[/TOOL_CALLS]"
reference (strip_segment under strip_outside_think) -> "Here is the answer.[/TOOL_CALLS]"
StreamingMarkupStripper, replayed a character at a time -> "Here is the answer.[/TOOL_CALLS]"
Adding the closer to _STRIP_SENTINELS would not change any output, since no arm reachable from strip_segment matches it. It would only cost the fast path on responses containing the token.
The two lists differing here is deliberate and predates this work: the healer is the dependency-light module external inference servers import, and it carries arms the parser does not. That divergence is recorded in plans/tool_dedup_verdicts.md as one of the three things this branch specifically does not unify.
3fa0f1c to
20e6c0e
Compare
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 20e6c0e296
ℹ️ 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".
| # ``call`` lands on a token boundary often enough to matter. | ||
| self._scanned_upto = found | ||
| return self._unchanged(text) | ||
| self._first = found - self._floor |
There was a problem hiding this comment.
Retire sentinels that resolve to prose
When preserved prose contains an exact sentinel that is not actually call markup, such as See [TOOL_CALLS] docs, this assignment caches that position permanently, and every later token runs _full_strip over the growing tail, restoring quadratic behavior. Unlike the repaired call case, _is_provisional_call only expires that one sentinel, so syntactically disproven [TOOL_CALLS], <think, and similar hits remain pinned; revalidate or retire non-matching sentinels once following text proves they cannot start a strip arm.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced, and it is real, but it is not a regression this branch introduces, so I am leaving it.
See [TOOL_CALLS] docs. followed by 4,000 prose tokens:
pre-PR 3.869s
this PR 3.810s 1.02x
Identical, because with no { following it no arm matches and both paths do the same full strip per token. The branch does not improve that shape; it does not make it worse either. Contrast the open reasoning block from your other comment, which was 14.5x better than pre-PR and is now ~1400x after b829dfee3.
I looked at generalising _is_provisional_call and did not find a sound cheap rule. call is special: _GEMMA_BARE_TC_PREFIX_RE already exists and decides in O(1) whether a partial can still complete, and a bare call with a non-matching continuation provably cannot start the arm. [TOOL_CALLS] has no such predicate, because a { or [ arriving many tokens later still completes a Mistral arm, and <tool_call likewise waits on </tool_call>. Retiring those on "the following text looks like prose" would be a guess, and guessing wrong drops a real call from the display.
A sound version needs a per-arm minimal-continuation predicate, which is a larger change than belongs on this branch. Recorded rather than bolted on.
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5a5f3b1e62
ℹ️ 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".
| # straight back rather than rebuilding it a token at a time. It is returned, not | ||
| # kept: this is the path a plain prose answer takes on every token, and keeping | ||
| # it is exactly what would stop the caller growing it in place. | ||
| return text if self._floor_identity else self._floor_out + text[self._floor :] |
There was a problem hiding this comment.
Avoid aliasing the streamed accumulation on the fast path
When a streamed answer contains no sentinel, this returns the exact cumulative_display object, which the GGUF loops retain in cleaned and _last_emitted at llama_cpp.py:15819-15828 and 16708-16716. That extra reference prevents CPython from resizing cumulative_display += token in place, forcing the entire response to be copied on every token; consequently ordinary long answers still have quadratic accumulation cost despite this optimization. Retain only emission metadata or otherwise ensure the returned display value does not remain an alias of the append buffer.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The refcount mechanism is right, but the alias is not something this branch introduces, and the remedy does not remove it.
unicode_modifiable in Objects/unicodeobject.c requires Py_REFCNT(unicode) == 1, and _BINARY_OP_INPLACE_ADD_UNICODE in Python/bytecodes.c only clears the local so the append can see that refcount, so any third reference does force a copy. Confirmed on 3.13.12, plain append loop, 60k appends: 0.003s with nothing else holding the buffer, 1.04s with one alias.
Two things follow from that, and they both point away from a change here.
The merge base already returned the caller's own object. strip_tool_markup is a chain of re.sub, and re.sub hands back the original string when nothing matches, so cleaned is cumulative was already true at 19abc08bb for a prose answer:
merge base strip_tool_markup(prose, final=False) is prose True
merge base same, enabled_tool_names={"get_weather"} True
head StreamingMarkupStripper(...).strip(prose) is prose True
The final-answer loop at 16708 called _strip_tool_markup(cumulative) before this commit and gets the same object from it, so nothing about the aliasing changed.
The suggested fix does not reach the reference that matters. Both loops also yield {"type": "content", "text": cleaned}, and the consumer holds that event across the generator's resumption, so the refcount is still above 1 at the next += whatever _last_emitted holds. Replaying the loop shape with a consumer that keeps the previous event, 40k tokens:
as written 0.353s
_last_emitted as a length, cleaned dropped 0.305s
nothing outside the loop holding it 0.005s
Retaining only emission metadata buys 14 percent of a term that is already small; the 66x is in the yielded event, which is the emission contract. The other branch you offer, returning a value that is not an alias, means copying the whole buffer per token, which is exactly the O(n) per token this is trying to avoid.
And the optimization is not defeated. Prose-only stream, no sentinel, 4000 tokens to 232k chars, same harness with the real strip in it and the aliasing present in both arms:
pre-PR 36.084s
this PR 0.052s 694x
The residual copy is a few milliseconds of that 0.052s. It is a real property of the emission contract, it predates the branch, and I would rather not trade a whole-buffer copy per token for it.
generate_chat_completion_with_tools ran the full tool-markup strip over the entire accumulated response once per content token: strip_outside_think plus the mistral / bracket-tag / gemma / function-XML / GLM scans, ~10 regex substitutions and the rehearsal tail arm, all over a string that grows with every token. That is quadratic in the response length, and on a long answer it is the dominant cost in the streaming path. StreamingMarkupStripper replaces the per-token full rescan. Two properties make it possible, and both are tested rather than assumed: - every strip arm is anchored on one of a small set of literals, so text containing none of them comes back unchanged and does no regex work at all; - no arm can match before the first of those literals, so the text before it can be sliced off and the strip run on the remainder only. The scan for that first literal resumes where the previous call stopped, with a _SENTINEL_MAX_LEN - 1 overlap so a literal split across two appends is still found, which makes the pre-markup phase amortized constant per token instead of linear. A completed reasoning block is folded into a settled prefix, since strip_outside_think already processes each segment in isolation and a segment boundary is a point nothing downstream reaches back across. While a clean block is still streaming the buffer is unchanged, so that phase is constant too. Measured, old vs new, per-token strip over a whole response: 16k tokens, plain prose 69.4s -> 0.04s 16k tokens, prose then a tool call 69.0s -> 0.62s 16k tokens, reasoning then an answer 44.9s -> 0.62s 16k tokens, markup at offset 0 8.7s -> 8.9s The last row is the case nothing can be settled or sliced in, so it does the same work as before; a degenerate-state flag keeps it from paying the bookkeeping on top, leaving it within measurement noise. Three subtleties the property tests caught while this was being written, each of which produced wrong display text: - the rehearsal arm matches NAME[ARGS], so the match starts before its [ARGS] literal and the cut has to back up over the preceding run; - the [TOOL_CALLS] and [ARGS] arms are gated on markdown code spans and an opening fence can sit arbitrarily far back, so a backtick before the cut means no cut is safe; - the fence pattern is ^ anchored, so cutting mid-line can turn a mid-line fence into one that opens a block and flip the in-code gate. The cut snaps to a line start. Verification. test_streaming_stripper.py asserts the two properties directly (including 20k fuzz samples of near-miss markup), then replays every corpus entry through both the old and the new implementation one character at a time and asserts the results are equal at every prefix, plus the same over random multi-character chunkings and 400 fuzz strings. A timing test compares growth rates rather than an absolute so it stays meaningful on a noisy box. End to end in Studio against unsloth/gemma-4-E2B-it-GGUF:UD-Q4_K_XL and unsloth/Qwen3.5-4B-MTP-GGUF:UD-Q4_K_XL: plain chat, reasoning, a fenced code example that must survive the strip, and a real tool loop (the model called the Python tool, the sandbox returned 6765, the answer rendered clean) all stream correctly with no tool markup reaching the display.
Two of the properties the incremental strip rests on were not quite true.
Sentinel completeness. `_GEMMA_BARE_TC_RE` is `call\s*:`, so `call :name{...}`
and `call\n:name{...}` are calls, but the sentinel was the literal `call:`.
Neither shape carried a sentinel, so the buffer was handed back verbatim and
the raw markup rendered while the call still executed. The sentinel is now
`call`, confirmed in `_first_sentinel` against the arm itself rather than taken
at face value: an ordinary "I will call the tool" is not an anchor, and taking
it as one measured slower than the code this replaces.
Prefix split. The markerless Gemma arm keys on the whole segment, not on its
own anchor: a whole-JSON or leading-JSON answer is data and its examples stay
visible. Slicing the buffer hid that from it, and a pretty printed JSON answer
documenting a tool lost the example out of the middle of it. Earlier arms can
also leave behind a tail that is whole JSON when the untrimmed buffer was not.
A reasoning closer with no opener is the same hazard from the other side, since
it makes offset 0 of the segment meaningful. Both are detected after the
sentinel scan and strip the buffer whole, which is the pre-change cost and only
for a buffer that actually holds one.
Found by replaying every prefix against the non-incremental strip over inputs
spliced from whole markup fragments; the existing fuzz builds its inputs from
an alphabet and almost never assembles a complete call, which is why it missed
all of these. 160,000 spliced inputs now replay identically. Per-token cost on
a 16k-token answer: plain prose 64.8s to 0.03s, prose containing the word
"call" 13.6s to 0.02s, reasoning then answer 45.8s to 0.89s.
_strip_bracket_tag_calls stands down over _MAX_BRACKET_SCAN_CHARS and returns
the segment untouched. Cutting at a late sentinel brings the tail back under
that limit and turns the arm on again, so a very long answer with a rehearsal
near its end kept text the full scan removes: a million characters of prose
followed by search[ARGS]{"x": 1} tail left " tail" visible.
A segment that has passed the limit is now left whole. Only answers past a
million characters take that path.
_first_sentinel accepts a bare call when the buffer ends inside a possible one, because the next token may complete it. Committing that hit was wrong twice over. It never expired, so the ordinary word call landing on a token boundary pinned the scan and sent every later token through the whole-buffer checks: the same 2,000-token answer took 9.1s split as ["I will call", " it now. "] against 0.006s as one token. And the partial test used search rather than match, so a call at the very end of the buffer validated an unrelated earlier one, which diverged from the reference. Nothing is committed now: the scan stops at the possible call and resumes there next time, and the partial has to start where the hit is. Same split answer is 0.014s, and a real call arriving one character at a time is still caught.
The streaming loop grows the answer with cumulative_display += token, and CPython only resizes a string in place while nothing else refers to it. Keeping it in _last_in / _last_out for the extension check and the repeat memo added that reference, so every append copied the whole answer and the concatenation went quadratic even though the scanning here did not. The cost landed on the caller, which is why the scan benchmarks did not show it: over an append-only loop, 1.14s at 64k tokens against 0.003s without the reference. Length and the two end samples are all the extension check needs, so that is all that is kept. The exact-repeat memo goes with it; it saved one strip per response, at the end of the turn, not one per token. 64k tokens now costs 0.074s and the growth is linear: 0.018 / 0.037 / 0.074s at 16k / 32k / 64k. test_the_caller_can_still_grow_its_buffer_in_place measures the growth and test_no_reference_to_the_buffer_is_retained asserts the property directly.
…k that cannot decide Two problems an independent pass found. The stripper is built once per request, above the tool loop, but each iteration starts a fresh cumulative_display inside it. _is_extension samples a length and 64 bytes at each end rather than comparing, so a new buffer agreeing on those is accepted; the scan then resumes at an offset belonging to the previous iteration and never looks below it again, and raw markup renders for the rest of the turn. The collision is a coincidence rather than a systematic path, but the class docstring promises a rewind is safe and it is not, so the caller now says explicitly that the buffer is new. Within an iteration every mutation is an append, which makes the sampled check exact for this caller. Second, once the cut is 0 and nothing is settled, the two arms are the same expression, so _needs_whole_buffer was two full-buffer scans that could not change the answer, paid on every token. An answer with markup near its front measured SLOWER than the full rescan this replaces: 0.86 to 0.89x over 100k tokens. The check is ordered after the cut now, so it only runs where it can decide something. Same three shapes measure 0.99 to 1.01x. Verified: 12,000 fresh randomized inputs replayed character by character against the non-incremental strip on Python 3.9 and 3.13, 0 divergences, and the cross-tree output digest over 4,000 inputs is still byte-identical to merge base on both.
The open-block branch restarted at the opener on every token: find(closer) and _first_sentinel both swept the whole body again. A reasoning body is most of a reasoning model's answer, so that left the common case quadratic, just with a smaller constant than the code this replaces. It resumes from where it got to now, overlapping by _SENTINEL_MAX_LEN - 1 so a closer or sentinel split across two appends is still seen. Everything below the resume point was checked on an earlier token and cannot change. An open block of 16k tokens: 7.42s before, 0.048s after, and the growth is linear (0.003 / 0.007 / 0.018 / 0.048s at 2k / 4k / 8k / 16k). Against the code this branch replaces, which is 4.3s at 4k, roughly 1400x at 16k. Verified: 12,000 fresh randomized inputs replayed character by character against the non-incremental strip on Python 3.9 and 3.13, 0 divergences, and the cross-tree digest over 4,000 inputs is still byte-identical to merge base. Six shapes that specifically exercise the resume - closer mid-body, nested blocks, both marker families, a closer mentioned inside the body - are pinned.
There are two streamed loops in this generator, not one. The tool-generation loop was made incremental; the final-answer loop that runs after the tool iteration budget is exhausted kept calling the whole strip over its growing buffer on every content token. That path is uncommon, but when it is taken it was the largest cost left in the file: 50.5s over a 16k-token answer. It calls the strip with final=False, so it does not want the end-of-turn arms the tool loop does. Rather than reach for the other loop's instance and change what renders, StreamingMarkupStripper takes seg_final and this loop gets its own with it off. Fewer arms run, anchored on the same sentinels, and every guard in _safe_cut stays a superset, so the incremental reasoning is unchanged. 1k tokens 0.204s -> 0.0013s 160x 8k tokens 12.478s -> 0.0123s 1016x 16k tokens 50.506s -> 0.0328s 1539x Verified against strip_tool_markup(final=False) by replaying every prefix of 12,000 randomized inputs over three enabled-name gates: 0 divergences in 935,286 comparisons. Found by a codebase-wide scan for remaining superlinear paths.
5a5f3b1 to
8091529
Compare
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
_strip_function_xml_calls treats a <function> opener sitting inside an unclosed <parameter> as a literal inside an argument value, not a nested call, and it decides that from the text before the opener. _safe_cut did not know that, so it could snap the cut to a newline in the middle of an open parameter and throw away the context. Visible <parameter=x>\n<function=a></function>TEXT</function> before this branch Visible <parameter=x>\n on this branch Visible <parameter=x>\nTEXT</function> which leaks the nested markup into the displayed answer. The cut now stands down when the text before it holds an unclosed parameter, gated on a literal "<param" test so the common case never reaches the scan. A closed parameter block is still cut, so the guard is not blanket. Verified with the differential replay fuzz against the pre-refactor whole-buffer reference: zero divergences. refactor_guard verify still reports inventory, golden outputs, idempotence and patch targets all matching, without a re-snapshot, and the prose path is still linear (16k tokens, 0.032s).
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…lothai/unsloth into studio/streaming-strip-linear # Conflicts: # studio/backend/core/inference/llama_cpp.py
|
Merged the current #8427 branch in. This PR had gone to One real conflict, in
|
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
On the Mac red here: It is not this branch. #8494 is rebased directly onto this merge commit, so it contains every line of this PR plus the worst-case scan work on top, and its run of the same Mac workflow passed (run For completeness on the other reds: This PR is backend-only, no frontend files, and the composer permission control does not depend on the streaming strip. I also checked the one runtime-visible thing the merge changed, the now-unused |
…inued _is_extension samples instead of comparing, because comparing the whole buffer would be linear per token and reintroduce the cost the class removes. It sampled the head and the previous tail only, so a buffer that kept the length and both ends but changed in between was taken for a continuation. The scan then resumed at the old offset and never looked at the part that changed: first = "A"*64 + "x"*11 + "Z"*64 second = "A"*64 + "<tool_call>" + "Z"*64 expected AAAA...A got AAAA...A<tool_call>ZZZ...Z Not reachable from either caller in this repo, since both keep one instance per buffer and reset between them, but the class docstring claimed an arbitrary rewind was safe and that was not true. Sampling the middle as well closes that case at the same O(1) cost, and the docstring now states the precondition instead of promising more than the check delivers: one instance per buffer, appended to, reset() before a new one. Two tests: the reproducer above, and a control asserting an ordinary append-only stream is still recognised as a continuation, so the extra sample cannot quietly push the normal path onto the slow one. test_reset_clears_the_cached_prefix_for_a_new_buffer used to assert the check accepted its impostor. It no longer does, so that assertion is dropped; the test still covers what it is for, which is that reset() clears the cached prefix, and its docstring now explains that the sampling is not something to rely on either way. Differential over 2,820 inputs against the merge base: shared surface identical (78,960 rows), strip_segment identical (22,560 rows), streaming invariant 316,672 prefix comparisons with 0 mismatches, and no idempotence failure introduced. 382 tests pass.
|
Re-verified with deterministic checks ( The defect. Not reachable from either caller here, since both keep one instance per buffer and reset between them, but the class docstring claimed an arbitrary rewind was safe and that was not true. It now samples the middle as well, at the same O(1) cost, and the docstring states the precondition instead of promising more than the check delivers. Two tests cover it: the reproducer, and a control that an ordinary append-only stream is still recognised as a continuation. Results after the fix. The streaming suite puts only the whole-buffer reference in the comparable digest, because the stripper does not exist on the base; comparing it there would diverge by construction and hide a real difference elsewhere. The invariant that matters is checked within the head: at 316,672 prefixes the incremental result equals the whole-buffer reference, 0 mismatches. Idempotence measured on both sides: base and head both fail on 6 inputs in One difference I am not fixing, because it is an improvement. On text with no tool sentinel but deep bracket nesting, the prefilter returns before any regex or JSON work, where the old whole-buffer path recursed. Measured on the streaming path at depth 2000:
On 3.13 both raise at the same depth. This only applies when there is no sentinel; with a sentinel plus deep nesting the full strip still runs and still raises, so it is a partial and incidental improvement rather than a fix for that crash. |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
The problem
generate_chat_completion_with_toolsran the full tool-markup strip over the entire accumulated response, once per content token:Each of those calls runs
strip_outside_thinkplus the mistral / bracket-tag / gemma / function-XML / GLM scans, ~10 regex substitutions and the rehearsal tail arm, over a string that grows with every token. That is quadratic in the response length, and on a long answer it is the dominant cost in the streaming path.The fix
StreamingMarkupStripperreplaces the per-token full rescan. Two properties make it possible, and both are tested rather than assumed:<tool_call,<|tool_call,<function,[TOOL_CALLS],[ARGS],<|python_tag|>,<|,<think,call:, ...), so text containing none of them comes back unchanged and does no regex work at all.The scan for that first literal resumes where the previous call stopped, with a
_SENTINEL_MAX_LEN - 1overlap so a literal split across two appends is still found. That makes the pre-markup phase amortized constant per token instead of linear.A completed reasoning block is folded into a settled prefix:
strip_outside_thinkalready processes each segment in isolation, so a segment boundary is a point nothing downstream reaches back across. While a clean block is still streaming the buffer is unchanged, so that phase is constant too. Both are deliberately conservative and only fire on an unambiguous block whose body carries no other markup, because a</think>inside a call's arguments is that call's data, not a closer.Measured
Per-token strip over a whole response, old vs new:
The last row is the honest one: with markup at the very start there is nothing to settle and nothing to slice, so it does the same work as before. A degenerate-state flag keeps it from paying the bookkeeping on top, leaving it within the run-to-run spread (~2.5% measured in isolation).
Note this is not the
cumulative += tokenconcatenation. CPython grows that in place here, so it is already amortized linear; the full-string rescan was the problem.Three subtleties the property tests caught
Each of these produced wrong display text while this was being written, and each was found by the differential replay rather than by reading the code:
NAME[ARGS], so the match starts before its[ARGS]literal. Cutting at the literal splits the match. The cut backs up over the preceding non-whitespace run.[TOOL_CALLS]and[ARGS]arms are gated on markdown code spans, and an opening fence can sit arbitrarily far back. A backtick before the cut means no cut is safe.^anchored, so cutting mid-line can turn a mid-line fence into one that opens a block and flip the in-code gate. The cut snaps to a line start.Verification
test_streaming_stripper.py:test_refactor_guard.pyfrom #8427 still passes unchanged: the AST and runtime surface, the output digests over the corpus, idempotence and all 210 string patch targets.890 targeted tests pass, and the failure list over the touched areas is identical to a clean tree.
End to end in Studio
Isolated
UNSLOTH_STUDIO_HOME, driven through the real UI with Playwright, againstunsloth/gemma-4-E2B-it-GGUF:UD-Q4_K_XLandunsloth/Qwen3.5-4B-MTP-GGUF:UD-Q4_K_XL:6765, and the final answer rendered as "The 20th Fibonacci number is 6,765." with no tool markup reaching the display.