Repository navigation
Studio: stop rescanning the whole answer on every streamed token - #8538
Conversation
Rebuilt on main after the tool-call strip dedup landed as a squash.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 71aa0bf107
ℹ️ 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".
| out = self._full_strip(text) | ||
| self._note(text) | ||
| return out | ||
| stripped = tail[:cut] + self._full_strip(tail[cut:]) if cut else self._full_strip(tail) |
There was a problem hiding this comment.
Advance past sentinels that resolve to prose
When a streamed answer contains a sentinel that is intentionally retained—such as an inactive foo[ARGS]{} example or an unanchored call:a{} mention after a visible prefix—_first remains pinned to it, so this branch runs _full_strip over the ever-growing remainder on every subsequent token (in addition to the whole-buffer checks above). In the GGUF _S_STREAMING callsite this leaves the operation quadratic and makes such answers slower than the implementation being replaced; a confirmed non-markup sentinel needs to be retired or folded into the settled prefix.
Useful? React with 👍 / 👎.
…r paths (unslothai#8494) * Studio: linear-time tool signal scanning in the safetensors and healer paths Rebuilt on main after unslothai#8427 and unslothai#8538 landed as squashes. * Studio: pin the safetensors loop's display strip to the exported helper The loop now drives a StreamingMarkupStripper, so the exported strip_tool_markup_streaming had no call site left in the module while ten assertions in this file still targeted it. Agreement is now asserted at every prefix, so the suite guards the path the loop actually runs. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
E AssertionError: early markup cost 1.451s against the reference's 1.316s E assert 1.4506334609999385 <= (1.3157524960000728 * 1.1) Introduced by #8538 (2026-08-12), which added the test with time.perf_counter. The source it guards is fine and is untouched here; the test has measured the wrong quantity since it was written. It compares how much WORK two code paths do, with a 10% margin, but timed them on the wall clock, which also measures whatever else the machine is running. A 10% margin does not survive that. On a 4-vCPU runner with other pytest workers in flight it failed while the code under test had not changed. process_time measures this process's CPU time, which is what the assertion is about and what neighbours cannot move. The margin and the min-of-3 sampling are untouched. I have NOT reproduced the original failure locally, so this is not verified as a fix for that specific run: three busy processes on the same core slow both arms equally and the ratio holds. What is demonstrated is the mechanism, on identical work: idle core: wall=0.0161s cpu=0.0160s core shared with 3 hogs: wall=0.0599s cpu=0.0150s Wall clock inflates 3.7x, CPU time does not move. Robustification: process_time is coarser than perf_counter, and 0.0 <= 0.0 * 1.10 is true, so a stopped clock or a lowered count would silently turn this into an assertion that cannot fail. Both arms now have to measure something. Checked by mutating the clock to return 0.0: reference arm measured 0.0000s; too small to compare against Whole file: 64 passed.
* Measure the streaming stripper against CPU time, not wall clock E AssertionError: early markup cost 1.451s against the reference's 1.316s E assert 1.4506334609999385 <= (1.3157524960000728 * 1.1) Introduced by #8538 (2026-08-12), which added the test with time.perf_counter. The source it guards is fine and is untouched here; the test has measured the wrong quantity since it was written. It compares how much WORK two code paths do, with a 10% margin, but timed them on the wall clock, which also measures whatever else the machine is running. A 10% margin does not survive that. On a 4-vCPU runner with other pytest workers in flight it failed while the code under test had not changed. process_time measures this process's CPU time, which is what the assertion is about and what neighbours cannot move. The margin and the min-of-3 sampling are untouched. I have NOT reproduced the original failure locally, so this is not verified as a fix for that specific run: three busy processes on the same core slow both arms equally and the ratio holds. What is demonstrated is the mechanism, on identical work: idle core: wall=0.0161s cpu=0.0160s core shared with 3 hogs: wall=0.0599s cpu=0.0150s Wall clock inflates 3.7x, CPU time does not move. Robustification: process_time is coarser than perf_counter, and 0.0 <= 0.0 * 1.10 is true, so a stopped clock or a lowered count would silently turn this into an assertion that cannot fail. Both arms now have to measure something. Checked by mutating the clock to return 0.0: reference arm measured 0.0000s; too small to compare against Whole file: 64 passed. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…ead of timing it (#16315) ## Problem `studio/backend/tests/test_streaming_stripper.py::test_prose_containing_the_word_call_is_still_amortized` failed in `(Python 3.13, a-f)` on #16311, a frontend-only PR: ``` AssertionError: incremental cost grew 5.7x vs the reference's 8.6x on prose containing the word 'call' ``` The test timed 300 and then 1200 tokens once each and required the stripper's growth to stay under half of the reference strip's growth. Both measurements take a few milliseconds (about 1 ms and 4 ms locally), so on a loaded runner the linear code read 5.7x and the quadratic reference only 8.6x, where 4x and 16x are expected. The code under test is unchanged on main. The timing was what flaked. ## Change The test now counts work in the same way `test_scan_is_amortized_not_quadratic` above it already does. It counts the characters handed to `_first_sentinel` and to `StreamingMarkupStripper._full_strip`, and it also asserts that the prose comes back unchanged on every token. The counts are deterministic: | | 300 tokens | 1200 tokens | growth | |---|---|---|---| | main | 13,132 | 51,832 (2.7 per buffer character) | 3.9x | | `_first_sentinel` returning every bare `call` unconfirmed | 722,400 | 11,529,600 (600 per buffer character) | 16.0x | The assertion requires under 8x growth and at most 8 characters of work per buffer character. ## Verification - The new test passes on main, and the whole file passes 67/67 three times under `-n 4`. - Sabotage: with the confirmation in `_first_sentinel` removed, so that any bare `call` counts as a sentinel, the test fails with `work grew 16.0x for 4x the tokens (722400 -> 11529600 characters over a 19200-character buffer)`. That is the regression the test was written for in #8538.
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.