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: bound the passthrough healer gate to openers the parser would scan (#15717)
Daniel Han41c6a0d04563
diff --git a/studio/backend/core/inference/passthrough_healing.py b/studio/backend/core/inference/passthrough_healing.pyindex 6c2b99a73ad..773f5a9b1b7 100644--- a/studio/backend/core/inference/passthrough_healing.py+++ b/studio/backend/core/inference/passthrough_healing.py@@ -5,6 +5,7 @@unmatched output; response_format requests untouched; auto_heal_tool_calls false andUNSLOTH_DISABLE_TOOL_CALL_HEALING=1 opt out"""+import bisectimport jsonimport osimport re@@ -268,6 +269,8 @@ _STRICT_CLOSE_TOKENS = ("</tool_call>", "<|end_message|>", "<tool_call|>", "</fu_CALLS_TAG = "[TOOL_CALLS]"_ARGS_TAG = "[ARGS]"_WS_RE = re.compile(r"\s*")+# A rehearsal name[ARGS] needs a name character right before the tag.+_NAME_CHAR_RE = re.compile(r"[\w-]")_SPAN_SKIP_RE = re.compile(r'[^"{}\\]*')_STRING_SKIP_RE = re.compile(r'[^"\\]*')_BRACKET_SKIP_RE = re.compile(r'[^"\[\]{}]*')@@ -342,7 +345,7 @@ class _StrictParseGate:Each chunk scans only the appended text; any buffer that does not extend the last one starts over."""- __slots__ = ("_buf", "_closer", "_calls", "_args", "_scans")+ __slots__ = ("_buf", "_closer", "_calls", "_args", "_scans", "_brace_close", "_any_close")def __init__(self) -> None:self._reset()@@ -354,6 +357,14 @@ class _StrictParseGate:self._args: list = []# (open index, is array) -> resumable scan state, or the close index once balanced.self._scans: dict = {}+ # Last "}" and last "]" or "}": an opener after them cannot balance yet.+ self._brace_close = -1+ self._any_close = -1++ def release(self) -> None:+ """Drop the scan once the healer lets go of its held text."""+ if self._buf:+ self._reset()def may_parse(self, buffer: str) -> bool:prev_len = len(self._buf)@@ -371,22 +382,31 @@ class _StrictParseGate:for tag, found in ((_CALLS_TAG, self._calls), (_ARGS_TAG, self._args)):pos = buffer.find(tag, max(0, prev_len - len(tag) + 1))while pos >= 0:- found.append(pos)+ if found is self._calls or (pos and _NAME_CHAR_RE.match(buffer, pos - 1)):+ found.append(pos)pos = buffer.find(tag, pos + len(tag))if not self._calls and not self._args:return False- # Every opener _iter_bracket_spans can try; regexes rerun since a tail match can still change.+ brace_close = buffer.rfind("}", prev_len)+ if brace_close >= 0:+ self._brace_close = brace_close+ brace_close = self._brace_close+ any_close = max(buffer.rfind("]", prev_len), brace_close, self._any_close)+ self._any_close = any_close+ # Openers _iter_bracket_spans would scan; regexes rerun since a tail match can still change.opens = []- for pos in self._calls:+ calls = self._calls+ for pos in calls[: bisect.bisect_right(calls, any_close)]:m = _MISTRAL_BRACKET_RE.match(buffer, pos)- if m is not None:+ if m is not None and m.end() < brace_close:opens.append((m.end(), False))m = _MISTRAL_ARRAY_RE.match(buffer, pos)- if m is not None:+ if m is not None and m.end() < any_close:opens.append((m.end(), True))- for pos in self._args:+ args = self._args+ for pos in args[: bisect.bisect_right(args, brace_close)]:brace = _WS_RE.match(buffer, pos + len(_ARGS_TAG)).end()- if buffer.startswith("{", brace):+ if brace < brace_close and buffer.startswith("{", brace):opens.append((brace, False))scans = self._scansfor key in opens:@@ -451,6 +471,7 @@ class StreamToolCallHealer:def structured_tool_call_seen(self) -> list:"""Go dormant; flush anything held so no text is swallowed."""self.dormant = True+ self._strict_gate.release()held, self._buffer, self._holding = self._buffer, "", Falsereturn [("text", held)] if held else []@@ -464,6 +485,7 @@ class StreamToolCallHealer:events: list = []while True:if not self._holding:+ self._strict_gate.release()start = _earliest_signal(self._buffer)if start >= 0:if start:@@ -534,6 +556,7 @@ class StreamToolCallHealer:def finalize(self) -> list:"""Keeps event order; only promoted call markup is dropped and all other residue flushes as text."""+ self._strict_gate.release()if not self._buffer:return []residue, self._buffer = self._buffer, ""diff --git a/studio/backend/tests/test_passthrough_healing_strict_gate.py b/studio/backend/tests/test_passthrough_healing_strict_gate.pyindex e7481f1a647..88966c0b3c3 100644--- a/studio/backend/tests/test_passthrough_healing_strict_gate.py+++ b/studio/backend/tests/test_passthrough_healing_strict_gate.py@@ -21,6 +21,9 @@ from core.tool_healing import _balanced_bracket_end, _balanced_json_span # noqaclass _AlwaysParse:+ def release(self):+ pass+def may_parse(self, buffer):return True@@ -140,3 +143,73 @@ def test_long_held_call_is_not_reparsed_per_chunk(monkeypatch, opening, closing)events += healer.finalize()assert [kind for kind, _ in events] == ["tool_call"]assert len(calls) <= 2+++_FUZZ_PIECES = (+ "[TOOL_CALLS]",+ "[ARGS]",+ "[CALL_ID]",+ "python",+ "web_search",+ "-",+ " ",+ "{",+ "}",+ "[",+ "]",+ '"',+ "\\",+ ":",+ "x",+)+++def test_random_marker_soup_matches_always_reparsing_healer():+ rng = random.Random(15618)+ for _ in range(300):+ doc = "".join(rng.choice(_FUZZ_PIECES) for _ in range(rng.randint(1, 24)))+ for chunks in (+ [doc],+ [doc[i : i + 1] for i in range(len(doc))],+ [doc[i : i + 5] for i in range(0, len(doc), 5)],+ ):+ assert _events(ph.StreamToolCallHealer, chunks) == _events(+ _ReparsingHealer, chunks+ ), doc+++def _count_scans(monkeypatch):+ scans = []+ for name in ("_resume_json_span", "_resume_bracket_end"):+ real = getattr(ph, name)+ monkeypatch.setattr(+ ph, name, lambda text, state, _real = real: scans.append(1) or _real(text, state)+ )+ return scans+++ "text",+ [+ "[TOOL_CALLS]f" + "python[ARGS]{" * 2000,+ "[TOOL_CALLS]python{" * 2000,+ '[TOOL_CALLS]python{"query": "' + "[ARGS]{" * 2000 + "}",+ ],+ ids = ["rehearsal_no_closer", "bracket_no_closer", "nameless_quoted"],+)+def test_openers_that_cannot_parse_are_not_scanned(monkeypatch, text):+ scans = _count_scans(monkeypatch)+ for chunks in ([text], [text[i : i + 64] for i in range(0, len(text), 64)]):+ scans.clear()+ assert _events(ph.StreamToolCallHealer, chunks) == _events(_ReparsingHealer, chunks)+ assert len(scans) <= len(chunks), len(scans)+++def test_gate_lets_go_of_released_text():+ healer = ph.StreamToolCallHealer({"python"}, TOOLS)+ healer.feed("[TOOL_CALLS]python[ARGS]{" + "x" * (ph._MAX_HOLD_CHARS + 10))+ assert healer._buffer == "" and healer._strict_gate._buf == ""+ healer.feed('<tool_call>{"name": "python"')+ assert healer._strict_gate._buf+ healer.finalize()+ assert healer._strict_gate._buf == ""