Skip to content

studio: tool calling + healing parity for Llama-3, Mistral, Gemma 4 on safetensors + MLX - #5620

Merged
danielhanchen merged 87 commits into
mainfrom
studio-tools-multi-format-v2
Jul 6, 2026
Merged

danielhanchen merged 87 commits into
mainfrom
studio-tools-multi-format-v2

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

DRAFT - holding open while we validate end to end with real models. Do not merge until safetensors + MLX behaviour is verified for every covered family.

danielhanchen and others added 3 commits May 19, 2026 14:27
…LX (#5615)

Adds tool calling for Llama-3, Mistral (pre-v11 + v11+ + [ARGS]), and Gemma 4 to the safetensors / transformers and MLX backends. Parser patched against llama.cpp / vLLM / SGLang per-family parsers and normalises to OpenAI shape. 96 targeted unit tests + cross-OS staging CI (ubuntu / macos-14 / windows) green on the multi-format probe.
After the multi-format parser landed in #5615, the safetensors / MLX
agentic loop and the GGUF loop still differed on healing behaviour.
This commit closes the gaps in both directions so the two backends
react the same way to identical model output.

Changes:

1. core/inference/llama_cpp.py -- the GGUF BUFFERING state machine
   now wakes on every emission marker the shared parser knows. Was
   ("<tool_call>", "<function="); is now the five-tuple imported
   from core.inference.tool_call_parser (Qwen / Qwen3.5 / Llama-3
   <|python_tag|> / Mistral [TOOL_CALLS] / Gemma 4 <|tool_call>).
   Stream cleanup is delegated to the same shared strip_tool_markup
   so leaked markup from any family is removed from assistant
   content.

2. core/inference/llama_cpp.py -- per-tool canonical heal key. When
   a tool arguments field is a bare string and JSON parsing fails,
   the GGUF path now heals to {"code": raw_args} for python,
   {"command": raw_args} for terminal, and {"query": raw_args} for
   everything else. Was hard-coded to {"query": raw_args}, which
   silently routed every python / terminal emission through
   web_search. Mirrors safetensors_agentic._CANONICAL_HEAL_ARG.

3. core/inference/safetensors_agentic.py -- re-prompt on plan-
   without-action. When the model emits a short forward-looking
   intent ("I'll search for that", "Let me check", "First, I
   will...") and no tool call, the loop nudges the model to act
   instead of silently returning a plan-only answer. Up to
   _MAX_REPROMPTS=3 (matches GGUF). The intent regex, character
   cap, and instruction text are byte-identical to the GGUF path.
   The buffer-end fall-through is unified so a buffered intent
   emission that never exits the BUFFERING state still triggers
   the re-prompt.

4. core/inference/safetensors_agentic.py -- extra iteration slots
   for re-prompts. The loop now budgets max_tool_iterations +
   _MAX_REPROMPTS + 1 total iterations and tracks the tool-call
   count separately, so a stalling model can be nudged 3x without
   eating the caller's tool-call budget. Mirrors the _extra slot
   reservation in the GGUF path.

Tests (14 new safetensors-side units; 5 GGUF parity pins):

  TestLoopRePrompt                 -- intent-trigger, plain-answer,
                                      no-tools, cap-at-three, budget
                                      preserved, buffer-end intent.
  TestLoopCanonicalHealKey         -- python / terminal / unknown.
  TestGGUFSafetensorsHealingParity -- shared markers used, shared
                                      strip used, canonical heal keys
                                      identical, intent regex matches
                                      same phrases, _MAX_REPROMPTS
                                      equal on both backends.

All 110 targeted tests pass locally; the broader tool / inference /
model-config / sandbox / anthropic / mlx suites stay green.

Why this matters

Without this parity, Llama-3.2 / Mistral / Gemma 4 emissions on Mac
(MLX) and Linux-safetensors stop the agentic loop as soon as the
model says "Let me...", because the GGUF re-prompt logic never
existed on these backends. The two-marker GGUF BUFFERING tuple also
let non-Qwen tool emissions stream out as plain prose when
llama-server's structured channel did not pick them up. Both paths
now drain the same way, heal the same way, and re-prompt the same
way -- so a tool call that works on GGUF works identically on
safetensors / MLX.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request May 19, 2026
Mirrors the healing-parity follow-up commit from PR unslothai#5620:

1. GGUF BUFFERING tuple now uses the shared 5-format
   TOOL_XML_SIGNALS so non-Qwen tool emissions wake the state
   machine (was only 2 markers).
2. GGUF stream cleanup delegates to the shared strip_tool_markup
   so leaked markup from any family is removed from assistant
   content.
3. GGUF per-tool canonical heal key (python -> code, terminal
   -> command, * -> query) when arguments is a bare string.
4. Safetensors / MLX re-prompt on plan-without-action with
   _MAX_REPROMPTS=3 + extra iteration slots so re-prompts do
   not eat the tool budget.

Also pulls in core/tool_healing.py which staging was missing
(the legacy two-format helper module that llama_cpp.py imports
the regex constants from).

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request significantly expands the tool-call parsing capabilities to support multiple model families, including Llama-3, Mistral, and Gemma 4, while ensuring parity between GGUF and safetensors backends. It introduces a re-prompting mechanism to nudge models that express intent without taking action and implements per-tool canonical heal keys. Feedback highlights potential issues with regex patterns for Mistral and Llama-3 that could lead to incorrect truncation or leaked markup, a bug in string unescaping that corrupts non-ASCII characters, and an order-dependency in sentinel stripping logic.

Comment thread studio/backend/routes/inference.py Resolved
shimmyshimmer and others added 2 commits May 19, 2026 14:56
Three high-priority gemini findings on the tool-call parsing additions:

  1. unicode_escape on UTF-8 bytes corrupts non-ASCII literals
     (e.g. ✨ becomes â\x9c¨). Replace with json.loads on a quoted
     string -- preserves emoji / CJK / RTL while still handling
     \n \t \uXXXX escapes.

  2. Llama-3 sentinel stripping is order-dependent. A leading
     `<|eot_id|><|begin_of_text|>` left `<|begin_of_text|>` behind
     because the loop had already passed that sentinel. Loop until
     no sentinel matches at the start.

  3. Mistral v11+ `[TOOL_CALLS] name { json }` regex uses non-greedy
     `\{.*?\}` which truncates at the first `}` of a nested JSON
     argument, leaking the tail (e.g. `}}`) into user-visible
     streamed text. Same problem for the v0.3 array pattern with
     nested brackets. Strip those with balanced brace/bracket
     scanning via a new `_strip_mistral_closed_calls` helper called
     from `strip_tool_markup`.

Also fix the inference routes' parallel `_TOOL_XML_RE`:

  - Same nested-JSON truncation in the Mistral patterns; route the
    strip through the parser's balanced-scan helper via a thin
    `_strip_tool_xml` wrapper that all existing callers now use.
  - Llama-3 `<|python_tag|>[^\n<]*` stopped at any `<`, leaking the
    tail of any tool call whose argument contained a literal `<`
    (queries, code snippets). Relax to `[^\n]*` which keeps the
    strip confined to the actual end-of-line.
@danielhanchen

Copy link
Copy Markdown
Member Author

Looks safe to land. Pulled pr-5620 and verified against pr-5615.

What 5620 adds beyond 5615 (parser/inference scope):

File LOC What's new
tool_call_parser.py +137 Balanced brace/bracket Mistral stripping, sentinel-loop, UTF-8-safe KV decoder
safetensors_agentic.py +82 Intent re-prompt loop, _MAX_REPROMPTS=3, BUFFERING fall-through to STREAMING
llama_cpp.py +39 Shared TOOL_XML_SIGNALS + per-tool canonical heal key (parity with safetensors)
routes/inference.py +46 All 9 _TOOL_XML_RE.sub sites switched to _strip_tool_xml()
tests/test_safetensors_tool_loop.py +253 TestLoopRePrompt (6) + TestLoopCanonicalHealKey (3)

Each of the five #5615 regressions has a fix + test in 5620 — details in #5615/#5619.

Tests: pytest studio/backend/tests/test_safetensors_tool_loop.py studio/backend/tests/test_safetensors_capability_advertise.py -q → 110 passed in 3.86s (had to pip install structlog — missing dev dep, not a code issue).

Worth watching when the validation phase finishes:

  • False-positive tool detection on prose JSON. _parse_llama3_bare_json (tool_call_parser.py:486-547) triggers on any leading { with name + parameters|arguments. The strict parameters/arguments dict guard mitigates this, but a user echoing back {"name":"foo","arguments":{}} in a code fence isn't stripped first — worth a quick fence-aware preamble check.
  • python_tag multi-line code. The full parser (_parse_llama3_python_tag) handles multi-line via _balanced_brace_end, but the routes-level _strip_tool_xml() helper is single-line ([^\n]*). Multi-line python.call(code="…\n…") will have only the first line stripped at the route layer; remaining lines may leak in non-parser paths.
  • Partial Mistral buffer. _strip_mistral_closed_calls correctly leaves unclosed [TOOL_CALLS]… in place, but the BUFFERING state machine caps at _MAX_BUFFER_CHARS=32 (safetensors_agentic.py:44). A long [TOOL_CALLS] very_long_name [ARGS] {… that exceeds 32 chars before reaching { may flush to user. Worth a test that names a tool with a long identifier and asserts no early flush.
  • Re-prompt bound is _MAX_REPROMPTS=3 and _tool_iters_done = iteration + 1 - reprompt_count (safetensors_agentic.py:447), with test_max_reprompts_capped_at_three (test_safetensors_tool_loop.py:893) covering the cap. Looks correct.

Holding the [DRAFT] flag while the end-to-end real-model validation finishes is the right call. Once that's green, this is ready to merge.

Daniel Han and others added 2 commits May 22, 2026 08:18
Earlier revisions of _TOOL_XML_RE in studio.backend.routes.inference
oscillated between two bug shapes:

  5615    r"<\|python_tag\|>[^\n<]*"   -- stopped at any literal "<"
                                         so code='if x < 10: pass'
                                         leaked '< 10: pass)' to the
                                         user.
  5620.1  r"<\|python_tag\|>[^\n]*"    -- single-line only; the second
                                         line of
                                         python.call(code="a\nb")
                                         leaked.

The full parser (_parse_llama3_python_tag) already handles both via
balanced-brace scanning, so the parsing path was fine; the LEAK was
in the streaming strip path that runs on every cumulative emission
while content is still arriving.

Switch to r"<\|python_tag\|>(?:[^<]|<(?!\|))*" so the strip consumes:

  * any character that is not a "<" (newlines, JSON, code, ...),
  * a "<" only when it is NOT followed by "|" (i.e. NOT a Llama-3
    sentinel start like <|eot_id|>, <|eom_id|>, <|begin_of_text|>).

This means:

  * code='if x < 10' stays inside the strip (5615 fix preserved),
  * multi-line code stays inside the strip (5620 round 2),
  * the strip terminates at the next Llama-3 sentinel so trailing
    assistant content survives.

Tests: TestRoutesPythonTagStrip (8 cases)
  pytest test_safetensors_tool_loop.py test_safetensors_capability_advertise.py
    -> 118 passed in 1.81s (was 110).
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed 7ef4b115 closing the routes-level multi-line python_tag gap flagged earlier. The full parser already handled this via balanced-brace scanning; the leak was only on the streaming strip path that runs while content is still arriving.

Earlier history of _TOOL_XML_RE's python_tag clause:

Revision Pattern Bug
#5615 <|python_tag|>[^\n<]* Stopped at literal < so code="if x < 10" leaked < 10: pass)
#5620 round 1 <|python_tag|>[^\n]* Single-line only — the second line of python.call(code="a\nb") leaked
this commit <|python_tag|>(?:[^<]|<(?!|))* Consumes everything that is NOT a Llama-3 <|sentinel|> start. Multi-line code, embedded JSON, and literal < in code all stay inside the strip.

pytest studio/backend/tests/test_safetensors_tool_loop.py studio/backend/tests/test_safetensors_capability_advertise.py -q → 118 passed in 1.81s (was 110, +8 new tests in TestRoutesPythonTagStrip covering single-line, less-than-in-code, multi-line, multi-line-with-less-than, sentinel-stop, and JSON-form multi-line cases).

The _MAX_BUFFER_CHARS=32 concern I raised earlier turned out to be unfounded — the BUFFERING state machine treats a fully arrived [TOOL_CALLS] as a match (length 12, well under 32) and transitions to DRAINING, so a long-tool-name [TOOL_CALLS] very_long_name [ARGS] {… never accumulates 32 chars in BUFFERING. The 32-char cap only applies to partial signal prefixes (e.g. <|py waiting to complete to <|python_tag|>), and the longest signal is 14 chars (<|python_tag|>), so the cap is already more than 2× the worst-case prefix length.

The remaining false-positive concern (a model echoing back {"name":"foo","arguments":{}} as the very first non-whitespace characters of an assistant response triggering _parse_llama3_bare_json) is bounded by the strict parameters/arguments dict guard, which keeps plain prose unaffected — happy to add a fence-aware preamble check in a follow-up if you want belt-and-suspenders on that path too.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request May 22, 2026
Each PR ran the same staged source files before, which went stale when
the upstream PR commits advanced. Refactor to one job per PR with an
actions/checkout of that PR's head ref, so cross-OS validation
always uses the latest commit:

  - PR unslothai#5603 sandbox            -> studio-sandbox-hardening
  - PR unslothai#5620 parser parity      -> studio-tools-multi-format-v2
  - PR unslothai#5696 mtp reload guards  -> followup-mtp-reload-guards (unslothai#5582 followup)
  - PR unslothai#5695 lockfile audit     -> followup-lockfile-audit-regressions (unslothai#5604 followup)

4 jobs x 3 OSes = 12 runs; Windows = 4 (below the 5-concurrent cap).
cancel-in-progress per (workflow, ref) keeps iteration cheap.

All tests stay CPU-only and rely on the CUDA spoof harness in
tests/conftest.py + tests/_zoo_aggressive_cuda_spoof.py, so no real GPU
is required on any runner.
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request May 22, 2026
unslothai#5620 parser tests transitively import the safetensors loop, which
needs the datasets package. unslothai#5696 route-guard tests import
routes/inference.py, which transitively imports core/training (uses
matplotlib). Add both, plus the auth deps (pyjwt/cryptography/
aiosqlite/python-multipart) needed for any test that touches the
FastAPI route module so route-level imports resolve cleanly on all
three OSes.
danielhanchen and others added 4 commits May 27, 2026 12:19
Conflict in studio/backend/routes/inference.py: combine #5620's
multi-format strip (Llama-3 <|python_tag|>, Gemma 4 <|tool_call>...
<tool_call|>, Mistral [TOOL_CALLS] via parser helper) with main's
speculative-buffer leak fixes (orphan open to EOF, bare orphan close,
tail-only </parameter> anchored to \Z so mid-text <parameter> in user
code samples survives).

pytest studio/backend/tests/test_safetensors_tool_loop.py \
       studio/backend/tests/test_safetensors_capability_advertise.py -q
-> 118 passed.
Comments were narrating what the code already says. Cut historical
"earlier revisions used X, then Y" narratives down to one-line WHY
notes where the footgun still matters (canonical heal-key parity,
balanced-brace vs non-greedy regex, ``(?:[^<]|<(?!\|))*`` over
``[^\n<]*``/``[^\n]*``). Drop section-header banners.

No behaviour change. Re-ran:
  pytest studio/backend/tests/test_safetensors_tool_loop.py \
         studio/backend/tests/test_safetensors_capability_advertise.py -q
  -> 118 passed.
Regression replay (parser + _coerce_arguments on the 5 #5615 inputs)
  -> 21/21.
danielhanchen and others added 3 commits May 27, 2026 13:31
Three surgical extensions to the multi-format tool-call parser, each
covering a real fine-tune / template emission shape that the current
parser silently drops. No path narrows; all changes widen what is
accepted.

1. `_parse_tool_call_json` now accepts both `arguments` and
   `parameters` keys. A Hermes / Qwen `<tool_call>{json}</tool_call>`
   wrapper around a Llama-3.2 fine-tune that emits the `parameters`
   key was extracting the tool name and silently discarding the
   args, producing a working-shaped call with an empty payload. The
   bare-JSON and python_tag paths already accepted both keys; this
   path now matches them.

2. `_TC_FUNC_START_RE`, `_TC_PARAM_START_RE`, and `_TC_PARAM_CLOSE_RE`
   now also match the attribute form
   `<function name="..."><param name="...">v</param></function>` used
   by MiniCPM-5 and MiniMax-M2. Names land in either capture group,
   and `</param>` is accepted as a short close.

3. `_parse_llama3_bare_json` sentinel-strip now consumes the role
   label inserted between `<|start_header_id|>` and
   `<|end_header_id|>` by Meta's official Llama-3.x chat template.
   Without this, every assistant turn re-fed through the template
   prefix `<|start_header_id|>assistant<|end_header_id|>\n\n{json}`
   parsed to zero calls, so any history-with-tool-call round-trip
   in production silently dropped.

Tests in `studio/backend/tests/test_safetensors_tool_loop.py`:

* `TestParserRobustness::test_tool_call_json_accepts_parameters_key`
* `TestParserRobustness::test_function_xml_attribute_form`
* `TestParserRobustness::test_function_xml_attribute_form_multi_param`
* `TestParserRobustness::test_function_xml_legacy_equals_form_still_works`
  (regression guard for the existing `<function=name>` syntax)
* `TestParserRobustness::test_llama3_chat_template_round_trip`
* `TestParserRobustness::test_llama3_round_trip_all_roles`
* `TestParserRobustness::test_llama3_round_trip_with_eot_prefix`

`pytest studio/backend/tests/test_safetensors_tool_loop.py
        studio/backend/tests/test_safetensors_capability_advertise.py -q`
goes from 118 to 125 passed.
Two conflicts, both in the tool-call markup-strip plumbing:

* `studio/backend/core/inference/tool_call_parser.py` -- main widened
  `<function=NAME>` and `<parameter=NAME>` from `\w+` to `[\w-]+` so
  MCP tool ids with hyphens (mcp__srv__list-issues, `repo-name`,
  `issue-number`) parse the same as the built-ins. PR-5620 had
  broadened the same patterns to `[\w\.\-]+` (also handles dotted
  module names) and added the python_tag / Mistral / Gemma 4 strip
  families plus the `TOOL_XML_SIGNALS` constant. Resolved by keeping
  PR-5620's full pattern set; `[\w\.\-]+` already accepts the hyphens
  main was widening to, so no MCP coverage is lost.

* `studio/backend/routes/inference.py` -- `_TOOL_XML_RE` regex on
  the route-level scrub path. Same hyphen widening on main vs.
  PR-5620's union of (closed pair / orphan open / Gemma 4 /
  python_tag / `</parameter>` tail-only). Resolved by unioning all
  five patterns and applying main's `[\w-]+` on the `function=` name
  char class so hyphenated MCP names get stripped on the route too.

pytest studio/backend/tests/test_safetensors_tool_loop.py
       studio/backend/tests/test_safetensors_capability_advertise.py -q
-> 125 passed.
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request May 27, 2026
Four fixes addressing review of the parent commit:

1. GLM <arg_value> coercion: tighten the
   json.loads -> ast.literal_eval -> raw cascade to only deserialize
   when the body unambiguously looks like a JSON literal (object,
   array, JSON-encoded string, true/false/null, or numeric). Strings
   like ``True`` / ``None`` (Python literals, not JSON) and arbitrary
   prose now stay raw. The bare-numeric / bare-boolean ambiguity with
   string args remains an inherent limitation of the template without
   schema access -- documented in the new comment. Drops the ast
   import entirely (closes Gemini's :1036 suggestion).

2. Kimi K2 bare-counter ids (e.g. ``<|tool_call_begin|>3``) are now
   dropped rather than surfaced as a tool literally named "3". Matches
   vLLM behaviour; SGLang's schema-infer fallback is out of scope at
   the parse site. Real Kimi K2 emissions use ``functions.NAME:IDX``
   so this is the exception path.

3. Restore the elaborate ``<|python_tag|>(?:[^<]|<(?!\|))*`` clause in
   routes.inference._TOOL_XML_RE -- the simpler ``[^\n<]*`` form
   regressed PR unslothai#5620's multi-line / literal-``<`` python_tag fix.
   Restore ``TestRoutesPythonTagStrip`` (8 tests) adapted to call
   ``_TOOL_XML_RE.sub`` directly since the ``_strip_tool_xml`` helper
   was inlined this PR.

4. Add the spaced and backslash-escaped DeepSeek opener variants
   (``<|tool calls begin|>``, ``<|tool\_calls\_begin|>``) to
   ``TOOL_XML_SIGNALS`` for streaming-gate parity with
   ``_DEEPSEEK_BEGIN_RE``.

Also updates the llama.cpp / vLLM citations in the parser docstrings:
``common/chat-parser.cpp`` was split into ``common/chat.cpp`` +
``common/chat-peg-parser.cpp`` by llama.cpp PR unslothai#18675, and vLLM
moved the tool parsers from ``vllm/entrypoints/openai/tool_parsers/``
to ``vllm/tool_parsers/``. Pin to pre-refactor commit ``51fa458a92d6``
where the cited line numbers still resolve.

New regression tests in ``test_pr5624_regressions.py`` cover the GLM
coercion heuristic shapes, GLM literal-``<`` in arg_value, Kimi K2
dotted name, Kimi K2 bare-counter drop, DeepSeek V3.1 truncated
mid-stream, and routes-layer strip across all three new families.

Tests:
  pytest studio/backend/tests/test_safetensors_tool_loop.py
         studio/backend/tests/test_safetensors_capability_advertise.py
         studio/backend/tests/test_pr5624_regressions.py -q
  -> 170 passed in 1.91s
danielhanchen and others added 2 commits May 27, 2026 14:23
…all>

`_parse_function_xml` was looking for `</tool_call>` (the Hermes
wrapper) as the body terminator. When a model emits a standalone
`<function=NAME><parameter=K>v</parameter></function>` followed by
explanatory prose (which models routinely do), no `</tool_call>` is
present, so the body extended to end-of-string and the trailing
prose leaked into the LAST parameter value.

Pre-existing on main (the legacy `<function=NAME>` form had this
bug too). Same affects PR #5620's new attribute-form
`<function name="NAME"><param name="K">v</param></function>`
emission used by MiniCPM-5 / MiniMax-M2.

Fix: `_TC_END_TAG_RE` now matches either `</tool_call>` OR
`</function>`. The existing `_TC_FUNC_CLOSE_RE` / `_TC_PARAM_CLOSE_RE`
strips are unchanged. Multi-call inputs still bound each function
at the next `<function=` start, so no over-eager consumption.

New tests:

* `test_function_xml_followed_by_prose` (legacy form + prose)
* `test_function_attribute_xml_followed_by_prose` (attribute form + prose)

Existing `test_code_with_embedded_xml` still passes (a parameter
value containing literal `<a></a>` is preserved because the
embedded close tag is `</a>`, not `</function>`).

`pytest studio/backend/tests/test_safetensors_tool_loop.py
        studio/backend/tests/test_safetensors_capability_advertise.py -q`
goes from 125 to 127 passed.
A fuzz pass on PR #5811 turned up that ``_parse_llama3_bare_json``
accepted ``parameters`` as a string, contradicting the docstring's
"parameters or arguments is a dict" guard. Prose JSON like
``{"name":"foo","parameters":"a sentence"}`` would wrongly fire the
parser, which the agentic loop would then heal into a real
``foo(query="a sentence")`` call.

Same code lives on this branch, so the same fix applies here.

Tightened guard:

  - ``parameters`` must be a dict (Llama-3 spec).
  - ``arguments`` may be a dict, or a JSON-encoded string that
    decodes to a dict (OpenAI shape, e.g.
    ``"arguments":"{\"q\":\"x\"}"``). Plain non-JSON strings or
    JSON-strings of lists / scalars / null no longer pass.

Mirrors the fix landed in PR #5811 commit 615b860. Adds the same
4 regression tests under TestParserMultiFormat.

Existing test suite stays green: 127 -> 131 passing.
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request May 27, 2026
The JSON sub-path of ``_parse_llama3_python_tag`` was fabricating
``{"value": args}`` when the model emitted a non-dict / non-string
``arguments`` value (e.g. ``42``, ``[1,2,3]``, ``null``, ``true``).
This silently turned a malformed emission into a real tool call,
which the agentic loop would then execute with arguments the model
never intended.

Tightened: skip the call instead of fabricating. The same
behaviour now matches the bare-JSON guard tightened earlier
(strict-guard merge from PR unslothai#5620, inherited via merge here).

Added a regression test covering the four non-scalar shapes.
Pass count on this branch: 158 -> 159.

Sites in ``_parse_tool_call_json`` and ``_consume_mistral_call``
keep the existing looser behaviour for now; both are reached
only after explicit ``<tool_call>`` / ``[TOOL_CALLS]`` markers
so the false-positive surface there is much narrower.
danielhanchen and others added 2 commits May 31, 2026 13:17
…ALL_ID / THINK, attribute-form signal)

Three GGUF-parity fixes to the safetensors tool-call parser, each matching
llama.cpp's reference behaviour:

- Mistral Small 3.2 emits [TOOL_CALLS]name[CALL_ID]<id>[ARGS]{json}. The
  parser stopped after the name on seeing [CALL_ID] (neither [ARGS] nor {),
  dropping the call. Skip an optional [CALL_ID]<id> segment in both the
  parse and strip paths. llama.cpp parses this (test-chat.cpp:4785).

- Magistral wraps reasoning in [THINK]...[/THINK]. A [TOOL_CALLS] inside the
  reasoning was parsed as a real call, producing a phantom call. Strip a
  leading [THINK] block before scanning so only the post-reasoning call
  counts (test-chat.cpp:2285); a literal [THINK] inside a later argument is
  left intact.

- The standalone MiniCPM-5 / MiniMax-M2 <function name="..."> attribute form
  parsed correctly but was absent from TOOL_XML_SIGNALS and the markup strip
  patterns, so the streaming safety-net parse was gated off (dropping the
  call) and markup leaked into displayed text. Add the signal and broaden
  the strip regexes.

Adds regression tests for all three.
danielhanchen and others added 2 commits July 5, 2026 09:18
…lerant Mistral guard, strict strip shape

Four document-order and containment fixes. A leading attribute-form
call now parses before the shared XML pass, so markup quoted in its
parameter stays data. The open-parameter scan lets the parameter's own
close tag decide, so any number of literal function closes inside one
value stay data, restoring the pre-close-scan behavior for multi-close
arguments. The leading-Mistral guard tolerates a visible preamble, with
the leading-bare-JSON guard running first so a trigger quoted inside a
leading JSON object stays data. The bare-JSON strip requires the
parser's top-level name in every mode, so nested-name JSON answers
survive name-agnostic stripping.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: c51d7a9df2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

The leading-call ownership contract (a leading executable call owns the turn;
foreign markup quoted in its string arguments or trailing prose stays data) was
enforced for the bare-JSON, Mistral and attribute-form leading calls but not
for the Llama-3 <|python_tag|> form. The shared tool_healing XML pass runs
before _parse_llama3_python_tag and does not recognise <|python_tag|>, so a
<function=...> / <tool_call> / [TOOL_CALLS] literal quoted inside a
<|python_tag|> .call(...) string argument (or its JSON parameters) was promoted
and the wrong tool executed. Well-formed single-format examples:

  <|python_tag|>web_search.call(query="... <function=foo> ...")  ->  foo
  <|python_tag|>python.call(code="<function=render_html>..</function>")  ->  render_html

both returned the phantom inner tool instead of the real leading call.

Add a leading-<|python_tag|> guard mirroring the other leading-call guards:
when the tag is the first tool signal, parse it before tool_healing so quoted
foreign markup stays data. A foreign signal before the tag keeps normal
document order. Added TestPythonTagOuterOverXmlLiteral (7 cases).
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fa10f75ae8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +437 to +443
bare_probe = strip_llama3_leading_sentinels(stripped)
if (
not is_match
and not is_prefix
and tool_protocol_active
and bare_probe.startswith("{")
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Buffer split Llama sentinels before bare JSON

When a Llama-3.2 bare-JSON call is preceded by chat-template sentinels and the stream chunk boundary falls inside the sentinel, for example the first delta is <|start_header, strip_llama3_leading_sentinels cannot remove it yet and this condition is false. Because those sentinels are not in tool_xml_signals, the code falls through to the streaming branch and emits the sentinel plus subsequent {"name":...} tool JSON as content before the end-of-turn safety parser executes the tool. Hold partial Llama sentinels the same way as tool-signal prefixes before deciding this is not a call.

Useful? React with 👍 / 👎.

Comment on lines +568 to +574
calls = _tool_healing.parse_tool_calls_from_text(
content,
id_offset = id_offset,
allow_incomplete = allow_incomplete,
)
if calls:
return calls

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Route attr-style params to the extended XML parser

When the model mixes the legacy function opener with the attr-style parameter alias this file says it supports, e.g. <function=get_weather><param name="city">Tokyo</param></function>, core.tool_healing recognizes the function but ignores the <param name> body and returns a call with {}. The early return here prevents _parse_function_xml from recovering the argument, so tools execute without required parameters; either route these shapes to the extended parser first or teach tool_healing the same parameter aliases.

Useful? React with 👍 / 👎.

re.DOTALL,
),
re.compile(
r"<\|python_tag\|>(?=\s*(?:\{|[A-Za-z_][\w.]*\()|\s*$).*$",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Strip hyphenated python_tag calls after parsing

When a Llama <|python_tag|> call uses a hyphenated tool name, such as an MCP/OpenAI-style list-issues, the parser accepts it via the [\w.\-]+ call-head regex, but this final-strip guard only recognizes [\w.]* before (. The tool is executed while strip_tool_markup(..., final=True) leaves the raw call in assistant content/history, so clients can see it and the next turn can replay it; include - here to match the parser's name class.

Useful? React with 👍 / 👎.

Comment on lines +70 to +72
re.compile(
r"\[TOOL_CALLS\](?=\s*(?:[\[{]|[A-Za-z_][\w.\-]*[\[{])|\s*$).*$",
re.DOTALL,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Strip spaced Mistral named-call fragments

When a Mistral v11 named call is truncated and contains whitespace between the name and the JSON body, e.g. [TOOL_CALLS]web_search {"q":"x, the parser's named form accepts that whitespace but this final-strip pattern only recognizes a name immediately followed by [ or {. The DRAINING no-call path with Auto-Heal enabled therefore leaks the raw malformed tool-call text to the user instead of dropping it; allow the same whitespace here that _MISTRAL_V11_NAME_RE accepts.

Useful? React with 👍 / 👎.

Comment on lines +393 to +394
end = _balanced_brace_end(text, i)
return None if end is None else end + 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep truncated Mistral envelopes from promoting inner XML

When a leading Mistral call starts a valid named JSON body but truncates before the closing brace, this returns None, so _xml_signal_inside_leading_mistral treats the trigger as non-owning. If an argument string contains literal XML such as <function=evil>...</function>, the later XML parser can execute that inner literal instead of rejecting the malformed outer Mistral call; treat an unbalanced but syntactically-started Mistral region as owning the turn so quoted fallback markup cannot be promoted.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: fa10f75ae8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f0ecde668a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +791 to +794
val, length = _llama3_kv_value(body, p, n)
if length is None:
i = km.end()
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject unsupported Llama call arguments instead of dropping them

When a Llama <|python_tag|>name.call(...) value uses a Python/JSON compound literal such as items=["a"] or opts={"k":1} (valid for custom/MCP tool schemas), _llama3_kv_value returns no length and these lines skip only that key while still emitting the tool call. The loop then executes name with incomplete arguments (often {}) rather than preserving, healing, or rejecting the malformed parse, so tools can run with missing required inputs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The NAME.call(...) Python syntax is the Llama-3 built-in-tools-only protocol (brave_search / wolfram_alpha), whose schemas take a single string query; custom and MCP tools are invoked as JSON (function=name with a JSON body, or a name/parameters object), which the parser handles with full compound-value support. So a compound-literal .call() argument is not legitimate Llama-3 wire format and the dropped-arg case is unreachable on well-formed single-format input. Rejecting the whole call would also risk regressing valid scalar calls the scanner does not recognize.

Comment on lines +72 to +73
r"<\|python_tag\|>(?=\s*(?:\{|[A-Za-z_][\w.]*\()|\s*$).*$",
re.DOTALL,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound python_tag stripping at Llama sentinels

When a Llama text-form call is followed by a real sentinel such as <|eom_id|>/<|eot_id|> and then visible assistant text, this final-strip pattern consumes from <|python_tag|> through EOF. The safetensors/MLX tool loops use strip_tool_markup(final=True) after parsing, so they drop sentinel-delimited trailing content that the route-level stripper explicitly preserves for the same input.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eom_id and eot_id are turn-terminal: generation halts at them, so legitimate visible assistant text after the sentinel does not occur in a single-turn safetensors emission. For the realistic case (call plus terminal sentinel, no trailing text) the strip-to-end is correct and cleaner than the route-level regex, which leaves a stray sentinel visible. The divergence surfaces only on non-well-formed input; display residue. Eating unclosed tails at end-of-turn is documented intended behavior.

Comment on lines +38 to +42
_HEAL_SIGNALS = (
"<tool_call>",
"<|tool_call>",
"<function=",
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Heal the new text-form markers in passthrough

In client-tool passthrough mode, if llama-server emits a Llama <|python_tag|> or Mistral [TOOL_CALLS] call as text instead of structured deltas, _has_heal_signal is false because those newly supported markers are excluded here. That means the non-streaming and streaming healers relay the call as prose rather than a function_call item, leaving /v1/responses and chat passthrough broken for exactly the new templates this change teaches the local loops to parse.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The passthrough deliberately uses the narrow core.tool_healing signal set, kept equal to the pre-PR TOOL_XML_SIGNALS, so Llama python_tag and Mistral bracket calls were never healed there and behavior is preserved, not regressed. The decoupling from the expanded local-loop signals exists precisely to avoid the hold-a-streamed-call-then-flush-as-prose bug that adding the markers would reintroduce. Full passthrough parity for those formats needs switching passthrough to the new parser (with_spans support it currently lacks) and is separate future work, not a bug this PR introduced.

Comment on lines +428 to +430
end = _balanced_brace_end(content, i)
if end is None:
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep XML inert inside truncated outer calls

When a leading bare-JSON tool call is truncated before its matching }, this guard returns false and the parser falls through to the XML parsers. With Auto-Heal on, an argument string such as "<function=evil><parameter=x>1</parameter></function>" inside the unfinished outer call can then be promoted and executed as a separate XML tool call instead of being treated as data from the truncated Llama-3.2 emission.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The guard returns False only when the leading object is truncated (unbalanced braces), which is the malformed/truncated-markup class; when the object is balanced it correctly treats the embedded XML as data. The truncated outer call is itself never executed, so nothing legitimate is lost, and the case additionally needs the embedded name to be a declared and enabled tool. Adding truncated-recovery logic here could suppress legitimate XML calls following an unclosed brace in prose.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: f0ecde668a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen marked this pull request as ready for review July 6, 2026 17:06
@danielhanchen
danielhanchen merged commit f0a5c52 into main Jul 6, 2026
38 of 47 checks passed
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@danielhanchen
danielhanchen deleted the studio-tools-multi-format-v2 branch July 6, 2026 17:06
danielhanchen added a commit that referenced this pull request Jul 6, 2026
* studio: deterministic backend tool-calling wiring test

Add a deterministic, download-free test that exercises the shared tool-calling
seam both inference backends use. InferenceBackend (transformers) and
MLXInferenceBackend both render the prompt through
apply_chat_template_for_generation(..., tools=...) and stream cumulative text
into run_safetensors_tool_loop. The existing test_safetensors_tool_loop.py
covers the parser and the loop state machine with fake generators but does not
cover the backend's own tool-injection seam, so a regression that drops the
tool schema before the tokenizer, or fails to feed a tool result back into
generation, would slip through.

The test drives that seam with fakes: a tokenizer that records the tools it is
handed, a canned tool-call generation, and a stub executor. It asserts the full
chain: tools reach the chat template, the loop parses the call, the tool is
dispatched once with the parsed arguments, the result is fed back, generation
re-enters, and the final answer streams after the tool result. It also guards
that the raw tool-call markup never leaks to the client as content.

The test imports no torch, unsloth, or mlx, so it runs in the portable Backend
CI alongside the tool-call parser tests and stays sub-second. Follow-up to the
parser test PRs #5620 and #5704.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studio: assert the tool result is fed back before the final turn

Strengthen the wiring test so single_turn records each turn's conversation and
the test asserts the tool result message is present in the conversation handed
to the final generation turn. Event ordering alone did not catch a loop that
stops appending the tool output before re-entering generation, because the fake
generation ignores the conversation; this closes that gap.

* studio: tighten comments in tool-calling wiring test

* studio: shorten comments in tool-calling wiring test

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Jul 6, 2026
…afetensors + MLX (#5624)

* studio: tool calling for Llama-3, Mistral, Gemma 4 on safetensors + MLX (#5615)

Adds tool calling for Llama-3, Mistral (pre-v11 + v11+ + [ARGS]), and Gemma 4 to the safetensors / transformers and MLX backends. Parser patched against llama.cpp / vLLM / SGLang per-family parsers and normalises to OpenAI shape. 96 targeted unit tests + cross-OS staging CI (ubuntu / macos-14 / windows) green on the multi-format probe.

* studio: tool-call healing parity between safetensors / MLX and GGUF

After the multi-format parser landed in #5615, the safetensors / MLX
agentic loop and the GGUF loop still differed on healing behaviour.
This commit closes the gaps in both directions so the two backends
react the same way to identical model output.

Changes:

1. core/inference/llama_cpp.py -- the GGUF BUFFERING state machine
   now wakes on every emission marker the shared parser knows. Was
   ("<tool_call>", "<function="); is now the five-tuple imported
   from core.inference.tool_call_parser (Qwen / Qwen3.5 / Llama-3
   <|python_tag|> / Mistral [TOOL_CALLS] / Gemma 4 <|tool_call>).
   Stream cleanup is delegated to the same shared strip_tool_markup
   so leaked markup from any family is removed from assistant
   content.

2. core/inference/llama_cpp.py -- per-tool canonical heal key. When
   a tool arguments field is a bare string and JSON parsing fails,
   the GGUF path now heals to {"code": raw_args} for python,
   {"command": raw_args} for terminal, and {"query": raw_args} for
   everything else. Was hard-coded to {"query": raw_args}, which
   silently routed every python / terminal emission through
   web_search. Mirrors safetensors_agentic._CANONICAL_HEAL_ARG.

3. core/inference/safetensors_agentic.py -- re-prompt on plan-
   without-action. When the model emits a short forward-looking
   intent ("I'll search for that", "Let me check", "First, I
   will...") and no tool call, the loop nudges the model to act
   instead of silently returning a plan-only answer. Up to
   _MAX_REPROMPTS=3 (matches GGUF). The intent regex, character
   cap, and instruction text are byte-identical to the GGUF path.
   The buffer-end fall-through is unified so a buffered intent
   emission that never exits the BUFFERING state still triggers
   the re-prompt.

4. core/inference/safetensors_agentic.py -- extra iteration slots
   for re-prompts. The loop now budgets max_tool_iterations +
   _MAX_REPROMPTS + 1 total iterations and tracks the tool-call
   count separately, so a stalling model can be nudged 3x without
   eating the caller's tool-call budget. Mirrors the _extra slot
   reservation in the GGUF path.

Tests (14 new safetensors-side units; 5 GGUF parity pins):

  TestLoopRePrompt                 -- intent-trigger, plain-answer,
                                      no-tools, cap-at-three, budget
                                      preserved, buffer-end intent.
  TestLoopCanonicalHealKey         -- python / terminal / unknown.
  TestGGUFSafetensorsHealingParity -- shared markers used, shared
                                      strip used, canonical heal keys
                                      identical, intent regex matches
                                      same phrases, _MAX_REPROMPTS
                                      equal on both backends.

All 110 targeted tests pass locally; the broader tool / inference /
model-config / sandbox / anthropic / mlx suites stay green.

Why this matters

Without this parity, Llama-3.2 / Mistral / Gemma 4 emissions on Mac
(MLX) and Linux-safetensors stop the agentic loop as soon as the
model says "Let me...", because the GGUF re-prompt logic never
existed on these backends. The two-marker GGUF BUFFERING tuple also
let non-Qwen tool emissions stream out as plain prose when
llama-server's structured channel did not pick them up. Both paths
now drain the same way, heal the same way, and re-prompt the same
way -- so a tool call that works on GGUF works identically on
safetensors / MLX.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studio: fix tool-call parser bugs from gemini review on #5620

Three high-priority gemini findings on the tool-call parsing additions:

  1. unicode_escape on UTF-8 bytes corrupts non-ASCII literals
     (e.g. ✨ becomes â\x9c¨). Replace with json.loads on a quoted
     string -- preserves emoji / CJK / RTL while still handling
     \n \t \uXXXX escapes.

  2. Llama-3 sentinel stripping is order-dependent. A leading
     `<|eot_id|><|begin_of_text|>` left `<|begin_of_text|>` behind
     because the loop had already passed that sentinel. Loop until
     no sentinel matches at the start.

  3. Mistral v11+ `[TOOL_CALLS] name { json }` regex uses non-greedy
     `\{.*?\}` which truncates at the first `}` of a nested JSON
     argument, leaking the tail (e.g. `}}`) into user-visible
     streamed text. Same problem for the v0.3 array pattern with
     nested brackets. Strip those with balanced brace/bracket
     scanning via a new `_strip_mistral_closed_calls` helper called
     from `strip_tool_markup`.

Also fix the inference routes' parallel `_TOOL_XML_RE`:

  - Same nested-JSON truncation in the Mistral patterns; route the
    strip through the parser's balanced-scan helper via a thin
    `_strip_tool_xml` wrapper that all existing callers now use.
  - Llama-3 `<|python_tag|>[^\n<]*` stopped at any `<`, leaking the
    tail of any tool call whose argument contained a literal `<`
    (queries, code snippets). Relax to `[^\n]*` which keeps the
    strip confined to the actual end-of-line.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studio: tool calling for DeepSeek (R1/V3/V3.1), GLM 4.x, Kimi K2

Adds three more emission-family parsers to tool_call_parser.py so the
shared safetensors / MLX / GGUF agentic loop covers the major open-
weight reasoning families. Patterns ported from llama.cpp
(common/chat-parser.cpp legacy pre-PEG branch), vLLM
(tool_parsers/deepseekv3*, glm4_moe, kimi_k2), and SGLang
(function_call/deepseekv31_detector, glm4_moe_detector, kimik2_detector).
All three references are MIT (llama.cpp) or Apache-2.0 (vLLM, SGLang).

Formats covered:

  DeepSeek R1     <|tool▁calls▁begin|><|tool▁call▁begin|>function
                  <|tool▁sep|>NAME\n```json\n{...}\n```<|tool▁call▁end|>
                  <|tool▁calls▁end|>
                  -- args wrapped in a Markdown json fence, ``function``
                  literal prefix per llama.cpp common_chat_parse_
                  deepseek_r1 (chat-parser.cpp:801-820)

  DeepSeek V3/V3.1
                  <|tool▁calls▁begin|><|tool▁call▁begin|>NAME
                  <|tool▁sep|>{json}<|tool▁call▁end|><|tool▁calls▁end|>
                  -- bare JSON, no code fence, no ``function`` prefix
                  per llama.cpp common_chat_parse_deepseek_v3_1
                  (chat-parser.cpp:822-879)

  GLM 4.5/4.6/4.7 <tool_call>NAME\n<arg_key>k1</arg_key>
                  \n<arg_value>v1</arg_value>...</tool_call>
                  -- strings raw, non-strings JSON-encoded per
                  chat_template.jinja; multi-call is back-to-back
                  blocks. Per llama.cpp common_chat_parse_glm_4_5
                  (chat-parser.cpp:1040-1052)

  Kimi K2         <|tool_calls_section_begin|><|tool_call_begin|>
                  functions.NAME:IDX<|tool_call_argument_begin|>{json}
                  <|tool_call_end|><|tool_calls_section_end|>
                  -- bare name recovered by stripping ``functions.``
                  prefix and ``:IDX`` suffix; full id preserved as
                  tool_calls[i].id so the roundtrip replays verbatim.
                  Per llama.cpp common_chat_parse_kimi_k2
                  (chat-parser.cpp:896-913)

Marker collisions

GLM uses the same ``<tool_call>`` opener as Qwen but with a bare
function name + ``<arg_key>`` body (Qwen has ``\s*{`` after the tag).
The dispatch keeps Qwen first; Qwen's _TC_JSON_START_RE returns no
matches on a GLM emission, so the fall-through to _parse_glm_tool_
calls handles it correctly. Existing Qwen tests confirm zero
regression.

Streaming buffer

TOOL_XML_SIGNALS extended from 5 markers to 12 so the BUFFERING state
machine wakes on every new family's section opener. Added the
DeepSeek alternative markers (ASCII underscores, short ``<|tool▁calls|>``
form) because real checkpoints emit those variants.

Strip patterns

_TOOL_CLOSED_PATS adds DeepSeek envelope (``<|tool▁calls▁begin|>...
<|tool▁calls▁end|>``) and Kimi section (``<|tool_calls_section_begin|>
...<|tool_calls_section_end|>``). _TOOL_ALL_PATS adds the same plus
the unclosed-tail variants so a truncated stream does not leak
markup.

Route gate

_detect_safetensors_features._PARSER_MARKERS grows to include
DeepSeek and Kimi markers plus ``<arg_key>`` (the unique GLM signal).
_TOOL_XML_RE (the route-layer markup-strip regex) gets DeepSeek and
Kimi closed-pair patterns. _TOOL_TEMPLATE_MARKERS in llama_cpp.py
adds ``message['role'] == 'tool'``, ``message['tool_calls']``, and
``tool_calls is defined`` so the classifier recognises DeepSeek's
subscripted-access template style (it has no top-level
``{% if tools %}`` block).

Tests (39 new):

  TestParserDeepSeek  (7) -- R1 fence, short-form opener, V3.1 bare,
                             multi-call, with-reasoning, strip,
                             signal-wakes-streaming
  TestParserGLM       (6) -- single, mixed types, multi-call,
                             unclosed-heal, no-Qwen-regression, strip
  TestParserKimi      (6) -- single, multi-call, dotted-name, unclosed,
                             strip, signal-wakes-streaming
  TestParserCrossFormatRouting (2) -- dispatch routing, signal coverage
  TestLoopBasic loop integration (3) -- DeepSeek / GLM / Kimi end-to-end
  Capability advertise (3) -- DeepSeek / GLM / Kimi templates flip
                             supports_tools=True

All 398 targeted tests pass locally (115 safetensors + 27 capability
+ rest of tool / inference / sandbox / model-config suites). Builds
on PR #5620 (parser + healing parity for Llama-3 / Mistral / Gemma 4);
will rebase cleanly onto main once #5620 lands. PR opened as draft -
do not merge until validated against real models for each family.

Sources

- llama.cpp common/chat-parser.cpp lines 801-913, 1040-1052 (MIT)
- vLLM vllm/tool_parsers/deepseekv31_tool_parser.py (Apache-2.0)
- vLLM vllm/tool_parsers/glm4_moe_tool_parser.py (Apache-2.0)
- vLLM vllm/tool_parsers/kimi_k2_tool_parser.py (Apache-2.0)
- SGLang python/sglang/srt/function_call/{deepseekv31,glm4_moe,kimik2}_
  detector.py (Apache-2.0)
- Live chat templates: deepseek-ai/DeepSeek-V3.1, zai-org/GLM-4.6,
  moonshotai/Kimi-K2-Instruct, unsloth/DeepSeek-V3-0324,
  unsloth/GLM-4.5-Air, unsloth/Kimi-K2-Instruct

* studio/routes: make python_tag strip multi-line aware

Earlier revisions of _TOOL_XML_RE in studio.backend.routes.inference
oscillated between two bug shapes:

  5615    r"<\|python_tag\|>[^\n<]*"   -- stopped at any literal "<"
                                         so code='if x < 10: pass'
                                         leaked '< 10: pass)' to the
                                         user.
  5620.1  r"<\|python_tag\|>[^\n]*"    -- single-line only; the second
                                         line of
                                         python.call(code="a\nb")
                                         leaked.

The full parser (_parse_llama3_python_tag) already handles both via
balanced-brace scanning, so the parsing path was fine; the LEAK was
in the streaming strip path that runs on every cumulative emission
while content is still arriving.

Switch to r"<\|python_tag\|>(?:[^<]|<(?!\|))*" so the strip consumes:

  * any character that is not a "<" (newlines, JSON, code, ...),
  * a "<" only when it is NOT followed by "|" (i.e. NOT a Llama-3
    sentinel start like <|eot_id|>, <|eom_id|>, <|begin_of_text|>).

This means:

  * code='if x < 10' stays inside the strip (5615 fix preserved),
  * multi-line code stays inside the strip (5620 round 2),
  * the strip terminates at the next Llama-3 sentinel so trailing
    assistant content survives.

Tests: TestRoutesPythonTagStrip (8 cases)
  pytest test_safetensors_tool_loop.py test_safetensors_capability_advertise.py
    -> 118 passed in 1.81s (was 110).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studio: review follow-ups for DeepSeek / GLM / Kimi tool calling

Four fixes addressing review of the parent commit:

1. GLM <arg_value> coercion: tighten the
   json.loads -> ast.literal_eval -> raw cascade to only deserialize
   when the body unambiguously looks like a JSON literal (object,
   array, JSON-encoded string, true/false/null, or numeric). Strings
   like ``True`` / ``None`` (Python literals, not JSON) and arbitrary
   prose now stay raw. The bare-numeric / bare-boolean ambiguity with
   string args remains an inherent limitation of the template without
   schema access -- documented in the new comment. Drops the ast
   import entirely (closes Gemini's :1036 suggestion).

2. Kimi K2 bare-counter ids (e.g. ``<|tool_call_begin|>3``) are now
   dropped rather than surfaced as a tool literally named "3". Matches
   vLLM behaviour; SGLang's schema-infer fallback is out of scope at
   the parse site. Real Kimi K2 emissions use ``functions.NAME:IDX``
   so this is the exception path.

3. Restore the elaborate ``<|python_tag|>(?:[^<]|<(?!\|))*`` clause in
   routes.inference._TOOL_XML_RE -- the simpler ``[^\n<]*`` form
   regressed PR #5620's multi-line / literal-``<`` python_tag fix.
   Restore ``TestRoutesPythonTagStrip`` (8 tests) adapted to call
   ``_TOOL_XML_RE.sub`` directly since the ``_strip_tool_xml`` helper
   was inlined this PR.

4. Add the spaced and backslash-escaped DeepSeek opener variants
   (``<|tool calls begin|>``, ``<|tool\_calls\_begin|>``) to
   ``TOOL_XML_SIGNALS`` for streaming-gate parity with
   ``_DEEPSEEK_BEGIN_RE``.

Also updates the llama.cpp / vLLM citations in the parser docstrings:
``common/chat-parser.cpp`` was split into ``common/chat.cpp`` +
``common/chat-peg-parser.cpp`` by llama.cpp PR #18675, and vLLM
moved the tool parsers from ``vllm/entrypoints/openai/tool_parsers/``
to ``vllm/tool_parsers/``. Pin to pre-refactor commit ``51fa458a92d6``
where the cited line numbers still resolve.

New regression tests in ``test_pr5624_regressions.py`` cover the GLM
coercion heuristic shapes, GLM literal-``<`` in arg_value, Kimi K2
dotted name, Kimi K2 bare-counter drop, DeepSeek V3.1 truncated
mid-stream, and routes-layer strip across all three new families.

Tests:
  pytest studio/backend/tests/test_safetensors_tool_loop.py
         studio/backend/tests/test_safetensors_capability_advertise.py
         studio/backend/tests/test_pr5624_regressions.py -q
  -> 170 passed in 1.91s

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studio: tighten verbose comments in tool-call parser sections

Comments were narrating what the code already says. Cut historical
"earlier revisions used X, then Y" narratives down to one-line WHY
notes where the footgun still matters (canonical heal-key parity,
balanced-brace vs non-greedy regex, ``(?:[^<]|<(?!\|))*`` over
``[^\n<]*``/``[^\n]*``). Drop section-header banners.

No behaviour change. Re-ran:
  pytest studio/backend/tests/test_safetensors_tool_loop.py \
         studio/backend/tests/test_safetensors_capability_advertise.py -q
  -> 118 passed.
Regression replay (parser + _coerce_arguments on the 5 #5615 inputs)
  -> 21/21.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studio: GLM 4.7 no-newline emission + Kimi multi-section parity

Two fixes surfaced by triple-confirm verification against the live
HF chat templates and upstream llama.cpp / vLLM / SGLang parsers.

1. GLM 4.7 silent drop
   ``zai-org/GLM-4.7/chat_template.jinja`` line 65 uses
   ``{{- '<tool_call>' + tc.name -}}`` which Jinja strips trailing
   whitespace from, so the first ``<arg_key>`` follows the function
   name with NO ``\n`` between them. Real emissions look like
   ``<tool_call>get_weather<arg_key>city</arg_key><arg_value>London
   </arg_value></tool_call>``. The previous ``_GLM_TC_OPEN_RE`` ended
   the name with ``\n`` so GLM-4.7 calls were silently dropped
   (parser returned ``[]``).

   Fix: relax the name terminator to a lookahead that accepts EITHER
   ``\n`` OR the next ``<arg_key>``:
       _GLM_TC_OPEN_RE = re.compile(
           r"<tool_call>\s*([^\n<{][^\n<]*?)\s*(?=\n|<arg_key>)"
       )
   The first-char restriction ``[^\n<{]`` still excludes Qwen's
   ``<tool_call>{json}`` form so the Qwen-vs-GLM dispatch remains
   mutually exclusive.

2. Kimi multi-section parity with vLLM / SGLang
   ``vllm/tool_parsers/kimi_k2_tool_parser.py`` and SGLang's
   ``kimik2_detector.py`` both use ``re.findall`` and so collect every
   ``<|tool_calls_section_begin|>...<|tool_calls_section_end|>`` block
   in a single stream. The previous implementation stopped at the
   first ``<|tool_calls_section_end|>``. Kimi K2 doesn't emit
   multi-section in practice, but parity is cheap.

   Fix: wrap the existing per-call body parser in an outer loop that
   advances past each ``<|tool_calls_section_end|>`` and continues to
   the next ``<|tool_calls_section_begin|>``. Body parsing extracted
   to ``_parse_kimi_section_body`` for clarity. Truncated final
   section is still surfaced via the existing in-body balanced-brace
   walk.

Verified independently against the live HF templates:
* GLM-4.7 emission constructed from the live template parses to the
  expected ``{name, arguments}`` shape.
* GLM-4.5 / 4.6 newline shape continues to parse (the lookahead also
  matches ``\n``).
* Qwen ``<tool_call>{json}`` still dispatches to the Qwen path -- the
  first-char restriction stops the GLM regex from biting JSON bodies.
* Kimi two-section stream surfaces both calls in order with full ids
  preserved.
* Bare-counter Kimi ids still drop.

Tests added in ``test_pr5624_regressions.py``:
* ``test_glm_4_7_no_newlines_between_name_and_arg_key``
* ``test_glm_4_7_no_newlines_multi_call``
* ``test_glm_4_7_does_not_break_qwen_path``
* ``test_kimi_two_sections_in_one_stream_both_parse``

  pytest studio/backend/tests/test_safetensors_tool_loop.py
         studio/backend/tests/test_safetensors_capability_advertise.py
         studio/backend/tests/test_pr5624_regressions.py -q
  -> 174 passed in 1.93s

  pytest studio/backend/tests/ -q -k 'not gpu and not llama_cpp_integration'
  -> 2038 passed, 15 failed (pre-existing CI gaps).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studio: parser robustness fixes for PR #5620

Three surgical extensions to the multi-format tool-call parser, each
covering a real fine-tune / template emission shape that the current
parser silently drops. No path narrows; all changes widen what is
accepted.

1. `_parse_tool_call_json` now accepts both `arguments` and
   `parameters` keys. A Hermes / Qwen `<tool_call>{json}</tool_call>`
   wrapper around a Llama-3.2 fine-tune that emits the `parameters`
   key was extracting the tool name and silently discarding the
   args, producing a working-shaped call with an empty payload. The
   bare-JSON and python_tag paths already accepted both keys; this
   path now matches them.

2. `_TC_FUNC_START_RE`, `_TC_PARAM_START_RE`, and `_TC_PARAM_CLOSE_RE`
   now also match the attribute form
   `<function name="..."><param name="...">v</param></function>` used
   by MiniCPM-5 and MiniMax-M2. Names land in either capture group,
   and `</param>` is accepted as a short close.

3. `_parse_llama3_bare_json` sentinel-strip now consumes the role
   label inserted between `<|start_header_id|>` and
   `<|end_header_id|>` by Meta's official Llama-3.x chat template.
   Without this, every assistant turn re-fed through the template
   prefix `<|start_header_id|>assistant<|end_header_id|>\n\n{json}`
   parsed to zero calls, so any history-with-tool-call round-trip
   in production silently dropped.

Tests in `studio/backend/tests/test_safetensors_tool_loop.py`:

* `TestParserRobustness::test_tool_call_json_accepts_parameters_key`
* `TestParserRobustness::test_function_xml_attribute_form`
* `TestParserRobustness::test_function_xml_attribute_form_multi_param`
* `TestParserRobustness::test_function_xml_legacy_equals_form_still_works`
  (regression guard for the existing `<function=name>` syntax)
* `TestParserRobustness::test_llama3_chat_template_round_trip`
* `TestParserRobustness::test_llama3_round_trip_all_roles`
* `TestParserRobustness::test_llama3_round_trip_with_eot_prefix`

`pytest studio/backend/tests/test_safetensors_tool_loop.py
        studio/backend/tests/test_safetensors_capability_advertise.py -q`
goes from 118 to 125 passed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim verbose comments in tool-call parser sections for PR #5624

Pure comment / docstring tightening on top of the GLM 4.7 + Kimi
multi-section fixes. No behavioural change.

* Drop multi-paragraph prelude and post-refactor citation chatter in
  the DeepSeek, GLM and Kimi parser docstrings; keep the shape and
  upstream-commit pin.
* Collapse ``parse_tool_calls_from_text``'s 9 per-family blocks into
  a single ordered loop with one combined comment.
* Tighten the GLM coercion, Kimi bare-counter and ``_TOOL_XML_RE``
  comments to one or two lines each.
* Same trim pass on ``_PARSER_MARKERS`` and the regression-test
  docstrings.

Tests:
  pytest studio/backend/tests/test_safetensors_tool_loop.py
         studio/backend/tests/test_safetensors_capability_advertise.py
         studio/backend/tests/test_pr5624_regressions.py -q
  -> 174 passed in 2.00s

* Fix O(N^2) DeepSeek V3.1 backtracking for PR #5624

Adversarial input ``<|tool▁calls▁begin|><|tool▁call▁begin|>fn<|tool▁sep|>``
followed by a long body that does NOT contain a closing brace caused
the V3 path's ``([^\n<]+?)<|tool▁sep|>`` regex to backtrack
quadratically: at each position the lazy quantifier extends one char
at a time looking for a sep that isn't there, taking ~19s on 50k
chars.

Replace the regex search with ``str.find`` on the sep marker plus a
left-walk to recover the name. ``str.find`` is O(N); the walk stops
on ``\n`` (turn boundary), ``<`` (start of a tag), or ``>`` (end of
an optional ``<|tool▁call▁begin|>`` prefix). Same observable
behaviour as the regex on every canonical input.

Tests:
  test_deepseek_v3_1_huge_truncated_body_is_linear (new) -- 50k chars
  must parse in &lt; 1s.
  pytest studio/backend/tests/test_safetensors_tool_loop.py
         studio/backend/tests/test_safetensors_capability_advertise.py
         studio/backend/tests/test_pr5624_regressions.py -q
  -> 175 passed in 1.97s
  pytest studio/backend/tests/ -q -k 'not gpu and not llama_cpp_integration'
  -> 2038 passed, 15 pre-existing failures unchanged.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studio: terminate function-XML body at </function>, not just </tool_call>

`_parse_function_xml` was looking for `</tool_call>` (the Hermes
wrapper) as the body terminator. When a model emits a standalone
`<function=NAME><parameter=K>v</parameter></function>` followed by
explanatory prose (which models routinely do), no `</tool_call>` is
present, so the body extended to end-of-string and the trailing
prose leaked into the LAST parameter value.

Pre-existing on main (the legacy `<function=NAME>` form had this
bug too). Same affects PR #5620's new attribute-form
`<function name="NAME"><param name="K">v</param></function>`
emission used by MiniCPM-5 / MiniMax-M2.

Fix: `_TC_END_TAG_RE` now matches either `</tool_call>` OR
`</function>`. The existing `_TC_FUNC_CLOSE_RE` / `_TC_PARAM_CLOSE_RE`
strips are unchanged. Multi-call inputs still bound each function
at the next `<function=` start, so no over-eager consumption.

New tests:

* `test_function_xml_followed_by_prose` (legacy form + prose)
* `test_function_attribute_xml_followed_by_prose` (attribute form + prose)

Existing `test_code_with_embedded_xml` still passes (a parameter
value containing literal `<a></a>` is preserved because the
embedded close tag is `</a>`, not `</function>`).

`pytest studio/backend/tests/test_safetensors_tool_loop.py
        studio/backend/tests/test_safetensors_capability_advertise.py -q`
goes from 125 to 127 passed.

* Studio: tighten Llama-3.2 bare-JSON guard

A fuzz pass on PR #5811 turned up that ``_parse_llama3_bare_json``
accepted ``parameters`` as a string, contradicting the docstring's
"parameters or arguments is a dict" guard. Prose JSON like
``{"name":"foo","parameters":"a sentence"}`` would wrongly fire the
parser, which the agentic loop would then heal into a real
``foo(query="a sentence")`` call.

Same code lives on this branch, so the same fix applies here.

Tightened guard:

  - ``parameters`` must be a dict (Llama-3 spec).
  - ``arguments`` may be a dict, or a JSON-encoded string that
    decodes to a dict (OpenAI shape, e.g.
    ``"arguments":"{\"q\":\"x\"}"``). Plain non-JSON strings or
    JSON-strings of lists / scalars / null no longer pass.

Mirrors the fix landed in PR #5811 commit 615b8608. Adds the same
4 regression tests under TestParserMultiFormat.

Existing test suite stays green: 127 -> 131 passing.

* Studio: skip non-scalar args in python_tag JSON form

The JSON sub-path of ``_parse_llama3_python_tag`` was fabricating
``{"value": args}`` when the model emitted a non-dict / non-string
``arguments`` value (e.g. ``42``, ``[1,2,3]``, ``null``, ``true``).
This silently turned a malformed emission into a real tool call,
which the agentic loop would then execute with arguments the model
never intended.

Tightened: skip the call instead of fabricating. The same
behaviour now matches the bare-JSON guard tightened earlier
(strict-guard merge from PR #5620, inherited via merge here).

Added a regression test covering the four non-scalar shapes.
Pass count on this branch: 158 -> 159.

Sites in ``_parse_tool_call_json`` and ``_consume_mistral_call``
keep the existing looser behaviour for now; both are reached
only after explicit ``<tool_call>`` / ``[TOOL_CALLS]`` markers
so the false-positive surface there is much narrower.

* studio: fix safetensors tool-call parser gaps vs llama.cpp (Mistral CALL_ID / THINK, attribute-form signal)

Three GGUF-parity fixes to the safetensors tool-call parser, each matching
llama.cpp's reference behaviour:

- Mistral Small 3.2 emits [TOOL_CALLS]name[CALL_ID]<id>[ARGS]{json}. The
  parser stopped after the name on seeing [CALL_ID] (neither [ARGS] nor {),
  dropping the call. Skip an optional [CALL_ID]<id> segment in both the
  parse and strip paths. llama.cpp parses this (test-chat.cpp:4785).

- Magistral wraps reasoning in [THINK]...[/THINK]. A [TOOL_CALLS] inside the
  reasoning was parsed as a real call, producing a phantom call. Strip a
  leading [THINK] block before scanning so only the post-reasoning call
  counts (test-chat.cpp:2285); a literal [THINK] inside a later argument is
  left intact.

- The standalone MiniCPM-5 / MiniMax-M2 <function name="..."> attribute form
  parsed correctly but was absent from TOOL_XML_SIGNALS and the markup strip
  patterns, so the streaming safety-net parse was gated off (dropping the
  call) and markup leaked into displayed text. Add the signal and broaden
  the strip regexes.

Adds regression tests for all three.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studio: fix GLM and Kimi K2 safetensors tool-call parser gaps vs llama.cpp

Four GGUF-parity fixes for the GLM and Kimi K2 families:

- GLM 4.7 zero-argument inline call <tool_call>name</tool_call> was dropped:
  the open-tag lookahead only allowed \n or <arg_key> after the name. Allow
  </tool_call> too so a no-arg call parses to empty args (vLLM / SGLang /
  llama.cpp all parse it).

- GLM string argument values were stripped, losing significant leading /
  trailing whitespace in code / diff arguments. Keep the raw value for the
  string fallback and only strip the copy used to probe for a JSON literal,
  matching vLLM glm4_moe which never strips string args.

- Kimi K2 calls emitted without the <|tool_calls_section_begin|> wrapper
  were dropped. llama.cpp makes the section optional (Kimi can call a tool
  straight after reasoning without opening a section); parse a bare
  <|tool_call_begin|> when no section is present.

- Kimi K2 malformed / truncated JSON in one call dropped every later call in
  the section. Skip the bad call and keep parsing so valid subsequent calls
  are recovered (vLLM parity).

Adds regression tests for all four.

* studio: fire safetensors tool calls for the bare-JSON (Llama-3.2) form

The agentic loop's streaming safety-net parse was gated on
has_tool_signal(), which is False for the Llama-3.1 / 3.2 bare-JSON tool
form {"name":..,"parameters":..} (no XML marker). Real tool calls were
therefore dropped: the loop logged "model planned without calling tools",
re-prompted three times, then gave up with zero tool calls, while GGUF's
llama-server parses the same emission natively.

Run parse_tool_calls_from_text() unconditionally in the safety net. The
parser is strict (only fires on a valid tool-call shape) so plain answers
are unaffected. Reproduced on a real unsloth/Llama-3.1-8B-Instruct run:
the model emits {"name":"web_search","parameters":{...}} which now
executes the tool instead of being re-prompted into a no-op.

Adds a loop regression test for the bare-JSON form.

* studio: fire safetensors tool calls for Gemma 4 (native template + stripped parser)

Gemma-4 safetensors fired no tools while its GGUF fired reliably. Three gaps:

- The Studio swaps in the Unsloth "gemma-4" chat template, which does not
  render the tools schema (the model's native template does), so the model
  never saw the tools. Fall back to the model's native template when the
  override template renders identically with and without tools. Same fix
  helps any family whose override template drops tools.
- skip_special_tokens strips the <|tool_call> wrapper and <|"|> string
  markers, so a streamed Gemma-4 call arrives as a bare call:NAME{k:v, ...}
  with unquoted values. Parse that form, keeping commas/braces inside a
  code or command value, normalising surrounding quotes, and stripping the
  leaked markup from the final answer.
- Without a grammar a small model can loop, repeating one call for the whole
  tool budget. Collapse exact-duplicate calls within a turn and force a final
  answer after a turn that made no new tool progress (llama-server's lazy
  grammar prevents this loop on the GGUF side).

Adds parser tests for the bare/stripped Gemma-4 form.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: complete strict-mode contract and fix parser import paths

Address review findings on the multi-format tool-call parser:

- Honor allow_incomplete=False in the remaining sub-parsers. The Llama-3
  <|python_tag|>NAME.call(...) parser, the pre-v11 Mistral [TOOL_CALLS] array
  parser, and the Gemma 4 <|tool_call> parser ignored strict mode, so a
  truncated call (missing closing paren, ], or <tool_call|>) was still healed
  and executed with Auto-Heal disabled. Thread strictness through and reject
  the unclosed forms, matching the JSON and function-XML paths.
- Drop the duplicate tool_call_parser import block in llama_cpp.py and the
  redundant un-aliased TOOL_XML_SIGNALS; only the _SHARED_TOOL_XML_SIGNALS
  alias is used as a value.
- Import _strip_mistral_closed_calls from core.inference.tool_call_parser in
  routes/inference.py instead of studio.backend.core... The self-contained
  run.py launch mode only puts studio/backend on sys.path, so the absolute
  package path raised ModuleNotFoundError on the server-tool strip path.

Add strict-mode regression tests for the truncated Llama-3 dot-call and the
unclosed Mistral array.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: harden DeepSeek/Kimi tool-call parsing and strip

Address review findings on the DeepSeek and Kimi parsers:

- Honor allow_incomplete=False for DeepSeek. An envelope with no closing
  <|tool▁calls▁end|> is truncated mid-stream; reject it in strict mode
  instead of healing the body out to EOF, matching the strict XML and Mistral
  paths.
- Do not skip a following tool call when the current call's end marker is
  missing. The DeepSeek V3 and Kimi loops advanced by searching forward for the
  next <|tool▁call▁end|> / <|tool_call_end|>, which could land on a later
  call's end marker and drop the call in between. Advance by the JSON end; the
  loop re-locates the next call marker from there.
- Strip truncated DeepSeek and Kimi section blocks in the route-level display
  regex. The patterns required the closing marker; add the end-of-text
  alternative so a block truncated by EOS does not leak raw markup to the UI.

Add regression tests for the truncated DeepSeek envelope, and for DeepSeek and
Kimi multi-call recovery when the first call's end marker is missing.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: preserve XML param indentation and alias Mistral array parameters

Two parser-correctness fixes found by auditing against the model chat templates
and the SGLang / vLLM reference parsers:

- Qwen3.5 XML parameter values lost their leading indentation. The chat template
  emits <parameter=k>\nVALUE\n</parameter>, but the parameter-start regex ate the
  wrapping newline AND the value's first-line indentation with a trailing \s*,
  then str.strip() removed the rest. Narrow the trailing class to horizontal
  whitespace only and trim exactly one wrapping newline (via _trim_param_value),
  preserving indentation in code/diff arguments. Matches SGLang's qwen3_coder
  detector. Applies to both _parse_function_xml (tool_call_parser.py) and the XML
  path in tool_healing.py.
- Mistral pre-v11 array objects keyed on parameters dropped their payload.
  _consume_mistral_call read only the arguments key; alias parameters the same way
  the JSON/XML paths and SGLang's base detector do.

Add regression tests for preserved multi-line indentation and the array
parameters alias.

* Studio: DeepSeek strip sync, Gemma nested args, GLM/Kimi strict mode

Parser-correctness fixes found by auditing DeepSeek/GLM/Kimi against vLLM,
SGLang, and the model chat templates:

- DeepSeek: the short <|tool▁calls|> opener (and the space / escaped-underscore
  spellings) was parsed but never stripped, so a short-opener envelope leaked raw
  markup to the UI. Share one opener alternation between _DEEPSEEK_BEGIN_RE and
  the strip patterns (and the route-level display regex) so a signal we parse can
  never be left un-stripped.
- Gemma wrapper-less stream: a nested object/array argument (loc:{city:NYC},
  labels:[bug,ui]) was kept as a literal string. Parse it recursively when the
  bare value is a balanced {} / [], falling back to the raw string for a
  truncated value.
- GLM and Kimi ignored allow_incomplete. With Auto-Heal off, a GLM block with no
  </tool_call>, a Kimi section with no <|tool_calls_section_end|>, or a Kimi call
  with no <|tool_call_end|> are truncated and must be rejected, matching the
  strict behavior of the JSON/XML/Mistral/DeepSeek paths and vLLM/SGLang.

Add regression tests for the short-opener strip, the Gemma nested args, and GLM /
Kimi strict-mode rejection.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: tighten tool-call parser comments

Make the comments in the multi-format tool-call parser and its callers succinct:
compress verbose docstrings/blocks to one or two lines, drop ones that restate the
code, and trim the tiny balanced-scanner helpers. Correctness rationale and
upstream provenance (SGLang/llama.cpp parity, the strict-mode / Auto-Heal
contract, whitespace-preservation, and the Unicode / full-width-pipe notes) are
kept in compact form.

Comment-only: no code or behavior change (verified with comment_tools.py check
--strip-docstrings; parser suite green).

* Studio: tighten DeepSeek/GLM/Kimi parser comments

Compress the comments added for the DeepSeek/GLM/Kimi parsers and the Gemma
wrapper-less helpers to one or two lines, keeping the upstream provenance
(llama.cpp 51fa458a92d6), the O(N^2) / strict-mode rationale, and the vLLM parity
notes intact.

Comment-only: no code or behavior change (verified with comment_tools.py check
--strip-docstrings; parser suite green).

* Studio: make DeepSeek R1 / GLM parsing linear and close routes strip gaps

Review follow-up for the DeepSeek/GLM/Kimi parser:

- DeepSeek R1 detection used a greedy ``([^\n]+)\n```json`` regex that backtracks
  O(N^2) on a fence-less truncated body; scan with str.find instead (mirrors the
  V3 path).
- GLM arg pairs used a lazy-group finditer that rescanned to EOF from each bare
  <arg_key> in an unclosed body (O(N^2)); walk pairs with str.find.
- The route display strip (_TOOL_XML_RE) accepted fewer DeepSeek openers than the
  parser (missed the space / escaped-underscore spellings) and missed bare
  section-less Kimi calls, so a call we parse could leak raw markup to the UI.
  Reuse the parser's shared _DEEPSEEK_OPEN_RE_SRC and add a bare-Kimi arm.

Add ReDoS-linearity regressions for the R1 and GLM paths, a positive R1
fenced-json parse test, and routes-strip tests for the space/escaped DeepSeek
openers and the bare Kimi call.

* Studio: fix test_mcp_servers _TOOL_XML_RE reconstruction after _DS_OPEN_SRC reuse

The routes strip fix made _TOOL_XML_RE reference the module-level
_DS_OPEN_SRC variable. test_mcp_servers reconstructs the regex by exec-ing
the extracted compile() source in a namespace that only defined _re, so it
raised NameError. Inject _DS_OPEN_SRC into that namespace, matching the same
fix already applied in test_tool_xml_strip.

* Studio: make Llama-3 .call and Mistral-array healing parsing linear

Two more O(n^2) ReDoS paths in the multi-format parser, both reachable from
the agentic loop on a long truncated body with no length cap:

- _LLAMA3_KV_RE.finditer over a .call(...) body retried at every offset of a
  long word run / unterminated quote (40K -> 14s). Replace with a hand-scan
  that reuses the same key/number/literal sub-regexes via anchored match and
  walks the string body by hand, so an unterminated quote is O(n). Verified
  byte-identical to the old regex over 200K fuzzed inputs.
- _parse_mistral_array healing ran _balanced_brace_end from every { in the
  body (20K -> 17s). Walk top-level objects, advancing past each balanced
  {...}; this also drops the phantom call the old scan emitted from a nested
  argument object.

Add adversarial-length linearity regressions plus positive .call kwargs and
unclosed-array recovery coverage.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: strengthen #5624 regression assertions and strip-test harness guards

- test_strip_tool_markup_handles_deepseek_envelope used `A or B` where B was the
  preservation property the next line already asserts, masking the real check.
  Replace with an explicit assertion that the call name and args are stripped.
- The test_tool_xml_strip source-extraction harness reconstructs _TOOL_XML_RE and
  _strip_tool_xml_for_display from routes/inference.py via lazy regexes that could
  silently grab a shorter slice. Assert the extracted regex carries the DeepSeek /
  bare-Kimi arms and the helper body reached the _TOOL_XML_RE.sub call.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: honor strict mode in safety-net, keep empty Gemma args, strip attribute-form function XML

- safetensors safety-net parser now forwards allow_incomplete=auto_heal_tool_calls,
  matching the draining path, so a late incomplete tool call is not healed and
  executed when Auto-Heal is off.
- Gemma empty bare value ({k:}) now serialises as "" instead of invalid {"k":},
  which previously dropped the whole call.
- Route _TOOL_XML_RE also strips the <function name="..."> attribute form
  (MiniCPM-5 / MiniMax-M2) so it no longer leaks to the UI.

* Studio: linearize wrapper-less Gemma nested-arg parsing and correct parser provenance

- _gemma_parse_value/_gemma_parse_mapping/_gemma_parse_array now parse nested
  {}/[] in a single forward pass instead of pre-scanning each subtree with a
  balanced-brace walk and re-parsing it. Deeply nested wrapper-less Gemma args
  were O(n^2); they are now ~linear (and ~40x faster at depth 400).
- Correct the DeepSeek/GLM/Kimi provenance comments: the cited commit
  51fa458a92d6 is unrelated, and GLM/Kimi were never standalone
  common_chat_parse_* functions (llama.cpp uses common_chat_params_init_glm_4_5
  plus a generalized XML parser, PRs #15904 / #16932).
- Add tests: Gemma deep-nesting linearity, nested object/array preservation,
  same-turn distinct-call cap, and the native-template tool-render fallback.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: guard Gemma value parser against non-advancement and missing tokenizer

Addresses Gemini review:
- _gemma_parse_value now consumes one character when a stray }/]/, sits where a
  value is expected, so _gemma_parse_array can never stall at the same index on
  malformed input (a latent infinite loop).
- _render_with_native_template returns None when neither a tokenizer nor a
  processor is present instead of raising AttributeError.
- Tests for both.

* Studio: fix attribute-form function-XML literal close tag and zero-arg strict call

Addresses Codex review of the <function name="..."> attribute form in
_parse_function_xml (MiniCPM-5 / MiniMax-M2):
- End the call body at the LAST </function> / </tool_call> within the call's
  window, so a literal close tag inside a code/search argument (e.g.
  print("</function>")) is preserved instead of truncating the call.
- Accept a closed call with no parameters as a valid zero-argument call in strict
  mode (the function close is already required), instead of rejecting it as a
  truncated call.
- Tests for both, mirroring the legacy <function=...> coverage.

* Studio: drop scratch review/planning artifacts from the branch

* Studio: fix tool-call parser/loop review findings on the multi-format path

Address the live code-review findings on the safetensors/MLX + GGUF tool path:

- routes: include the attribute form <function name="..."> in the safetensors
  capability whitelist so MiniCPM-5 / MiniMax-M2 templates keep the tool pill
  (parser already handles the form; the post-filter wrongly suppressed it).
- safetensors loop: build the plan-without-action re-prompt from the active
  tools instead of a hardcoded web_search/python string, and gate it on
  auto_heal_tool_calls, matching the GGUF loop.
- safetensors loop: hold a leading bare-JSON object ({"name":..,"parameters":..})
  during BUFFERING until it closes, then drain it as a tool call instead of
  streaming the raw JSON to clients. The DRAINING/STREAMING resolvers still
  recover a plain JSON answer, so this can never drop content.
- parser: anchor the Llama-3 <|python_tag|>NAME.call(...) scan to the tag and
  chain ; -separated calls, so all semicolon-separated built-ins parse and a
  literal <|python_tag|>x.call(...) inside a JSON string argument no longer
  fires the wrong tool.
- parser: consume the optional trailing </s> after a named Mistral
  [TOOL_CALLS]name{json} call, mirroring the array shape.
- GGUF streaming strip: use the shared parser patterns (which know
  [TOOL_CALLS] and <|python_tag|>) so a textual tool call entering DRAINING is
  stripped instead of leaking the marker to streaming clients.
- routes: hoist the _strip_mistral_closed_calls import to module level.

Adds regression tests covering each fix; existing parser suite stays green.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: fix DeepSeek/GLM/Gemma tool-call review findings

Address the live code-review findings specific to the DeepSeek / GLM / Kimi
and native-template additions:

- parser: in strict mode (Auto-Heal off) require the per-call
  <|tool▁call|end|> terminator for DeepSeek V3 calls instead of executing on
  a bare balanced object closed only by the envelope end.
- parser: keep GLM string arguments that begin with a quote verbatim (drop
  the leading-quote case from the JSON-decode probe) so a quoted search query
  is not decoded down to its inner text.
- parser: reject a GLM call with an unclosed <arg_value> in strict mode, and
  under Auto-Heal keep the partial value rather than dropping it to a no-arg
  call.
- parser: add a balanced wrapper-less Gemma strip (call:NAME{...}) so a nested
  object/array argument is removed whole instead of leaving a trailing brace;
  run the balanced Mistral and Gemma strips on the streaming display paths too.
- safetensors loop: buffer a leading wrapper-less Gemma call:NAME{...} so it
  drains and executes instead of streaming the raw call text.
- inference: render the native-template fallback on a shallow tokenizer copy
  instead of mutating the shared tokenizer outside the generation lock, and
  load the native template from base_model for LoRA adapters.

Adds regression tests for each; existing parser suite stays green.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: harden multi-format tool-call detection from review findings

Apply five targeted fixes from the review pass over the multi-format tool
path:

- routes: route display strip delegates to _strip_tool_xml so Mistral
  [TOOL_CALLS] blocks with nested JSON are removed from streamed display
  text, not just the XML forms.
- tool_call_parser: skip function/parameter starts that fall inside an
  already-open parameter block (_inside_open_parameter) so nested example
  payloads are not mis-parsed as new calls; extract
  strip_llama3_leading_sentinels so the bare-JSON guard is shared.
- safetensors_agentic: probe bare JSON through strip_llama3_leading_sentinels
  before the balanced-brace check so a leaked header sentinel does not defeat
  the guard.
- tool_healing: allow dotted tool names in the Gemma wrapped start pattern.
- llama_cpp (GGUF): buffer wrapper-less Llama-3.2 {"name":..} calls that carry
  no XML signal, drain a complete object silently and hold an incomplete one,
  and run the end-of-stream safety net unconditionally so markerless calls are
  detected and never leak the raw JSON (including truncated fragments).

Adds regression tests for the GGUF bare-JSON streaming path and the Mistral
display strip.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: stop bare-JSON tool calls leaking at EOF, oversized, and into history

The second review pass flagged that the Llama-3.2 bare-JSON tool-call handling
still leaked raw JSON in several spots; ``strip_tool_markup`` only knows
XML/bracket markup, so the bare-JSON form survived it. Fix them symmetrically
across the safetensors and GGUF loops:

- Safetensors stream-end resolver now routes a held bare-JSON fragment to
  DRAINING (mirroring GGUF) so a truncated ``{"name":..`` cut off by the end of
  the stream is dropped instead of flushed as assistant content. The 7/10
  reviewer finding.
- Both loops now drain (suppress) an oversized still-open bare-JSON call once it
  passes ``_MAX_BARE_JSON_BUFFER`` instead of streaming the raw prefix, gated on
  a ``"name"`` key so a giant plain JSON answer still streams; a complete
  oversized call still executes via the safety net.
- Add a shared ``strip_leading_bare_json_call`` helper and apply it to the
  content kept for the assistant turn in both loops, so an executed bare-JSON
  call is not replayed as visible text or fed back as next-turn history.

Plain JSON answers without a ``"name"`` key are untouched throughout. Adds
regression tests for the EOF, oversized, and next-turn cases on both backends
plus unit tests for the helper.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: bound the Llama-3 python_tag strip on real control sentinels

The route display strip's <|python_tag|> arm ran to the next <| of any kind.
A tool-call argument carrying a literal <|...|> token (for example <|cite|>
inside a string value) truncated the strip early and leaked the call tail into
the visible response. Narrow the stop condition to the genuine Llama control
sentinels (eot_id, eom_id, python_tag, start/end_header_id, begin_of_text,
finetune_right_pad_id) so embedded markup and JSON are consumed while real
header/turn boundaries still bound the strip.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: harden GLM/Gemma parsing, cap GGUF textual calls, share native-template fallback

GLM 4.x parser walked a body pre-bounded by the first </tool_call>, so a string
argument containing a literal </tool_call> (e.g. code that prints it) was
truncated. Walk arg_key/arg_value pairs against the full content instead, since
each <arg_value> is delimited by its own </arg_value> and the call's real close
is the </tool_call> that precedes the next <arg_key>.

Add a truncated wrapper-less Gemma pattern (call:NAME{... with no closing brace)
to the markup strip so a call cut off mid-arguments does not leak raw into the
visible stream. It runs after the closed form, so a complete call keeps trailing
prose.

Cap and dedup tool calls parsed from the GGUF TEXTUAL fallback at
_MAX_TOOL_CALLS_PER_TURN, mirroring the safetensors loop. Structured
delta.tool_calls are grammar-bounded by llama-server, but text parsed straight
from content is not, so one runaway turn could fan out into dozens of
executions.

Extract the native-chat-template fallback into chat_template_helpers
(render_native_template / render_with_native_template_fallback) so the
transformers and MLX text backends share one implementation. The MLX text path
now applies it too, so an Unsloth override template that drops the tools schema
no longer silently stops MLX from advertising tools. The MLX VLM path renders
via the processor for image tokens and is intentionally left on its own render.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: gate markerless bare JSON on enabled tools and close parser/strip asymmetries

The Llama-3.2 custom_tools bare-JSON form has no marker, so any JSON object with a
name key was read as a tool call. An ordinary JSON answer like
{"name":"Alice","parameters":{"age":30}} was misclassified as a call to a
disabled tool and dropped from the visible response. Gate the markerless form on
the enabled tool names (threaded through parse_tool_calls_from_text and
strip_leading_bare_json_call, supplied by both streaming loops): an object whose
name is not an enabled tool is ordinary content. The marker-based forms keep
their name-agnostic behaviour (an explicit signal is a real call attempt), and
unrestricted mode stays ungated.

Also fix two parser/strip asymmetries the parser already tolerated:
- A literal </function> inside a parameter value (print("</function>")) truncated
  both the core and route strips at the first close, leaking the tail. Extend the
  strip to the call's real close (last </function> before the next opener),
  mirroring the parser, without merging separate calls.
- The single-object Mistral [TOOL_CALLS]{...} shape parsed but _strip_mistral_closed_calls
  left it, leaking the raw object into display. Strip the balanced object while
  keeping trailing prose, matching the array and name shapes.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio tools: fix strip/parse symmetry and native-template token for DeepSeek/GLM/Kimi

Pass-3 review follow-ups on the multi-format tool parser:

- Bare Kimi call (<|tool_call_begin|>...<|tool_call_end|> with no section
  wrapper) is accepted by the parser, so add it to the closed strip patterns
  so the streaming (non-final) display strip removes it instead of leaking the
  markup mid-generation.
- Route display strip now also runs the wrapper-less Gemma cleanup, so a
  Gemma 4 call:NAME{..} no longer leaks into the visible answer.
- MLX model record carries base_model for a LoRA adapter so the native-template
  fallback loads the base repo template rather than the adapter's
  (often template-less) tokenizer.
- Native-template reload forwards the load-time HF token so a gated/private
  model's repo template can still be fetched (transformers and MLX text paths).
- GGUF end-of-stream bare-call heuristic is gated on the enabled tool names so a
  truncated ordinary JSON object ({"name":"Alice","age":) streams as the answer
  instead of being dropped as a tool call.

Adds regression tests for each case.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio tools: gate GGUF bare-JSON suppression on enabled tools and fix python-tag exponent parsing

Pass-4 review follow-ups on the GGUF tool loop and Llama-3 parser:

- The GGUF bare-JSON suppression sites still keyed off a raw "name" substring,
  so an ordinary JSON answer whose name is not an enabled tool was dropped when
  it was truncated, oversized, or reached the no-tool DRAINING fallback (the
  parser, helper, and safetensors paths were already gated). All three sites now
  use the shared enabled-name gate, and a held bare-JSON buffer that turns out not
  to be an enabled call is shown as the answer instead of dropped at stream end.
- The Llama-3 python-tag numeric kwarg regex matched only the mantissa, so
  scientific notation was truncated to its leading digits (1e-3 parsed as 1) and a
  tool executed with the wrong value. The regex now accepts exponent and decimal
  forms, and the int/float classification keys off the exponent too.

Adds regression tests for the truncated / oversized disabled-name JSON cases (and
a counterpart that a truncated enabled call still does not leak) plus the
scientific-notation kwargs.

* Studio: drop accidentally committed async worker transcripts

Eight generated reviewer / async-worker transcripts were committed under
studio/backend/async_task_outputs/. They are not imported or referenced by any
code and carry only internal task state, so they should never ship in the repo.
Remove them and gitignore the directory so they cannot be re-added.

* Studio tools: gate safetensors bare-JSON drain, fix nested-name gate and function-XML strip

Pass-4 review follow-ups on the shared parser / safetensors loop:

- The safetensors oversized and end-of-stream bare-JSON drain branches keyed off
  a raw "name" substring, so a large or truncated ordinary JSON answer whose name
  is not an enabled tool was drained instead of streamed. Both now use the shared
  enabled-tool-name gate, matching the GGUF path.
- strip_leading_bare_json_call matched the first "name" anywhere, so a plain JSON
  answer with a nested name equal to an enabled tool ({"result":{"name":"web_search"}})
  was wrongly suppressed. It now extracts the TOP-LEVEL name only, walking past
  nested objects/arrays and keeping the text when a top-level value is truncated.
- The function-XML display strip used a regex negative-lookahead that stopped at a
  literal <function=...> opener inside a parameter value and then dropped the rest
  of the answer to EOF. A scan-based strip mirrors the parser (ignores openers
  inside an open <parameter> via _inside_open_parameter) and closes each call at its
  real </function>, so trailing assistant text after such a call survives.

Adds regression tests for each.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: keep tools prompt when native-template probe raises; make helper tests hermetic

Pass-4 review follow-ups on the native-template fallback:

- render_with_native_template_fallback re-renders the live template with tools=None
  to detect whether it dropped the schema. A template that requires tools can raise
  on that probe; that must not discard the already-valid tools prompt. The probe is
  now wrapped so any error returns the original formatted_prompt (transformers would
  otherwise fall back to manual formatting and lose the schema; MLX would let the
  exception escape).
- The native-template helper tests imported InferenceBackend just to reach the
  thin wrapper, which pulls in unsloth and its optional vllm package metadata. They
  now call the dependency-light render_native_template helper directly so they pass
  in a backend/test environment without vllm. Adds a probe-raises regression test.

* Tool parsing: 3.9 import safety, disabled-Auto-Heal contract, capability gate

Round-2 review follow-ups on the multi-format tool-call parser:

- tool_call_parser: add `from __future__ import annotations`. The module
  is dependency-light by design (external llama-server wrappers import it
  standalone) and the package targets python >=3.9, where its PEP 604
  `int | None` return annotations would raise TypeError on import.
- safetensors + GGUF drain fallback: gate the leading bare-JSON strip on
  auto_heal_tool_calls. With Auto-Heal off, a truncated enabled-name
  fragment that did not parse now stays visible, matching the XML strip
  in the same branch and the disabled-Auto-Heal contract. With Auto-Heal
  on it is still suppressed.
- safetensors capability gate: match the bare-JSON `{"name":` template
  marker with a whitespace/escape-tolerant regex so a pretty-printed
  `{ "name" :` or JSON-escaped `{\"name\":` template is not mis-classified
  as tool-less. The parser already accepts that whitespace via
  raw_decode, so the gate must too.

Regression tests added for each case.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* GLM tool-call display strip: treat literal close tag in arg value as data

Round-2 review follow-up on the GLM 4.x tool-call format.

The GLM call shape is <tool_call>NAME<arg_key>k</arg_key><arg_value>v
</arg_value>...</tool_call>. The parser was hardened to walk arg_key /
arg_value pairs so a literal </tool_call> inside an argument value (e.g.
print("</tool_call>")) is treated as data and the call's real close is the
</tool_call> that precedes the next <arg_key>. The display strips still used a
non-greedy <tool_call>.*?</tool_call> regex, which stopped at the literal and
leaked the call's tail into visible content and stale history.

Add _strip_glm_calls, a scan that mirrors the parser's close detection, and run
it before the regex arms in every strip pipeline: the core strip_tool_markup,
the route _strip_tool_xml display/history cleanup, and the safetensors + GGUF
streaming strips. Qwen / Hermes <tool_call>{json} has no NAME token after the
opener, so it is left to the regex arms unchanged.

Regression tests cover the literal-close-tag leak (core + route), normal GLM
calls, back-to-back GLM calls, zero-arg GLM, truncated GLM, and untouched Qwen.

* Tool parsing: symmetric "function" bare-JSON alias and route strip parity

Round-3 review follow-ups, all parser/strip symmetry fixes.

- Bare-JSON "function" alias: the markerless parser accepts a call name via
  obj.get("name") or obj.get("function"), but the strip/gates only knew "name",
  so a {"function":<enabled tool>} call executed while its raw JSON leaked. Teach
  _top_level_bare_json_name the alias (with "name" precedence and the same nested
  and truncated-name guards), and widen the guards in strip_leading_bare_json_call,
  the safetensors and GGUF _looks_like_enabled_bare_json gates, and the route
  capability marker regex.
- Route display/history cleanup: strip a tail-only </param> alias close (the
  parser accepts <param name="...">...</param>), and run the parser's guarded
  function-XML scan (_inside_open_parameter) before _TOOL_XML_RE so a literal
  nested <function=...></function> inside an argument value does not truncate the
  strip and leak the tail.

Regression tests added for each.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio tools: fix DeepSeek strict recovery, Kimi dotted names, Gemma spaced streaming

Round 3 review fixes for the DeepSeek / GLM / Kimi tool-call parsing path.

- DeepSeek R1 and V3/V3.1 strict parsing (Auto-Heal off): when a call is
  truncated (missing closing fence or <tool_call_end> terminator), skip it
  and keep scanning for later well-formed calls instead of breaking out and
  dropping the rest of the envelope. This matches the Kimi strict parser's
  recovery behaviour.

- Kimi dotted tool names: keep the full name after stripping only the
  functions. prefix and :idx suffix, e.g. functions.mcp.server-list:0 stays
  mcp.server-list. The previous split on "." truncated dotted MCP names to
  their last segment. This matches current vLLM
  (tool_id.split(":")[0].removeprefix("functions.")) and SGLang
  (^(?:functions\.)?(?P<name>[\w.\-]+):(?P<index>\d+)$).

- Gemma wrapper-less call streaming: hold the whitespace-tolerant prefix
  (call : NAME) in the streaming suppression buffer, matching the parser's
  _GEMMA_BARE_TC_RE, so the spaced spelling split across chunks is buffered
  instead of leaking as visible text. Applied to both the safetensors and
  llama.cpp streaming paths.

- Remove dead _render_with_native_template method and the now-unused copy
  import from inference.py; the live path uses render_with_native_template_fallback.

Adds regression tests for DeepSeek R1/V3 strict recovery, Kimi full dotted
name preservation, and the Gemma spaced-call streaming suppression.

* Studio tools: honor tool budget in GGUF loop and guard function-XML streaming strip

Round 4 review fixes. Both are asymmetric-fix bugs where the final/steady path got a
guard the analogous streaming/loop path did not.

- GGUF tool-call budget: the safetensors loop counts real tool-call turns against
  max_tool_iterations (re-prompt stalls excepted), but the GGUF loop only bounded the
  turn count by the enlarged range (max_tool_iterations + _MAX_REPROMPTS). Since this
  PR raised _MAX_REPROMPTS from 1 to 3, a model that keeps making valid tool calls
  could run up to three extra tool rounds (with max_tool_iterations=1, four rounds
  instead of one). Add a _tool_iters_done counter that increments only when a tool
  actually executed in the turn, and stop once the caller's budget is spent so the
  post-loop final-answer nudge fires. A duplicate/disabled no-op turn is a correction
  turn (like a plan-without-action re-prompt) and does not consume budget, preserving
  the existing "already completed" re-prompt behavior.

- Streaming display strip: the final strip runs the guarded _strip_function_xml_calls
  scanner (a literal <function=...> inside a parameter value is data, not a nested
  call), but the GGUF and safetensors streaming strips still used only the open-ended
  regex arms. When a tool-call argument contained literal function markup, the regex
  tail ate everything to end-of-text and dropped the real trailing prose after the
  call's true </function>. Run the guarded scanner (and the balanced Mistral strip)
  before the regex arms in both streaming paths so streaming and final display agree.

Adds regression tests: GGUF valid tool calls respect max_tool_iterations, and the
streaming strip keeps trailing prose after a function-XML call with a literal marker.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio tools: safetensors tool budget counts only executed turns (GGUF parity)

Follow-up to the GGUF budget fix. The safetensors loop charged max_tool_iterations
per non-re-prompt iteration (iteration + 1 - reprompt_count), so a duplicate/disabled
no-op turn spent a budget slot even though no tool ran. With a small cap this dropped
real work: for max_tool_iterations=2, a model that made a valid call, repeated it (an
internal no-op correction turn), then made a distinct valid call executed only the
first -- the third turn was se…
danielhanchen added a commit that referenced this pull request Jul 7, 2026
The shared MAX_ACT_REPROMPTS was set to 1, but GGUF's established default
(llama_cpp.py) has re-prompted a stalling model up to 3 times since #5620.
Restore the GGUF-matched cap so safetensors and MLX inherit the same
behavior, and update the safetensors cap test to assert the cap dynamically.
danielhanchen added a commit that referenced this pull request Jul 7, 2026
* Studio chat: tool-call nudging on by default (API stays opt-in)

Healing is already default-on everywhere and the nudge retry from the
client-tool passthrough is opt-in on the API. Studio chat had neither
signal: the frontend never sent nudge_tool_calls, and the safetensors
and MLX server-side loop lacked the GGUF loop's plan-without-action
re-prompt entirely.

Backend: the re-prompt helpers move from llama_cpp.py into
tool_call_parser.py (shared, cycle-free; the GGUF loop imports them
under its old names with zero behavior change) and
run_safetensors_tool_loop now re-prompts once at the streaming
no-tool-call exit, gated on Auto-Heal, active tools, nothing executed
yet, and short forward-looking text. Re-prompts do not consume tool
iterations.

Frontend: the chat adapter sends nudge_tool_calls from a new
nudgeToolCalls runtime setting (default true) with the same
persistence, hydration, and settings toggle plumbing as Auto-Heal.
Request-model defaults are untouched, so raw API callers stay opt-in.

* Address review: persist the nudge setting, consume the flag in the loops, skip the re-prompt after RAG autoinject

ChatSettingsPayload uses extra forbid, so a settings patch containing
nudgeToolCalls failed to persist any settings; the field is now typed
and round-trips. nudge_tool_calls now plumbs into both server-side tool
loops and gates the plan-without-action re-prompt with None meaning on,
so API callers keep today's behavior, explicit false disables it, and
Studio's default-on flag actually controls the path Studio chat runs.
The safetensors loop no longer re-prompts after RAG autoinject: the
injected retrieval bypasses the tool controller, so the nothing-executed
gate saw an empty history and re-asked after a successful retrieval.

* Safetensors loop: the plan-without-action retry requires an explicit nudge flag

The retry is new on this loop, so an omitted nudge_tool_calls must not
change existing API behavior; Studio opts in explicitly. The GGUF loop
keeps None as on because its re-prompt predates the flag.

* Suppress the plan-without-action re-prompt after a denied tool confirmation

A denial appends TOOL_REJECTED_MESSAGE but records nothing in the tool
controller history, so the nothing-executed gate re-prompted the model
to call the tool the user had just rejected, producing another
confirmation prompt. A denial now suppresses the re-prompt for the rest
of the request, mirroring the RAG autoinject handling.

* Tighten plan-without-action re-prompt comments

* Tighten plan-without-action re-prompt comments

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: match unified plan-without-action nudge cap to GGUF default of 3

The shared MAX_ACT_REPROMPTS was set to 1, but GGUF's established default
(llama_cpp.py) has re-prompted a stalling model up to 3 times since #5620.
Restore the GGUF-matched cap so safetensors and MLX inherit the same
behavior, and update the safetensors cap test to assert the cap dynamically.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Imagineer99 pushed a commit to Imagineer99/unsloth that referenced this pull request Aug 12, 2026
…hai#8427)

* Studio: give the tool-call strip one owner and one scan order

core/tool_healing.py and core/inference/tool_call_parser.py define 13 of the
same top-level names. tool_healing.py is the elder module (created 2026-05-19,
unslothai#5583) and the parser copied the balanced scanners out of it on 2026-07-06
(unslothai#5620), after which changes landed on one side only. Its own docstring already
says "Any change here must also land there".

Separately the ~15 line tool-strip scan order (mistral -> bracket-tag -> gemma
wrapperless -> function XML -> GLM -> regex arms -> rehearsal tail, wrapped in
strip_outside_think) was copy-pasted into four places.

Unified only what the evidence supports:

- _balanced_brace_end, _balanced_bracket_end, _trim_param_value and
  _TC_FUNC_CLOSE_RE now live once, in tool_healing.py. Divergence over a 1833
  input corpus was measured at zero before merging them. The healer's brace
  scanner keeps its Gemma quote mode and gains the parser's position guard; the
  bracket scanner keeps counting {} toward the depth (the Gemma array
  normalizer relies on it) and also gains the guard. The -1 / None sentinel
  split is resolved to None, with the marker tuples in _build_markers keeping -1
  because marker_coverage is a cross-module contract.
- _inside_open_parameter is one body taking its opener regex and closer tags as
  arguments. The parser's wider vocabulary (<param name="...">, </param>,
  </tool_call>) came from the GLM 4.x / Kimi K2 work in unslothai#5624 and is deliberate,
  so it is passed in rather than flattened.
- The scan order is now tool_call_parser.strip_segment, called by
  strip_tool_markup, the GGUF streaming strip and the safetensors loop.

Left alone on purpose:

- The two parse_tool_calls_from_text are layered, not forked: the parser calls
  the healer first and only then runs its extra formats. On 70 corpus inputs
  they legitimately return different call lists.
- _TOOL_ALL_PATS / _TOOL_CLOSED_PATS are not in a superset relation. The
  overlapping arms differ in content (name classes, [CALL_ID] handling, one
  level vs lazy JSON) and order within each list is load bearing, so splicing
  them would be a behaviour change dressed up as deduplication.
- routes/inference.py::_strip_tool_xml_for_display predates the parser and
  never picked up the markdown code gating, so it deletes a rehearsal inside a
  fenced code block that the canonical strip keeps. That is a real bug, but
  changing it changes what a shipped streaming route displays, so it is pinned
  in test_route_strip_drift.py for a separate decision rather than folded in
  here.

Also in this change:

- _gguf_request_intent enumerated GgufLoadIntent's fields with vars(source).
  dataclasses.fields() answers the same question without depending on the
  instance carrying a __dict__.
- The constant ggml GPU backend regex in _cpu_isolated_binary is compiled once
  at module level instead of on every call.
- Empty __slots__ on LlamaServerNotFoundError, _LlamaStreamCancelled and
  CountAborted, which only ever signal.

Verification. tests/tools/refactor_guard.py pins the AST and runtime surface of
all five modules, a digest of every guarded function's output over the corpus,
the idempotence of the strip family, and the 210 string patch targets the suite
relies on; test_refactor_guard.py runs it. Behavioural output is unchanged:
every diff against the pre-change baseline is confined to the two scanners' own
return value moving from -1 to None, and every one of those is int -> None,
never one index to a different index. 880 targeted tests pass and the failure
list over the touched areas is identical to a clean tree.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: make the refactor guard drive the entry points it guards

_drive only supplied `final` when it had a default, but `final`, `seg_final`
and `id_offset` are keyword-only and mostly required, and the positional loop
skips keyword-only parameters. Fourteen guarded functions therefore raised
TypeError on every input and their digest pinned one constant, `strip_segment`
among them - the function this branch extracts.

Supply the keyword-only flags, and add the three serializations the corpus had
no fragment for (DeepSeek, Kimi, GLM), so their parsers are exercised too.
Constant-valued functions drop from 34 of 81 to 16, and every remaining one is
a multi-argument helper the driver reports as undrivable rather than a silent
TypeError. Baselines regenerated.

Also correct what the empty __slots__ on the three signal exceptions is claimed
to do: BaseException declares a dict itself, so a subclass cannot remove it.

* Studio: stop the guard writing off a deleted patch target as environmental

importlib.import_module("mod.attr") raises ModuleNotFoundError for a deleted
attribute exactly as it does for a missing optional dependency, so the
environment classification caught both and the CI check filters those entries
out. A patch target whose symbol was genuinely removed was therefore reported
and ignored, which is the failure the check exists to make loud.

Only treat it as environmental when the parent is a package and the thing that
could not be imported is something other than the candidate itself, which
ModuleNotFoundError.name distinguishes. Regression test drives two deleted
targets through and asserts neither is excused.

* Studio: read and write the guard baselines as UTF-8

The corpus now carries DeepSeek's full-width markers, so the baseline files
are no longer ASCII and the reads and writes have to say so. On Windows the
platform default is cp1252 and both would fail. tests/test_source_read_encoding
covers this and caught it.

* Studio: pin the busy modules by symbol, not by signature

Replicating this branch onto a staging repo and running the org CI there showed
the AST inventory failing on a change that has nothing to do with it: an
unrelated commit gave InferenceBackend._generate_bicodec two keyword-only
arguments. Merged as it stood, the baseline would have failed every later PR
that touched llama_cpp.py or inference.py, and a baseline that gets regenerated
reflexively guards nothing.

The two modules this branch restructures stay pinned in full, signatures,
decorators and regex literals included. The other three are pinned by name and
kind only, which is the whole question being asked of them: this refactor must
not drop a symbol out of them. Verified both directions - removing
_GGML_GPU_BACKEND_RE from llama_cpp still reports REMOVED, and the signature
drift above now reports nothing.

* Studio: keep the display strip's bracket depth rule

Unifying the bracket scanner took the healer's body wholesale, and the healer
counts braces toward the bracket depth. That changed the display path: a stray
} before the real ] now ended the span at the brace, so
strip_tool_markup("[TOOL_CALLS] [} prose ] tail", final=True) went from "tail"
at merge base 19abc08 to "prose ] tail", leaving the tail of a malformed call
and its closing bracket on screen. My earlier reply on this compared
strip_tool_call_markup, which is the healer's entry point and unaffected; the
parser's strip_tool_markup is what the GGUF and safetensors paths call, and it
did regress.

The scanner stays shared, with braces_count selecting the depth rule: the
healer keeps counting braces, which its Gemma array normalizer needs, and the
parser passes braces_count=False, which is what it has always done. All three
entry points are now byte-identical to merge base across the whole 2,126 input
corpus. test_the_two_bracket_depth_rules_stay_separate pins both rules and the
case above.

* Studio: make the guard's three weakest checks actually check

Three ways the guard passed while proving less than it claims.

A patch target that resolves through core.inference's PEP 562 __getattr__ raises
AttributeError when the name is no longer exported, and the broad handler called
that an environment gap, which the CI test filters out. Only an ImportError from
that path is environmental; an AttributeError is a dead target.

snapshot wrote patch_targets.json and verify never read it. A patch string
edited to a different but still resolvable namespace, or a patch dropped during
a refactor, passed while the recorded routing went stale. It is diffed now.

_drive returned a <undrivable> sentinel for any unrecognised required argument,
so fifteen functions shared one digest and any rewrite of them passed. There is
a fixture per parameter now, and a function whose real output is an accumulator
it was handed has that accumulator recorded rather than its None. Functions
pinning a single value across the corpus drop from 34 to 2, neither a sentinel.

test_no_guarded_function_is_driven_by_a_sentinel and
test_a_dropped_lazy_export_is_not_written_off_as_environmental pin the first and
third; the second is covered by verify itself, checked in both directions
(dropping a patch reports REMOVED, moving one reports five differences).

* Studio: drive the coverage check over the whole corpus

A 200 entry slice reports coverage gaps that are not there: several guarded
functions are constant over any small prefix and only become interesting once
the rarer serializations appear. Over the full corpus the count is 3, over 200
it is 6.

* Studio: run the routing comparison where CI runs, and inventory annotated globals

The patch-target comparison went into verify(), and nothing invokes verify():
the Studio workflow runs pytest. A patch string repointed at a different but
still resolvable namespace passed CI with the recorded routing stale. It is a
test now, checked to fail on a dropped entry.

ast.AnnAssign was not collected, so annotated globals were missing from the
inventory entirely. In llama_cpp.py that is _SWA_CACHE, _LOADS_IN_FLIGHT,
_OVERRIDE_TENSOR_FLAGS and _BOOTSTRAP_SWA_DEFAULTS, none of which the guard
would have noticed being renamed, despite pinning that module by symbol name
being the whole reason it is listed.

* Studio: drive the argument parser and the offset predicates properly

_gemma_arguments_to_json takes a raw Gemma argument body, and the driver handed
it whole corpus entries: 2,125 of 2,126 came back as <raised JSONDecodeError>
and one as {}, so the digest pinned the exception rather than any of the key
quoting, bare value or array normalization it exists for. It gets a real body
now, extracted from the entry, and produces 12 distinct results.

_inside_open_parameter was driven only at pos = len(text), two distinct values
over the whole corpus, for a function this branch rewrites. Predicates that
take an offset are driven across the text now, and it produces 13.

Single-valued guarded functions: 2 of 82, both genuinely constant on this
corpus rather than sentinels.

* Studio: make the guard catch the changes it exists to catch

An independent pass found five production changes that passed both the verify
CLI and the suite. The worst is squarely on the function this branch extracts:
swapping the function-XML and GLM arms inside strip_segment turns

  <function=x><tool_call> t <arg_key>c</arg_key></function><parameter=p>

from '<parameter=p>' into '', swallowing everything after the call on all three
unified paths at once. Reproduced, verify exited 0.

Four causes, all fixed:

- Boolean contracts were driven at one value. final, seg_final, with_spans,
  allow_incomplete and gemma_quotes are each driven at both now and keyed into
  the digest. final=False is the streaming path and had no coverage at all.
- The corpus only ever concatenated whole calls, so no arm could consume a
  later arm's opener and the scan order was invisible. Eight fragments nest one
  format's markup inside another format's argument value.
- The regex inventory recorded the source of re.compile calls, so a pattern
  built by interpolating a constant pinned the constant's NAME. Every compiled
  pattern reachable in the module namespace is recorded by its actual text, and
  inline re.match / re.search / re.sub are collected as well.
- Additions now only fail for the two modules this branch owns. Replicating
  this onto a staging repo and running the org CI there showed the guard
  failing on an unrelated new global in llama_cpp.py and one new patch target;
  merged as it stood it would have failed most later PRs, and a baseline that
  gets re-snapshotted reflexively guards nothing. A dropped symbol still fails.

The verify CLI also now filters environment-only patch failures, matching the
pytest check, so it stays usable without every optional backend installed.

All four mutations are caught after this. Verified by applying each to the
production code and confirming verify and pytest both fail.

* Studio: apply the additive tolerance in CI, and drive both variants for idempotence

Three gaps in what I did last round.

The additive tolerance went into verify() and _ast_problems(), but the pytest
tests that CI actually runs still called _diff with its strict default. The
tripwire staging CI showed was therefore still live on the path that matters.
Both tests now go through the same helper.

The idempotence check skipped any function whose driver result was not a str,
and driving the boolean contracts at both values made those results a dict, so
it silently stopped covering strip_segment, strip_tool_markup and
strip_tool_call_markup - the centralized strippers it exists for. Each variant
is now checked separately against itself.

Fixing that surfaced a second bug of mine: a parser returning a dict was being
read as a set of variants and driven back into itself. Variants carry a tag
now, and a function with 'parse' in its name is not a text projection whatever
else the name contains.

Verified in both directions: making strip_segment drop a trailing space fails
verify and the suite; an added symbol in llama_cpp.py and an added patch target
are tolerated while a removal still fails. Pre-existing non-idempotent
functions recorded in the baseline go from 4 to 6; both new entries were
confirmed non-idempotent at merge base 19abc08 as well.

* Studio: drop the strip imports llama_cpp no longer uses

The streaming segment strip now calls the parser's shared strip_segment, so the
per-format arms and the healer's bracket-tag/rehearsal helpers are imported and
never referenced. The import-hoist lint blocks on exactly that: an import that
was used before and is unused after reads as a rename that missed a reference.

* Studio: close three holes in the refactor guard's own comparisons

Key the idempotence baseline on the boolean variant, not just the function.
Every recorded entry already carried a variant, but the lookup ignored it, so a
pre-existing final=True failure whitelisted a new one on the final=False
streaming path. The witness loop had the same shape: it stopped at the first
failure per function, so the other variant was never even computed. It now
witnesses per (function, variant), which is why the baseline grows by two
entries. Both are pre-existing failures of strip_segment and strip_tool_markup
at seg_final/final = False that the early stop had been hiding; no guarded
behaviour changed, and the other four baselines are byte-identical.

Keep the import error while probing module prefixes. A package whose __init__
eagerly imports an app dependency makes every prefix raise, and discarding the
exception reported the four live routes.* targets as dead patches. Blocking
fastapi reproduces it: all four come back 'no importable module prefix' with no
environment flag, so verify fails on a healthy tree. A ModuleNotFoundError
naming a prefix of the target still means the module is genuinely gone.

Compare occurrence lists by count. The same file patching one target several
times records one entry each, and 128 recorded targets have duplicates, so
set-differencing them made a partial repoint invisible: dropping one of four
patches of core.export.get_export_backend reported nothing. Counted, it reports
4 -> 3. A full removal still reads REMOVED and dir() lists are unaffected.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: record patch targets platform-independently and stop skipping namespaces

Serialize each occurrence with as_posix(). str() on a relative path is the native
form, so on Windows every entry came back as tests\\test_x.py against a baseline
written as tests/test_x.py and an identical checkout read as a full inventory
rewrite. On POSIX the two are the same string, so the recorded values do not move.

Widen the target regex to the remaining first-party packages. The check advertises
every string patch target, but the namespace list stopped at core/routes/utils/state
and skipped 32 live targets under hub, storage and picker, among them
hub.utils.dataset_cache.latest_cached_dataset_path and storage.studio_db.finish_run.
All 32 resolve today, so the re-snapshot is purely additive: no recorded target was
removed and no occurrence list changed.

* Studio: tighten comments in the tool-call strip dedup change

* Studio: drive the anchoring predicate and re-record the guard baselines

Main added _gemma_call_is_anchored and _GEMMA_ANCHOR_CLOSERS to the Gemma
wrapper-less strip, and renamed several stt test modules. Merging main leaves the
recorded baselines describing code that no longer exists, so the guard reports 16
differences it was never meant to flag.

The new predicate takes a scan origin the driver had no fixture for, so it recorded
as undrivable and its golden digest pinned nothing. Give floor the origin the strip
itself starts from, which drives the predicate to both answers across the corpus
(1616 anchored, 1211 not), then re-record inventory, golden outputs, idempotence and
patch targets against the merged tree.

The dedup itself is unaffected: the differential harness run against main's tip is
IDENTICAL over 78,960 rows with no idempotence failure introduced by the PR.

* Studio: correct what strip_segment claims about the passthrough path

The docstring listed routes/inference.py among the callers that now delegate here.
It does not: the passthrough path deliberately keeps its own arm order, which
tests/test_route_strip_drift.py pins. Name the two callers that do delegate and
record the passthrough divergence as intentional.

* Studio: tighten the comments around the shared strip path

Collapse the multi-line explanations in the unified strip helpers, the shared
healer scanners and the refactor guard to their load-bearing lines. Comment and
docstring text only, no behaviour change.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
danielhanchen added a commit that referenced this pull request Aug 17, 2026
…d hole

Three tests in this file fail on main if the file runs first, or on its own,
against the dependency set Backend CI installs:

  ImportError: Unsloth: Please install unsloth_zoo via `pip install unsloth_zoo`

Which PR, and which side is wrong:

  #5620 (2026-07-06) added this file, with no stub, from the start
  #8342 (2026-08-10) added the stub guard, which does not look here

Neither is wrong about its own subject, and neither is reverted. #5620's tests
are correct; they just relied on another file having stubbed unsloth first.
#8342's guard exempts imports inside a function on purpose, because those are
lazy and cannot fail COLLECTION, which is the disaster it was written for.

The hole is that pytest.importorskip USED to make a lazy import safe and no
longer does. Since pytest 8.2 it skips on ModuleNotFoundError only, and
unsloth/_gpu_init.py raises a plain ImportError when unsloth_zoo is missing, so
the call fails instead of skipping. #8342's exemption was sound when written and
stopped being sound under a pytest it did not choose.

Fix: install the same stub the sibling files install, at module scope. Stubbing
rather than skipif keeps the coverage: the module under test is still the real
core.inference.inference, and only unsloth is faked. A skipif would have made
three tests silently stop running on the backend job.

Robustification: a second guard beside #8342's, for modules reached through
pytest.importorskip at any scope, with its own reason stated rather than folded
into the collection guard. Verified against main's version of this file:

  1 test module(s) reach a backend module that needs unsloth through
  pytest.importorskip without installing the stub ... ['test_safetensors_reasoning_stream.py']

It is pinned in both directions (an unstubbed sample is an offence, a stubbed one
and an importorskip of numpy are not) so it cannot pass by matching nothing.

I also swept the other five files that importorskip a core.* or unsloth* module
without stubbing. Under the no-unsloth_zoo condition all five pass, so this file
was the only live case:

  test_active_generations            84 passed
  test_bypass_permissions           117 passed
  test_diffusion_dataset_clips       22 passed
  test_mlx_inference_backend         80 passed, 10 skipped
  test_offline_gguf_cache_fallback  202 passed
  test_safetensors_reasoning_stream   3 FAILED, 10 passed

Verified by hiding unsloth_zoo's metadata to reproduce the CI shape:

  before: 3 failed, 10 passed
  after:  13 passed
danielhanchen added a commit that referenced this pull request Aug 17, 2026
…#9027)

* Stub unsloth in test_safetensors_reasoning_stream, and close the guard hole

Three tests in this file fail on main if the file runs first, or on its own,
against the dependency set Backend CI installs:

  ImportError: Unsloth: Please install unsloth_zoo via `pip install unsloth_zoo`

Which PR, and which side is wrong:

  #5620 (2026-07-06) added this file, with no stub, from the start
  #8342 (2026-08-10) added the stub guard, which does not look here

Neither is wrong about its own subject, and neither is reverted. #5620's tests
are correct; they just relied on another file having stubbed unsloth first.
#8342's guard exempts imports inside a function on purpose, because those are
lazy and cannot fail COLLECTION, which is the disaster it was written for.

The hole is that pytest.importorskip USED to make a lazy import safe and no
longer does. Since pytest 8.2 it skips on ModuleNotFoundError only, and
unsloth/_gpu_init.py raises a plain ImportError when unsloth_zoo is missing, so
the call fails instead of skipping. #8342's exemption was sound when written and
stopped being sound under a pytest it did not choose.

Fix: install the same stub the sibling files install, at module scope. Stubbing
rather than skipif keeps the coverage: the module under test is still the real
core.inference.inference, and only unsloth is faked. A skipif would have made
three tests silently stop running on the backend job.

Robustification: a second guard beside #8342's, for modules reached through
pytest.importorskip at any scope, with its own reason stated rather than folded
into the collection guard. Verified against main's version of this file:

  1 test module(s) reach a backend module that needs unsloth through
  pytest.importorskip without installing the stub ... ['test_safetensors_reasoning_stream.py']

It is pinned in both directions (an unstubbed sample is an offence, a stubbed one
and an importorskip of numpy are not) so it cannot pass by matching nothing.

I also swept the other five files that importorskip a core.* or unsloth* module
without stubbing. Under the no-unsloth_zoo condition all five pass, so this file
was the only live case:

  test_active_generations            84 passed
  test_bypass_permissions           117 passed
  test_diffusion_dataset_clips       22 passed
  test_mlx_inference_backend         80 passed, 10 skipped
  test_offline_gguf_cache_fallback  202 passed
  test_safetensors_reasoning_stream   3 FAILED, 10 passed

Verified by hiding unsloth_zoo's metadata to reproduce the CI shape:

  before: 3 failed, 10 passed
  after:  13 passed

* Drop the stubs once the module is built, so they do not outlive it

The first version of this fix installed the unsloth stub and left it in
sys.modules for the rest of the process. Staging CI caught it on all four
interpreters:

  tests/test_audio_type_inconclusive.py:159: in test_the_stubs_do_not_outlive_this_module
      assert name not in sys.modules, name
  E   AssertionError: unsloth

That test exists precisely to forbid what I did. Every other file installs its
stubs, performs its heavy import, then pops them, and a stub left behind is a
cross-file leak: every other _stub_if_missing returns early when the name is
already present, so its own bookkeeping never runs and its cleanup has nothing
to undo.

Traded this file's order dependency for a worse one, in other words.

Now it follows the same shape as test_audio_type_inconclusive.py: stub, build
core.inference.inference while the stubs are live, drop the stubs. The three
tests reach the module through pytest.importorskip and get it from sys.modules,
so the stubs only need to exist for that one import.

It did not reproduce locally, which is why it reached staging: run the file
alone and the victim's own _STUBBED list is empty, so its loop asserts nothing
and passes vacuously. It takes xdist interleaving the two files on one worker
to put the leak in front of that assertion.

* Close two holes in the importorskip guard

Both reported on the guard added by this PR, both confirmed by construction
against the guard's own helpers.

1. The bare-name form was invisible. "from pytest import importorskip" then a
   bare importorskip("core.inference.inference") is a call on an ast.Name, not
   an attribute, so matching only pytest.importorskip returned no targets:

     bare-name form detected as target: []

   Both call shapes are matched now.

2. A module-scope call was judged by the wrong boundary. The check scanned the
   whole module for a stub, so a file that calls importorskip at module scope
   and installs its stub BELOW that line read as safe:

     late-stub form judged stubbed (scanning whole module): True

   while the call runs during collection and the import has already raised. The
   boundary is now the call's own line at module scope, and the end of the
   module only inside a def, where the call really does run after the body.

The pinning test covers all four shapes and both boundaries, so neither hole
can reopen silently. The guard still names the file this PR fixes when run
against main's version of it.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Judge import-time calls and dropped stubs correctly in the guard

Two more gaps on the guard this PR adds, both verified against its own helpers
before changing anything.

1. Definition-time calls were given the wrong boundary. _runtime_nodes stops at
   every def and class, so a call in a class body, a decorator, an annotation or
   a default expression was treated as lazy and got the end-of-module boundary:

     class body, stub below    calls=[('core.inference.inference', 5)] judged_safe=True
     default arg, stub below   calls=[('core.inference.inference', 5)] judged_safe=True

   All of those run while the module is being imported. Only a function BODY is
   deferred, so the scope walk now keeps class bodies and definition-time
   expressions and excludes just the body.

   No file in this tree does this today; all five class-level importorskip calls
   are inside methods, which really are lazy. Fixed anyway, because a guard that
   is wrong about when Python runs things is not much of a guard.

2. A lazy call was judged only on whether a stub was ever installed, not on
   whether it was still there. A module that installs the stubs, drops them
   again, and then reaches the heavy module lazily passes that check and still
   raises at test time. This PR's own file is safe only because it imports the
   target eagerly while the stubs are live, and nothing made that a requirement,
   so a copy that omitted the eager import would have read as safe.

   Now: a lazy call is an offence when the module drops its stubs and does not
   import the target itself. A module that keeps its stubs installed is fine
   lazily, which is why the removal is part of the condition rather than the
   eager import alone.

The decision is one function used by both the guard and the test that pins it.
My first version of this test reimplemented the logic instead, and a mutation
that deleted the real rule left it green.

  scope walk narrowed back to _runtime_nodes  -> 1 failed
  eager-import rule deleted                   -> 1 failed
  stub-removal condition dropped              -> 1 failed

* Judge a dropped stub at import time too, not only for lazy calls

Reported on this PR and correct. The guard asked "were the stubs dropped again,
and was the target never imported eagerly" only in the lazy branch, so a module
that installs the stub, pops it, and then calls importorskip at module scope
satisfied the install check and read as safe, while collection still dies: the
stub is gone by the time the call runs and nothing put the target in sys.modules.

Both questions now take the same boundary as the install check. _drops_stubs and
_eagerly_imports stop at that line, so an import-time call is judged on the pops
and imports ABOVE it and a lazy call on the whole module body, which is what the
old lazy-only branch computed. Three cases pinned: stub-pop-call is an offence,
stub-call-pop is not, and stub-import-pop-call is not.

Mutating the branch back to the lazy-only form fails the new pin.
6 passed.

* Four precision fixes to the importorskip guard

All four reported on this PR, all four real, each pinned and each verified by
reverting the fix and watching the pin fail.

1. An eager import only counts if the stubs were live for it. A file that probes
   the target in try/except ImportError before installing the stubs, then stubs,
   pops, and calls importorskip lazily, was read as safe. On the dependency-light
   matrix that probe fails and Python removes the half-initialised module, so the
   later call still reaches the real dependency. The check now asks _stubs_before
   for the statement's own line, so there is one answer to "are the stubs live"
   in this file rather than two that can drift.

2. A drop has to be OUR stubs being dropped. Any x.modules.pop counted, so an
   unrelated sys.modules.pop("routes.foo", None) in a properly stubbed file got
   that file reported as an offender, and a pop on any object with a .modules
   counted as well. The receiver must now be sys.modules and the statement must
   name the required stub the same way an install does, directly or through a
   module-level list it reads, which is how the real files spell it.

3. importorskip(modname = "...") is the documented signature
   (modname, minversion=None, reason=None, *, exc_type=None), and node.args is
   empty for it, so a file written that way walked straight past the guard. The
   keyword is read now.

4. exc_type=ImportError is pytest's own opt-in to skipping on a plain
   ImportError, which is the exact failure this guard is about, so such a call is
   safe unstubbed and flagging it was a false report. Those calls are excluded.
   exc_type=ModuleNotFoundError is the default and stays flagged. Confirmed
   against the pytest reference: exc_type arrived in 8.2, "must be ImportError or
   a subclass", and defaults to ModuleNotFoundError.

  6 passed, and reverting each of the four in turn: 1 failed each time
  test_safetensors_reasoning_stream.py + the guard together: 19 passed

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Install peft on the backend job, and stop misreading unrelated cleanup as a stub drop

Two items from this round, both reported here.

1. The eager import in test_safetensors_reasoning_stream.py was failing on the
   backend matrix and the handler was swallowing it, so the three importorskip
   tests SKIPPED rather than ran: 10 passed and 3 skipped, green either way.
   core/inference/inference.py imports peft at module scope, and peft is listed
   only in extras-no-deps.txt and no-torch-runtime.txt, neither of which this job
   installs. Confirmed both ways: the install log for a real matrix leg lists
   torchao and transformers and no peft, and hiding peft behind a meta_path
   finder locally reproduces exactly 10 passed and 3 skipped.

   Fixed by installing it rather than stubbing it. A stub does not work here:
   transformers probes importlib.util.find_spec("peft") during its own import,
   which raises ValueError on a stub whose __spec__ is None, so stubbing turns a
   silent skip into a collection error. Installing it also means these tests
   exercise the real import chain, which is the coverage the file is for.

   The swallow now records the error and a new test reads it back, so a
   module-scope dependency added to inference.py that this job does not install
   fails by name instead of quietly removing three tests.

2. _drops_stubs accumulated every module-level assignment target, so an unrelated
   cleanup list popped from sys.modules read as the unsloth stubs being dropped
   and got properly stubbed files reported as offenders. It now follows the link:
   a module-scope call naming the required stub identifies the helper, and
   whatever module-level name that helper appends to is the record. Two cases
   pinned, and the pin for the real shape now spells out the helper body, because
   that is what the link is followed through.

  test_safetensors_reasoning_stream.py + the guard: 20 passed
  with peft hidden: the new test FAILS by name instead of 3 silent skips
  restoring the old accumulation: 1 failed

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Install peft after the CPU torch wheel, not before it

Reported on this PR and correct, and this was my mistake in the previous commit.
peft declares `torch >=1.13.0` with no index constraint (checked against its
wheel metadata), so placed above the CPU-index line it resolves torch from PyPI,
which on Linux is the CUDA build. That version satisfies the >=2.4,<2.11 the next
line asks for, so pip leaves it, and a nominally CPU-only job ends up carrying
the CUDA distribution and its nvidia-* dependencies on all four legs: minutes of
download against a limit this job was already cancelling at, and runner disk.

Moved below the torch and transformers lines, where the pinned CPU torch already
satisfies the dependency and nothing re-resolves.

* Judge eager imports and helper calls by what actually runs at import

Three items from this round, all reported here, all real.

1. An eager import under `if TYPE_CHECKING:` or `if False:` never runs, so it is
   not what left the target in sys.modules, and a file that stubs, "imports"
   there, then drops the stubs still raises. The walk pruned nothing and read it
   as safe. It now skips a branch whose test is a constant the interpreter will
   not take, or TYPE_CHECKING, and nothing beyond that is guessed at.

2. The opposite error in the same walk: a class body, a decorator, a default and
   an annotation all execute while the module is being imported, so an eager
   import written in one of them DOES cache the target. _runtime_nodes stopped at
   every def and class, so such a file was reported as an offender when it is
   safe. That is what _import_time_nodes was already built for, so the eager
   check uses it now, with the reachability pruning above on top.

3. A def is only deferred while nothing runs it. Where the MODULE BODY calls a
   helper, that helper executes during collection, so an importorskip inside it
   runs then too, and the end-of-module boundary let a stub installed BELOW the
   call site read as being in place. Those calls now take the line they are
   invoked from. Followed one level, which is the shape that occurs; a helper
   reached only through another helper keeps the deferred boundary rather than
   being guessed at.

Four cases pinned: TYPE_CHECKING import is an offence, a class-body import is
not, a helper called at import time takes the call site's line, and the same
helper never called keeps the end-of-module boundary. Reverting each of the three
fixes fails a pin.

  6 passed, and 20 passed with test_safetensors_reasoning_stream.py

* Resolve importorskip aliases, and prune the else of a constant-true test

Both reported on this PR, both real, both pinned and mutation-checked.

1. `from pytest import importorskip as ios` then `ios(...)` is a valid call, and
   matching the callee against the literal string missed it, so an unstubbed
   module written that way walked past the guard. Bare names bound to it are
   collected now, through the import and through a plain rebinding of the
   attribute form. `from mymod import importorskip` is not one of them and is
   pinned as such.

2. The other half of the unreachable-branch hole I closed last round: pruning the
   body of `if False:` while still descending into the `else:` of `if True:` left
   an import that never runs counting as the one that cached the target. The
   traversal now takes only the branch the interpreter takes, for either constant.
   Both directions pinned.

  6 passed, and reverting each fix fails its pin

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Follow import-time helper calls all the way down

Reported on this PR and correct, and my "conservative" one-level stop was
conservative in the wrong direction. Stopping hands the inner helper the
end-of-module boundary, which is the LENIENT answer: a stub installed anywhere in
the file then reads as in time, while collection has already run the inner import
and failed.

Reachability now propagates through the module-level call graph to a fixed point,
and a helper reached only through another helper inherits the outer call site's
line, which is when it actually runs.

Two cases pinned: the module calls the outer helper and the inner one holds the
importorskip, which is an offence at the outer call's line; and the same chain
with nothing calling it at import time, which keeps the deferred boundary.
Removing the closure fails the first.

  6 passed

* Propagate only through the calls the helper actually makes

Reported on this PR and correct, and this one fails a SAFE file rather than
passing an unsafe one. ast.walk visits a call under `if False:` and a call inside
a nested def that nothing invokes, and handing those the outer helper's
import-time boundary judged an importorskip as running before a later stub when
Python never executes that path during collection.

It now walks the helper's body under the same reachability rule the module body
uses, so the two cannot answer differently.

Two cases pinned, both safe: an inner call under a constant-false test, and one
inside a nested def that is returned rather than called. Reverting to ast.walk
fails them.

  6 passed

* Do not report a call the interpreter never reaches

Reported on this PR and correct, and it is the same false-positive direction as
the last one: an importorskip under `if False:` or `if TYPE_CHECKING:` was
collected as a module-scope call, so the guard failed a file that only
type-checks the import or deliberately disables it. The helper seeding had the
same gap for a helper invoked only inside such a branch.

Both traversals are reachability-aware now. The call walk prunes constant
branches wherever they appear, inside a function body as well as at module scope,
since a call under `if False:` never runs there either.

Three cases pinned, all safe: a TYPE_CHECKING call, an `if False:` call, and a
helper called only from a disabled branch. Reverting either traversal fails them.

  6 passed, and 20 passed with test_safetensors_reasoning_stream.py

* Attribute a call to the innermost function that holds it

Reported on this PR and correct, and the same false-positive direction as the
last two. ast.walk descends into a nested def, so an importorskip written there
was attributed to the enclosing module-level function and handed that function's
import-time boundary. A nested body cannot run until something calls it, by which
time a stub installed below the outer call is in place, so the guard rejected a
file that works.

Nested bodies are deferred now, and a call inside one falls through to the
end-of-module boundary, which is what deferred means.

Pinned: an importorskip inside a nested def that the outer helper returns rather
than calls, with the stub after, is safe. Restoring ast.walk fails it.

  6 passed, and 20 passed with test_safetensors_reasoning_stream.py

* Stub the heavy imports in the peft-gated TTS test

Reported on this PR, real, and a consequence of installing peft in the previous
commit. test_audio_tts_cancellation.py gates on pytest.importorskip("peft") and
then imports core.inference.inference in the test body without stubbing anything.
That gate used to skip, so the import never ran. With peft installed it opens,
and the import works only because collecting test_safetensors_reasoning_stream.py
has already cached that module: module-level code runs during COLLECTION, before
any test body, so the whole suite hides it. Running the file on its own does not.

That is the same order dependence this PR exists to remove, reintroduced by the
fix, which makes it worth more than the P2 it came in as.

The file now stubs unsloth and trl, imports core.inference.inference while they
are live, and drops them again, exactly as its siblings do. The peft gate stays,
so a machine without peft still skips rather than failing.

Verified: with peft hidden the file skips cleanly on its own (17 passed, 1
skipped), and 59 passed across it plus test_audio_type_inconclusive.py,
test_safetensors_reasoning_stream.py and the guard. Locally the eager import is
blocked only by a torch/torchao ScalingType mismatch inside peft, which is
present on main too and has nothing to do with unsloth; with the stubs installed
that is the sole remaining blocker, checked directly.

Worth flagging separately: seven more files are in the same class, importing a
heavy backend module lazily while never stubbing --
test_chat_eos_template_refresh.py, test_chat_template_continuation.py,
test_control_markup_neutralize_7066.py, test_generation_timing.py,
test_nudge_tool_calls_wiring.py, test_online_tokenization_wiring.py and
test_training_preflight.py. All are masked by the same collection-time caching.
They are latent rather than failing, and fixing eight files belongs in its own
change rather than inflating this one.

* Widen the stub guard to module-scope with/if blocks and helper-held stubs

_first_heavy_import_line only read the direct children of the module body, so a
heavy import inside a module-scope with or if was invisible to the guard: a file
written as 'with something(): from core.training.trainer import X' without stubs
would take collection down unseen. It now uses the import-time traversal, with
try/except ImportError exempt since that is a deliberate guard.

That widening needs the matching read on the other side. Two files hold their
stubs with 'with _stubbed():' and import the heavy module inside that block, so
the installing code is one call away from module scope and the statement spells
neither the module name nor sys.modules. _stubs_before now reads through a call
to a module-level helper, the same way the stub-record check already does, and
keeps asking what the helper DOES rather than merely what it names.

Pins added for both halves plus the helper that names the module without
installing anything; each is mutation-checked.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Take the backend CI peft version from the requirements pin

An unconstrained 'pip install peft' takes the newest release (0.20.0 on the last
staging run), while extras-no-deps.txt pins peft==0.18.1 deliberately, because
0.19.0 breaks Unsloth's export subprocess. That left this job exercising the
newly enabled inference tests against a peft that production never ships and no
other job installs.

The version is read out of extras-no-deps.txt rather than written here again, so
a change to the pin cannot leave this workflow behind. peft 0.18.1 declares
torch>=1.13.0, transformers unbounded and python>=3.10, so it holds across the
3.10 to 3.13 matrix and does not disturb the CPU torch installed above it.

* Make both sides of the stub guard reachability and order aware

Two follow-ons to widening the search into module-scope compound statements.

The widened search used the plain import-time traversal, which descends into
both branches of every conditional, so an import under if TYPE_CHECKING: or
if False: read as an import-time dependency. A file with a legitimate type-only
import would have failed this guard until someone added a stub it does not need.
It uses the reachability-aware traversal now.

And widening one side without narrowing the other read the whole enclosing
statement as preceding the import, so

    if True:
        import core.inference.inference
        _stub_if_missing("unsloth", ())

counted as stubbed while Python attempts that import first and collection dies.
Only the part of a statement that runs before the import line is read now.

The stub side gets the same reachability treatment, from the other direction: a
stub installed under if False: installs nothing, so counting it would report a
file safe that still raises.

Three pins added, each mutation-checked.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Follow the import's own branch, and match except clauses by what they catch

Line order alone merges branches that exclude each other:

    if enabled:
        _stub_if_missing("unsloth", ())
    else:
        import core.inference.inference

puts the stub above the import while the two can never both run, and the guard
called that file stubbed. What is walked now is the import's own chain: at each
level only the block CONTAINING the import is descended into, and only the
statements above it there. Those did run, because the import running means its
branch was taken. A stub that merely might have run does not count either.

That last rule needs one exemption, and the tree already had the case:
test_training_progress_callback.py installs its stubs under
'if not _TRAINER_PRE_IMPORTED', where the flag is
'"core.training.trainer" in sys.modules'. Skipping the stubs on the other branch
is not an omission, because the import resolves out of sys.modules there and
never reaches the real dependency. A test that asks sys.modules whether the
target is already imported keeps its branch, read through a module-level flag as
well as directly, since that is how it is written.

Separately, the ImportError exemption matched substrings, so 'except
MyImportError:' and 'except ExceptionGroup:' both exempted a try that catches
neither. Handler types are compared as whole names now, including tuple members
and the last component of a dotted name. ModuleNotFoundError is deliberately not
in the set: it is a subclass, so it catches strictly less.

Ten pins added across the four behaviours, each mutation-checked.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Take the loaded-models indicator suite off the UI job's critical path (#9060)

* Take the indicator suite off the UI job's critical path

Unsloth UI CI / Chat UI Tests has been timing out at its 30 minute limit on
almost every open PR: 5 of the 6 currently open, at 30m09s to 30m24s. Nothing
was failing. The job was simply longer than the limit, and a limit is a
guillotine, so the steps after the cut never ran at all.

Where it goes: "Cross-browser loaded-models indicator" is 853s of the 30
minutes, three browser engines at about 4.7 minutes each, each booting its own
Unsloth. Everything downstream of it -- the other-engines update banner
regression, both image staged-download regressions, the model-picker
per-model-config suite and the IME / multilingual paste regression -- was
reported "skipped" and has been running on no PR at all.

It is now its own job rather than a step, so it runs beside the rest instead of
inside their budget. That leaves ui-smoke around 16 minutes and the new job
around 15, both with real margin, and the five skipped suites run again. The new
job carries no HF cache and no GGUF: the suite stubs the four /status reads with
page.route, so it needs no model, no GPU and no llama.cpp build.

Moving the work rather than the limit is deliberate. The limit here already went
25 -> 30 for this exact symptom, with the comment on it still describing that
round, so raising it again buys one more release of silence.

Also tests/studio/test_playwright_suites_run_in_ci.py, because these drivers are
standalone scripts that nothing collects: a suite runs only because a workflow
step or a .github/scripts helper names it, and deleting that line leaves every
job green. It fails if any tests/studio/playwright_*.py is named by no workflow
and no CI script. Deleting either the new step or the driver call inside
run-studio-indicator-browser.sh fails it.

It also found two suites already in that state, exempted with a reason each
rather than quietly ignored: playwright_tauri_python_tool_images.py needs the
Tauri desktop shell no runner here builds, and playwright_train_pickers.py needs
a dataset and model resolved through huggingface_hub while the UI workflows boot
API-only. Both are worth wiring up, separately from this.

  test_playwright_suites_run_in_ci.py:  3 passed, and 2 failed under each mutation
  test_stt_model_search_locator_contract.py + test_composer_rtl_bidi_attribute.py: 34 passed

* Count only helper scripts a workflow can actually reach

Reported on this PR and correct: reading every file under .github/scripts counts
an orphaned helper as coverage, so a driver named only by a script nothing calls
reads as covered while it runs nowhere, which is the regression this test exists
to catch.

The workflows now seed the text and a helper joins only once something already in
it names the helper, repeated to a fixed point because one helper can call
another. .github/actions is included the same way, since a workflow reaches a
composite action by uses: and the action then calls the script.

Verified by making the reference unreachable in all three UI workflows while
leaving run-studio-indicator-browser.sh in the tree. The new version reports the
driver as running nowhere; the scan-everything version reports it covered. That
one helper is named by the Linux, Windows and Mac UI workflows, which is why
removing it from one is correctly still covered.

  3 passed

* Count only the workflow fields that run something

Reported on this PR and correct. Reading a workflow whole counts a driver named
in on.pull_request.paths as an invocation, and studio-frontend-ci.yml names
playwright_strip_ansi_smoke.py in both its trigger list and its step, so deleting
the step alone left this guard green while the suite ran nowhere. Trigger paths
say when CI runs, not what it runs.

The scan now parses each workflow and reads only the executable fields: a job's
uses, and each step's run, uses and with. Helper reachability is followed from
that text as before.

Verified by deleting only the run line in studio-frontend-ci.yml and leaving the
trigger path: the guard now reports playwright_strip_ansi_smoke.py as running
nowhere, where before it stayed green.

  3 passed

* Follow a composite action by the directory workflows reference it with

Reported on this PR and correct. A composite action is used as
`./.github/actions/<name>`, never as the action.yml inside it, so the
reachability walk never opened one and a driver launched from inside an action
read as an orphan. An action.yml now also matches on its containing directory.

Pinned with a line from inside install-unsloth-local's own body rather than
something a workflow could also contain, so the pin fails if the walk matches the
uses: reference without opening the action. Dropping the directory match fails it.

  3 passed

* Run the coverage guard from the workflow that has no paths filter

Reported on this PR and correct: the guard could not catch the regression it
exists for. It ran only in studio-backend-ci.yml's Repo tests job, whose paths do
not include .github/workflows/**, .github/scripts/** or .github/actions/**, so a
PR that only deletes a Playwright invocation never collected it and stayed green
until the post-merge run on main.

It now runs in workflow-trigger-lint.yml instead, which carries no paths filter
at all and says so in its own header comment, deliberately, for the same reason:
a gate that only runs for some PRs does not gate workflow changes. Cost is the
same shape as the lint beside it, filesystem reads in seconds, and that job
already installs PyYAML, which is all this needs besides pytest.

  3 passed, run bare from the repo root as that job runs it
  the workflow-trigger lint itself still passes: 42 workflow files scanned

* Pin the three browser engines to the job that runs them

Reported on this PR and correct: the repo-wide check cannot see this job
disappear. run-studio-indicator-browser.sh is named by the Mac and Windows UI
workflows too, so deleting all three calls from the Linux workflow leaves every
guard green while the Chromium/Firefox/WebKit coverage this job exists for is
gone.

Asserted against the ui-indicator job itself rather than the file, so a step
moved back into ui-smoke fails it too: that is the 30-minute limit this change
moved the work out of.

  4 passed, and deleting the three calls fails the new test by naming all three

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Count a driver as covered only where CI actually runs it

Reported on this PR and correct, with a real instance: substring presence is not
coverage. .github/scripts/kaggle_studio_ci/report.py names playwright_chat_ui.py
inside a result description, and the workflows name drivers in comments and in
trigger paths, so deleting every real invocation could leave this guard green on
prose alone.

Every driver and helper in this repo is run the same way, as an argument to an
interpreter, so that is what is matched now: the name at the end of a path token
being handed to python, python3, node, bash or sh. Composite actions keep the
directory match, since a workflow reaches one through uses: rather than a command.

Verified by removing every real invocation of playwright_chat_ui.py while leaving
report.py's description in place. The substring is still present and the guard now
reports the driver as running nowhere; before, it stayed green.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Stop a commented-out invocation counting as coverage

Reported on this PR and correct: commenting a command out is how one gets
disabled, and the scan reads workflow run: bodies and helper scripts verbatim, so
`# python tests/studio/x.py` matched the invocation shape through the whitespace
before python.

Comments are stripped before matching. Shell, YAML and Python all take # to end of
line, and a # inside a string only ever appears in prose here, which is not an
invocation either way.

Verified by commenting out every real invocation of playwright_chat_ui.py: the
guard now reports it as running nowhere, where before it stayed green.

  4 passed

* Tighten the comments in the coverage guard

Comments and docstrings only. The code is byte-identical once docstrings are
stripped, checked by comparing the parsed trees, and the tests still pass.

* Read the browser-engine guard through the comment stripper

The cross-engine check tested raw step bodies for the substring, so prefixing
all three invocations with # left it green while the job ran no browser suite,
which is the regression it exists to prevent. It uses the same _uncommented()
helper the repo-wide scan does, and a pin asserts the disabled form of one of
those lines does not read as coverage.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Keep the killed-by-signal exit status when release() fails (#9072)

* Keep the killed-by-signal exit status when release() fails

A cancelled launcher reported success. The signal handler deletes the kernels
and then re-raises the signal so the status still reads killed, but the delete
was outside any try: a raise there propagated out of the handler into whatever
the main thread was doing, main()'s except BaseException caught it, and finish()
called release() a second time. When that second call worked, which is what a
transient OSError out of a subprocess spawn on a loaded runner looks like, main
RETURNED 0 and the job read as completed.

Caught on a contended runner rather than by inspection, and reproduced by
failing the first delete only: returncode 0 instead of -SIGTERM.

The delete is now best effort, retried once, and the death by signal happens
either way. If both attempts fail the slugs stay in the registry and the next
launcher's orphan sweep reclaims them, which is the same path a kill -9 already
takes.

The subprocess waits in the suite move from 30s to a named budget of 120s. They
guard against a launcher that never dies, not against latency, and the repo
suite now runs four of these at once on a four-core runner.

* Make the stall outlast the death budget, and assert the signal did the killing

Raising the wait to 120s put it past the 60s stall the launcher sits in, which
defangs the tests it was meant to make robust: a handler that swallows its
signal leaves the process asleep and then resuming, so it wakes, runs finish(),
deletes the kernels through the ordinary path and exits INSIDE the wait. The
deletion assertions are satisfied by that, so those tests would have passed on a
launcher that ignored the signal entirely.

The stall is now a named 900s against the named 120s budget, and a test asserts
the relationship rather than leaving it to whoever next tunes one of the two
numbers.

The deletion test also asserts the exit status now. Without it, the deletion is
satisfied by finish() doing its usual work, so nothing there said the signal was
what caused it.

Verified by making the handler return instead of re-raising: with the stall at
900s that fails all four signal tests, and with it at 60s the relationship test
fails as well.

* Tighten the comments added here

* Read a stub helper only as far as it has run

Reading the whole helper body accepted a sys.modules write below the yield of a
context manager. That code runs on the way OUT of the with block, after the
import inside it has already been attempted, so it stubs nothing for that import
and the file still dies at collection while the guard stays green.

The scan now stops at the helper's first yield, and drops unreachable and merely
optional branches the way the module-scope side already does. The yield has to be
the helper's own: one belonging to a generator defined inside it says nothing
about when the helper suspends, and taking it cut the scan off above the install
the real files do perform.

Three pins, each mutation-checked.

* Count only the finally of a try as certain

A try body whose handler swallows the exception is exactly a block that may stop
part way: an optional import fails, the handler catches it, the stub call below
it never runs, and the heavy import after the try does. Counting the whole body
reported that file stubbed.

Only the finally counts now, which runs on both paths. The else and the handlers
are conditional by construction and were already excluded. No test module in the
tree installs its stubs inside a try body, so nothing legitimate changes.

Two pins, both mutation-checked.

* Read the polarity of the already-imported guard, and reach nested helpers

Three holes, all about when code runs rather than what it says.

The already-imported exemption accepted any branch whose test mentioned
sys.modules, either way up. Written as 'if _PRE:' the stubs are installed only
when they are not needed and skipped when they are, and the import then fails at
collection with the guard green. The polarity is read now, through a negation and
through a module-level flag, and only the branch that runs when the module is
ABSENT counts, since that is the one whose stubs the import needs.

A while-else was treated as certain. It is skipped when the loop leaves through
break, so it is not.

And nested defs were left out of the function map entirely. Deferring a nested
body is right while nothing calls it, but an outer helper the module body calls,
which defines and calls an inner one, runs that inner body during collection. The
call inside it was handed the end-of-module boundary, the lenient answer, so a
stub installed after the outer call read as being in time while the inner import
had already run. Nested defs are in the map now and inherit the boundary of the
call that reaches them; one nothing calls at import is still deferred.

Seven pins across the three, each mutation-checked.

* Judge handlers, helper exits and stub calls by what they do

Three more exemptions that were granted on shape rather than effect.

A handler naming ImportError does not necessarily absorb it: 'except ImportError:
raise', and one raising a replacement, both take collection down while the try
body read as guarded, which hid the import from the guard entirely. Any raise the
handler can reach disqualifies it now. A module-level pytest.skip is a call rather
than a raise, so the skip idiom these files use stays exempt.

A helper that can return before installing has not installed anything, so the scan
stops at an exit rather than reading on to the call below it. Two exits are benign
and both are already in the tree: a return under 'name in sys.modules', and one
under the importlib probe inside an absorbing try. On each of those paths the
module is AVAILABLE, so skipping the stub is the point of the branch. Without that
distinction five correct files became offenders, which is how the shape of the
exemption was found.

And a call was treated as installing a stub because its name contained 'stub',
which counted _remove_stub and _validate_stub. Where the module defines the
callee, what it does decides. The name stays as the fallback for a helper imported
from elsewhere, since a name defined nowhere would raise NameError at import and
never reach collection.

Nine pins, four mutation-checked behaviours.

* Honour handler dispatch order, and stop at deferred bodies and dead code

Python dispatches an exception to the FIRST handler that matches it, so 'except
Exception: raise' followed by 'except ImportError: pass' still propagates. Asking
whether ANY handler absorbs found the second one and exempted a try that does not
guard the import. Only the first handler that would catch it is asked now.

The re-raise check also descended into a def the handler merely DEFINES. That body
does not run while the exception is being handled, so a properly guarded file was
reported as an offender. The traversal stops at deferred bodies now.

And the call-graph closure walked past an unconditional exit, handing a helper
named below one the outer call's import-time boundary although it never ran, which
rejected a stub installed below that call. It stops at such an exit now, checked
AFTER the statement since 'return _inner()' runs its own expression, and only for
an unconditional one: the path that skips a conditional exit still reaches the
calls below it.

Five pins, three mutation-checked behaviours.

* Keep every definition of a helper name, and stop reachability at dead code

Two enclosing functions can each define a helper of the same name. Keeping only
the first dropped the second from the call graph, so its importorskip took the
end-of-module boundary and a stub installed after the enclosing call read as being
in time. All definitions of a name are kept now. Which one a given call names
cannot be told apart here, so all of them take the boundary, which is the strict
answer.

And the general reachability walk did not stop at an unconditional exit, so an
importorskip written after a bare return or raise was reported as an unstubbed
offence. Python cannot execute it, so that is a file failing CI over dead code.
The walk now ends a statement list at a return, raise, break or continue, which
the import-time traversal beside it already did.

Four pins, both mutation-checked.

* Judge every heavy import, not just the first

Separate branches can each import a heavy module, and only one of them needs to be
stubbed for the first to look fine. A file that stubs before the import in the if
and forgets the one in the else dies at collection whenever the else runs, while
reducing the module to a single line reported it safe.

Every import-time heavy import is collected now and each is judged against the
stubs that precede it on its own path. Any single unstubbed one is an offence,
whatever the others do.

Two pins, mutation-checked.

* Require the availability guard to name the module, and drop async installers

The already-imported exemption fired on any sys.modules membership test, so
'if "pytest" not in sys.modules:' decided whether the stubs under it counted.
An unrelated cached package says nothing about unsloth, and the branch is skipped
exactly when that package is present. The key now has to be the required stub or
a heavy backend module. A key this file cannot read gets that latitude only inside
a stub helper deciding about its own argument, which is the idiom
_stub_if_missing opens with, and never at module scope.

And calling an async def builds a coroutine and runs none of its body, so reading
through such a call credited the module with stubs it never installed. Only
synchronous helpers are read through now.

Six pins, three mutation-checked behaviours.

* Drop the review bookkeeping from the comments

Thirty-three comments ended in 'Reported on this PR', which says nothing to
anyone reading the file afterwards: once merged there is no this PR. The reasoning
each comment records is what matters and is kept.

* Name the file rather than the pull request

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants