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: bound tool-call stream scans and decode passthrough lines once (#15591)

Daniel Han0de1f4eb27c9
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index d9ccd917a29..148af3515be 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -2538,11 +2538,19 @@ def _is_rehearsal_prefix(stripped: str, active_tools: list[dict]) -> bool:
def _held_rehearsal_tail_len(text: str, active_tools: list[dict]) -> int:
"""Holds a trailing bare tool name back while its [ARGS] may still arrive, including a bare-Gemma call:NAME{ prefix that the signal scan misses until its brace."""
+ # A tail longer than every NAME[ARGS] cannot be a prefix, so the scan stops there (CJK has no spaces).
+ limit = max(
+ (len(name) for name in _gguf_active_tool_names(active_tools) if isinstance(name, str)),
+ default = 0,
+ ) + len("[ARGS]")
i = len(text)
- while i > 0 and not text[i - 1].isspace():
+ stop = max(0, i - limit - 1)
+ while i > stop and not text[i - 1].isspace():
i -= 1
tail = text[i:]
- held = len(tail) if tail and _is_rehearsal_prefix(tail, active_tools) else 0
+ held = (
+ len(tail) if tail and len(tail) <= limit and _is_rehearsal_prefix(tail, active_tools) else 0
+ )
return max(
held, held_bare_gemma_tail_len(text, lambda: set(_gguf_active_tool_names(active_tools)))
)
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index a7d1d2e462c..99f71e81050 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -158,13 +158,26 @@ def _held_rehearsal_tail_len(
unrestricted: bool = False,
) -> int:
"""Length of a trailing bare tool-name token held while streaming so the name does not leak; also call:NAME{ prefixes, seen only once the brace arrives."""
+ # Restricted mode: same NAME[ARGS] bound as llama_cpp._held_rehearsal_tail_len.
+ limit = (
+ len(text)
+ if unrestricted
+ else max(
+ (len(name) for name in _active_tool_names(active_tools) if isinstance(name, str)),
+ default = 0,
+ )
+ + len("[ARGS]")
+ )
i = len(text)
- while i > 0 and not text[i - 1].isspace():
+ stop = max(0, i - limit - 1)
+ while i > stop and not text[i - 1].isspace():
i -= 1
tail = text[i:]
held = (
len(tail)
- if tail and _is_rehearsal_prefix(tail, active_tools, unrestricted = unrestricted)
+ if tail
+ and len(tail) <= limit
+ and _is_rehearsal_prefix(tail, active_tools, unrestricted = unrestricted)
else 0
)
return max(
diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.py
index 6603e1eac9f..3c2ce4eb0d3 100644
--- a/studio/backend/core/inference/tool_call_parser.py
+++ b/studio/backend/core/inference/tool_call_parser.py
@@ -1103,6 +1103,18 @@ def _unmask_blocked_bodies(text: str, bodies: list) -> Optional[str]:
return result if count == len(bodies) else None
+def _search_from_literal(pattern: re.Pattern, literal: str, text: str, pos: int):
+ """``pattern.search(text, pos)`` for a pattern whose every match starts with ``literal``: the regex is
+ tried only where ``find`` lands, not at every position (a lookbehind still sees the text before)."""
+ at = text.find(literal, pos)
+ while at >= 0:
+ m = pattern.match(text, at)
+ if m:
+ return m
+ at = text.find(literal, at + 1)
+ return None
+
+
def _strip_gemma_wrapperless_calls(text: str, enabled_tool_names: Optional[set] = None) -> str:
"""Strips closed bare call:NAME{...} calls; non-promotable, quoted and unanchored ones stay visible; None strips every anchored closed non-execution call."""
if _whole_content_is_json_value(text):
@@ -1117,7 +1129,7 @@ def _strip_gemma_wrapperless_calls(text: str, enabled_tool_names: Optional[set]
floor = blocked_markerless_prefix_end(text, cursor, enabled_tool_names)
code_spans, code_from = None, 0
while cursor < n:
- m = _GEMMA_BARE_TC_RE.search(text, cursor)
+ m = _search_from_literal(_GEMMA_BARE_TC_RE, "call", text, cursor)
if not m:
out.append(text[cursor:])
break
diff --git a/studio/backend/core/tool_healing.py b/studio/backend/core/tool_healing.py
index 1a190a5e386..ada3fdab24e 100644
--- a/studio/backend/core/tool_healing.py
+++ b/studio/backend/core/tool_healing.py
@@ -269,6 +269,12 @@ def _balanced_json_span(text: str, start: int) -> int | None:
return None
+# Unrolled loops with nothing after them never backtrack; possessive quantifiers need Python 3.11+.
+_BRACE_SKIP_RE = re.compile(r'[^"{}]*')
+_BRACE_SKIP_GEMMA_RE = re.compile(r'[^"{}<]*(?:<(?!\|"\|>)[^"{}<]*)*')
+_JSON_STRING_BODY_RE = re.compile(r'[^"\\]*(?:\\.[^"\\]*)*', re.DOTALL)
+
+
def _balanced_brace_end(
content: str,
brace_start: int,
@@ -278,30 +284,32 @@ def _balanced_brace_end(
"""Index of the brace matching brace_start, or None; shared with core/inference/tool_call_parser.py."""
if brace_start >= len(content) or content[brace_start] != "{":
return None
+ n = len(content)
+ skip = _BRACE_SKIP_GEMMA_RE.match if gemma_quotes else _BRACE_SKIP_RE.match
+ string_body = _JSON_STRING_BODY_RE.match
depth = 0
i = brace_start
- in_string = False
- in_gemma_string = False
- while i < len(content):
- if gemma_quotes and not in_string and content.startswith(_GEMMA_QUOTE, i):
- in_gemma_string = not in_gemma_string
- i += len(_GEMMA_QUOTE)
- continue
+ while i < n:
+ i = skip(content, i).end()
+ if i >= n:
+ return None
ch = content[i]
- if in_gemma_string:
+ if ch == "<":
+ close = content.find(_GEMMA_QUOTE, i + len(_GEMMA_QUOTE))
+ if close < 0:
+ return None
+ i = close + len(_GEMMA_QUOTE)
+ continue
+ if ch == '"':
+ i = string_body(content, i + 1).end()
+ # The body stops at the closing quote, at the end, or before a trailing lone backslash.
+ if i >= n or content[i] != '"':
+ return None
i += 1
continue
- if in_string:
- if ch == "\\" and i + 1 < len(content):
- i += 2
- continue
- if ch == '"':
- in_string = False
- elif ch == '"':
- in_string = True
- elif ch == "{":
+ if ch == "{":
depth += 1
- elif ch == "}":
+ else:
depth -= 1
if depth == 0:
return i
@@ -392,7 +400,15 @@ def _iter_bracket_spans(
("name", _MISTRAL_BRACKET_RE),
("rehearsal", _REHEARSAL_RE),
)
- nexts = {kind: rx.search(text, start) for kind, rx in specs}
+ # Each regex needs its case-sensitive literal tag, so str.find gates it exactly.
+ has_calls_tag = text.find("[TOOL_CALLS]", start) >= 0
+ nexts = {
+ "array": _MISTRAL_ARRAY_RE.search(text, start) if has_calls_tag else None,
+ "name": _MISTRAL_BRACKET_RE.search(text, start) if has_calls_tag else None,
+ "rehearsal": (
+ _REHEARSAL_RE.search(text, start) if text.find("[ARGS]", start) >= 0 else None
+ ),
+ }
if not any(nexts.values()):
return
last_brace_close = text.rfind("}")
@@ -1034,10 +1050,14 @@ def _tool_call_markup_spans(text: str) -> list[tuple[int, int]]:
def _think_spans_outside_tool_markup(text: str) -> list[tuple[int, int]]:
"""A think tag opening inside a tool-call span is argument data, so it is not a reasoning block."""
- think_spans = [m.span() for m in _THINK_TAG_RE.finditer(text)]
+ think_spans = (
+ [m.span() for m in _THINK_TAG_RE.finditer(text)]
+ if "<think>" in text or "[THINK]" in text
+ else []
+ )
call_spans = _tool_call_markup_spans(text)
# Prefilled reasoning: the template opens <think> in the prompt, so a leading span skips calls rehearsed there.
- close = _THINK_CLOSE_RE.search(text)
+ close = _THINK_CLOSE_RE.search(text) if "</think>" in text or "[/THINK]" in text else None
if close is not None:
opener = _THINK_OPEN_RE.search(text)
if (
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 42dfd621b0e..f1bdab4e85c 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1262,28 +1262,40 @@ def _normalize_openai_passthrough_sse_line(
raw_line: str, *, cap_parallel_tool_calls: bool = False
) -> str:
"""Relay comments, [DONE] and unparsable lines as-is; re-serialize only when a compat fix applies."""
+ return _normalize_openai_passthrough_sse_line_and_data(
+ raw_line, cap_parallel_tool_calls = cap_parallel_tool_calls
+ )[0]
+
+
+_SSE_LINE_UNPARSED = object()
+
+
+def _normalize_openai_passthrough_sse_line_and_data(
+ raw_line: str, *, cap_parallel_tool_calls: bool = False
+) -> tuple[str, Any]:
+ """The normalized line plus its decoded JSON when the check had to parse it, so the relay need not."""
if not raw_line.startswith("data:"):
- return raw_line
+ return raw_line, _SSE_LINE_UNPARSED
# Fast path: skip the JSON parse when neither key appears in the line.
if '"reasoning_content"' not in raw_line and not (
cap_parallel_tool_calls and '"tool_calls"' in raw_line
):
- return raw_line
+ return raw_line, _SSE_LINE_UNPARSED
payload = raw_line[len("data:") :].lstrip()
if payload.strip() in ("", "[DONE]"):
- return raw_line
+ return raw_line, _SSE_LINE_UNPARSED
try:
obj = json.loads(payload)
except Exception:
- return raw_line
+ return raw_line, _SSE_LINE_UNPARSED
if not isinstance(obj, dict):
- return raw_line
+ return raw_line, obj
changed = _add_empty_content_to_reasoning_deltas(obj)
if cap_parallel_tool_calls and _drop_parallel_tool_call_deltas(obj):
changed = True
if not changed:
- return raw_line
- return "data: " + json.dumps(obj, separators = (",", ":"), ensure_ascii = False)
+ return raw_line, obj
+ return "data: " + json.dumps(obj, separators = (",", ":"), ensure_ascii = False), obj
def _prompt_tokens_details(upstream):
@@ -7289,6 +7301,17 @@ def _monitor_openai_sse_line(
data = json.loads(data_str)
except json.JSONDecodeError:
return None
+ return _monitor_openai_sse_data(monitor_id, data, context_length)
+
+
+def _monitor_openai_sse_data(
+ monitor_id: Optional[str],
+ data: Any,
+ context_length = None,
+) -> Optional[str]:
+ """Core of ``_monitor_openai_sse_line`` for a data line the caller already decoded."""
+ if not monitor_id:
+ return None
if isinstance(data, dict):
error_message = _monitor_openai_error_message(data)
if error_message:
@@ -46080,15 +46103,16 @@ async def _openai_passthrough_stream_admitted(
yield raw_line + "\n\n"
monitor_done = True
break
- raw_line = _normalize_openai_passthrough_sse_line(
+ raw_line, chunk_data = _normalize_openai_passthrough_sse_line_and_data(
raw_line,
cap_parallel_tool_calls = payload.parallel_tool_calls is False,
)
- data_text = raw_line[5:].strip()
- try:
- chunk_data = json.loads(data_text)
- except json.JSONDecodeError:
- chunk_data = None
+ if chunk_data is _SSE_LINE_UNPARSED:
+ data_text = raw_line[5:].strip()
+ try:
+ chunk_data = json.loads(data_text)
+ except json.JSONDecodeError:
+ chunk_data = None
if isinstance(chunk_data, dict):
if isinstance(chunk_data.get("id"), str):
last_chunk_id = chunk_data["id"]
@@ -46110,7 +46134,10 @@ async def _openai_passthrough_stream_admitted(
saw_stream_error = True
mark_response_failed(getattr(request, "scope", None))
if not client_wants_progress and _is_prefill_progress_only(chunk_data):
- _monitor_openai_sse_line(monitor_id, raw_line, llama_backend.context_length)
+ # chunk_data decodes raw_line (a data: line), so skip the monitor's re-parse.
+ _monitor_openai_sse_data(
+ monitor_id, chunk_data, llama_backend.context_length
+ )
if progress_keepalive.due():
yield _OPENAI_PREFILL_PROGRESS_SSE
continue
@@ -46150,10 +46177,17 @@ async def _openai_passthrough_stream_admitted(
yield finish_line + "\n\n"
saw_finish_reason = True
for out_line in out_lines:
- monitor_event = _monitor_openai_sse_line(
- monitor_id,
- out_line,
- llama_backend.context_length,
+ monitor_event = (
+ # The healer leaves chunk_data untouched whenever it relays raw_line.
+ _monitor_openai_sse_data(
+ monitor_id, chunk_data, llama_backend.context_length
+ )
+ if out_line is raw_line and chunk_data is not None
+ else _monitor_openai_sse_line(
+ monitor_id,
+ out_line,
+ llama_backend.context_length,
+ )
)
if monitor_event == "error":
saw_stream_error = True
diff --git a/studio/backend/tests/data/refactor_guard/ast_inventory.json b/studio/backend/tests/data/refactor_guard/ast_inventory.json
index bef2ee547d4..70f3d28f6fc 100644
--- a/studio/backend/tests/data/refactor_guard/ast_inventory.json
+++ b/studio/backend/tests/data/refactor_guard/ast_inventory.json
@@ -1845,6 +1845,11 @@
"kind": "def",
"signature": "text: str, first: int"
},
+ "_search_from_literal": {
+ "decorators": [],
+ "kind": "def",
+ "signature": "pattern: re.Pattern, literal: str, text: str, pos: int"
+ },
"_signal_inside_leading_wrapperless_gemma": {
"decorators": [],
"kind": "def",
@@ -2057,8 +2062,11 @@
},
"core.tool_healing": {
"compiled": {
+ "_BRACE_SKIP_GEMMA_RE": "'[^\"{}<]*(?:<(?!\\\\|\"\\\\|>)[^\"{}<]*)*' flags=32",
+ "_BRACE_SKIP_RE": "'[^\"{}]*' flags=32",
"_CODE_SPAN_RE": "'^[ \\\\t]*(?:>[ \\\\t]*)*(?:(?P<bt>```+)[^`\\\\n]*$.*?(?:^[ \\\\t]*(?:>[ \\\\t]*)*(?P=bt)`*[ \\\\t\\\\r]*$|\\\\Z)|(?P<tl>~~~+)[^\\\\n]*$.*?(?:^[ \\\\t]*(?:>[ \\\\t]*)*(?P=tl)~*[ \\\\t\\\\r]*$|\\\\Z))|``(?:[^`]|`(?!`))*?``|`[^`\\\\n]*`' flags=56",
"_GEMMA_NEXT_KEY_RE": "'\\\\s*[A-Za-z_][\\\\w.\\\\-]*\\\\s*:' flags=32",
+ "_JSON_STRING_BODY_RE": "'[^\"\\\\\\\\]*(?:\\\\\\\\.[^\"\\\\\\\\]*)*' flags=48",
"_MISTRAL_ARRAY_RE": "'\\\\[TOOL_CALLS\\\\]\\\\s*(?=\\\\[)' flags=32",
"_MISTRAL_BRACKET_RE": "'\\\\[TOOL_CALLS\\\\]\\\\s*([\\\\w-]+)(?:\\\\[CALL_ID\\\\][\\\\w-]+)?(?:\\\\[ARGS\\\\])?\\\\s*(?=\\\\{)' flags=32",
"_REHEARSAL_CLOSED_STRIP_RE": "'(?<!\\\\[CALL_ID\\\\])\\\\b([\\\\w-]+)\\\\[ARGS\\\\]\\\\s*\\\\{[^{}]*(?:\\\\{[^{}]*\\\\}[^{}]*)*\\\\}' flags=48",
@@ -2122,6 +2130,9 @@
"re.compile('<tool_call>.*$', re.DOTALL)": 1,
"re.compile('<tool_call>.*?</tool_call>', re.DOTALL)": 1,
"re.compile('<tool_call\\\\|>')": 2,
+ "re.compile('[^\"\\\\\\\\]*(?:\\\\\\\\.[^\"\\\\\\\\]*)*', re.DOTALL)": 1,
+ "re.compile('[^\"{}<]*(?:<(?!\\\\|\"\\\\|>)[^\"{}<]*)*')": 1,
+ "re.compile('[^\"{}]*')": 1,
"re.compile('\\\\[/TOOL_CALLS\\\\]')": 1,
"re.compile('\\\\[TOOL_CALLS\\\\].*$', re.DOTALL)": 1,
"re.compile('\\\\[TOOL_CALLS\\\\]\\\\s*(?=\\\\[)')": 1,
@@ -2139,6 +2150,12 @@
"EXECUTION_CLASS_TOOL_NAMES": {
"kind": "assign"
},
+ "_BRACE_SKIP_GEMMA_RE": {
+ "kind": "assign"
+ },
+ "_BRACE_SKIP_RE": {
+ "kind": "assign"
+ },
"_BRACKETED_JSON_ONE_LEVEL": {
"kind": "assign"
},
@@ -2154,6 +2171,9 @@
"_GEMMA_QUOTE": {
"kind": "assign"
},
+ "_JSON_STRING_BODY_RE": {
+ "kind": "assign"
+ },
"_MAX_BRACKET_SCAN_CHARS": {
"kind": "assign"
},
diff --git a/studio/backend/tests/data/refactor_guard/runtime_inventory.json b/studio/backend/tests/data/refactor_guard/runtime_inventory.json
index 1cc122429e2..de3dc27c9e0 100644
--- a/studio/backend/tests/data/refactor_guard/runtime_inventory.json
+++ b/studio/backend/tests/data/refactor_guard/runtime_inventory.json
@@ -161,6 +161,7 @@
"_partial_call_word_len",
"_promotable_gemma_call_pos",
"_safe_cut",
+ "_search_from_literal",
"_signal_inside_leading_wrapperless_gemma",
"_skip_mistral_call_id",
"_strictly_inside",
@@ -268,6 +269,7 @@
"_partial_call_word_len": "core.inference.tool_call_parser._partial_call_word_len(text: 'str') -> 'int'",
"_promotable_gemma_call_pos": "core.inference.tool_call_parser._promotable_gemma_call_pos(text: 'str', start: 'int', enabled_tool_names) -> 'int'",
"_safe_cut": "core.inference.tool_call_parser._safe_cut(text: 'str', first: 'int') -> 'int'",
+ "_search_from_literal": "core.inference.tool_call_parser._search_from_literal(pattern: 're.Pattern', literal: 'str', text: 'str', pos: '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'",
"_strictly_inside": "core.inference.tool_call_parser._strictly_inside(spans: 'list', pos: 'int') -> 'bool'",
@@ -315,11 +317,14 @@
"core.tool_healing": {
"dir": [
"EXECUTION_CLASS_TOOL_NAMES",
+ "_BRACE_SKIP_GEMMA_RE",
+ "_BRACE_SKIP_RE",
"_BRACKETED_JSON_ONE_LEVEL",
"_CODE_SPAN_RE",
"_FUNC_CLOSE_TAG",
"_GEMMA_NEXT_KEY_RE",
"_GEMMA_QUOTE",
+ "_JSON_STRING_BODY_RE",
"_MAX_BRACKET_SCAN_CHARS",
"_MCP_TOOL_PREFIX",
"_MISTRAL_ARRAY_RE",
diff --git a/studio/backend/tests/test_regex_floor_syntax.py b/studio/backend/tests/test_regex_floor_syntax.py
new file mode 100644
index 00000000000..c61058c5751
--- /dev/null
+++ b/studio/backend/tests/test_regex_floor_syntax.py
@@ -0,0 +1,105 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Studio installs on Python 3.9 and 3.10, where possessive quantifiers and atomic groups (3.11+) are
+a re.error at import. CI runs 3.11+, so this parses every literal pattern and rejects that syntax."""
+
+import ast
+import sys
+from pathlib import Path
+
+import pytest
+
+pytestmark = pytest.mark.skipif(
+ sys.version_info < (3, 11), reason = "the 3.11 parser is what can name the 3.11-only opcodes"
+)
+
+_BACKEND = Path(__file__).resolve().parents[1]
+_RE_FUNCTIONS = {
+ "compile",
+ "match",
+ "search",
+ "fullmatch",
+ "finditer",
+ "findall",
+ "sub",
+ "subn",
+ "split",
+}
+
+
+def _uses_311_syntax(parsed) -> bool:
+ from re import _constants, _parser
+
+ newer = {_constants.POSSESSIVE_REPEAT, _constants.ATOMIC_GROUP}
+ stack = [parsed]
+ while stack:
+ item = stack.pop()
+ if isinstance(item, _parser.SubPattern):
+ for op, av in item.data:
+ if op in newer:
+ return True
+ stack.append(av)
+ elif isinstance(item, (list, tuple)):
+ stack.extend(item)
+ return False
+
+
+def _literal_patterns():
+ for path in sorted(_BACKEND.rglob("*.py")):
+ if "node_modules" in path.parts:
+ continue
+ try:
+ text = path.read_text(encoding = "utf-8")
+ except UnicodeDecodeError:
+ continue
+ # Every possessive or atomic pattern contains one of these; most files have none to parse.
+ if not any(token in text for token in ("*+", "++", "?+", "}+", "(?>")):
+ continue
+ try:
+ tree = ast.parse(text)
+ except SyntaxError:
+ continue
+ for node in ast.walk(tree):
+ if (
+ isinstance(node, ast.Call)
+ and getattr(node.func, "attr", None) in _RE_FUNCTIONS
+ and node.args
+ and isinstance(node.args[0], ast.Constant)
+ and isinstance(node.args[0].value, str)
+ ):
+ yield path, node.lineno, node.args[0].value
+
+
+def test_the_check_sees_possessive_and_atomic_syntax():
+ from re import _parser
+ for pattern in (
+ r'[^"{}]*+',
+ r'(?:[^"{}<]++|<)*+',
+ r"a?+",
+ r"a{2,3}+",
+ r"(?>ab|a)c",
+ r"x(?:(?>y))",
+ ):
+ assert _uses_311_syntax(_parser.parse(pattern)), pattern
+ for pattern in (r'[^"{}]*', r"\++", r"[*+]", r"a{2,3}", r"(?:ab|a)c", r"(?=a+)"):
+ assert not _uses_311_syntax(_parser.parse(pattern)), pattern
+
+
+def test_backend_patterns_compile_on_the_python_floor():
+ import warnings
+
+ from re import _parser
+
+ found = []
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ for path, line, pattern in _literal_patterns():
+ try:
+ parsed = _parser.parse(pattern)
+ except Exception:
+ continue # Not a regex argument (str.split, a bytes-like helper); nothing to check.
+ if _uses_311_syntax(parsed):
+ found.append(f"{path.relative_to(_BACKEND)}:{line}: {pattern!r}")
+ assert (_BACKEND / "core" / "tool_healing.py").is_file(), _BACKEND
+ assert not found, "\n".join(found)
diff --git a/studio/backend/tests/test_stream_scan_costs.py b/studio/backend/tests/test_stream_scan_costs.py
new file mode 100644
index 00000000000..f761a01d26a
--- /dev/null
+++ b/studio/backend/tests/test_stream_scan_costs.py
@@ -0,0 +1,206 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Per-chunk scans in the streaming tool loops: same answers as the plain walks, without the rescans."""
+
+from __future__ import annotations
+
+import random
+import sys
+from pathlib import Path
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+
+from core import tool_healing
+from core.inference import llama_cpp, safetensors_agentic
+from core.inference.tool_call_parser import held_bare_gemma_tail_len
+
+_TOOLS = [
+ {"type": "function", "function": {"name": name}}
+ for name in ("web_search", "terminal", "python", "mcp__srv__tool", " padded ")
+] + [{"type": "function", "function": {"name": 7}}, {"type": "function", "function": "bad"}]
+
+
+def _walk_tail(text: str) -> str:
+ i = len(text)
+ while i > 0 and not text[i - 1].isspace():
+ i -= 1
+ return text[i:]
+
+
+def _gguf_hold_reference(text: str, tools: list) -> int:
+ tail = _walk_tail(text)
+ held = len(tail) if tail and llama_cpp._is_rehearsal_prefix(tail, tools) else 0
+ names = lambda: set(llama_cpp._gguf_active_tool_names(tools)) # noqa: E731
+ return max(held, held_bare_gemma_tail_len(text, names))
+
+
+def _st_hold_reference(text: str, tools: list, unrestricted: bool) -> int:
+ tail = _walk_tail(text)
+ held = (
+ len(tail)
+ if tail and safetensors_agentic._is_rehearsal_prefix(tail, tools, unrestricted = unrestricted)
+ else 0
+ )
+ names = lambda: None if unrestricted else safetensors_agentic._active_tool_names(tools) # noqa: E731
+ return max(held, held_bare_gemma_tail_len(text, names))
+
+
+def _brace_end_reference(content: str, brace_start: int, gemma_quotes: bool) -> int | None:
+ quote = tool_healing._GEMMA_QUOTE
+ if brace_start >= len(content) or content[brace_start] != "{":
+ return None
+ depth, i, in_string, in_gemma = 0, brace_start, False, False
+ while i < len(content):
+ if gemma_quotes and not in_string and content.startswith(quote, i):
+ in_gemma = not in_gemma
+ i += len(quote)
+ continue
+ ch = content[i]
+ if in_gemma:
+ i += 1
+ continue
+ if in_string:
+ if ch == "\\" and i + 1 < len(content):
+ i += 2
+ continue
+ if ch == '"':
+ in_string = False
+ elif ch == '"':
+ in_string = True
+ elif ch == "{":
+ depth += 1
+ elif ch == "}":
+ depth -= 1
+ if depth == 0:
+ return i
+ i += 1
+ return None
+
+
+def test_held_tail_matches_the_unbounded_walk():
+ rng = random.Random(0)
+ pieces = ["web_search", "web_sea", "[ARGS]", "[AR", " ", "\n", " ", "\xa0", "x", "中文"]
+ pieces += ["call", "call:", "call:web_search{", "}", "{", "terminal", "python[ARGS]", "padded"]
+ for _ in range(1500):
+ tools = rng.sample(_TOOLS, rng.randint(0, len(_TOOLS)))
+ text = "".join(rng.choice(pieces) for _ in range(rng.randint(0, 24)))
+ assert llama_cpp._held_rehearsal_tail_len(text, tools) == _gguf_hold_reference(
+ text, tools
+ ), (text, tools)
+ for unrestricted in (False, True):
+ got = safetensors_agentic._held_rehearsal_tail_len(
+ text, tools, unrestricted = unrestricted
+ )
+ assert got == _st_hold_reference(text, tools, unrestricted), (text, unrestricted)
+
+
+def test_held_tail_does_not_rewalk_spaceless_text():
+ """CJK prose has no spaces, so walking back to the last one per chunk made a reply quadratic."""
+ tools = _TOOLS[:3]
+
+ # A count of indexed reads, not a timing, so it is the same on every runner.
+ class CountingStr(str):
+ reads = 0
+
+ def __getitem__(self, key):
+ CountingStr.reads += 1
+ return str.__getitem__(self, key)
+
+ for module in (llama_cpp, safetensors_agentic):
+ reads = []
+ for n in (100, 10_000):
+ CountingStr.reads = 0
+ assert (
+ module._held_rehearsal_tail_len(CountingStr("这是没有空格的中文文本" * n), tools)
+ == 0
+ )
+ reads.append(CountingStr.reads)
+ assert reads[0] == reads[1] < 100, (module.__name__, reads)
+ held = CountingStr("这是没有空格的中文文本" * 10_000 + " web_sea")
+ assert module._held_rehearsal_tail_len(held, tools) == 7
+
+
+def test_balanced_brace_end_matches_the_character_walk():
+ rng = random.Random(1)
+ pieces = ["{", "}", '"', "\\", '\\"', "\\\\", '<|"|>', "<|", '"|>', "<", "a", " ", "中", "\n"]
+ for _ in range(3000):
+ text = "".join(rng.choice(pieces) for _ in range(rng.randint(0, 20)))
+ for start in range(len(text) + 1):
+ for gemma in (False, True):
+ assert tool_healing._balanced_brace_end(
+ text, start, gemma_quotes = gemma
+ ) == _brace_end_reference(text, start, gemma), (text, start, gemma)
+
+
+def test_passthrough_normalize_hands_back_the_decoded_line():
+ """The relay reuses this decode instead of parsing the line again, so it must equal one."""
+ import json
+
+ from routes.inference import (
+ _SSE_LINE_UNPARSED,
+ _normalize_openai_passthrough_sse_line,
+ _normalize_openai_passthrough_sse_line_and_data,
+ )
+
+ calls = '[{"index":0,"function":{"name":"a"}},{"index":1,"function":{"name":"b"}}]'
+ lines = [
+ 'data: {"choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":null}]}',
+ 'data: {"choices":[{"index":0,"delta":{"reasoning_content":"t é 🙂"}}],"x":1e400}',
+ 'data:{"choices":[{"index":0,"delta":{"reasoning_content":"t","content":"c"}}]}',
+ 'data: {"choices":[{"delta":{"tool_calls":' + calls + "}}]}",
+ 'data: ["reasoning_content"]',
+ 'data: "reasoning_content"',
+ 'data: {"reasoning_content": broken',
+ "data: [DONE]",
+ ": keepalive",
+ ]
+ for line in lines:
+ for cap in (False, True):
+ out, data = _normalize_openai_passthrough_sse_line_and_data(
+ line, cap_parallel_tool_calls = cap
+ )
+ assert out == _normalize_openai_passthrough_sse_line(line, cap_parallel_tool_calls = cap)
+ if data is _SSE_LINE_UNPARSED:
+ continue
+ assert data == json.loads(out[len("data:") :].strip()), (line, cap)
+
+
+def test_literal_anchored_search_matches_the_regex_search():
+ from core.inference import tool_call_parser as tcp
+
+ pieces = [
+ "call",
+ "call:",
+ "call :",
+ "call:web_search{",
+ "xcall:a{",
+ "_call:a{",
+ "recall:b{",
+ "{",
+ "}",
+ ]
+ pieces += [
+ " ",
+ "\n",
+ "a",
+ "b:",
+ "<tool_call>",
+ "</tool_call>",
+ "中",
+ "call:\n web_search {",
+ '<|"|>',
+ ]
+ rng = random.Random(0)
+ for _ in range(20000):
+ text = "".join(rng.choice(pieces) for _ in range(rng.randint(0, 30)))
+ pos = rng.randint(0, len(text))
+ want = tcp._GEMMA_BARE_TC_RE.search(text, pos)
+ got = tcp._search_from_literal(tcp._GEMMA_BARE_TC_RE, "call", text, pos)
+ assert (want and (want.span(), want.groups())) == (got and (got.span(), got.groups())), (
+ text,
+ pos,
+ )
diff --git a/studio/backend/tests/test_streaming_stripper.py b/studio/backend/tests/test_streaming_stripper.py
index d74b7dc80ce..0663413413c 100644
--- a/studio/backend/tests/test_streaming_stripper.py
+++ b/studio/backend/tests/test_streaming_stripper.py
@@ -150,34 +150,27 @@ def test_repeated_call_is_cached():
assert stripper.strip(text) is stripper.strip(text)
-def test_scan_is_amortized_not_quadratic():
- """Prose-only text must cost constant work per token, not grow with length; compared as a ratio."""
- import time
-
- def elapsed(fn, tokens):
- text = ""
- start = time.perf_counter()
- for token in tokens:
- text += token
- fn(text)
- return time.perf_counter() - start
+def test_scan_is_amortized_not_quadratic(monkeypatch):
+ """Prose-only text costs constant work per token: the sentinel scan resumes where it stopped.
- short = ["word " for _ in range(300)]
- long = ["word " for _ in range(1200)]
+ Counts the characters handed to the sentinel scan instead of timing, so it does not depend on how
+ fast the full strip is (a cheaper full strip once made a ratio against it meaningless)."""
+ scanned = []
+ real = tool_call_parser._first_sentinel
- def incremental(tokens):
- stripper = StreamingMarkupStripper(ENABLED)
- return elapsed(stripper.strip, tokens)
-
- # 4x the tokens: the reference rescans everything (~16x), the incremental one resumes
- # (~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)
+ def counting(text, start, *args, **kwargs):
+ scanned.append(len(text) - max(start, 0))
+ return real(text, start, *args, **kwargs)
- 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"
- )
+ monkeypatch.setattr(tool_call_parser, "_first_sentinel", counting)
+ stripper = StreamingMarkupStripper(ENABLED)
+ text = ""
+ for _ in range(1200):
+ text += "word "
+ assert stripper.strip(text) == text
+ overlap = tool_call_parser._SENTINEL_MAX_LEN
+ # Rescanning from the start every token would read about len(text) ** 2 / 10 (3.6M).
+ assert sum(scanned) <= len(text) + 1200 * overlap, sum(scanned)
# Each case diverged from the reference strip before its guard was added.