Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop rescanning the whole answer on every streamed token (#8538)
Daniel Han0e470511f732
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 8428d4f4867..f156e6bf533 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -78,7 +78,7 @@ from core.inference.tool_call_parser import (_GEMMA_BARE_TC_RE,_balanced_brace_end,TOOL_XML_SIGNALS as _SHARED_TOOL_XML_SIGNALS,- strip_segment as _parser_strip_segment,+ StreamingMarkupStripper as _StreamingMarkupStripper,RAG_MAX_SEARCHES_PER_TURN,RAG_SEARCH_CAP_NUDGE,parse_tool_calls_from_text as _shared_parse_tool_calls_from_text,@@ -87,8 +87,6 @@ from core.inference.tool_call_parser import (strip_tool_markup as _shared_strip_tool_markup,)-# The strip arms moved into the parser's ``strip_segment``; only think splitting is here.-from core.tool_healing import strip_outside_thinkfrom utils.native_path_leases import child_env_without_native_path_secretfrom utils.child_stdio import utf8_child_envfrom utils.hf_xet_fallback import hf_hub_download_with_xet_fallback@@ -16150,20 +16148,19 @@ class LlamaCppBackend:text, final = final, enabled_tool_names = _enabled_names_gate)+ # Wraps the parser's ``strip_segment`` so the accumulated response is not rescanned+ # end to end on every content token (that was quadratic in the response length).+ # Think blocks stay verbatim inside it: a rehearsed call in one must not be deleted.+ _streaming_stripper = _StreamingMarkupStripper(_enabled_names_gate)++ # The final-answer loop has its own buffer and strips with ``final = False``, so it+ # needs its own instance rather than sharing the one above.+ _final_answer_stripper = _StreamingMarkupStripper(_enabled_names_gate, seg_final = False)+def _strip_tool_markup_streaming(text: str, *, force: bool = False) -> str:if not (auto_heal_tool_calls or force):return text-- def _seg(segment: str, is_last: bool) -> str:- # Scan order lives in the parser's ``strip_segment`` so this path, the- # safetensors loop and ``strip_tool_markup`` cannot drift. No separate- # final pass here, so the last segment takes the end-of-turn arms.- return _parser_strip_segment(- segment, seg_final = is_last, enabled_tool_names = _enabled_names_gate- )-- # Preserve think blocks verbatim (a rehearsed call inside one must not be deleted).- return strip_outside_think(text, _seg)+ return _streaming_stripper.strip(text)def _build_metadata_event(usage, timings, finish_reason):"""Final usage+timings metadata event for the given pass, merging its@@ -16374,6 +16371,8 @@ class LlamaCppBackend:_reasoning_summary_emitted = False_deferred_reasoning_summary = Nonecumulative_display = "" # Cumulative yielded text (with <think>)+ # A new buffer, not a continuation of the previous iteration's.+ _streaming_stripper.reset()in_thinking = Falsehas_content_tokens = Falsetool_calls_acc = {} # Structured delta.tool_calls fragments@@ -17589,7 +17588,11 @@ class LlamaCppBackend:cumulative += "</think>"in_thinking = Falsecumulative += token- cleaned = _strip_tool_markup(cumulative)+ cleaned = (+ _final_answer_stripper.strip(cumulative)+ if auto_heal_tool_calls+ else cumulative+ )# Emit only when cleaned text grows (monotonic).if len(cleaned) > len(_last_emitted):_last_emitted = cleaneddiff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.pyindex e493efb5b97..e1574acee4b 100644--- a/studio/backend/core/inference/tool_call_parser.py+++ b/studio/backend/core/inference/tool_call_parser.py@@ -742,6 +742,438 @@ def strip_tool_markup(return result.strip() if final else result+# Every strip arm above is anchored on one of these literals, so text containing none of+# them is returned unchanged; ``StreamingMarkupStripper`` uses that to skip the whole scan.+# ``test_refactor_guard.py`` fuzzes the claim, so an arm added without its literal here+# breaks that test rather than production.+_STRIP_SENTINELS = (+ "<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+ "[ARGS]", # reasoning-model rehearsal+ "<|python_tag|>", # Llama-3 built-in tools+ "<|content_invoke_tool_json|>", # TML Inkling+ "<|", # DeepSeek's full-width pipe opens every one of its markers+ "<think", # reasoning segmentation+ "</think",+ "[THINK",+ "[/THINK",+ "call", # markerless Gemma; ``call\s*:`` tolerates whitespace before the colon+)+# Confirmed against ``_GEMMA_BARE_TC_RE``, not taken at face value: see ``_first_sentinel``.+_GEMMA_BARE_SENTINEL = "call"+_SENTINEL_MAX_LEN = max(len(sentinel) for sentinel in _STRIP_SENTINELS)+# Bytes sampled from each end when checking that a buffer continues the previous one.+_EXTENSION_SAMPLE = 64+++def _first_sentinel(text: str, start: int) -> int:+ """Lowest index >= ``start`` at which any strip sentinel occurs, or -1.++ ``call`` is the one sentinel that is also an ordinary English word, and treating+ every "I will call the tool" as markup would put the full strip back on the per-token+ path for a plain prose answer. It is therefore confirmed against the arm it stands+ for: either the whole ``call:NAME{`` anchor is present, or the buffer ends inside a+ partial one that the next token could complete (``_GEMMA_BARE_TC_PREFIX_RE``, which+ the parser already keeps for exactly that reason). Every append is checked, so a call+ that arrives a character at a time is caught while it is still a partial.+ """+ best = -1+ for sentinel in _STRIP_SENTINELS:+ if sentinel == _GEMMA_BARE_SENTINEL:+ continue+ found = text.find(sentinel, start)+ if found >= 0 and (best < 0 or found < best):+ best = found+ at = start+ while True:+ found = text.find(_GEMMA_BARE_SENTINEL, at)+ if found < 0 or (0 <= best <= found):+ return best+ if _GEMMA_BARE_TC_RE.match(text, found) or _GEMMA_BARE_TC_PREFIX_RE.match(text, found):+ return found+ at = found + len(_GEMMA_BARE_SENTINEL)+++def _is_provisional_call(text: str, found: int) -> bool:+ """True when ``found`` is a ``call`` that only qualifies while it ends the buffer.++ ``_first_sentinel`` accepts such a hit because the next token may complete it, but+ the acceptance has to expire: the word ``call`` at a token boundary would otherwise+ pin the scan and put the full strip back on every later token.+ """+ return text.startswith(_GEMMA_BARE_SENTINEL, found) and not _GEMMA_BARE_TC_RE.match(text, found)+++def _unmatched_think_closer(text: str, start: int = 0) -> int:+ """Lowest index >= ``start`` of a reasoning closer with no opener ahead of it, or -1.++ A stray closer is what a prefilled reasoning turn looks like, and+ ``strip_outside_think`` handles it by synthesising a span that begins at offset 0 of+ the segment. Anything that changes where offset 0 sits therefore has to leave such a+ segment alone.+ """+ best = -1+ for opener, closer in (("<think>", "</think>"), ("[THINK]", "[/THINK]")):+ close_at = text.find(closer, start)+ if close_at < 0:+ continue+ open_at = text.find(opener, start)+ if 0 <= open_at < close_at:+ continue+ if best < 0 or close_at < best:+ best = close_at+ return best+++def _safe_cut(text: str, first: int) -> int:+ """Largest index <= ``first`` that no strip decision can depend on text before.++ Every arm anchors on a sentinel, so a match cannot begin before the first sentinel --+ with two exceptions, both of which reach backwards:++ * the rehearsal form is ``NAME[ARGS]{...}``, whose match starts at the name, before+ its ``[ARGS]`` sentinel. A name contains no whitespace, so backing up to the start+ of the preceding run covers it. (``[TOOL_CALLS] NAME[ARGS]`` needs no wider window:+ ``[TOOL_CALLS]`` is itself a sentinel, so it would be the first one found.)+ * the ``[TOOL_CALLS]`` and ``[ARGS]`` arms are gated on markdown code spans, and an+ opening fence can sit arbitrarily far back. If any backtick or tilde precedes the+ cut, no cut is safe.++ (The markerless Gemma arm reaches back to the start of the segment as well, but is+ handled by its caller rather than here: see ``StreamingMarkupStripper.strip``.)++ The result is then snapped back to a line start. The code-fence pattern is anchored+ with ``^``, so cutting mid-line can turn a fence that was mid-line into one that opens+ a block -- which flips the in-code gate and changes the output. Snapping to a newline+ keeps ``^`` meaning the same thing on the slice as on the whole buffer.+ """+ if first <= 0:+ return 0+ if len(text) > _tool_healing._MAX_BRACKET_SCAN_CHARS:+ # Past this length ``_strip_bracket_tag_calls`` stands down. Cutting would bring+ # the tail back under the limit and turn the arm back on, so leave it whole.+ return 0+ cut = first+ if text.startswith("[ARGS]", first):+ while cut > 0 and not text[cut - 1].isspace():+ cut -= 1+ cut = text.rfind("\n", 0, cut) + 1+ head = text[:cut]+ if "`" in head or "~" in head:+ return 0+ # A closer with no opener makes everything before it reasoning, which+ # ``_think_spans_outside_tool_markup`` decides from offset 0 of the segment. Trimming+ # moves offset 0, so cut only when there is nothing before that closer.+ close_at = _unmatched_think_closer(text)+ if 0 <= close_at and first < close_at:+ return 0+ # ``_strip_function_xml_calls`` treats a ``<function>`` opener inside an unclosed+ # ``<parameter>`` as a literal in an argument value, and decides that from the text+ # before it. Cutting there loses the context and the nested markup leaks into the+ # display. The literal test keeps the common case off the scan.+ if "<param" in head and _inside_open_parameter(text, cut):+ return 0+ return cut+++class StreamingMarkupStripper:+ """Strip tool markup from an append-only buffer without rescanning it every token.++ The streaming display path used to call the full strip on the entire accumulated+ response once per content token, which is a linear scan with ~10 regex passes per+ token and therefore quadratic in the response length. Two properties make that+ avoidable, both asserted by ``test_refactor_guard.py``:++ * text containing no sentinel from ``_STRIP_SENTINELS`` is returned unchanged, so a+ prose-only response does no regex work at all; and+ * no arm can match before the first sentinel, so+ ``strip(text) == text[:first] + strip(text[first:])``.++ The scan for that first sentinel resumes where the previous call stopped (overlapping+ by ``_SENTINEL_MAX_LEN - 1`` so a sentinel split across two appends is still seen),+ which makes the pre-markup phase amortized constant per token rather than linear.++ The instance assumes append-only growth: one instance per buffer, appended to, with+ ``reset()`` before a new buffer. A shorter buffer, or one whose sampled head, middle+ or previous tail no longer matches, re-derives the state, so an ordinary rewind is+ handled. That check samples rather than compares in full, because comparing in full+ would be linear in the buffer and reintroduce the cost this class removes, so it is a+ guard against misuse rather than a guarantee for arbitrary call sequences.+ """++ __slots__ = (+ "_enabled_tool_names",+ "_seg_final",+ "_scanned_upto",+ "_first",+ "_floor",+ "_floor_out",+ "_floor_identity",+ "_degenerate",+ "_open_at",+ "_open_scanned",+ "_seen_len",+ "_seen_head",+ "_seen_mid",+ "_seen_tail",+ )++ def __init__(+ self,+ enabled_tool_names: Optional[set] = None,+ *,+ seg_final: bool = True,+ ):+ self._enabled_tool_names = enabled_tool_names+ # Whether the last segment gets the end-of-turn arms. The tool-generation loop+ # wants them (partial markup must never render); the final-answer loop strips with+ # ``final = False`` and does not. The incremental machinery is the same either+ # way: fewer arms on the same sentinels, and ``_safe_cut``'s guards stay a superset.+ self._seg_final = seg_final+ self._reset()++ def _reset(self):+ self._scanned_upto = 0+ self._first = -1+ # Settled prefix: text below ``_floor`` is final, and ``_floor_out`` is its output.+ self._floor = 0+ self._floor_out = ""+ # True while nothing has been removed, which lets the sentinel-free path hand back+ # the caller's own string instead of rebuilding it every token.+ self._floor_identity = True+ # Set when non-reasoning markup sits at offset 0 of the unsettled text. Nothing can+ # then ever settle or be sliced off, so the bookkeeping is pure overhead on a strip+ # that must run in full anyway; this flag skips to it, so the worst case is no+ # slower than before.+ self._degenerate = False+ # Offset of the reasoning opener currently streaming, and how far its body is scanned.+ self._open_at = -1+ self._open_scanned = 0+ # Length and both end samples of the last buffer, never the buffer itself: see ``_note``.+ self._seen_len = -1+ self._seen_head = ""+ self._seen_mid = ""+ self._seen_tail = ""++ def _think_block(self, text: str, first: int) -> str:+ """Classify the reasoning block opening at absolute offset ``first``.++ Returns ``"settled"`` when a complete, unambiguous block was folded into the+ settled prefix, ``"open"`` when a clean block is still streaming (its content is+ preserved verbatim, so the whole buffer is currently unchanged), or ``""`` when+ the shape is anything else and the full strip has to run.++ ``strip_outside_think`` already processes each segment in isolation, so a segment+ boundary is a point nothing downstream can reach back across -- unlike a cut inside+ a segment, which is why this needs neither the line-start snap nor the backtick+ check that ``_safe_cut`` does.++ Deliberately conservative: it only fires on a block whose opener is the first+ sentinel in the remaining text and whose body carries no other markup. A+ ``</think>`` sitting inside a call's arguments is that call's data, not a closer,+ and this refuses to guess about it.+ """+ for opener, closer in (("<think>", "</think>"), ("[THINK]", "[/THINK]")):+ if text.startswith(opener, first):+ break+ else:+ return ""+ body_start = first + len(opener)+ # Resume inside the body, overlapping enough that a closer or sentinel split+ # across two appends is still seen.+ resume = body_start+ if self._open_at == first and self._open_scanned > body_start:+ resume = max(body_start, self._open_scanned - _SENTINEL_MAX_LEN + 1)+ end = text.find(closer, resume)+ if end < 0:+ # Still streaming. An unclosed block runs to EOF verbatim and the text before+ # it is markup-free, so the buffer is untouched unless something else needs+ # stripping. Scan from ``resume``, not from the opener: everything below it+ # was checked on an earlier token, and a reasoning body is most of a reasoning+ # model's answer, so restarting each token is the quadratic this class removes.+ if _first_sentinel(text, resume) >= 0:+ self._open_at = -1+ return ""+ self._open_at = first+ self._open_scanned = len(text)+ return "open"+ self._open_at = -1+ end += len(closer)+ body = text[self._floor : end]+ if _first_sentinel(body.replace(opener, "").replace(closer, ""), 0) >= 0:+ return ""+ settled = self._full_strip(body)+ self._floor_out += settled+ self._floor_identity = self._floor_identity and settled == body+ self._floor = end+ self._first = -1+ self._scanned_upto = end+ return "settled"++ def _needs_whole_buffer(self, text: str) -> bool:+ """True when no split of ``text`` is safe and the strip has to see all of it.++ Two shapes reach back to the start of a segment rather than to their own anchor:++ * the markerless Gemma arm keeps a whole-JSON or leading-JSON answer's+ ``call:NAME{...}`` examples visible as data, and earlier arms can leave behind+ a trimmed segment that is whole JSON when the untrimmed one was not; and+ * a reasoning closer with no opener, which makes offset 0 of the segment the+ thing ``_think_spans_outside_tool_markup`` decides from.++ Either way a split can delete text out of the user's answer, so the buffer is+ stripped whole instead. That is the pre-change cost, paid only by a buffer that+ actually holds one of these -- and only once markup is present, since this runs+ after the sentinel scan rather than in front of it.+ """+ return bool(_GEMMA_BARE_TC_RE.search(text, self._floor)) or (+ self._floor > 0 and _unmatched_think_closer(text, self._floor) >= 0+ )++ def _full_strip(self, text: str) -> str:+ def _seg(segment: str, is_last: bool) -> str:+ # Streaming has no separate ``final`` pass, so the last segment takes the+ # end-of-turn arms and partial markup never renders.+ return strip_segment(+ segment,+ seg_final = is_last and self._seg_final,+ enabled_tool_names = self._enabled_tool_names,+ )++ return _tool_healing.strip_outside_think(text, _seg)++ def reset(self):+ """Drop every cached prefix, for a caller starting a new buffer.++ The streaming caller keeps one instance for the whole request but begins a fresh+ ``cumulative_display`` in each tool iteration. ``_is_extension`` samples the ends+ rather than comparing, deliberately, so it cannot be relied on to notice: two+ buffers agreeing on a length and 64 bytes at each end are accepted, and the scan+ then resumes at an offset belonging to the previous iteration and never looks+ below it again. Saying so explicitly costs nothing and makes the sampled check+ exact for that caller, since within an iteration every mutation is an append.+ """+ self._reset()++ def _note(self, text: str):+ """Record what this call saw, as measurements rather than as the buffer.++ Holding a reference to the caller's string is what makes this expensive: the+ streaming loop grows it with ``cumulative_display += token``, and CPython can+ only resize a string in place while nothing else refers to it. One extra+ reference turns every append into a full copy, so the concatenation goes+ quadratic even though the scanning here does not. Measured over an append-only+ loop at 64k tokens: 1.14s holding the buffer, 0.003s holding these three.+ """+ self._seen_len = len(text)+ # A buffer at or under the sample size aliases itself here. Harmless: the copy+ # that forces is bounded by the sample size.+ self._seen_head = text[:_EXTENSION_SAMPLE]+ self._seen_tail = text[-_EXTENSION_SAMPLE:]+ mid = len(text) // 2+ self._seen_mid = text[mid : mid + _EXTENSION_SAMPLE]++ def _is_extension(self, text: str) -> bool:+ """Cheap check that ``text`` continues the previous call's buffer.++ A full ``startswith`` would be linear in the buffer and so reintroduce the+ quadratic cost this class exists to remove, so this samples three fixed windows+ instead: the head, the middle, and the previous buffer's last bytes. All three+ are O(1) and all three must still match.++ This is a guard against obvious misuse, not a proof. Two different buffers that+ agree on all three windows and on length would still be taken for a continuation;+ the middle window exists because head and tail alone missed the case where only+ the middle changed. The contract remains: one instance per buffer, appended to,+ and ``reset()`` before a new one. Both callers in this repo do exactly that.+ """+ end = self._seen_len+ if end < 0:+ return True+ if len(text) < end:+ return False+ sample = _EXTENSION_SAMPLE+ if text[:sample] != self._seen_head:+ return False+ if text[end - sample : end] != self._seen_tail:+ return False+ mid = end // 2+ return text[mid : mid + sample] == self._seen_mid++ def strip(self, text: str) -> str:+ if not self._is_extension(text):+ # Not an extension: the cached prefix no longer applies.+ self._reset()++ if self._degenerate:+ # Guarded on ``_floor``: with nothing settled the two arms are the same+ # expression, so the check would be two scans that cannot change the answer.+ out = (+ self._floor_out + self._full_strip(text[self._floor :])+ if self._floor and not self._needs_whole_buffer(text)+ else self._full_strip(text)+ )+ self._note(text)+ return out++ # Offsets stay absolute so the buffer is never sliced just to look for a sentinel;+ # a slice is linear per token and puts back the cost this class removes. Loop so+ # several reasoning blocks can settle in one call.+ while True:+ if self._first < 0:+ # Resume where the last scan stopped, overlapping just enough to catch a+ # sentinel straddling two appends. This is what keeps the pre-markup+ # phase from rescanning the whole buffer per token.+ resume = self._scanned_upto - _SENTINEL_MAX_LEN + 1+ found = _first_sentinel(text, resume if resume > self._floor else self._floor)+ if found < 0:+ self._scanned_upto = len(text)+ return self._unchanged(text)+ if _is_provisional_call(text, found):+ # A ``call`` that only qualifies because the buffer ends inside it.+ # One more token decides it, so commit nothing and resume here next+ # time. Committing would send every later token through the+ # whole-buffer checks below, and the ordinary word ``call`` lands on+ # a token boundary often enough to matter.+ self._scanned_upto = found+ return self._unchanged(text)+ self._first = found - self._floor+ state = self._think_block(text, self._floor + self._first)+ if state == "open":+ return self._unchanged(text)+ if state != "settled":+ break++ tail = text[self._floor :]+ # Markup at offset 0 of the unsettled text: the cut is 0 and stays 0 as the buffer+ # grows, and nothing can settle, so skip the bookkeeping from here on.+ self._degenerate = self._first == 0+ # Recomputed per call, not cached: the sentinel may have been found before the run+ # preceding it finished streaming, so re-deriving keeps the cut exact.+ cut = _safe_cut(tail, self._first)+ # After the cut, not before: with nothing settled and nothing to trim, the+ # whole-buffer strip below already is the split one, so these two scans would+ # decide nothing and an answer with markup near its front would pay them per token.+ if (cut or self._floor) and self._needs_whole_buffer(text):+ 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)+ out = self._floor_out + stripped if self._floor else stripped+ self._note(text)+ return out++ def _unchanged(self, text: str) -> str:+ """Result when nothing after the settled prefix needs stripping."""+ self._note(text)+ # With nothing removed the answer is the caller's own string, so hand it straight+ # back rather than rebuilding it a token at a time. Returned, not kept: holding a+ # reference is exactly what would stop the caller growing it in place.+ return text if self._floor_identity else self._floor_out + text[self._floor :]++def has_tool_signal(text: str) -> bool:return any(s in text for s in TOOL_XML_SIGNALS)diff --git a/studio/backend/tests/data/refactor_guard/ast_inventory.json b/studio/backend/tests/data/refactor_guard/ast_inventory.jsonindex 642ce965108..0534b947bf9 100644--- a/studio/backend/tests/data/refactor_guard/ast_inventory.json+++ b/studio/backend/tests/data/refactor_guard/ast_inventory.json@@ -858,6 +858,53 @@"REPROMPT_MAX_CHARS": {"kind": "assign"},+ "StreamingMarkupStripper": {+ "bases": [],+ "decorators": [],+ "kind": "class",+ "methods": {+ "__init__": {+ "decorators": [],+ "signature": "self, enabled_tool_names: Optional[set]=None, *, seg_final: bool=True"+ },+ "_full_strip": {+ "decorators": [],+ "signature": "self, text: str"+ },+ "_is_extension": {+ "decorators": [],+ "signature": "self, text: str"+ },+ "_needs_whole_buffer": {+ "decorators": [],+ "signature": "self, text: str"+ },+ "_note": {+ "decorators": [],+ "signature": "self, text: str"+ },+ "_reset": {+ "decorators": [],+ "signature": "self"+ },+ "_think_block": {+ "decorators": [],+ "signature": "self, text: str, first: int"+ },+ "_unchanged": {+ "decorators": [],+ "signature": "self, text: str"+ },+ "reset": {+ "decorators": [],+ "signature": "self"+ },+ "strip": {+ "decorators": [],+ "signature": "self, text: str"+ }+ }+ },"TOOL_ERROR_NUDGE": {"kind": "assign"},@@ -909,12 +956,18 @@"_EMBEDDED_MARKER_RE": {"kind": "assign"},+ "_EXTENSION_SAMPLE": {+ "kind": "assign"+ },"_FUNC_CLOSE_TAG_RE": {"kind": "assign"},"_GEMMA_ANCHOR_CLOSERS": {"kind": "assign"},+ "_GEMMA_BARE_SENTINEL": {+ "kind": "assign"+ },"_GEMMA_BARE_TC_PREFIX_RE": {"kind": "assign"},@@ -1038,6 +1091,12 @@"_REPEAT_TRAIL_PUNCT": {"kind": "assign"},+ "_SENTINEL_MAX_LEN": {+ "kind": "assign"+ },+ "_STRIP_SENTINELS": {+ "kind": "assign"+ },"_TC_END_TAG_RE": {"kind": "assign"},@@ -1095,6 +1154,11 @@"kind": "def","signature": "content: str"},+ "_first_sentinel": {+ "decorators": [],+ "kind": "def",+ "signature": "text: str, start: int"+ },"_gemma_balanced_brace_end": {"decorators": [],"kind": "def",@@ -1150,6 +1214,11 @@"kind": "def","signature": "text: str, pos: int"},+ "_is_provisional_call": {+ "decorators": [],+ "kind": "def",+ "signature": "text: str, found: int"+ },"_leading_json_value_end": {"decorators": [],"kind": "def",@@ -1240,6 +1309,11 @@"kind": "def","signature": "content: str, *, id_offset: int, allow_incomplete: bool=True"},+ "_safe_cut": {+ "decorators": [],+ "kind": "def",+ "signature": "text: str, first: int"+ },"_signal_inside_leading_wrapperless_gemma": {"decorators": [],"kind": "def",@@ -1283,6 +1357,11 @@"_trim_param_value": {"kind": "assign"},+ "_unmatched_think_closer": {+ "decorators": [],+ "kind": "def",+ "signature": "text: str, start: int=0"+ },"_whole_content_is_json_value": {"decorators": [],"kind": "def",diff --git a/studio/backend/tests/data/refactor_guard/golden_outputs.json b/studio/backend/tests/data/refactor_guard/golden_outputs.jsonindex a64c9a9b41a..f3ba76bc7f9 100644--- a/studio/backend/tests/data/refactor_guard/golden_outputs.json+++ b/studio/backend/tests/data/refactor_guard/golden_outputs.json@@ -5,6 +5,7 @@"_disabled_gemma_call_end_containing_signal": "0c729e5b5d323409e5cd1faa4f12bf74ce36d3262a53ca33ac4f1abdf1528611","_find_outside_json_strings": "f7a4f18776183812e63cae649a827973ca39ab2062f398840ed8bedc6e8c6aea","_first_foreign_tool_signal": "9c097a395b83ce19b9433c4a043986a50c4c2b310dc8018c52bb79e29a8ae816",+ "_first_sentinel": "0a353eefe33a3d276fa1f469306707ce44d3ddd68752eabee81a0dfc12eb3a15","_gemma_balanced_brace_end": "9c9a8cd028e69b56a15f17d2a7ce65ea04f75f09b618f6e91baa758cebc701fb","_gemma_body_brace_end": "ddae97cf5311cb80b9b8e8ace5c1e9dbd4a6cccd2fe49c1c790968a527e344c0","_gemma_call_is_anchored": "7b3e7bd82e97757f6369bfb0420a4c6c72570b1ed950b7e07480f05109a7f354",@@ -15,6 +16,7 @@"_gemma_parse_value": "51efb0454a30a6238dcb05b641b24b4e9954ba498b9d3cadd85a2d8e6fc754e4","_glm_value_close": "0e1b8de8b3632f135803573d4dd807bb3094bb17eef851a300d5a815360cac9a","_inside_open_parameter": "3ae52bcd608a5a31a0d7b2e520d91c612e4a17c4c678e99f971e627391d404a4",+ "_is_provisional_call": "06880f81dab32db455d739c5a48ea10a2810d7668f9fb142acc4b3bee1cabc5b","_leading_json_value_end": "91cda3d5eaa095f7f39776e836dbd8d4fa39e06b6f856d795cdb472013e4e217","_llama3_kv_value": "a736ea7b33cc5cdf1cc3e39a37e74cf6bc04462510e61ec67dbd0fb883f04a66","_marker_inside_leading_envelope": "c1d295882b8a347dd53f4091f22b07cc5209d6589d2b26a88fbc2fcd83d0ba60",@@ -33,6 +35,7 @@"_parse_mistral_array": "0bd038fd65d4bb4d239a56d4518453e6fd051c052c7aaa81e342c6e2fd18596d","_parse_mistral_tool_calls": "2ae4da3184a1dc1bc51112d518b74a802e0555562e7256a471bade7d486ab2d1","_parse_tool_call_json": "06430b767c1bd5b8d2b05ba783d95e04b9e8573331d2d4df561d55a57732ac9c",+ "_safe_cut": "89f6425f15ffdb1e29ac6499694cd3f1dedc8b1dc09f725c4cd50841e83b2999","_signal_inside_leading_wrapperless_gemma": "b0c119aa9207f580333210185d4abbe6fd84d936fbacb181f8cf9e4bc7271916","_skip_mistral_call_id": "00bd559e1139e3a728f3deed4fdc6da5ada6307a1a5661fbc74cd5cf1fd9850c","_strip_function_xml_calls": "a7aaa09ef7a2e5baa5213c0e188d62eae99d5959fc64c862adad6b8fb1c08a98",@@ -41,6 +44,7 @@"_strip_mistral_closed_calls": "7ebf4866dba733c640847d5c9229b97e37537114cd89dfbd7b05b14c810e1aba","_strip_mistral_reasoning": "d887d6a2447d5ffc1bd33ee864f8d7b659dce4d7d19748bb3efec882d38c3f36","_top_level_bare_json_name": "c163fc1b44ef9e8ca9f0b89e39d6549926b76ddef667fca061ed07f1c5080773",+ "_unmatched_think_closer": "b5b4b3f626ad29ba15abe8fe8cb66f978fa1fed89e6cf0a909f8f2ad3d1ba9d1","_whole_content_is_json_value": "84a53ad03ec850e98790b989a61241aea5883935c617943c9a89a810f8ed1f16","_xml_signal_inside_leading_bare_json": "e2f035c2538e13b465b6e9356549d4447ef6c7f2ed615edf59d3b2d62e5ad244","_xml_signal_inside_leading_mistral": "27154f3fd8e5919e0af7dbc2d5fe07cc6719f37b62ccc9f743eb084da1b9a7e5",diff --git a/studio/backend/tests/data/refactor_guard/runtime_inventory.json b/studio/backend/tests/data/refactor_guard/runtime_inventory.jsonindex 089f31ba00a..f5d481f6906 100644--- a/studio/backend/tests/data/refactor_guard/runtime_inventory.json+++ b/studio/backend/tests/data/refactor_guard/runtime_inventory.json@@ -12,6 +12,7 @@"RAG_SEARCH_CAP_NUDGE","RENDER_HTML_REPEAT_NUDGE","REPROMPT_MAX_CHARS",+ "StreamingMarkupStripper","TOOL_ERROR_NUDGE","TOOL_ERROR_PREFIXES","TOOL_XML_SIGNALS",@@ -29,8 +30,10 @@"_DEEPSEEK_R1_FUNC_MARKER","_DEEPSEEK_SEP","_EMBEDDED_MARKER_RE",+ "_EXTENSION_SAMPLE","_FUNC_CLOSE_TAG_RE","_GEMMA_ANCHOR_CLOSERS",+ "_GEMMA_BARE_SENTINEL","_GEMMA_BARE_TC_PREFIX_RE","_GEMMA_BARE_TC_RE","_GEMMA_KEY_RE",@@ -72,6 +75,8 @@"_OUTER_ENVELOPE_OPEN_RE","_REPEAT_LEAD_PUNCT","_REPEAT_TRAIL_PUNCT",+ "_SENTINEL_MAX_LEN",+ "_STRIP_SENTINELS","_TC_END_TAG_RE","_TC_FUNC_CLOSE_RE","_TC_FUNC_START_RE",@@ -87,6 +92,7 @@"_disabled_gemma_call_end_containing_signal","_find_outside_json_strings","_first_foreign_tool_signal",+ "_first_sentinel","_gemma_balanced_brace_end","_gemma_body_brace_end","_gemma_call_is_anchored",@@ -98,6 +104,7 @@"_gemma_strip_quoted_leaves","_glm_value_close","_inside_open_parameter",+ "_is_provisional_call","_leading_json_value_end","_llama3_kv_value","_marker_inside_leading_envelope",@@ -116,6 +123,7 @@"_parse_mistral_array","_parse_mistral_tool_calls","_parse_tool_call_json",+ "_safe_cut","_signal_inside_leading_wrapperless_gemma","_skip_mistral_call_id","_strip_function_xml_calls",@@ -126,6 +134,7 @@"_tool_healing","_top_level_bare_json_name","_trim_param_value",+ "_unmatched_think_closer","_whole_content_is_json_value","_xml_signal_inside_leading_bare_json","_xml_signal_inside_leading_mistral",@@ -151,6 +160,7 @@"_disabled_gemma_call_end_containing_signal": "core.inference.tool_call_parser._disabled_gemma_call_end_containing_signal(content: 'str', enabled_tool_names: 'Optional[set]') -> 'int | None'","_find_outside_json_strings": "core.inference.tool_call_parser._find_outside_json_strings(text: 'str', needle: 'str', start: 'int') -> 'int'","_first_foreign_tool_signal": "core.inference.tool_call_parser._first_foreign_tool_signal(content: 'str') -> 'int | None'",+ "_first_sentinel": "core.inference.tool_call_parser._first_sentinel(text: 'str', start: 'int') -> 'int'","_gemma_balanced_brace_end": "core.inference.tool_call_parser._gemma_balanced_brace_end(text: 'str', brace_pos: 'int', hard_stop: 'int') -> 'int | None'","_gemma_body_brace_end": "core.inference.tool_call_parser._gemma_body_brace_end(text: 'str', brace_pos: 'int') -> 'int | None'","_gemma_call_is_anchored": "core.inference.tool_call_parser._gemma_call_is_anchored(text: 'str', start: 'int', floor: 'int') -> 'bool'",@@ -162,6 +172,7 @@"_gemma_strip_quoted_leaves": "core.inference.tool_call_parser._gemma_strip_quoted_leaves(value: 'Any') -> 'Any'","_glm_value_close": "core.inference.tool_call_parser._glm_value_close(text: 'str', vs: 'int', *, strict: 'bool' = False) -> 'int'","_inside_open_parameter": "core.inference.tool_call_parser._inside_open_parameter(text: 'str', pos: 'int') -> 'bool'",+ "_is_provisional_call": "core.inference.tool_call_parser._is_provisional_call(text: 'str', found: 'int') -> 'bool'","_leading_json_value_end": "core.inference.tool_call_parser._leading_json_value_end(text: 'str') -> 'int | None'","_llama3_kv_value": "core.inference.tool_call_parser._llama3_kv_value(body: 'str', p: 'int', n: 'int') -> 'tuple[Any, int | None]'","_marker_inside_leading_envelope": "core.inference.tool_call_parser._marker_inside_leading_envelope(content: 'str', enabled_tool_names: 'Optional[set]' = None) -> 'bool'",@@ -180,6 +191,7 @@"_parse_mistral_array": "core.inference.tool_call_parser._parse_mistral_array(content: 'str', start: 'int', id_offset: 'int', allow_incomplete: 'bool' = True) -> 'list[dict]'","_parse_mistral_tool_calls": "core.inference.tool_call_parser._parse_mistral_tool_calls(content: 'str', *, id_offset: 'int', allow_incomplete: 'bool' = True) -> 'list[dict]'","_parse_tool_call_json": "core.inference.tool_call_parser._parse_tool_call_json(content: 'str', *, id_offset: 'int', allow_incomplete: 'bool' = True) -> 'list[dict]'",+ "_safe_cut": "core.inference.tool_call_parser._safe_cut(text: 'str', first: 'int') -> 'int'","_signal_inside_leading_wrapperless_gemma": "core.inference.tool_call_parser._signal_inside_leading_wrapperless_gemma(content: 'str', enabled_tool_names: 'Optional[set]') -> 'bool'","_skip_mistral_call_id": "core.inference.tool_call_parser._skip_mistral_call_id(text: 'str', pos: 'int') -> 'int'","_strip_function_xml_calls": "core.inference.tool_call_parser._strip_function_xml_calls(text: 'str', *, final: 'bool') -> 'str'",@@ -189,6 +201,7 @@"_strip_mistral_reasoning": "core.inference.tool_call_parser._strip_mistral_reasoning(content: 'str') -> 'str'","_top_level_bare_json_name": "core.inference.tool_call_parser._top_level_bare_json_name(probe: 'str') -> 'Optional[str]'","_trim_param_value": "core.tool_healing._trim_param_value(val: 'str') -> 'str'",+ "_unmatched_think_closer": "core.inference.tool_call_parser._unmatched_think_closer(text: 'str', start: 'int' = 0) -> 'int'","_whole_content_is_json_value": "core.inference.tool_call_parser._whole_content_is_json_value(text: 'str') -> 'bool'","_xml_signal_inside_leading_bare_json": "core.inference.tool_call_parser._xml_signal_inside_leading_bare_json(content: 'str') -> 'bool'","_xml_signal_inside_leading_mistral": "core.inference.tool_call_parser._xml_signal_inside_leading_mistral(content: 'str') -> 'bool'",diff --git a/studio/backend/tests/test_streaming_stripper.py b/studio/backend/tests/test_streaming_stripper.pynew file mode 100644index 00000000000..529d9f8b0b3--- /dev/null+++ b/studio/backend/tests/test_streaming_stripper.py@@ -0,0 +1,627 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Correctness proof for ``StreamingMarkupStripper``.++The incremental stripper is only sound if two claims hold, so both are tested directly+rather than assumed:++1. **Sentinel completeness** - text containing no literal from ``_STRIP_SENTINELS`` is+ returned unchanged by the strip. If an arm could fire without one of those literals,+ the fast path would silently skip a strip that should have happened.+2. **Prefix split** - ``strip(text) == text[:i] + strip(text[i:])`` for any ``i`` at or+ before the first sentinel. This is what lets the stripper keep a settled prefix.++On top of those, the whole thing is replayed token by token against the non-incremental+strip and asserted byte-identical at every step, over every chunking the corpus produces.+"""++import random+import sys+from pathlib import Path++import pytest++BACKEND_ROOT = Path(__file__).resolve().parents[1]+if str(BACKEND_ROOT) not in sys.path:+ sys.path.insert(0, str(BACKEND_ROOT))++from core import tool_healing # noqa: E402+from core.inference import tool_call_parser # noqa: E402+from core.inference.tool_call_parser import ( # noqa: E402+ _STRIP_SENTINELS,+ StreamingMarkupStripper,+ _first_sentinel,+ _safe_cut,+ strip_segment,+)++sys.path.insert(0, str(BACKEND_ROOT / "tests" / "tools"))+import refactor_guard # noqa: E402++ENABLED = {"get_weather", "search", "trunc", "broken"}+++def _reference_strip(text, enabled_tool_names = ENABLED):+ """The pre-refactor streaming strip: full rescan, no caching."""++ def _seg(segment, is_last):+ return strip_segment(segment, seg_final = is_last, enabled_tool_names = enabled_tool_names)++ return tool_healing.strip_outside_think(text, _seg)++[email protected](scope = "module")+def corpus():+ return refactor_guard.build_corpus()+++def _sentinel_free(text):+ return not any(sentinel in text for sentinel in _STRIP_SENTINELS)+++def test_sentinel_free_text_is_returned_unchanged(corpus):+ """Claim 1 over the corpus."""+ checked = 0+ for text in corpus:+ if not _sentinel_free(text):+ continue+ checked += 1+ assert _reference_strip(text) == text, f"strip altered sentinel-free text: {text!r}"+ assert checked, "corpus contained no sentinel-free input to check"+++def test_sentinel_free_fuzz_is_returned_unchanged():+ """Claim 1 over random text built from characters the markup is made of.++ Drawing from ``<>|[]{}/:=_`` and backticks rather than plain prose is what makes this+ a real test: it produces near-miss markup that a too-narrow sentinel list would let+ through.+ """+ rng = random.Random(20260811)+ alphabet = "<>|[]{}/:=_`~ \n\tabcTOOLCALSfunctionthinkARGSpython_tagcall"+ checked = 0+ for _ in range(20000):+ text = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 60)))+ if not _sentinel_free(text):+ continue+ checked += 1+ assert _reference_strip(text) == text, f"strip altered sentinel-free text: {text!r}"+ assert checked > 1000, f"fuzz produced too few sentinel-free samples ({checked})"+++def test_prefix_split_property(corpus):+ """Claim 2: splitting at ``_safe_cut`` does not change the result."""+ for text in corpus:+ first = _first_sentinel(text, 0)+ cut = _safe_cut(text, first) if first >= 0 else len(text)+ expected = _reference_strip(text)+ assert (+ text[:cut] + _reference_strip(text[cut:]) == expected+ ), f"prefix split at {cut} changed the result for {text!r}"+++def test_prefix_split_property_fuzz():+ """Claim 2 on random near-miss markup, where an off-by-one cut would show up."""+ rng = random.Random(20260813)+ alphabet = "<>|[]{}/:=_-`~ \n\tabcTOOLCALSfunctionthinkARGSpython_tagcall\"'0129"+ for _ in range(20000):+ text = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 80)))+ first = _first_sentinel(text, 0)+ cut = _safe_cut(text, first) if first >= 0 else len(text)+ assert text[:cut] + _reference_strip(text[cut:]) == _reference_strip(+ text+ ), f"prefix split at {cut} changed the result for {text!r}"+++def test_incremental_matches_reference_token_by_token(corpus):+ """The acceptance test: replay each corpus entry one character at a time."""+ for text in corpus:+ stripper = StreamingMarkupStripper(ENABLED)+ for end in range(len(text) + 1):+ prefix = text[:end]+ assert stripper.strip(prefix) == _reference_strip(+ prefix+ ), f"diverged at offset {end} of {text!r}"+++def test_incremental_matches_reference_for_random_chunkings(corpus):+ """Same, but with realistic multi-character token boundaries."""+ rng = random.Random(20260812)+ for text in corpus:+ stripper = StreamingMarkupStripper(ENABLED)+ pos = 0+ while pos < len(text):+ pos = min(len(text), pos + rng.randint(1, 7))+ prefix = text[:pos]+ assert stripper.strip(prefix) == _reference_strip(+ prefix+ ), f"diverged at offset {pos} of {text!r}"+++def test_incremental_matches_reference_on_fuzz():+ """Char-by-char replay on random near-miss markup, fences and newlines included."""+ rng = random.Random(20260814)+ alphabet = "<>|[]{}/:=_-`~ \n\tabcTOOLCALSfunctionthinkARGSpython_tagcall\"'0129"+ for _ in range(400):+ text = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 50)))+ stripper = StreamingMarkupStripper(ENABLED)+ for end in range(len(text) + 1):+ prefix = text[:end]+ assert stripper.strip(prefix) == _reference_strip(+ prefix+ ), f"diverged at offset {end} of {text!r}"+++def test_rewind_resets_cached_state():+ """A caller that does not append monotonically still gets the right answer."""+ stripper = StreamingMarkupStripper(ENABLED)+ long_text = 'hello <tool_call>{"name": "search", "arguments": {}}</tool_call> world'+ assert stripper.strip(long_text) == _reference_strip(long_text)+ # Unrelated shorter text: not an extension of the previous input.+ assert stripper.strip("different") == _reference_strip("different")+ assert stripper.strip(long_text) == _reference_strip(long_text)+++def test_repeated_call_is_cached():+ stripper = StreamingMarkupStripper(ENABLED)+ text = "no markup here at all"+ assert stripper.strip(text) is stripper.strip(text)+++def test_scan_is_amortized_not_quadratic():+ """A prose-only response must not cost more per token as it grows.++ Measures work rather than wall clock: the reference does a full pass per token, so+ its total character-visits grow quadratically; the incremental stripper resumes its+ scan and must stay linear. Compared as a ratio so the assertion is machine+ independent.+ """+ import time++ def elapsed(fn, tokens):+ text = ""+ start = time.perf_counter()+ for token in tokens:+ text += token+ fn(text)+ return time.perf_counter() - start++ short = ["word " for _ in range(300)]+ long = ["word " for _ in range(1200)]++ def incremental(tokens):+ stripper = StreamingMarkupStripper(ENABLED)+ return elapsed(stripper.strip, tokens)++ # 4x the tokens: the reference rescans everything (~16x), the incremental one resumes+ # (~4x). Comparing growth ratios rather than absolutes keeps this meaningful on a+ # noisy CI box while still catching a regression to full rescanning.+ reference_growth = elapsed(_reference_strip, long) / max(elapsed(_reference_strip, short), 1e-9)+ incremental_growth = incremental(long) / max(incremental(short), 1e-9)++ assert incremental_growth < reference_growth / 2, (+ f"incremental cost grew {incremental_growth:.1f}x vs the reference's "+ f"{reference_growth:.1f}x; expected roughly linear against its quadratic"+ )+++# Cases the corpus and the alphabet fuzz both missed. Each produced a real divergence from+# the reference strip before the guard it names was added, so each is pinned as a literal.+_MISSED_BY_THE_CORPUS = (+ # ``_GEMMA_BARE_TC_RE`` is ``call\s*:``, so a space or newline before the colon is+ # still a call. Sentinel completeness needs the literal ``call``, not ``call:``.+ "call :get_weather{city:Paris}",+ "call\n:get_weather{city:Paris}",+ "The answer.\ncall : get_weather{city:Paris}",+ # A JSON answer is data: its ``call:NAME{...}`` examples stay visible. That decision+ # keys on the whole segment, so trimming the segment must not reach it.+ '{\n "tool_syntax": "call:get_weather{city:Paris}",\n "note": "example"\n}',+ '[\n "call:search{q:1}"\n]',+ # Earlier arms can leave behind a segment that is whole JSON when the untrimmed one+ # was not, which is the same hazard arrived at from the other side.+ 'answer\n[TOOL_CALLS]search[ARGS]{"q":1}{\n "k": "call:get_weather{c:P}"\n}',+ # A reasoning closer with no opener makes offset 0 of the segment meaningful, so+ # nothing may be trimmed off the front of it.+ '\n[TOOL_CALLS]search[ARGS]{"q":1}[/THINK]<function=search>{}</function>',+ '[THINK]r[/THINK]<function name="s">{}</function>[/THINK]tail',+)++[email protected]("text", _MISSED_BY_THE_CORPUS)[email protected]("enabled", [ENABLED, None])+def test_incremental_matches_reference_on_known_hard_cases(text, enabled):+ stripper = StreamingMarkupStripper(enabled)+ for size in range(1, len(text) + 1):+ prefix = text[:size]+ assert stripper.strip(prefix) == _reference_strip(+ prefix, enabled+ ), f"diverged at {size} for {text!r}"++[email protected]("text", _MISSED_BY_THE_CORPUS)+def test_known_hard_cases_are_still_sentinel_reachable(text):+ """Each hard case must carry a sentinel, or claim 1 is what is broken."""+ assert not _sentinel_free(text)+++def test_incremental_matches_reference_on_structured_fuzz():+ """Fuzz built from whole markup fragments rather than from an alphabet.++ The alphabet fuzz above rarely assembles a complete, well-formed call, which is why+ it missed every case in ``_MISSED_BY_THE_CORPUS``. Splicing real fragments reaches+ the arms that only fire on a complete one.+ """+ fragments = _MISSED_BY_THE_CORPUS + (+ "Hello world. ",+ "I will call the tool. ",+ "<think>reasoning</think>",+ "[THINK]r[/THINK]",+ "[/THINK]",+ "</think>",+ "```py\ncode\n```\n",+ "~~~\nx\n~~~\n",+ '<tool_call>{"name": "search"}</tool_call>',+ "<function=search>{}</function>",+ '[TOOL_CALLS]search[ARGS]{"q": 1}',+ 'get_weather[ARGS]{"a": 1}',+ "<|python_tag|>x",+ "<|tool_call>call:search{q:1}<tool_call|>",+ "recall: not a call",+ )+ rng = random.Random(20260811)+ for _ in range(3000):+ text = "".join(rng.choice(fragments) for _ in range(rng.randint(1, 4)))+ enabled = rng.choice([ENABLED, None, set()])+ stripper = StreamingMarkupStripper(enabled)+ for size in range(1, len(text) + 1):+ prefix = text[:size]+ assert stripper.strip(prefix) == _reference_strip(+ prefix, enabled+ ), f"diverged at {size} for {text!r}"+++def test_prose_containing_the_word_call_is_still_amortized():+ """``call`` is a sentinel and an ordinary English word.++ Taking it at face value put the full strip back on the per-token path for any answer+ that says "I will call the tool", which measured slower than the code this replaces.+ ``_first_sentinel`` confirms the hit against the arm instead, and this pins that.+ """+ import time++ def elapsed(fn, tokens):+ text = ""+ start = time.perf_counter()+ for token in tokens:+ text += token+ fn(text)+ return time.perf_counter() - start++ short = ["I will call it. " for _ in range(300)]+ long = ["I will call it. " for _ in range(1200)]++ def incremental(tokens):+ return elapsed(StreamingMarkupStripper(ENABLED).strip, tokens)++ reference_growth = elapsed(_reference_strip, long) / max(elapsed(_reference_strip, short), 1e-9)+ incremental_growth = incremental(long) / max(incremental(short), 1e-9)++ assert incremental_growth < reference_growth / 2, (+ f"incremental cost grew {incremental_growth:.1f}x vs the reference's "+ f"{reference_growth:.1f}x on prose containing the word 'call'"+ )+++def test_a_real_bare_call_is_still_seen_as_a_sentinel():+ """The other side of the same refinement: a real call must not be skipped.++ Including while it is still a partial, which is the state the buffer is in for every+ token but the last one of it.+ """+ text = "Sure. call:get_weather{city:Paris}"+ for size in range(text.index("call") + len("call"), len(text) + 1):+ assert _first_sentinel(text[:size], 0) == text.index(+ "call"+ ), f"lost the call anchor at {size}: {text[:size]!r}"+ assert _first_sentinel("Please call me back tomorrow.", 0) == -1+ assert _first_sentinel("I made a call: yesterday it worked.", 0) == -1+++def test_the_bracket_scan_size_guard_survives_a_prefix_cut():+ """``_strip_bracket_tag_calls`` stands down over ``_MAX_BRACKET_SCAN_CHARS``.++ A cut shortens the segment, so a tail that fell under the limit would re-enable an+ arm the full scan had skipped and strip text the reference keeps.+ """+ prose = "word " * ((tool_healing._MAX_BRACKET_SCAN_CHARS // 5) + 1)+ text = prose + '\nsearch[ARGS]{"x": 1} tail'+ assert len(text) > tool_healing._MAX_BRACKET_SCAN_CHARS++ stripper = StreamingMarkupStripper(ENABLED)+ stripper.strip(prose)++ assert stripper.strip(text) == _reference_strip(text)+++def test_a_prose_call_at_a_token_boundary_stays_amortized():+ """``call`` ending a token is only a possible marker, and only until the next one.++ Committing that hit sends every later token through the whole-buffer checks, so the+ cost depended on where the tokenizer happened to split rather than on the text. This+ measures the same text under two chunkings; they have to stay comparable.+ """+ import time++ def elapsed(tokens):+ stripper = StreamingMarkupStripper(ENABLED)+ text = ""+ start = time.perf_counter()+ for token in tokens:+ text += token+ stripper.strip(text)+ return time.perf_counter() - start++ split = elapsed(["I will call", " it now. "] * 800)+ joined = elapsed(["I will call it now. "] * 800)++ assert (+ split < joined * 20 + 0.5+ ), f"a token boundary after 'call' cost {split:.3f}s against {joined:.3f}s joined"+++def test_a_real_call_arriving_a_character_at_a_time_is_still_caught():+ text = "Sure. call:search{q: 1} done"+ stripper = StreamingMarkupStripper(ENABLED)+ for size in range(1, len(text) + 1):+ assert stripper.strip(text[:size]) == _reference_strip(text[:size])+++def test_the_caller_can_still_grow_its_buffer_in_place():+ """The stripper must not hold a reference to the buffer it is handed.++ The streaming loop grows it with ``cumulative_display += token``, and CPython only+ resizes a string in place while nothing else refers to it. One extra reference turns+ every append into a full copy, so the concatenation goes quadratic even though the+ scanning does not, and that cost lands on the caller rather than here.+ """+ import time++ def elapsed(count):+ stripper = StreamingMarkupStripper(ENABLED)+ text = ""+ start = time.perf_counter()+ for _ in range(count):+ text += "word "+ stripper.strip(text)+ return time.perf_counter() - start++ short = elapsed(8000)+ long = elapsed(32000)++ # 4x the tokens. Linear in place, ~16x if every append copies the answer so far.+ assert long < short * 8 + 0.05, (+ f"4x the tokens cost {long / max(short, 1e-9):.1f}x the time "+ f"({short:.3f}s -> {long:.3f}s); the buffer is being copied per token"+ )+++def test_no_reference_to_the_buffer_is_retained():+ """The property the timing above measures, asserted directly."""+ import gc++ stripper = StreamingMarkupStripper(ENABLED)+ text = "some plain prose with no markup in it at all" * 4+ stripper.strip(text)++ assert not [+ holder+ for holder in gc.get_referrers(text)+ if holder is stripper.__class__ or holder is stripper+ ]+ assert all(getattr(stripper, slot) is not text for slot in StreamingMarkupStripper.__slots__)+++def test_reset_clears_the_cached_prefix_for_a_new_buffer():+ """The streaming caller keeps one instance across tool iterations, and each iteration+ starts a fresh ``cumulative_display``. ``_is_extension`` samples rather than compares,+ so it cannot be relied on to notice: a new buffer that agreed with the old one on+ length and on every sampled window would be accepted, the scan would resume at an+ offset from the previous iteration and never look below it again. The caller says so+ explicitly rather than depending on the sampling to catch it.+ """+ stripper = StreamingMarkupStripper(ENABLED)++ first = "x" * 200 + '<tool_call>{"name": "search", "arguments": {}}</tool_call>' + "y" * 200+ stripper.strip(first)++ second = first[:64] + "z" * (len(first) - 128) + first[-64:]+ assert len(second) == len(first) and second != first++ stripper.reset()++ assert stripper.strip(second) == _reference_strip(second)+++def test_early_markup_is_not_slower_than_the_code_it_replaces():+ """Once the cut is 0 and nothing is settled, both arms are the same strip.++ Paying the whole-buffer checks there cannot change the answer, and an answer with+ markup near its front would pay them on every token for the rest of the turn, which+ measured slower than the full rescan this replaces.+ """+ import time++ prefix = '`x` <tool_call>{"name": "search", "arguments": {}}</tool_call> '++ def elapsed(fn, count):+ text = prefix+ start = time.perf_counter()+ for _ in range(count):+ text += "word "+ fn(text)+ return time.perf_counter() - start++ count = 1500+ reference = min(elapsed(_reference_strip, count) for _ in range(3))+ incremental = min(elapsed(StreamingMarkupStripper(ENABLED).strip, count) for _ in range(3))++ assert (+ incremental <= reference * 1.10+ ), f"early markup cost {incremental:.3f}s against the reference's {reference:.3f}s"+++def test_an_open_reasoning_block_is_scanned_incrementally():+ """A reasoning body is most of a reasoning model's answer.++ The open-block branch restarted at the opener on every token, so the body was+ rescanned in full each time: the same quadratic this class exists to remove, with a+ smaller constant. 16k tokens cost 7.4s before this and 0.05s after.+ """+ import time++ def elapsed(count):+ stripper = StreamingMarkupStripper(ENABLED)+ text = "<think>"+ start = time.perf_counter()+ for _ in range(count):+ text += "reasoning "+ stripper.strip(text)+ return time.perf_counter() - start++ short = elapsed(2000)+ long = elapsed(8000)++ # 4x the tokens. Linear resumes at ~4x; restarting at the opener is ~16x.+ assert long < short * 8 + 0.05, (+ f"4x the tokens cost {long / max(short, 1e-9):.1f}x the time "+ f"({short:.4f}s -> {long:.4f}s); the reasoning body is being rescanned"+ )+++ "text",+ [+ "<think>reasoning goes here</think>the answer",+ "<think>reasoning with get_weather[ARGS]{} inside</think>answer",+ "[THINK]other family[/THINK]answer",+ "<think>unclosed to the end",+ "<think>a</think>b<think>c</think>d",+ "<think>mentions </think> early</think>tail",+ ],+)+def test_open_block_resume_does_not_change_the_result(text):+ """The resume must not miss a closer or a sentinel arriving mid-body."""+ stripper = StreamingMarkupStripper(ENABLED)+ for size in range(1, len(text) + 1):+ assert stripper.strip(text[:size]) == _reference_strip(+ text[:size]+ ), f"diverged at {size} for {text!r}"+++def _reference_strip_non_final(text, enabled_tool_names = ENABLED):+ """What the final-answer loop asks for: no end-of-turn arms."""+ from core.inference.tool_call_parser import strip_tool_markup+ return strip_tool_markup(text, final = False, enabled_tool_names = enabled_tool_names)+++ "text",+ [+ 'Sure.<tool_call>{"name": "get_weather", "arguments": {}}</tool_call>Done.',+ "call:get_weather{city:Paris} tail",+ "get_weather[ARGS]",+ '[TOOL_CALLS]get_weather[ARGS]{"c": 1} after',+ "<think>r</think>answer",+ "```\nget_weather[ARGS]{}\n```\n",+ "prose with no markup at all",+ ],+)+def test_non_final_stripper_matches_the_non_final_strip(text):+ """The final-answer loop after the tool budget is spent calls the strip with+ ``final = False``, which leaves the end-of-turn arms off. Sharing the tool loop's+ instance would silently turn them on, so it gets its own with the flag."""+ stripper = StreamingMarkupStripper(ENABLED, seg_final = False)+ for size in range(1, len(text) + 1):+ assert stripper.strip(text[:size]) == _reference_strip_non_final(+ text[:size]+ ), f"diverged at {size} for {text!r}"+++def test_the_final_answer_loop_is_not_quadratic():+ """That loop ran the whole strip over the growing buffer on every token.++ It is reached when the tool-iteration budget is exhausted, which is uncommon, but it+ was the largest single cost left in this file: 50s over a 16k-token answer.+ """+ import time++ def elapsed(fn, count):+ text = ""+ start = time.perf_counter()+ for _ in range(count):+ text += "word "+ fn(text)+ return time.perf_counter() - start++ count = 4000+ before = elapsed(_reference_strip_non_final, count)+ after = elapsed(StreamingMarkupStripper(ENABLED, seg_final = False).strip, count)++ assert (+ after < before / 10+ ), f"final-answer strip cost {after:.4f}s against the full rescan's {before:.4f}s"+++def test_a_cut_never_crosses_an_open_parameter_block():+ """``_strip_function_xml_calls`` treats a ``<function>`` opener inside an unclosed+ ``<parameter>`` as a literal in an argument value, and decides that from the text+ before it. Cutting there used to lose the context and leak the nested markup."""+ names = {"a"}+ for text in (+ "Visible <parameter=x>\n<function=a></function>TEXT</function>",+ 'Visible <param name="x">\n<function=a></function>TEXT</function>',+ ):+ expected = _reference_strip(text, names)+ stripper = StreamingMarkupStripper(names)+ got = None+ for i in range(1, len(text) + 1):+ got = stripper.strip(text[:i])+ assert got == expected+ assert "TEXT</function>" not in got++ # A closed parameter block still gets cut, so the guard is not blanket.+ closed = "Visible <parameter=x>v</parameter>\n<function=a></function>TEXT</function>"+ stripper = StreamingMarkupStripper(names)+ for i in range(1, len(closed) + 1):+ got = stripper.strip(closed[:i])+ assert got == _reference_strip(closed, names)+++def test_a_replaced_middle_is_not_taken_for_a_continuation():+ """The extension check samples rather than compares in full, so it has to sample+ somewhere the difference can show. Head and tail alone missed a buffer whose middle+ was replaced while both ends and the length stayed put, and the stripper then skipped+ rescanning the part that changed and returned a stale answer."""+ sample = tool_call_parser._EXTENSION_SAMPLE+ names = {"a"}+ first = "A" * sample + "x" * 11 + "Z" * sample+ second = "A" * sample + "<tool_call>" + "Z" * sample+ assert len(first) == len(second)++ stripper = StreamingMarkupStripper(names)+ stripper.strip(first)+ assert stripper._is_extension(second) is False+ assert stripper.strip(second) == _reference_strip(second, names)+++def test_an_append_only_stream_is_still_recognised_as_a_continuation():+ """Control for the test above: the extra sample must not push the ordinary+ append-only case onto the slow path, which is the whole point of the class."""+ names = {"a"}+ text = "some prose " * 400+ stripper = StreamingMarkupStripper(names)+ stripper.strip(text[:500])+ for i in range(600, len(text), 100):+ assert stripper._is_extension(text[:i]) is True+ stripper.strip(text[:i])diff --git a/studio/backend/tests/tools/refactor_guard.py b/studio/backend/tests/tools/refactor_guard.pyindex dd5aae078f5..73b54f7d256 100644--- a/studio/backend/tests/tools/refactor_guard.py+++ b/studio/backend/tests/tools/refactor_guard.py@@ -285,6 +285,10 @@ _ARG_FIXTURES = {"n": lambda text: len(text),"vs": lambda text: 0,"needle": lambda text: "[",+ # ``_safe_cut`` wants the real first-sentinel offset: at 0 it returns 0 for every+ # input and pins nothing.+ "first": lambda text: _parser_first_sentinel(text),+ "found": lambda text: max(_parser_first_sentinel(text), 0),"out": lambda text: [],"previous": lambda text: text,"markers": lambda text: _tool_healing_build_markers(text),