Repository navigation
Studio: give the tool-call strip one owner and one scan order - #8427
Conversation
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, #5583) and the parser copied the balanced scanners out of it on 2026-07-06 (#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 #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.
|
On the diff size: the source change is 172 added / 194 removed across 5 files, a net reduction. The rest of the line count is the guard's recorded baseline under That baseline is deliberately kept small. Recording every guarded function's full output over the corpus would have been a 7.2 MB file for no extra guarantee, so it stores a SHA-256 digest per function instead: any byte that changes anywhere in a function's results changes its digest. The corpus itself is rebuilt deterministically from Re-baseline with The streaming performance work is stacked on top of this in #8428. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 851b4209ce
ℹ️ 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".
| return None | ||
| # Shared with the healer rather than copied. The healer's version also counts ``{``/``}`` | ||
| # toward the depth, so a truncated object inside an array cannot close the array early. | ||
| _balanced_bracket_end = _tool_healing._balanced_bracket_end |
There was a problem hiding this comment.
Keep mismatched braces from closing Mistral arrays
When a model emits a malformed Mistral array containing an unmatched } before the eventual ], the shared healer scanner decrements the array depth on that brace and reports it as the array terminator. Consequently, strip_tool_markup("[TOOL_CALLS] [} prose ] tail") now returns " prose ] tail" instead of stripping the malformed call through ] and returning " tail", leaking tool-call body and markup into displayed output. Preserve delimiter-aware bracket matching here, or avoid sharing the healer's mixed {}/[] scanner for this parser path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked this one against the merge base rather than against the diff, and it is not a change this PR makes.
strip_tool_call_markup("[TOOL_CALLS] [} prose ] tail") on 19abc08bb already returns " prose ] tail". The healer has always counted {/} into the bracket depth, and the healer is what the GGUF display path has always called. What this PR changes is that the parser now agrees with it instead of keeping a second scanner that did not.
The input also needs a } with no opening { inside a [TOOL_CALLS] array, which no JSON serialization produces. The realistic malformed shape is a truncated object, and the shared scanner handles that one better than the parser copy did:
[TOOL_CALLS] [{"name": "x", "arguments": {"a": 1}] tail -> tail
Brace counting is load-bearing for the Gemma array normalizer, so splitting the scanner back in two to change this would cost more than it buys. Leaving it.
_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.
…ental
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.
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.
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.
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.
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).
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.
…ated 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.
_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.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b70810dbff
ℹ️ 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".
| new = [ | ||
| f"{entry['module']}.{entry['function']}[{entry['variant']}] for {entry['input']!r}" | ||
| for entry in refactor_guard.idempotence_failures(corpus) | ||
| if (entry["module"], entry["function"], entry["variant"]) not in baseline |
There was a problem hiding this comment.
Track idempotence regressions per input
The baseline comparison keys failures only by module, function, and boolean variant, so one recorded witness exempts every future failure for that variant. The committed baseline already contains both variants of the central parser strippers (strip_segment and strip_tool_markup), meaning a later change can make either stripper non-idempotent for additional corpus inputs and this condition will silently filter the regression out. Record and compare the failing input/output identity, and have idempotence_failures continue checking after its first witness, rather than treating a variant as globally exempt.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The second half is already done: since b70810d idempotence_failures witnesses per (function, variant) and only stops once every variant has one, which is what surfaced the two false entries now in the baseline.
Keying on the input as well is a different contract and not one worth having here. The baseline would have to enumerate every failing input rather than name the function, which means dropping the per-variant stop and double-driving all 2,827 inputs for every stripper, and the file would then churn on any corpus edit. That is the failure mode this baseline was built to avoid: a file regenerated reflexively is not read, and a check nobody reads guards nothing.
What the check claims is that the set of non-idempotent strippers does not grow, per boolean variant, and that is what it does. A stripper that is already non-idempotent for one input is already flagged as a known defect; broadening it does not change the verdict on that function.
… 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.
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Went back over this with deterministic checks rather than review, since the whole claim is that the output does not change. Scripts are in AST. Every definition in the 10 changed files, normalised (docstrings, line numbers and column offsets dropped, nothing semantic dropped): 1224 identical, 22 changed, 83 added, and importantly 0 moved across files and 0 removed. That is worth being precise about: this is not an exact relocation. The shared helpers were rewritten, not moved, so AST cannot certify this PR and the differential has to. Differential. 2820 inputs (24 adversarial fixtures, 1500 string constants harvested from the tool tests, 1500 spliced from the sentinels the code keys on), driven through every entry point at four The one thing that does differ. I did not want to take "no caller can see it" on trust, so I instrumented the head implementation to record every call where the new guard changes the answer, and drove the whole corpus through every entry point: 0 of 95,880 calls. Six of the seven call sites are directly preceded by an explicit Idempotence. |
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.
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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 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.
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…r paths (unslothai#8494) * Studio: linear-time tool signal scanning in the safetensors and healer paths Rebuilt on main after unslothai#8427 and unslothai#8538 landed as squashes. * Studio: pin the safetensors loop's display strip to the exported helper The loop now drives a StreamingMarkupStripper, so the exported strip_tool_markup_streaming had no call site left in the module while ten assertions in this file still targeted it. Agreement is now asserted at every prefix, so the suite guards the path the loop actually runs. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
What this is
core/tool_healing.pyandcore/inference/tool_call_parser.pydefine 13 of the same top-level names, 12 of which have diverged. Separately, the ~15 line tool-strip scan order is copy-pasted into four places.This is the deduplication half, split out on its own because it is behaviour-preserving and independently verifiable. The streaming performance work sits on top of it in a follow-up.
Which module is the original
git log -Lper symbol over the full history:f74710821core/tool_healing.pycreated (#5583)bb4eb88fdcore/inference/tool_call_parser.pycreated (#5520)f0a5c5282c00c1e70c85b49eeb5tool_healing.pyis the elder module and its docstring already says "Any change here must also land there", so it becomes the single owner.The Inkling case turned out not to be a bug:
tool_call_parser.parse_tool_calls_from_textcalls the healer first and only falls back to its own extra formats, so the Inkling parsing is reachable from both. Verified directly against<|message_model|>get_weather<|content_invoke_tool_json|>{...}<|end_message|>.Unified
_balanced_brace_end,_balanced_bracket_end,_trim_param_value,_TC_FUNC_CLOSE_REnow live once. Divergence over a 1,833 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 that) and also gains the guard.-1vsNonesentinel split is resolved toNone. The marker tuples in_build_markerskeep-1, becausemarker_coverageis a cross-module contract whose consumers testbrace_end < 0._inside_open_parameteris 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 and is deliberate, so it is passed in rather than flattened.tool_call_parser.strip_segment, called bystrip_tool_markup, the GGUF streaming strip and the safetensors loop.Left alone on purpose
parse_tool_calls_from_textare layered, not forked. The parser calls the healer first and then adds its own formats. On 70 corpus inputs they legitimately return different call lists. Merging them would be a behaviour change with no upside._TOOL_ALL_PATS/_TOOL_CLOSED_PATSare not in a superset relation. The overlapping arms differ in content, not just in count. For the Mistral arm:Different name classes, different
[CALL_ID]handling, one level vs lazy JSON, and order within each list is load bearing. Splicing them would be a behaviour change dressed up as deduplication.routes/inference.py::_strip_tool_xml_for_displaypredates the parser (it goes back to the February route refactor) and never picked up the markdown code gating. It deletes a rehearsal inside a fenced code block that the canonical strip keeps, and differs on 520 of 1,833 corpus inputs. That is a real bug, but changing it changes what a shipped streaming route displays, so it is pinned intest_route_strip_drift.pyfor a separate decision rather than folded in here.Also in this change
_gguf_request_intentenumeratedGgufLoadIntent's fields withvars(source).dataclasses.fields()answers the same question without depending on the instance carrying a__dict__._cpu_isolated_binaryis compiled once at module level instead of on every call. The other three in-functionre.compilesites are built from runtime values, so there is no constant to hoist. Measured, the full call costs 803 ns, of which the compile itself is 200 ns (a hit inre's internal cache) and 443 ns is there.escapeand string building that builds the cache key. Anlru_cachearound the whole builder would take it to 42 ns, but these sit on the model-load path and run a handful of times per load, so the saving is microseconds and they are left alone.__slots__onLlamaServerNotFoundError,_LlamaStreamCancelledandCountAborted, which only ever signal.Verification
tests/tools/refactor_guard.py(run bytest_refactor_guard.py) pins four things:re.compileliteral;dir()plusinspect.signature,__module__and__qualname__, which catches re-export aliasing the AST cannot see;patch("core.inference.llama_cpp.subprocess.run")and 209 others) still resolves. A moved symbol leaves those pointing at a namespace nobody reads, so the test passes while exercising unpatched code. That is the quiet failure this check makes loud.Behavioural output is unchanged. Every diff against the pre-change baseline is confined to the two scanners' own return value moving from
-1toNone, and every one of those isint -> None, never one index to a different index.880 targeted tests pass. The failure list over the touched areas is identical to a clean tree (91 pre-existing, 0 introduced), and a full backend run shows no new failures.
Note on
__slots__@dataclass(slots=True)onGgufLoadIntentwas tried behind asys.version_info >= (3, 10)gate and reverted. It passed 14 unit tests on both 3.9 and 3.13, then 500'd every GGUF load in Studio, becauseslotsremoves__dict__andvars(source)raises. Threetest_tensor_parallel.py::test_runtime_recovery_*tests failed the same way. The intent is built a handful of times per load, never in a hot loop, so there was no speed to buy with that risk. Thevars()fix is kept because it is a genuine robustness improvement either way.