Skip to content

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.

Studio: linear-time tool signal scanning in the safetensors and healer paths (#8494)

Daniel Han9a3a30e71302
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index 73d03f7d3f2..3a764b0e0f3 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -33,6 +33,7 @@ from core.inference.tool_call_parser import (
NUDGE_TOOL_CALLS_STATUS,
RAG_MAX_SEARCHES_PER_TURN,
RAG_SEARCH_CAP_NUDGE,
+ StreamingMarkupStripper,
TOOL_XML_SIGNALS,
is_reprompt_repeat,
is_short_intent_without_action,
@@ -84,14 +85,9 @@ _MAX_BARE_JSON_BUFFER = 16384
# exact-duplicate calls and cap the count so a runaway turn cannot fan out.
_MAX_TOOL_CALLS_PER_TURN = 8
-
-def _active_tool_names(active_tools: list[dict]) -> list[str]:
- names = [
- (tool.get("function") or {}).get("name")
- for tool in active_tools
- if isinstance(tool, dict) and isinstance(tool.get("function"), dict)
- ]
- return [name for name in names if name]
+# Enough settled text to catch a protocol literal split across two cumulative snapshots.
+# ``_rehearsal_name_start`` still walks back through the candidate when the split is ``[ARGS]``.
+_TOOL_SIGNAL_OVERLAP = max(map(len, TOOL_XML_SIGNALS)) - 1
def _active_tool_names(active_tools: list[dict]) -> list[str]:
@@ -175,6 +171,7 @@ def _earliest_tool_signal(
active_tools: list[dict],
*,
unrestricted: bool = False,
+ start: int = 0,
) -> int:
"""Index where the turn's first genuine tool-call boundary begins, or -1.
@@ -185,11 +182,11 @@ def _earliest_tool_signal(
best = -1
for sig in signals:
if sig != "[ARGS]":
- p = candidate.find(sig)
+ p = candidate.find(sig, start)
if p >= 0 and (best < 0 or p < best):
best = p
continue
- from_idx = 0
+ from_idx = start
while True:
p = candidate.find("[ARGS]", from_idx)
if p < 0:
@@ -347,8 +344,8 @@ _MISTRAL_RENDER_NAME_RE = re.compile(
_REHEARSAL_RENDER_NAME_RE = re.compile(r"(?<!\[CALL_ID\])\b([\w-]+)\[ARGS\]\s*(?=\{)")
-def _detect_render_html_tool_start(content: str) -> bool:
- """Return True when the FIRST tool call in ``content`` is clearly render_html.
+def _first_detected_tool_name(content: str) -> Optional[str]:
+ """Return the first clearly resolved tool name, or None while incomplete.
Covers every serialization the loop executes (XML ``<function=>`` / ``<tool_call>``,
Mistral ``[TOOL_CALLS]``, rehearsal ``NAME[ARGS]``); the earliest marker wins so a
@@ -396,9 +393,14 @@ def _detect_render_html_tool_start(content: str) -> bool:
break
if not candidates:
- return False
+ return None
_pos, name = min(candidates, key = lambda c: c[0])
- return name == "render_html"
+ return name or None
+
+
+def _detect_render_html_tool_start(content: str) -> bool:
+ """Return True when the FIRST tool call in ``content`` is clearly render_html."""
+ return _first_detected_tool_name(content) == "render_html"
def _coerce_arguments_with_provenance(
@@ -615,6 +617,18 @@ def run_safetensors_tool_loop(
# Gate the markerless bare-JSON form on enabled names so an ordinary JSON answer isn't misread as a call.
_enabled_tool_names = None if unrestricted_tools else set(_active_tool_names(active_tools))
+ # This loop receives cumulative snapshots, so keep both whole-prefix scans
+ # incremental: the stripper settles safe prefixes, the signal detector resumes
+ # with enough overlap for a literal split across snapshots.
+ _streaming_stripper = StreamingMarkupStripper(_enabled_names_gate)
+ _tool_signal_scanned_upto = 0
+
+ def _strip_streaming_display(text: str) -> str:
+ if not (auto_heal_tool_calls or tool_protocol_active):
+ return text
+ # Safetensors-only Magistral leading-reasoning removal first, then the shared strip.
+ return _streaming_stripper.strip(_strip_mistral_reasoning(text))
+
detect_state = _state_buffering
content_buffer = ""
content_accum = ""
@@ -642,6 +656,29 @@ def run_safetensors_tool_loop(
and not (permission_mode == "auto" and is_always_safe_tool("render_html"))
)
+ def _should_start_provisional_render_html(content: str) -> bool:
+ # Every part of this is re-resolved per chunk, exactly as before. The gates
+ # are a dict lookup and a scan of a handful of tools, so hoisting them saves
+ # nothing measurable and would bake in an invariant nothing enforces:
+ # active_tools is handed to the injectable single_turn callback, which is
+ # free to append to it while generating.
+ #
+ # The name lookup is likewise not cached. The first call's name is not final
+ # until its marker completes: a truncated ``<function=rende`` ahead of a
+ # finished ``<function=get_weather>`` reads as get_weather until it closes,
+ # then as render_html, so caching the first answer would drop the panel.
+ if (
+ _tool_succeeded("render_html")
+ or _provisional_confirm_gated
+ or provisional_render_html_started
+ ):
+ return False
+ if not any(
+ ((tool.get("function") or {}).get("name") == "render_html") for tool in active_tools
+ ):
+ return False
+ return _first_detected_tool_name(content) == "render_html"
+
gen = _call_single_turn(single_turn, conversation, active_tools)
prev_cumulative = ""
@@ -679,16 +716,7 @@ def run_safetensors_tool_loop(
content_accum += delta
if detect_state == _state_draining:
- if (
- not _tool_succeeded("render_html")
- and not _provisional_confirm_gated
- and any(
- ((tool.get("function") or {}).get("name") == "render_html")
- for tool in active_tools
- )
- and not provisional_render_html_started
- and _detect_render_html_tool_start(content_accum)
- ):
+ if _should_start_provisional_render_html(content_accum):
provisional_render_html_started = True
yield {
"type": "tool_start",
@@ -728,31 +756,21 @@ def run_safetensors_tool_loop(
# Earliest genuine boundary: bare [ARGS] in prose is skipped; a real NAME[ARGS] is
# pulled back to NAME so the name is not flushed.
signal_pos = _earliest_tool_signal(
- candidate, tool_xml_signals, _detect_tools, unrestricted = unrestricted_tools
+ candidate,
+ tool_xml_signals,
+ _detect_tools,
+ unrestricted = unrestricted_tools,
+ start = max(0, _tool_signal_scanned_upto - _TOOL_SIGNAL_OVERLAP),
)
if signal_pos >= 0:
before_tool = candidate[:signal_pos]
- cleaned_before = strip_tool_markup_streaming(
- before_tool,
- auto_heal_tool_calls = auto_heal_tool_calls,
- tool_protocol_active = tool_protocol_active,
- enabled_tool_names = _enabled_names_gate,
- )
+ cleaned_before = _strip_streaming_display(before_tool)
if len(cleaned_before) > len(last_emitted):
last_emitted = cleaned_before
yield {"type": "content", "text": cleaned_before}
cumulative_display = candidate
detect_state = _state_draining
- if (
- not _tool_succeeded("render_html")
- and not _provisional_confirm_gated
- and any(
- ((tool.get("function") or {}).get("name") == "render_html")
- for tool in active_tools
- )
- and not provisional_render_html_started
- and _detect_render_html_tool_start(content_accum)
- ):
+ if _should_start_provisional_render_html(content_accum):
provisional_render_html_started = True
yield {
"type": "tool_start",
@@ -769,13 +787,9 @@ def run_safetensors_tool_loop(
}
_live_args_streamed_upto = len(content_accum)
continue
+ _tool_signal_scanned_upto = len(candidate)
cumulative_display = candidate
- cleaned = strip_tool_markup_streaming(
- cumulative_display,
- auto_heal_tool_calls = auto_heal_tool_calls,
- tool_protocol_active = tool_protocol_active,
- enabled_tool_names = _enabled_names_gate,
- )
+ cleaned = _strip_streaming_display(cumulative_display)
# Hold a trailing bare active-tool-name (split rehearsal) until its [ARGS] arrives;
# released by later prose or the end-of-stream flush.
if tool_protocol_active:
@@ -896,26 +910,12 @@ def run_safetensors_tool_loop(
# Tool signal -- flush any visible prefix before DRAINING
# so the route sends it before tool_start.
cumulative_display += content_buffer
- cleaned = strip_tool_markup_streaming(
- cumulative_display,
- auto_heal_tool_calls = auto_heal_tool_calls,
- tool_protocol_active = tool_protocol_active,
- enabled_tool_names = _enabled_names_gate,
- )
+ cleaned = _strip_streaming_display(cumulative_display)
if len(cleaned) > len(last_emitted):
last_emitted = cleaned
yield {"type": "content", "text": cleaned}
detect_state = _state_draining
- if (
- not _tool_succeeded("render_html")
- and not _provisional_confirm_gated
- and any(
- ((tool.get("function") or {}).get("name") == "render_html")
- for tool in active_tools
- )
- and not provisional_render_html_started
- and _detect_render_html_tool_start(content_accum)
- ):
+ if _should_start_provisional_render_html(content_accum):
provisional_render_html_started = True
yield {
"type": "tool_start",
@@ -937,12 +937,7 @@ def run_safetensors_tool_loop(
else:
detect_state = _state_streaming
cumulative_display += content_buffer
- cleaned = strip_tool_markup_streaming(
- cumulative_display,
- auto_heal_tool_calls = auto_heal_tool_calls,
- tool_protocol_active = tool_protocol_active,
- enabled_tool_names = _enabled_names_gate,
- )
+ cleaned = _strip_streaming_display(cumulative_display)
# Same trailing-name hold as STREAMING for this first flush out of BUFFERING.
if tool_protocol_active:
_hold = _held_rehearsal_tail_len(
@@ -1060,12 +1055,7 @@ def run_safetensors_tool_loop(
else:
# Turn ended as a plain answer (no [ARGS] followed): the held rehearsal tail is real
# prose, release it.
- final_clean = strip_tool_markup_streaming(
- cumulative_display,
- auto_heal_tool_calls = auto_heal_tool_calls,
- tool_protocol_active = tool_protocol_active,
- enabled_tool_names = _enabled_names_gate,
- )
+ final_clean = _strip_streaming_display(cumulative_display)
if len(final_clean) > len(last_emitted):
yield {"type": "content", "text": final_clean}
yield {"type": "status", "text": ""}
diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.py
index e1574acee4b..c8da02f5008 100644
--- a/studio/backend/core/inference/tool_call_parser.py
+++ b/studio/backend/core/inference/tool_call_parser.py
@@ -697,8 +697,40 @@ def strip_segment(
# data. Qwen <tool_call>{json} is left to the regex arms.
seg = _strip_glm_calls(seg, final = seg_final)
pats = _TOOL_ALL_PATS if seg_final else _TOOL_CLOSED_PATS
- for pat in pats:
- seg = pat.sub("", seg)
+ required_pairs = (
+ ("</tool_call>", "<tool_call>"),
+ ("</function>", "<function"),
+ ("<tool_call|>", "<|tool_call>"),
+ ("]", "[TOOL_CALLS]"),
+ ("}", "[TOOL_CALLS]"),
+ ("<|tool▁calls▁end|>", "<|"),
+ ("<|tool_calls_section_end|>", "<|tool_calls_section_begin|>"),
+ ("<|tool_call_end|>", "<|tool_call_begin|>"),
+ )
+ for pat_idx, pat in enumerate(pats):
+ if pat_idx < len(required_pairs):
+ token, opener = required_pairs[pat_idx]
+ first_opener = seg.find(opener)
+ if first_opener < 0:
+ continue
+ last_close = seg.rfind(token)
+ if last_close < 0:
+ continue
+ scan_end = last_close + len(token)
+ if pat_idx == 3:
+ # The Mistral array arm keeps consuming an optional ``\s*</s>`` PAST
+ # the ``]`` the bound is taken from; without this the EOS survives.
+ eos = scan_end
+ while eos < len(seg) and seg[eos].isspace():
+ eos += 1
+ if seg.startswith("</s>", eos):
+ scan_end = eos + 4
+ if scan_end == len(seg):
+ seg = pat.sub("", seg)
+ else:
+ seg = pat.sub("", seg[:scan_end]) + seg[scan_end:]
+ else:
+ seg = pat.sub("", seg)
if seg_final:
# Trailing partial rehearsal the balanced scan cannot close; gated so prose
# ``foo[ARGS] ...`` survives.
@@ -1229,13 +1261,34 @@ def _marker_inside_leading_envelope(content: str, enabled_tool_names: Optional[s
return True
# A closed outer call PRECEDING the first marker owns the turn; the pre-pass must
# not steal a trailing example or argument data.
- for _pat in _OUTER_ENVELOPE_CLOSED_PATS:
- m = _pat.search(content)
+ required_pairs = (
+ ("</tool_call>", "<tool_call>"),
+ ("</function>", "<function"),
+ ("<tool_call|>", "<|tool_call>"),
+ )
+ for _pat, (token, opener) in zip(_OUTER_ENVELOPE_CLOSED_PATS, required_pairs):
+ first_opener = content.find(opener)
+ if first_opener < 0:
+ continue
+ last_close = content.rfind(token)
+ if last_close < 0:
+ continue
+ m = _pat.search(content, 0, last_close + len(token))
if m is not None and m.start() < first_marker.start():
return True
residue = content
- for _pat in _OUTER_ENVELOPE_CLOSED_PATS:
- residue = _pat.sub("", residue)
+ for _pat, (token, opener) in zip(_OUTER_ENVELOPE_CLOSED_PATS, required_pairs):
+ first_opener = residue.find(opener)
+ if first_opener < 0:
+ continue
+ last_close = residue.rfind(token)
+ if last_close < 0:
+ continue
+ scan_end = last_close + len(token)
+ if scan_end == len(residue):
+ residue = _pat.sub("", residue)
+ else:
+ residue = _pat.sub("", residue[:scan_end]) + residue[scan_end:]
marker = _EMBEDDED_MARKER_RE.search(residue)
if marker is None:
return True
@@ -1764,7 +1817,9 @@ def _parse_function_xml(
# Strict mode: an unclosed function call is truncated -- do not heal it.
if not allow_incomplete and not has_close:
continue
- body = _TC_FUNC_CLOSE_RE.sub("", content[body_start:body_end])
+ body = content[body_start:body_end]
+ if body.rstrip().endswith("</function>"):
+ body = _TC_FUNC_CLOSE_RE.sub("", body)
args: dict = {}
param_unclosed = False
@@ -1777,9 +1832,10 @@ def _parse_function_xml(
if len(param_starts) == 1:
pm = param_starts[0]
raw_val = body[pm.end() :]
- if not _TC_PARAM_CLOSE_RE.search(raw_val):
+ param_closed = raw_val.rstrip().endswith(("</parameter>", "</param>"))
+ if not param_closed:
param_unclosed = True
- val = _TC_PARAM_CLOSE_RE.sub("", raw_val)
+ val = _TC_PARAM_CLOSE_RE.sub("", raw_val) if param_closed else raw_val
args[pm.group(1) or pm.group(2)] = _trim_param_value(val)
else:
for pidx, pm in enumerate(param_starts):
@@ -1788,9 +1844,10 @@ def _parse_function_xml(
param_starts[pidx + 1].start() if pidx + 1 < len(param_starts) else len(body)
)
raw_val = body[val_start:next_param]
- if not _TC_PARAM_CLOSE_RE.search(raw_val):
+ param_closed = raw_val.rstrip().endswith(("</parameter>", "</param>"))
+ if not param_closed:
param_unclosed = True
- val = _TC_PARAM_CLOSE_RE.sub("", raw_val)
+ val = _TC_PARAM_CLOSE_RE.sub("", raw_val) if param_closed else raw_val
args[pm.group(1) or pm.group(2)] = _trim_param_value(val)
# Strict mode: a dangling parameter means the call was cut off; a closed
diff --git a/studio/backend/core/tool_healing.py b/studio/backend/core/tool_healing.py
index 28f5644a08f..59790eb6d0d 100644
--- a/studio/backend/core/tool_healing.py
+++ b/studio/backend/core/tool_healing.py
@@ -87,9 +87,13 @@ _TOOL_CLOSED_BLOCK_PATS = [_TC_JSON_CLOSED_PAT, _TC_FUNC_CLOSED_PAT]
# A lazy closed-pair pattern whose close token is absent would rescan to EOF from every
# opener; skip that doomed (quadratic) pass. Shared by both strip helpers.
_PAT_REQUIRED_TOKEN = {
- _TC_JSON_CLOSED_PAT: "</tool_call>",
- _TC_GEMMA_CLOSED_PAT: "<tool_call|>",
- _TC_FUNC_CLOSED_PAT: "</function>",
+ # A tuple marks a required CLOSER. Besides skipping the pass when it is absent, callers
+ # bound the regex at the LAST one: nothing matches past it, and a tail full of openers
+ # would retry a lazy pattern at each one (quadratic). The bound is unconditional --
+ # any gap test for "are there openers after it" is itself the quadratic case.
+ _TC_JSON_CLOSED_PAT: ("</tool_call>", "<tool_call>"),
+ _TC_GEMMA_CLOSED_PAT: ("<tool_call|>", "<|tool_call>"),
+ _TC_FUNC_CLOSED_PAT: ("</function>", "<function="),
# Literal in both rehearsal patterns: skips the sub AND its _code_spans scan on the
# common answer that has no rehearsal at all.
_REHEARSAL_CLOSED_STRIP_RE: "[ARGS]",
@@ -100,10 +104,24 @@ _PAT_REQUIRED_TOKEN = {
def strip_tool_patterns(text: str, patterns) -> str:
"""Apply ``patterns`` in order, skipping closed-pair passes with no close token."""
for pat in patterns:
- token = _PAT_REQUIRED_TOKEN.get(pat)
- if token is not None and token not in text:
- continue
- text = pat.sub("", text)
+ required = _PAT_REQUIRED_TOKEN.get(pat)
+ if isinstance(required, tuple):
+ token, opener = required
+ first_opener = text.find(opener)
+ if first_opener < 0:
+ continue
+ last_close = text.rfind(token)
+ if last_close < 0:
+ continue
+ scan_end = last_close + len(token)
+ if scan_end == len(text):
+ text = pat.sub("", text)
+ else:
+ text = pat.sub("", text[:scan_end]) + text[scan_end:]
+ else:
+ if required is not None and required not in text:
+ continue
+ text = pat.sub("", text)
return text
@@ -140,8 +158,18 @@ def apply_tool_strip_patterns(
unconditionally. A closed-pair pattern whose close token is absent is skipped so an
unclosed-marker stream stays linear."""
for pat in patterns:
- token = _PAT_REQUIRED_TOKEN.get(pat)
- if token is not None and token not in text:
+ required = _PAT_REQUIRED_TOKEN.get(pat)
+ scan_end = len(text)
+ if isinstance(required, tuple):
+ token, opener = required
+ first_opener = text.find(opener)
+ if first_opener < 0:
+ continue
+ last_close = text.rfind(token)
+ if last_close < 0:
+ continue
+ scan_end = last_close + len(token)
+ elif required is not None and required not in text:
continue
if pat in _REHEARSAL_STRIP_PATS:
# Same two gates the parser applies in _iter_bracket_spans, so a rehearsal that
@@ -150,7 +178,7 @@ def apply_tool_strip_patterns(
_t = text
text = pat.sub(lambda m: _rehearsal_strip(m, pat, _t, spans, enabled_tool_names), text)
else:
- text = pat.sub("", text)
+ text = pat.sub("", text[:scan_end]) + text[scan_end:]
return text
@@ -418,6 +446,10 @@ def _iter_bracket_spans(
("rehearsal", _REHEARSAL_RE),
)
nexts = {kind: rx.search(text, start) for kind, rx in specs}
+ if not any(nexts.values()):
+ return
+ last_brace_close = text.rfind("}")
+ last_array_close = max(text.rfind("]"), last_brace_close)
cursor = start
code_spans: list | None = None # computed on the first rehearsal candidate only
while cursor < n:
@@ -429,6 +461,13 @@ def _iter_bracket_spans(
if not live:
return
kind, m = min(live, key = lambda km: km[1].start())
+ last_close = last_array_close if kind == "array" else last_brace_close
+ if m.end() > last_close:
+ # This and every later candidate of the same kind lacks its closing character.
+ # Keep other formats live, but skip a balanced scan to EOF per doomed opener.
+ nexts[kind] = None
+ cursor = m.end()
+ continue
if kind == "array":
end = _balanced_bracket_end(text, m.end())
else:
@@ -649,25 +688,49 @@ def _inside_open_parameter(
if param_start_re is None:
param_start_re = _TC_PARAM_START_RE
last_param_start = -1
- for match in param_start_re.finditer(content, 0, pos):
- last_param_start = match.start()
+ # Both supported vocabularies begin with ``<param``, so search backwards to the nearest
+ # candidate and validate it with the regex instead of rescanning the whole prefix per
+ # marker. Unknown caller patterns keep the general finditer path.
+ reverse_param_search = (
+ param_start_re is _TC_PARAM_START_RE
+ or param_start_re.pattern.startswith(r"<(?:parameter|param)")
+ )
+ if reverse_param_search:
+ candidate = content.rfind("<param", 0, pos)
+ while candidate >= 0:
+ match = param_start_re.match(content, candidate, pos)
+ if match is not None:
+ last_param_start = candidate
+ break
+ candidate = content.rfind("<param", 0, candidate)
+ else:
+ for match in param_start_re.finditer(content, 0, pos):
+ last_param_start = match.start()
if last_param_start < 0:
return False
# The parameter's OWN close tag decides: if it closes after ``pos`` the position is
# argument data (even across literal function closes); an unclosed one falls back to func close.
- own_closes = [
- found
- for found in (content.find(tag, last_param_start) for tag in param_closers)
- if found >= 0
- ]
- if own_closes:
- return min(own_closes) > pos
- func_closes = [
- found
- for found in (content.find(tag, last_param_start) for tag in func_closers)
- if found >= 0
- ]
- return not func_closes or pos < min(func_closes)
+ # A closer at/before ``pos`` settles it. Bounded, so an absent alternate spelling
+ # does not scan the whole suffix on every later function marker.
+ for tag in param_closers:
+ found = content.find(tag, last_param_start, min(len(content), pos + len(tag)))
+ if 0 <= found <= pos:
+ return False
+ # Try the closer matching the opener spelling first. Cross-spelling closes are still
+ # accepted; the normal form just needs a shorter scan.
+ if content.startswith("<param", last_param_start) and not content.startswith(
+ "<parameter", last_param_start
+ ):
+ param_closers = tuple(reversed(param_closers))
+ if any(content.find(tag, pos + 1) >= 0 for tag in param_closers):
+ return True
+ # With no parameter close anywhere, only a function close at/before ``pos`` proves the
+ # candidate left the parameter. A later close and no close both mean still inside.
+ for tag in func_closers:
+ found = content.find(tag, last_param_start, min(len(content), pos + len(tag)))
+ if 0 <= found <= pos:
+ return False
+ return True
def _func_close_index(content: str, body_start: int, body: str) -> int:
@@ -701,7 +764,15 @@ def _marker_coverage(content: str, markers) -> list[tuple[int, int]]:
a paired close cover through it (markers before the close are data); balanced
without one cover only the braces, so a later sibling is still recovered."""
n = len(content)
- brace_regions = [(s, be) for (s, be, _k, _m) in markers if be >= 0]
+ brace_regions = sorted((s, be) for (s, be, _k, _m) in markers if be >= 0)
+ brace_starts = []
+ brace_max_ends = []
+ if len(brace_regions) >= 8:
+ brace_starts = [s for s, _be in brace_regions]
+ max_end = -1
+ for _s, be in brace_regions:
+ max_end = max(max_end, be)
+ brace_max_ends.append(max_end)
events = [] # (position, order) with order 0 = braces-done, 1 = close marker
for idx, (_start, brace_end, _kind, _m) in enumerate(markers):
if brace_end >= 0:
@@ -710,7 +781,12 @@ def _marker_coverage(content: str, markers) -> list[tuple[int, int]]:
for cm in close_re.finditer(content):
# A close inside another call's balanced braces is quoted data; it
# must not pop an earlier close-less marker and swallow a sibling.
- if any(s < cm.start() < be for s, be in brace_regions):
+ if brace_starts:
+ region_idx = bisect.bisect_left(brace_starts, cm.start()) - 1
+ inside_braces = region_idx >= 0 and cm.start() < brace_max_ends[region_idx]
+ else:
+ inside_braces = any(s < cm.start() < be for s, be in brace_regions)
+ if inside_braces:
continue
events.append((cm.start(), 1, kind, cm.end()))
events.sort(key = lambda e: (e[0], e[1]))
@@ -736,16 +812,27 @@ def _build_markers(content: str):
"""JSON/Gemma tool markers as ``(start, brace_end, kind, match)`` in document
order; ``brace_end < 0`` marks an unbalanced (to-EOF) open."""
markers = []
+ candidates = []
for start_re, gemma, kind in (
(_TC_JSON_START_RE, False, "json"),
(_TC_GEMMA_START_RE, True, "gemma"),
):
for m in start_re.finditer(content):
- if _inside_open_parameter(content, m.start()):
- continue
- brace_end = _balanced_brace_end(content, m.end() - 1, gemma_quotes = gemma)
- # Keep the ``-1`` sentinel: ``marker_coverage`` consumers test ``brace_end < 0``.
- markers.append((m.start(), -1 if brace_end is None else brace_end, kind, m))
+ candidates.append((m, gemma, kind))
+ many_candidates = len(candidates) > 1
+ has_parameter = "<parameter=" in content if many_candidates else True
+ last_brace = content.rfind("}") if many_candidates else None
+ for m, gemma, kind in candidates:
+ if has_parameter and _inside_open_parameter(content, m.start()):
+ continue
+ brace_start = m.end() - 1
+ brace_end = (
+ _balanced_brace_end(content, brace_start, gemma_quotes = gemma)
+ if last_brace is None or brace_start < last_brace
+ else None
+ )
+ # Keep the ``-1`` sentinel: ``marker_coverage`` consumers test ``brace_end < 0``.
+ markers.append((m.start(), -1 if brace_end is None else brace_end, kind, m))
markers.sort(key = lambda c: c[0])
return markers
@@ -800,8 +887,11 @@ def parse_tool_calls_from_text(
parsed_items = [] # (start, span_end, name, arguments) in document order
markers = [mk for mk in _build_markers(content) if not _in_think(mk[0])]
coverage = _marker_coverage(content, markers)
+ covered_until = -1
for idx, (start, brace_end, kind, m) in enumerate(markers):
- if any(s <= start < e for j, (s, e) in enumerate(coverage) if j != idx):
+ covered_by_earlier_marker = start < covered_until
+ covered_until = max(covered_until, coverage[idx][1])
+ if covered_by_earlier_marker:
continue
if brace_end < 0:
continue # unclosed: not parseable; the fallback still excludes its XML
@@ -870,7 +960,8 @@ def parse_tool_calls_from_text(
elif not allow_incomplete:
continue
else:
- body = _TC_FUNC_CLOSE_RE.sub("", body)
+ if body.rstrip().endswith(_FUNC_CLOSE_TAG):
+ body = _TC_FUNC_CLOSE_RE.sub("", body)
span_end = body_end
arguments: dict = {}
@@ -884,7 +975,8 @@ def parse_tool_calls_from_text(
continue
val = stripped_val[: -len(_PARAM_CLOSE_TAG)]
else:
- val = _TC_PARAM_CLOSE_RE.sub("", val)
+ if val.rstrip().endswith(_PARAM_CLOSE_TAG):
+ val = _TC_PARAM_CLOSE_RE.sub("", val)
arguments[pm.group(1)] = _trim_param_value(val)
else:
valid_params = True
@@ -902,7 +994,8 @@ def parse_tool_calls_from_text(
break
val = stripped_val[: -len(_PARAM_CLOSE_TAG)]
else:
- val = _TC_PARAM_CLOSE_RE.sub("", val)
+ if val.rstrip().endswith(_PARAM_CLOSE_TAG):
+ val = _TC_PARAM_CLOSE_RE.sub("", val)
arguments[param_name] = _trim_param_value(val)
if not valid_params:
continue
@@ -1030,12 +1123,22 @@ def _tool_call_markup_spans(text: str) -> list[tuple[int, int]]:
span the unclosed call's markup would leak after execution."""
# Skip a lazy closed-pair pattern whose close token is absent: its finditer would rescan
# to EOF from every opener (quadratic on a stream of unclosed openers).
- spans = [
- m.span()
- for pat in _TOOL_CLOSED_PATS
- if (_PAT_REQUIRED_TOKEN.get(pat) is None or _PAT_REQUIRED_TOKEN[pat] in text)
- for m in pat.finditer(text)
- ]
+ spans = []
+ for pat in _TOOL_CLOSED_PATS:
+ required = _PAT_REQUIRED_TOKEN.get(pat)
+ scan_end = len(text)
+ if isinstance(required, tuple):
+ token, opener = required
+ first_opener = text.find(opener)
+ if first_opener < 0:
+ continue
+ last_close = text.rfind(token)
+ if last_close < 0:
+ continue
+ scan_end = last_close + len(token)
+ elif required is not None and required not in text:
+ continue
+ spans.extend(m.span() for m in pat.finditer(text, 0, scan_end))
spans.extend((start, end) for start, end, _kind, _m in _iter_bracket_spans(text))
# An unclosed opener is a real incomplete call only outside closed/bracket spans.
for pat in _TOOL_OPEN_XML_TAIL_PATS:
@@ -1151,13 +1254,23 @@ def _strip_closed_blocks_outside_gemma(text: str) -> str:
if not ranges:
return strip_tool_patterns(text, _TOOL_CLOSED_BLOCK_PATS)
for pat in _TOOL_CLOSED_BLOCK_PATS:
- token = _PAT_REQUIRED_TOKEN.get(pat)
- if token is not None and token not in text:
+ required = _PAT_REQUIRED_TOKEN.get(pat)
+ scan_end = len(text)
+ if isinstance(required, tuple):
+ token, opener = required
+ first_opener = text.find(opener)
+ if first_opener < 0:
+ continue
+ last_close = text.rfind(token)
+ if last_close < 0:
+ continue
+ scan_end = last_close + len(token)
+ elif required is not None and required not in text:
continue
out: list[str] = []
pos = 0
while True:
- m = pat.search(text, pos)
+ m = pat.search(text, pos, scan_end)
if m is None:
out.append(text[pos:])
break
diff --git a/studio/backend/tests/test_safetensors_tool_loop.py b/studio/backend/tests/test_safetensors_tool_loop.py
index 84ccc22c2c9..6192dc8be83 100644
--- a/studio/backend/tests/test_safetensors_tool_loop.py
+++ b/studio/backend/tests/test_safetensors_tool_loop.py
@@ -17,6 +17,7 @@ from typing import cast
import pytest
from core.inference import safetensors_agentic
+from core.inference import tool_call_parser
from core.inference.safetensors_agentic import (
_coerce_arguments,
_detect_render_html_tool_start,
@@ -5247,3 +5248,58 @@ def test_both_tool_loops_say_they_are_waiting_for_approval():
and node.func.id == "awaiting_approval_status"
]
assert calls, f"{name} still announces a gated tool call as running"
+
+
+class TestStreamingDisplayStripStillMatchesTheExportedHelper:
+ """The loop used to call ``strip_tool_markup_streaming`` directly; it now drives a
+ ``StreamingMarkupStripper`` instead, and the exported helper has no call site left in
+ this module. Everything else in this file asserts on the helper, so without this the
+ suite would look like it guards the loop while guarding a parallel implementation.
+
+ This pins the two together: for the inputs the rest of the file uses, the incremental
+ path the loop actually runs must agree with the helper at every prefix.
+ """
+
+ @staticmethod
+ def _loop_strip(text, names = None):
+ """The loop's display strip, reproduced exactly: Magistral reasoning removal,
+ then the shared incremental stripper (see ``_strip_streaming_display``)."""
+ stripper = tool_call_parser.StreamingMarkupStripper(names)
+ return stripper.strip(safetensors_agentic._strip_mistral_reasoning(text))
+
+ @pytest.mark.parametrize(
+ "text",
+ [
+ 'before <tool_call>{"name": "search", "arguments": {}}</tool_call>',
+ "before <function=search><parameter=q>x</parameter></function> after",
+ "plain prose with no markup at all",
+ "<think>rehearsed <tool_call>{}</tool_call></think> visible",
+ "[TOOL_CALLS] search[ARGS]{}",
+ "trailing <function=search",
+ "",
+ ],
+ )
+ def test_the_loop_path_agrees_with_the_helper(self, text):
+ names = {"search"}
+ assert self._loop_strip(text, names) == strip_tool_markup_streaming(
+ text, enabled_tool_names = names
+ )
+
+ @pytest.mark.parametrize(
+ "text",
+ [
+ 'before <tool_call>{"name": "search", "arguments": {}}</tool_call> after',
+ "<function=search><parameter=q>a</parameter></function>tail",
+ ],
+ )
+ def test_the_loop_path_agrees_at_every_prefix(self, text):
+ """The loop feeds a growing buffer, so agreement has to hold at each step, not
+ only on the whole string."""
+ names = {"search"}
+ stripper = tool_call_parser.StreamingMarkupStripper(names)
+ for i in range(1, len(text) + 1):
+ prefix = text[:i]
+ incremental = stripper.strip(safetensors_agentic._strip_mistral_reasoning(prefix))
+ assert incremental == strip_tool_markup_streaming(
+ prefix, enabled_tool_names = names
+ ), f"diverged at offset {i}"
diff --git a/studio/backend/tests/test_streaming_stripper.py b/studio/backend/tests/test_streaming_stripper.py
index 529d9f8b0b3..833f96ee61b 100644
--- a/studio/backend/tests/test_streaming_stripper.py
+++ b/studio/backend/tests/test_streaming_stripper.py
@@ -195,8 +195,7 @@ def test_scan_is_amortized_not_quadratic():
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.
+ # (~4x). Ratios rather than absolutes keep this meaningful on a noisy CI box.
reference_growth = elapsed(_reference_strip, long) / max(elapsed(_reference_strip, short), 1e-9)
incremental_growth = incremental(long) / max(incremental(short), 1e-9)
@@ -625,3 +624,35 @@ def test_an_append_only_stream_is_still_recognised_as_a_continuation():
for i in range(600, len(text), 100):
assert stripper._is_extension(text[:i]) is True
stripper.strip(text[:i])
+
+
+def test_a_bounded_scan_still_takes_the_eos_after_a_malformed_mistral_array():
+ """The Mistral array arm keeps consuming an optional ``</s>`` after the ``]`` that the
+ bound is computed from, so bounding at the last ``]`` alone left the EOS in the
+ displayed text. Prose ``[1]`` before the marker is what turns the bound on, and a
+ malformed array is what gets past the string-aware pre-pass to this arm."""
+ text = 'See [1]. [TOOL_CALLS] [{"name": "get_weather", "ar}]</s> Done.'
+
+ assert tool_call_parser.strip_tool_markup(text, final = True) == "See [1]. Done."
+ assert tool_call_parser.strip_tool_markup(text, final = False) == "See [1]. Done."
+
+
+def test_openers_far_past_the_closer_do_not_reopen_the_quadratic_scan():
+ """The bound at the last closer is what keeps a tail of unclosed openers linear, so
+ deciding whether to apply it by probing a fixed window after the FIRST closer just
+ moves the cliff: put more prose than the window between the closed call and the
+ openers and the unbounded scan comes back. Prose length must not enter the decision."""
+ import time
+
+ def elapsed(n):
+ text = (
+ '<tool_call>{"name": "search", "arguments": {}}</tool_call>'
+ + "prose " * 60
+ + "<tool_call>" * n
+ )
+ start = time.perf_counter()
+ tool_healing.strip_tool_call_markup(text)
+ return time.perf_counter() - start
+
+ growth = elapsed(8000) / max(elapsed(2000), 1e-9)
+ assert growth < 8.0, f"4x the openers cost {growth:.1f}x; expected roughly linear"