Repository navigation
fix(server): keep schema-less MiniMax M3 leaves as strings under a tool schema - #3754
Conversation
…ol schema
mlx-vlm's MiniMax M3 parser reads a leaf that has no schema of its own in
"schema context" once the request declares tools: it stays the string the
model wrote, except `null`. Without tools it is JSON-decoded and otherwise
kept as written. mlxcel ran every such leaf through the shared loose
fallback, so with tools `true`, `42` and `02134` came back as `true`, `42`
and `2134` (the leading zero lost), and without tools `02134` still became
`2134`.
Carry mlx-vlm's `schema_context` flag down the M3 descent and read a
schema-less leaf (and mixed `$text`) with an M3-only helper. As in
mlx-vlm, a schema that gives no type to apply (`{}`, a description alone,
`Optional[Any]`) counts as no schema, a named child falls back to an
`additionalProperties` schema, and whether an `item` list keeps the
context follows mlx-vlm's schema-kind inference (`Optional[list]`,
`items` without `type`, `map`/`sequence`/`arr`). Leaves with a declared
type and the shared fallback used by MiniMax M2, Qwen3-Coder, GLM-4.7
and LongCat are unchanged.
Closes lablup#3739.
With lablup#3741 merged first, its port of mlx-vlm's test_object_keys_with_json_legal_punctuation_are_kept now uses upstream's value `true`, expecting the string "true" for all four keys under a tool schema. That covers the one-key test added here, so it is dropped. Add minimax_m3_client_schema_walk_is_bounded: a 60-level anyOf nest parsed through serde_json (the request-body nesting limit is what bounds the new schema-kind recursion) still keeps the item list in schema context, and a self-referential `$ref` is never resolved, so its leaves take the schema-less rule (as in mlx-vlm and vLLM). Refs lablup#3739, lablup#3754
|
Hardening review against #3739 and upstream, with follow-up commits pushed to this branch. Upstream check. I compared the port with mlx-vlm Schema walk bounds. Neither upstream resolves Changes pushed.
Validation (merged tree). |
Summary
Closes #3739.
With a tool schema in the request, mlx-vlm's MiniMax M3 parser keeps a leaf that has no schema of its own as the string the model wrote (only
nullbecomes JSON null). mlxcel ran the same leaf through the shared loose fallback, so the tool receivedtrue,42and2134for the texttrue,42and02134. The last one loses the leading zero of a ZIP code or account id. Without tools, mlx-vlm JSON-decodes the leaf and otherwise keeps it as written; mlxcel also tried an integer parse there, so02134still became2134.This PR ports mlx-vlm's
schema_contextrule to the MiniMax M3 path only, together with the two schema lookups that decide which leaves it reaches (additionalProperties, and schemas that carry no type). The shared fallback that MiniMax M2, Qwen3-Coder, GLM-4.7 and LongCat use is unchanged.Reference: Neywa-Labs/mlx-vlm@2208690a
mlx_vlm/tools/parsers/minimax_m3.py(_parse_invocation,_node_to_value,_nodes_to_object,_coerce_scalar,_schema_kinds,_schema_property). The file is unchanged at the current HEAD (3c1d8394).What changed
src/server/tool_calls/formats.rs, MiniMax M3 path only:try_minimax_m3setsschema_contextwhen the request declares at least one tool. This is mlx-vlm'sbool(tools) or isinstance(schema, dict): a function schema can only come from a non-empty tool list, so an empty list counts as no tools, and a call to a function the list does not name is still in the context.minimax_m3_parse_argumentsandminimax_m3_element_valuecarry the flag down the existing descent the way_node_to_valuepasses it:itemchildren of an element whose schema admits neither an array nor an object are read without it. mlx-vlm reads that list with_node_to_value(child)and its defaultschema_context=False, so with tools the items of an undeclareditemlist still decode ([42, true])._schema_kinds(newminimax_m3_schema_kinds): every listedtypecounts; without atype, theanyOf/oneOfalternatives, thenitems(array) andproperties/additionalProperties(object); its aliases (map,sequence,arr, ...). So Pydantic'sOptional[list]({"anyOf": [{"items": {}, "type": "array"}, {"type": "null"}]}) keeps the context for its items. It is used only for this decision; value coercion keepsminimax_m3_schema_type.minimax_m3_leafdecides how a leaf is read:typemlxcel knows, anenum, or ananyOf/oneOfwith such an alternative), throughminimax_m3_coerce_leaf, unchanged;{}, adescriptionortitlealone (PydanticAny),anyOf: [{}, {"type": "null"}](PydanticOptional[Any]), a boolean schema, a type name mlxcel does not know, anditems: {}(PydanticList[Any]). mlx-vlm's schema step finds nothing to apply in these either and leaves the value toschema_context.array-typed leaf that is not a JSON array literal is one occurrence of a repeated tag, so its own schema isitems: untyped or missingitemsgives the schema-less rule, typeditemsthe declared type as before.minimax_m3_schemaless_leafreads a leaf with no usable schema:"";nullin any casing gives JSON null and any other text stays the raw string;serde_json::from_str, or else the raw string.minimax_m3_child_in_schemafalls back to anadditionalPropertiesschema whenpropertiesdoes not name the child, as mlx-vlm's_schema_propertydoes (additionalProperties: truenames no schema). Without this, Pydantic'sDict[str, int]values would have no schema and, with the rule above, stay strings. The function is private and only called from the M3 descent.$text) goes throughminimax_m3_leaftoo, because mlx-vlm reads it as one more child element. Before, it was always a string.try_minimax_m3doc comment no longer says a value with no schema takes the loose fallback; it describes the new rule.truetrue"true"truetrue4242"42"4242021342134"02134"2134"02134"Truetrue"True"true"True"+5/5.5/5.0"+5"/"5."5/5.0"+5"/"5."null/NULLnull/"NULL"null/nullnull/"NULL"null/"NULL"[1, 2][1, 2]"[1, 2]"[1, 2][1, 2]""""""""With tools, for the schema shapes the review of this change raised:
{},{"description": ...},{"title": ...}02134/true2134/true"02134"/"true"{"type": "array", "items": {}}(List[Any]), items42,true,02134[42, true, 2134]["42", "true", "02134"]anyOf: [{"items": {}, "type": "array"}, {"type": "null"}](Optional[list]), items42,true,02134[42, true, 2134]["42", "true", "02134"]{"type": "object", "additionalProperties": {"type": "integer"}}(Dict[str, int]), a key555{"type": "boolean"}truetruetrue{"type": "string"}(Dict[str, str])021342134"02134"Tests
New tests in
src/server/tool_calls/formats.rs:minimax_m3_object_key_value_true_stays_a_string_under_a_tool_schema: mlx-vlm'stest_object_keys_with_json_legal_punctuation_are_kept, with valuetrueexpected as"true". Only its key without a/(aws:SourceAccount) is ported, because a/in a tag name is fix(server): MiniMax M3 tool-call parser truncates parameter names at "/" #3738 (PR fix(server): keep '/' in MiniMax M3 tool-call tag names #3741).minimax_m3_schemaless_leaves_match_mlx_vlm_with_and_without_tools: the issue's repro, checked with tools, withNoneand with an empty tool list.minimax_m3_schemaless_leaf_boundaries: 23 texts, each with and without tools. Covers empty, whitespace only,0,00, padded42,-7,+5,5.,2.5,1e5,u64::MAX,true/True/false,null/NULL/Null,none, a quoted string, a JSON array, a JSON object, broken JSON and prose. The tool used declares noparameters.minimax_m3_call_to_an_undeclared_function_keeps_schemaless_leavesminimax_m3_typed_leaves_are_unchanged_next_to_schemaless_ones:integer,booleanand a typed key inside an object still take their declared types.minimax_m3_item_lists_take_the_schema_context_mlx_vlm_gives_them: an{"type": "array"}list gives["42", "true"]; an undeclared list gives[42, true].minimax_m3_mixed_text_takes_the_schemaless_leaf_ruleminimax_m3_schemaless_rule_does_not_reach_the_other_xml_grammars: Qwen3-Coder, MiniMax M2, GLM-4.7 and LongCat still read an undeclared02134as2134.minimax_m3_many_schemaless_leaves_stay_linear: 1,024 leaves, the per-element child cap.minimax_m3_additional_properties_schema_types_the_values:Dict[str, int](5→5,02134→2134),Dict[str, bool](true→true),Dict[str, str],additionalProperties: trueand{}(strings), mixed text underDict[str, int]($text→7), andadditionalPropertieson the parameters object next to a declaredstringproperty.minimax_m3_schema_without_a_type_takes_the_schemaless_rule: adescriptionalone (under parameters withouttype),{},{"title": ...}(trueandnull),Optional[Any](02134andnull), a boolean schema, an unknown type name,{"type": "null"},List[Any]items, and repeated tags declaredarraywithitems: {}and with noitems.minimax_m3_item_list_context_follows_mlx_vlm_kind_inference:itemlists underOptional[list],anyOf: [array, null],oneOf: [array, string],itemswithouttype,sequence,arr,list,["string", "array"],["null", "array"](strings); under the object kindsmap,propertiesonly,additionalPropertiesonly,anyOf: [object, null],anyOf: [{}, {}](strings, see Deviations for the shape); understringandenum(decoded,[42, true, "02134"]).minimax_m3_declared_types_keep_their_mlxcel_reading: pins the deliberate differences listed under Deviations.New tests in
src/server/tool_calls/stream_parity_tests.rs:minimax_m3_schemaless_leaves_are_the_same_streamed_and_not: the issue's text throughStreamFilterunder every chunking the harness generates (whole, per character, widths 2/3/5/7, every two-piece split). Run once with the schema'd tool and once with a tool that declares no parameters. The content and arguments must match the non-streamed parse.minimax_m3_schema_shapes_are_the_same_streamed_and_not:Dict[str, int],Optional[list]and{}values in one call, under the same chunkings.Every expected value that the tests attribute to mlx-vlm is the output of mlx-vlm's
parse_tool_callon the same text and tool list (Python 3.12.3, the 2208690a file and the HEAD file both run standalone; the outputs are byte-identical). The values inminimax_m3_declared_types_keep_their_mlxcel_readingwere run through mlx-vlm too; its results are the ones listed under Deviations.Deviations from mlx-vlm
Each item below was checked by running mlx-vlm's parser on the same input.
integer,5.5→5.5); in this repository the5.5case is pinned by the Qwen3-Coder and LongCat tests, and this PR pins it for MiniMax M3 as well. mlx-vlm returns the raw string in each of these, because its context check runs after its schema step:integer,5.5: mlxcel5.5, mlx-vlm"5.5"; the same for anadditionalProperties: {"type": "integer"}value;integer,5.0: mlxcel5(integeraccepts a zero fraction), mlx-vlm"5.0";object(or any declared type) given a scalar02134: mlxcel2134, mlx-vlm"02134".The issue is about values the tool did not type, so this PR leaves these alone. The same goes for mlx-vlm's own schema step (for example a
booleanaccepting1/0).anyOf/oneOfis still used:Optional[List[int]]items42,true,02134give[42, true, 2134]here, where mlx-vlm only reads a top-levelitemsand gives["42", "true", "02134"].items(items: {"type": "integer"},42and7) gives[42, 7]here (existing behaviour); mlx-vlm checks each occurrence against the array schema itself and gives["42", "7"].itemsorpropertiesbut notypeis read by the schema-less rule here, because the kind inference is used only for theitem-list context. So02134stays"02134"as in mlx-vlm, but a JSON literal ([1, 2]under{"items": {}},{"a": 1}under{"properties": {}}) also stays a string here, where mlx-vlm decodes it to the array or object.itemlist under an object kind (map,propertiesoradditionalPropertiesonly,anyOf: [object, null]): mlx-vlm reads it as an object,{"item": ["42", "true", "02134"]}; mlxcel keeps its array,["42", "true", "02134"]. The leaves are the same strings. This and the other structure differences (mixed children under an array schema,$textcollision naming, an empty leaf under anarray/objecttype giving[]/{}in mlx-vlm and""here) are not touched.json.loads. Python also decodesNaN/Infinity(to floats that are not valid JSON on output) and keeps integers beyondu64exact. Here the first stay strings and the second becomef64, as before.Requests without tools
The no-tools branch matches mlx-vlm (
True,+5,02134stay strings;true,5decode), but no server route reaches it: every route that parses tool calls (chat streaming and non-streaming, Anthropic messages, Responses, the Responses MCP loop, in-process chat) checksshould_parse_tool_callsfirst, which is false whentoolsis absent or empty ortool_choiceis"none". Only direct callers of the parser (parse_tool_calls(text, None)) see the no-tools behaviour.Checks against past review findings
0/00,u64::MAX, everynullcasing, an empty tool list, a tool withoutparameters, a call to an undeclared function,{}, a boolean schema,additionalProperties: trueand{}are tested.boolpassed down the existing recursion, and each leaf does at most one JSON parse, as before.minimax_m3_schema_kindsruns once per element whose children are allitem, and walks only that element's schema (itsanyOf/oneOfalternatives, recursively). 1,024 leaves are tested.minimax_m3_element_value,minimax_m3_parse_arguments,minimax_m3_schema_for_childandminimax_m3_child_in_schemaare only called from the MiniMax M3 path (try_minimax_m3and the descent).minimax_m3_coerce_leaf(also used by MiniMax M2 and Qwen3-Coder throughcoerce_xml_param),minimax_m3_typed_coerce,minimax_m3_schema_typeandminimax_m3_fallback_coerce(also used by GLM-4.7 and LongCat throughcoerce_kv_value) are not modified, and their// Used by:lists stay accurate.incremental/qwen.rsonly usesminimax_m3_function_schema, which is unchanged.try_minimax_m3doc comment ("A value whose declared-type parse fails (or that has no schema) falls back to ...") lost its parenthetical, because it is no longer true; a new paragraph describes the rule. One sentence of theminimax_m3_element_valuedoc comment now says "admits neither an array nor an object" instead of "is neither an array nor an object".cargo fmt --all -- --checkpasses on the final tree.Relation to #3741
Independent of #3741 (same parser, tag names with
/). This branch is based onmainand merges cleanly onto currentmain(5bf7b8628) and onto #3741's branch, and #3741 merges cleanly ontomain(git merge-tree). #3741's port of the same upstream test uses the valueteam-aso that it does not depend on how a schema-less leaf is read. Whichever of the two merges second switches that test to upstream's valuetrue(expected"true"for all four keys) and drops the one-key test here (minimax_m3_object_key_value_true_stays_a_string_under_a_tool_schema), which it then covers. That combination was run (see Verification).Verification
Linux aarch64, NVIDIA GB10 (sm_121), CUDA 13.0, rustc 1.97.1.
Every "this commit" run below used exactly the commit's tree (
dd6d3be8, checked withgit write-treebefore and after the full gate).Fail before. On
main(9402cf8) plus only the new tests,cargo test --locked --profile test-fast --features cuda --lib -- --test-threads=1 server::tool_callsgives 571 passed, 13 failed. The 13 failures are 11 of the newformats.rstests and both new stream-parity tests. The other two new tests pin unchanged behaviour (minimax_m3_schemaless_rule_does_not_reach_the_other_xml_grammars,minimax_m3_declared_types_keep_their_mlxcel_reading), so they pass onmainas intended. For example, the issue repro (and, the same way, the stream-parity test, whose streamed and non-streamed results agree with each other onmaintoo) fails with:and the schema-shape tests with, for example,
{}→Number(2134)instead ofString("02134"),Optional[list]items →[Number(42), Bool(true), Number(2134)], andDict[str, str]→{"a": Number(5), "b": Number(2134)}.Pass after. The same command on this commit gives 584 passed, 0 failed.
cargo fmt --all -- --check: pass.cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings: pass.python3 scripts/ci/check_used_by.py:used-by: OK, 78 top-level pub fn in 2 shared files, 57 annotated, 715 caller-file references resolved, 3498 Rust files scanned.bash scripts/ci/check_used_by_test.sh: pass.Full gate.
make verify-test-cuda(cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1) gives 18,906 passed, 2 failed, 578 ignored over 207 test binaries. The two failures aremlx_test_guard_coverage::mlx_evaluating_lib_tests_take_mlx_test_guard(src/vision/encoders/nemotron_h_nano_omni_tests.rs:276 pos_embed_resample_runs_in_f32) andstep3p7_parity::text_decode_delegates_sequence_local_native_batching(assertion failed: !wrapper.supports_padded_prefill()). Both fail the same way on unmodifiedmain(9402cf8):cargo test --locked --profile test-fast --features cuda --test mlx_test_guard_coverage --test step3p7_parity --no-fail-fast -- --test-threads=1reports5 passed; 1 failedand7 passed; 1 failed, with the same two test names. They were pre-existing on the base; currentmainfixes both (feat(speculative): add DeepSeek-V4.1 bundled DSpark drafter (#3262) #3686, test: restore MLX guard scan and no-GPU catalog test gates #3765).Together with fix(server): keep '/' in MiniMax M3 tool-call tag names #3741.
main+ fix(server): keep '/' in MiniMax M3 tool-call tag names #3741's head at the time (65f9e9bb3) + this commit merge without conflicts (merged tree11af160b, the same asgit merge-tree). fix(server): keep '/' in MiniMax M3 tool-call tag names #3741's updated head, which only drops itsCHANGELOG.mdentry, merges with this commit to treebcc27142, which differs from11af160bonly inCHANGELOG.md. With a temporary, uncommitted port of mlx-vlm's test using all four keys (aws:SourceAccount,aws:ResourceTag/team,aws:RequestTag/${TagKey},application/json) and valuetrue,server::tool_callsgives 588 passed, 0 failed; every key gives"true".Limits