Skip to content

Block markerless execution-class tool-call promotion in Studio - #10507

Merged
danielhanchen merged 96 commits into
mainfrom
danielhanchen/block-markerless-exec-tools
Sep 10, 2026
Merged

danielhanchen merged 96 commits into
mainfrom
danielhanchen/block-markerless-exec-tools

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Two HIGH-severity prompt-injection to RCE findings in Unsloth Studio.

The markerless tool-call parsers promoted a bare call:NAME{...}, NAME[ARGS]{json} or {"name":...} found anywhere in assistant text into a real tool call, gated only on whether NAME was enabled. When the model quoted attacker-controlled content (web, RAG, pasted text) shaped like one of those, the safetensors, MLX and GGUF loops ran it through execute_tool -> _bash_exec / _python_exec. The model never decided to call a tool; it echoed text shaped like one.

Root cause: real Gemma, Mistral and Llama calls carry an unambiguous wrapper (<|tool_call>, [TOOL_CALLS], <|python_tag|>), but generation streams with skip_special_tokens=True, which strips the wrapper before the parser sees it and forces a bare-text fallback that cannot tell a real call from a quote.

Fix

1. Never promote a markerless execution-class call. EXECUTION_CLASS_TOOL_NAMES (python, terminal, edit_file, plus every mcp__*) is always prose in the markerless paths, regardless of the enabled list. Such a call must carry a wrapper or arrive as a structured tool_calls entry. New _markerless_promotable() in core/tool_healing.py; every markerless parse and strip path routes through it. Parse and strip stay symmetric, so a blocked call stays visible as text instead of silently vanishing.

2. Stop destroying the wrapper. NativeToolTokenDecoder (core/inference/native_tool_tokens.py) is a tokenizer proxy used on tool-enabled turns by the Transformers text and vision streamers and both MLX paths. It keeps the provenance-bearing controls (<tool_call>, [TOOL_CALLS], <|python_tag|>, <think>, DeepSeek and Kimi envelopes) and suppresses every other special token exactly as before. A tokenizer with no usable all_special_ids falls back to skip_special_tokens=True, so (1) remains the security boundary and this is capability restoration only.

Streaming: the safetensors and GGUF loops now treat a promotable bare Gemma call as a boundary and hold a trailing partial call:NAME{.., so a blocked-then-promotable chain cannot leak before the parse decides.

Impact

  • Unchanged: wrapped and structured calls (<|tool_call>, [TOOL_CALLS], <function=>, GGUF structured tool_calls) still promote python and terminal; benign bare tools like web_search still work.
  • Changed: a bare, wrapper-less python / terminal / edit_file / mcp__* call renders as text instead of executing. That is the fix. Wrapped and structured MCP calls are unaffected.

Verification

  • Loop-level A/B against the merge base: on main six markerless PoCs (quoted page, rehearsal, bare JSON, python, edit_file, mcp__*) all reach execute_tool; on this branch all six return no calls, while the wrapped, structured and benign-bare forms still execute.
  • Decoder fidelity on 22 cached tokenizers: decoded ordinary text is byte-identical to skip_special_tokens=True on every one. On unsloth/Llama-3.2-1B-Instruct, <|python_tag|> was being stripped and is now preserved, which is the difference between a lost wrapped call and a promoted one.
  • Real generation on an RTX 6000 Ada (Qwen2.5-0.5B-Instruct, gemma-3-270m-it): streams byte-identical with and without the decoder for ordinary answers; a genuine <tool_call>-wrapped terminal call still parses and strips cleanly.

Status

Branch is current with main. Local run on this head: 1190 passed, 16 skipped across the guard, parser, streaming and per-backend loop suites. CI runs fresh here; any red job will be triaged against main.

Supersedes #6967, which carried the same tree. The review history for the earlier rounds lives there.

danielhanchen and others added 30 commits July 8, 2026 09:05
The markerless tool-call parsers promoted a bare call:NAME{...} and
NAME[ARGS]{json} found anywhere in assistant text into a real tool call,
gated only by whether NAME was an enabled tool. When the model quotes
attacker-controlled content (web, RAG, pasted text) shaped like one of
those, the safetensors, MLX and GGUF loops would execute it via
execute_tool, so prose could be turned into host code execution through
the python and terminal tools.

Real Gemma and Mistral calls carry an unambiguous wrapper
(<|tool_call>...<tool_call|>, [TOOL_CALLS]), but generation streams with
skip_special_tokens=True, which strips that wrapper before the parser
sees it and forces the bare-text fallback that cannot tell a real call
from a quote.

Never promote or strip a markerless execution-class call. Add a shared
EXECUTION_CLASS_TOOL_NAMES = {python, terminal} and a _markerless_promotable
helper in tool_healing, and route every markerless parse and strip path
through it: the bare Gemma call, the bare rehearsal name[ARGS]{...}, the
bare Llama-3.2 {"name":...} JSON, and the two leading-dispatch guards.
Trusted wrapped and structured forms (<|tool_call>, [TOOL_CALLS],
<function=>, and GGUF structured tool_calls) still promote python and
terminal normally, and benign bare tools are unchanged.

Existing tests that used python/terminal as placeholder names to exercise
parser mechanics are re-pointed to benign tools; add
test_markerless_exec_tool_guard.py plus loop-level cases proving a bare
execution call in prose never reaches execute_tool while the wrapped
forms still execute.
# Conflicts:
#	studio/backend/core/inference/inference.py
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…-form arguments and thread the protocol flag through MLX for PR #10507
@danielhanchen

Copy link
Copy Markdown
Member Author

Round 9 pushed as 936c61c. Four items, all reproduced against head, all real. Thanks to whoever merged main in; the branch reads MERGEABLE now and I re-ran everything on the merged head before touching it, 1326 passing including the two files that were conflicted.

The most serious was a straight bypass of the guard. A padded name, {"name":" terminal "}, was promoted because it matched neither terminal nor an mcp__ prefix, and ToolLoopController.prepare_call then does .strip() and resolves it to the real tool. The guard was reading a different name from the one the executor would. Both checks now normalize exactly as the controller does.

Close behind: malformed top-level data before the classification key made the name scan give up, so the object was never classified as blocked and its quoted wrapper was promoted. The scan now resyncs to the next comma at the object depth, skipping strings and nested containers so a comma inside a value cannot resync early.

The other two were genuine calls being damaged rather than hostile ones getting through. The MiniCPM/MiniMax attribute form is now a protected span, and MLX declares the tool-protocol flag so the worker stops dropping it and the decoder stays on in unrestricted mode.

Two corrections to things I said earlier, both mine:

Last round I reported that I could not reproduce the MiniCPM half of the wrapper issue. I had tested the JSON-body spelling, which returns empty arguments for harmless input too, instead of the <parameter name=...> form. With the right shape it reproduces exactly as described. My follow-up check then mislabelled it as clean, because arguments is serialized JSON and the mask character is escaped there, so a raw chr(0xE000) membership test never matches.

The MLX gap was a consequence of my own round 7 change. I gated the flag on _backend_declares because MLX did not declare it, which avoided a TypeError but made the drop silent. Correct as a guard, wrong as a resting state, and the fix is that MLX now declares it properly.

Corpus over 3,430 cases: byte-identical on all three functions. Suites 1329 passed. Baselines merged by hand, 16 insertions and 1 deletion, the deletion being the one golden hash that moved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Round 10 pushed as cbf6adc. Three items, all reproduced against head, all real. Two of the three are loose ends from my own earlier fixes, which is worth saying plainly.

The P1 was the more interesting one. When I made blocked objects opaque in round 7 I exempted both classification keys wholesale, and that turned them into a place to park executable markup: {"name":"terminal","function":"<function=python>...","arguments":{}} kept the wrapper in plain sight and the light parser promoted it. Only the value actually used to classify the call needs to stay readable. The mask now takes the resolved name and blanks every other top-level value, including the unused classification field.

That fix cuts close to the guard itself, so I checked the opposite direction as carefully as the reported one: blanking the value a call is classified BY would quietly unwind everything. Classification by name, classification by the function alias when the name is falsey, and a promotable alias call keeping its arguments intact are all asserted now.

The two MLX items were consequences of round 9. I added the protocol flag to the decoder gate but left the think-prefill predicate reading bool(tools), so the two disagreed exactly in unrestricted mode: the decoder keeps </think> while the predicate says it will be stripped, and the opener is never re-emitted. The VLM decoder gate separately ignored vlm_reasoning_markers, an asymmetry with the text path that predates this PR but has a real consequence, since mlx-vlm has already stripped those controls from response.text.

While hoisting the resolved name into the truncated branch I found that the variable I was about to reference there is only bound in the other branch, so the change as first written would have read a stale name from the previous loop iteration. It is bound locally now.

Corpus over 3,430 cases: byte-identical on all three functions. Suites 1334 passed. Baselines merged by hand, three single-line changes, all the one signature that gained a parameter.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Round 11 pushed as f293ce1. Two items, both reproduced against head, both real.

The P1 was another shape of malformed argument body. {"name":"terminal","arguments":<function=python>...} has an argument value that is not valid JSON at all, and the scalar branch returned no span, so the raw wrapper stayed readable and the light parser promoted it. The branch now masks from the value start to the next comma at the object depth, or to the end when there is none. Same reasoning as the malformed-object case a couple of rounds ago: an unparseable value has no shape worth preserving.

The P2 was a genuine call being damaged rather than a hostile one getting through. <function=foo.bar> is accepted by the main parser but the trusted-span patterns used a narrower name class, so the call was not recognised as a wrapper and execution-shaped text in its own parameter was masked out of the arguments it delivered. I confirmed it before fixing: the call came back as foo.bar with q rewritten in U+E000.

One deliberate limit on that second fix. core.tool_healing has the same narrow name class in two other places, its unterminated span pattern and _TC_FUNC_START_RE, the light parser entry point. I widened only the pattern that the trusted-span lookup actually consults. The light parser does not promote a dotted call at all today, and widening the entry point would newly promote calls rather than fix a corruption, which is the risky direction for this change and not what was reported. Flagged on the thread in case the parity is wanted separately.

Corpus over 3,430 cases: byte-identical on all three functions. Suites 1338 passed. The baseline change is 5 lines, all the one regex under its four alias names.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: ae47b60285

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Round 13 pushed as d3f1688. Two items, both reproduced, both real, and one of them is a performance problem worth spelling out since it changes the picture.

Performance. Codex was right that a long blocked call makes the display path quadratic, and my own benchmark had missed it: my corpus interleaves SHORT blocked calls with prose, so it never streamed one long one. Reproduced at 4 characters per snapshot: 2KB 0.18s, 4KB 0.68s, 8KB 2.62s, 16KB 10.29s, four times the cost per doubling.

The profile corrected the diagnosis. The masking scan this PR adds is only about 9 percent of it. The real cost was _balanced_json_span, called eagerly in _rehearsal_strip to locate the kept call own argument end, re-run over the whole growing body every snapshot, and only ever READ when a sibling match exists inside that span, which for a single blocked call never happens. It is now lazy and memoized. Separately it cannot succeed when the text holds no closing brace at all, so it short-circuits on a C-level find, which is equivalent by construction and also helps blocked_markerless_prefix_end.

16KB goes 10.29s to 4.74s. What that does not do is remove the quadratic: the merge-base is 2.70s on the same input and is quadratic too, so this is a constant-factor regression on a pre-existing shape, now 1.8x rather than 3.8x. Closing the rest means caching a security-relevant span scan incrementally, and that is the exact class of change that produced several of the regressions in this PR, so I have left it visible rather than landing it unprompted.

For the ordinary paths, measured against the merge-base: prose 1.00x to 1.03x, prose with code fences 1.01x to 1.03x, benign wrapped calls 1.01x to 1.05x. The streaming path with blocked calls is 50 to 100 times FASTER than base, because a blocked call no longer enters the promotion and chain-hold machinery at all. The end-of-turn final strip is 1.2x to 1.5x on blocked content, which is +2ms once per response on 32KB.

The second item was a truncated Mistral array delivering corrupted arguments, and trusting the incomplete envelope turned out to have two halves. Masking was the reported half. While checking that fix I found the other: _mistral_region_end also refuses an unbalanced array, so the owns-the-turn guard never fired, and for [TOOL_CALLS][{"name":"terminal","arguments":{"c":"<function=python>..."}} the outer call was DROPPED and the quoted wrapper executed in its place, where the identical closed envelope correctly yields terminal. That reproduces at the previous head, so it predates these commits.

Corpus byte-identical on all three functions, and no golden hash moved for either performance change, which is the check that they are behaviour-preserving. Suites 1343 passed. Baseline change is 2 lines, the one signature that gained a keyword.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ose and in keys

Resolves the merge with main. Two files conflicted:

- tests/data/refactor_guard/patch_targets.json: took main's side under
  utils.hf_cache_settings.active_hf_hub_cache. This PR touches neither that
  setting nor test_rag_embeddings.py.
- tests/test_safetensors_tool_loop.py: main folded these into parametrized runs
  in #10499, so three of the four conflicts were main deleting tests whose ids
  it preserved as parametrize ids. Took the deletion. The fourth was a genuine
  union of this PR's guard class and main's DeepSeek helpers; kept both.

Main's fold re-encoded the pre-PR expectation that a markerless execution-class
rehearsal promotes, so six of its new cases asserted that python[ARGS]{...}
still fires. Applied the substitution this PR had already made to the
individual tests before the merge: a benign name in place of the blocked one.

Also fixes two ways a blocked bare-JSON body stayed readable:

- The masking walk only followed a chain from the START of the text, so
  "Answer:\n{"name":"terminal",...}" left it unwalked and the wrapper quoted
  inside the blocked body was reconsidered on its own and executed as python.
  It now resumes at the next brace, but only across inert prose: markup in the
  gap owns the object behind it, and resuming past a trusted marker masked a
  legitimately marked call's arguments.
- Only values were masked, so tool markup spelled into a top-level KEY was
  promoted out of a truncated object the balanced-leading-object guard cannot
  claim. Key contents are masked as data too; the classification keys stay
  readable so the call still reads as blocked downstream.

Corpus of 3430 cases: parse_tool_calls_from_text and strip_tool_markup are
byte-identical, and the 18 changed _mask_blocked_bodies cases are all prose
ahead of a blocked terminal call. Baselines merged by hand for the three new
symbols and the four hashes that moved.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: a18be6f540

ℹ️ 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 and others added 2 commits September 10, 2026 07:03
…ll's data

Preserving native tool-control tokens through decoding puts a real <|tool_call>
in the text, so a benign search whose query quotes one (web or RAG content the
model is repeating) had the INNER envelope win the turn: the parser returned
terminal instead of web_search, and the controller treated it as executable.

_parse_gemma_tool_calls deferred to the wrapped parser on the mere presence of
an opener, wherever it sat. The defer is now positional: it does not apply to an
opener inside a leading promotable call's own body, which is argument text.

Sweeping four outer forms (bare Gemma, <|"|>-quoted Gemma, rehearsal, bare JSON)
against five inner wrappers found the rehearsal outer leaking on a nested
<|tool_call> and <function=> as well, because tool_healing dispatches by opener
and a leading rehearsal had no owns-the-turn guard. It has one now, matching the
Mistral, MiniCPM and <|python_tag|> guards already there.

Inside only: a promotable call that CLOSES before the signal leaves a real
wrapped call behind it, and claiming the turn there would drop it. All 20 outer
by inner combinations now keep the outer call with the envelope as data, and a
wrapped call standing alone or following a closed outer call still fires.

The 3430-case corpus is unchanged across all three functions, and no
pre-existing golden hash moved. Baselines carry only the new symbol, plus the
argument fixture it needs to be driven at all.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: cd85b90b5a

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: cd85b90b5a

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment-only: collapse the multi-line rationales in the parser and the guard tests
to fewer lines without dropping the bug each one records. Comments the PR only
grazed are left as main wrote them.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants