Skip to content

Hoist tool-schema $defs to the tool-calling envelope root (fixes #432) - #434

Merged
davidkoski merged 2 commits into
ml-explore:mainfrom
jyauxi:fix/tool-envelope-hoist-defs
Jul 22, 2026
Merged

davidkoski merged 2 commits into
ml-explore:mainfrom
jyauxi:fix/tool-envelope-hoist-defs

Conversation

@jyauxi

@jyauxi jyauxi commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

Fixes #432.

GenerationSchema serializes named sub-schemas (nested @Generable types, named DynamicGenerationSchema nodes) as root-level $defs with root-anchored "$ref": "#/$defs/..." pointers. SchemaConverter.toolCallingEnvelopeObject embeds each tool's parameters schema as a nested object under oneOf[i].properties.arguments, which buries the tool's $defs inside arguments while the refs stay anchored to the (defs-less) envelope root. xgrammar resolves JSON Pointers from the document root, so any tool with a non-flat argument schema fails grammar compilation with constraintCompilationFailed("... Cannot find field $defs in {\"oneOf\": ...") at the first tool-calling turn. Flat, primitive-only tools don't emit $defs, which is why small demos pass.

This PR hoists each tool's $defs into the envelope root, namespaced per tool (<tool>__<def>, so same-named defs across tools can't collide), and rewrites that tool's $refs to match. The change is in toolCallingEnvelopeObject — the single composition point shared by both encodeToolCallingEnvelopeJSON and the structural-tag encodeToolCallingGrammar, so both encoders are covered.

Implementation note: the ref rewrite runs on the raw JSONEncoder output, where the #/$defs/ prefix appears literally. Rewriting a JSONSerialization re-serialization does not work — it escapes / as \/, the prefix never matches, and the refs silently survive unrewritten while the defs get hoisted under prefixed keys.

Tests added to ToolCallingSchemaTests (model-free, in the existing unit target):

  • a nested-@Generable fixture's def is hoisted to the envelope root and removed from the embedded arguments schema;
  • with two tools sharing a same-named nested type, every $ref in the envelope resolves within the document and the namespaced defs don't collide;
  • the nested-defs envelope compiles end-to-end with xgrammar (GrammarConstraint) — this is the direct regression test: it fails on main with the "Cannot find field $defs" check failure;
  • the structural-tag grammar embeds the hoisted $defs in both the wrapped and bare arms.

Beyond unit tests, this patch has run several hundred tool-calling generations in our downstream harness (macOS 27.0 beta 26A5378n, M4 Max) without a grammar-compilation failure.

Local verification note: this beta seed names GenerationOptions.SamplingMode.Kind cases randomTopK/randomProbabilityThreshold, where main matches .top/.nucleus from a newer seed — local builds needed that 2-line rename as a scratch commit, which is not part of this PR. CI on the newer seed should compile unmodified.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

🤖 Generated with Claude Code

GenerationSchema serializes named sub-schemas (nested @generable types,
named DynamicGenerationSchema nodes) as root-level $defs with
root-anchored #/$defs/... refs. Embedding a tool's parameters schema
under oneOf[i].properties.arguments buried those $defs inside
arguments while the refs stayed anchored to the (defs-less) envelope
root — xgrammar resolves JSON Pointers from the document root, so any
tool with a non-flat argument schema failed grammar compilation with
constraintCompilationFailed ("Cannot find field $defs in
{\"oneOf\": ...").

Hoist each tool's $defs into the envelope root, namespaced per tool
(<tool>__<def>) with that tool's refs rewritten to match, in
toolCallingEnvelopeObject — one composition point covering both the
envelope and structural-tag encoders. The ref rewrite runs on the raw
JSONEncoder output, where the #/$defs/ prefix appears literally (a
JSONSerialization re-encode escapes / as \/ and the prefix no longer
matches).

Fixes ml-explore#432

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@davidkoski

Copy link
Copy Markdown
Member

@thechriswebb FYI

@thechriswebb

Copy link
Copy Markdown
Collaborator

Thanks for tackling the $defs hoisting. The per-tool namespacing is a nice touch, and the xgrammar dangling-ref failure is exactly the kind of thing that's easy to miss. One edge case we should address before this lands.

The root of it is that the $ref rewrite is a blind text find-and-replace over the whole serialized schema rather than something that operates on the parsed structure:

.replacingOccurrences(of: "#\\/$defs\\/", with: "#\\/$defs\\/\(tool.name)__")

Because it matches the #/$defs/ substring wherever it shows up (not just in $ref values), any string that happens to contain that text gets the tool namespace spliced into it. A @Guide description is enough to trigger it, and the tool doesn't even need a nested @generable, so there's no real $defs to rewrite in the first place:

@Generable
private struct PointerDocArgs {
    @Guide(description: "A JSON Pointer such as #/$defs/Foo to resolve.")
    var pointer: String
}

let tool = Transcript.ToolDefinition(
    name: "probe_tool",
    description: "Resolves JSON Pointers",
    parameters: PointerDocArgs.generationSchema
)
let json = try SchemaConverter.encodeToolCallingEnvelopeJSON(tools: [tool])

The description comes back out mangled:

"description": "A JSON Pointer such as #/$defs/probe_tool__Foo to resolve."

It's a very niche situation, but the same thing would hit any const, enum, default, or pattern string that mentions #/$defs/, so it felt worth addressing.

Since the code already parses the schema right after, one option is to parse first and then walk the parsed tree, rewriting only the string under a "$ref" key. Worth noting $defs live at the root but the refs to them can be nested anywhere (including inside other $defs bodies), so the walk needs to cover the whole schema and run before the defs are hoisted out.

Here's a test that pins it down if it's useful:

@Test
func nonRefStringMentioningDefsPointerIsNotRewritten() throws {
    guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return }
    let probe = Transcript.ToolDefinition(
        name: "probe_tool",
        description: "Resolves JSON Pointers",
        parameters: PointerDocArgs.generationSchema
    )
    let json = try SchemaConverter.encodeToolCallingEnvelopeJSON(tools: [probe])
    let strings = collectStringValues(in: try parseAsDictionary(json))

    #expect(strings.contains { $0.contains("#/$defs/") })          // the pointer text made it into the schema
    #expect(strings.allSatisfy { !$0.contains("probe_tool__") })   // the description survived untouched
}

Thanks again for the work here!

Replace the string-level find-and-replace over the serialized schema
with a walk of the parsed tree that rewrites only the string value
under a $ref key. A description/const/enum/default/pattern string that
merely mentions the #/$defs/ pointer text now survives verbatim. The
walk runs before the defs are hoisted and recurses through the whole
tree, covering refs nested inside other $defs bodies (exercised by a
new doubly-nested fixture: Traveler's def body refs Passport).

Adds the reviewer's pinning test (a @Guide description containing
"#/$defs/Foo" is not rewritten) and drops the now-unneeded
escaped-form handling.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@jyauxi

jyauxi commented Jul 18, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review and the pinning test — you're right that the string-level rewrite could splice the namespace into innocent strings. Addressed in 72616a6: the rewrite now walks the parsed tree and touches only the string under a $ref key, running before the defs are hoisted so refs inside other $defs bodies are covered too (added a doubly-nested fixture for that case). Your test is included as-is and passes; full unit suite green locally (406 tests).

@thechriswebb

Copy link
Copy Markdown
Collaborator

LGTM. Thanks, @jyauxi!

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thank you for the fix!

@davidkoski
davidkoski merged commit 1032402 into ml-explore:main Jul 22, 2026
2 checks passed
@jyauxi
jyauxi deleted the fix/tool-envelope-hoist-defs branch July 22, 2026 23:26
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
…xplore#432) (ml-explore#434)

Fix tool-schema $defs resolution for grammar compilation in tool-calling envelopes.

Problem: Named sub-schemas (nested @Generable/DynamicGenerationSchema types) get serialized as root-level $defs with root-anchored #/$defs/... refs. When a tool's parameter schema is embedded under oneOf[i].properties.arguments, its $defs got buried there too, but refs still pointed to the envelope root — causing xgrammar's grammar compilation to fail (constraintCompilationFailed) for any tool with non-flat argument schemas.

Fix: Hoist each tool's $defs to the envelope root, namespacing them per tool (<tool>__<def>) and rewriting that tool's refs to match. Applied once in toolCallingEnvelopeObject, covering both envelope and structural-tag encoders.

Refinement (review feedback): The ref rewrite was made structure-aware — instead of a raw string find/replace, it walks the parsed schema tree and only rewrites string values under $ref keys. This prevents corrupting unrelated strings (e.g., a @Guide description that happens to mention #/$defs/Foo), and correctly handles refs nested inside other $defs bodies. Added a doubly-nested test fixture and a pinning test for the description-string edge case.

Fixes ml-explore#432
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…it read

From the independent review of ml-explore#434 + d-inference#2157:

- GLM5ToolCallParser.argumentTypes reads anyOf/oneOf branch types, as
  MiMo does, so Pydantic's Optional[str] keeps 123, 1.0, true and "q"
  as text (finding 5).
- Where no string is declared, a JSON value that is not a string keeps
  its JSON reading even if its type differs, so an integer-typed
  {"cmd":"x </arg_value> y"} is that object instead of a failed frame;
  a top-level JSON string is never kept, so it cannot run across frames
  (finding 2).
- MiMoV2ToolCallParser reads every value it accepted before exactly as
  before and only reads the values it refused (unions, other types) as
  generated: a typeless nullable 1.0 stays "1.0" (finding 6).
- Tests: the old fail-closed tables run against GLM5ToolCallParser
  (grammarOnly: false) (finding 4); Pydantic optional strings; the two
  value-boundary cases; MiMo values that parsed before.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…r-only

Tool parsers: return well-formed calls that break only their schema (GLM5, Gemma, MiMo V2; d-inference#2156)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants