Skip to content

feat(server): enforce required and named tool_choice on chat (#1319) - #1581

Merged
inureyes merged 8 commits into
mainfrom
feature/issue-1319-tool-choice-enforcement
Sep 2, 2026
Merged

inureyes merged 8 commits into
mainfrom
feature/issue-1319-tool-choice-enforcement

Conversation

@adrysn

@adrysn adrysn commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

Summary

/v1/chat/completions accepted tool_choice in all four OpenAI shapes but only none changed behaviour: required was validated and then ignored, and a named function still rendered every declared tool and only filtered the parsed calls afterwards, so a model that picked another tool returned an empty tool_calls array with finish_reason: "stop". This PR makes required and the named form steer generation: the tool list handed to the template is narrowed, an instruction is injected into the rendered prompt, unsatisfiable requests are rejected with 400, and on tool-call formats whose wire shape is a JSON object in a fixed wrapper the call is grammar-forced through the existing structured-output constraint.

Closes #1319

Semantics

tool_choice tools rendered prompt instruction constraint 400 when
absent / "auto" all none none never
"none" none none none never
"required" all "You must call one or more of the available functions ..." forced call on grammar-capable formats tools absent or empty
{"type":"function","function":{"name":"f"}} only f "You must call the 'f' function ..." forced call to f on grammar-capable formats f undeclared (matched exactly as sent), type not function, empty name

The instruction is appended to the first system message as "\n\n" + instruction, otherwise to the last user message (a content-parts message gets a trailing text part), otherwise inserted as a new leading system message. The injection happens on the message list handed to the renderer; the request object is never mutated. A forced choice combined with a constraining response_format is rejected with 400.

Grammar forcing is best effort on top of the prompt enforcement: when the loaded template's tool format has no fixed JSON wrapper, when the declared tool schemas exceed the grammar size or $ref budgets, when the grammar does not compile, or on the disaggregated router (whose prefill frame cannot carry a constraint to the decode node), the request proceeds with the narrowed tool list and the injected instruction only and the server logs the reason at warn. A forced choice that finishes without a parsed call is logged at warn as well, and finish_reason stays what the model produced.

Changes

  • src/server/types/request.rs: ToolChoice::is_required, ToolChoice::is_forced, and ToolChoice::validate(tools) carrying the 400 rules, shared by routes/chat.rs, routes/responses.rs, routes/anthropic.rs, and the disaggregated router_front.rs through validate_chat_tool_inputs. The named function is matched exactly as sent, because the renderer, the grammar builder and the response filter compare the raw string; a padded name is a 400 rather than a 200 with an empty tool_calls array.
  • src/server/chat_request.rs: effective_tools narrows to the named tool; tool_choice_instruction, inject_tool_choice_instruction, and with_tool_choice_instruction (a Cow clone only when a choice is forced). prepare_chat_request_with_cache and render_next_turn_history render from that list, so history_prompt stays a prefix of the prompt and the next-turn warm-up matches what a follow-up turn with the same tool_choice renders. request_options.rs documents that one narrowed tool still counts as tools rendered for the loop-detection gate.
  • src/server/chat_template.rs: forced_tool_call_format() cached at construction from template markers: Hermes on <tool_call> (excluding the XML-body dialects Qwen3-Coder <function=, GLM <arg_key>, and <function_name>), Mistral Nemo on [TOOL_CALLS] (excluding bracketed [ARGS]), Llama 3 on <|python_tag|> or "parameters":; ATEM templates return None.
  • src/server/tool_calls/mod.rs: tool_choice_grammar and tool_choice_grammar_with build the Lark grammar (start: <wrapper> %json { schema } <wrapper>) from per-tool schemas (name pinned by const, arguments or parameters typed by the tool's own schema, additionalProperties: false; anyOf over all tools for required). relocate_root_refs re-points a tool schema's root-relative $refs (#/$defs/..., the shape Pydantic, the OpenAI SDK and LangChain emit for nested models) at the place the schema comes to rest inside the wrapper, so those schemas compile and two tools' identically named definitions stay apart. special_token_id resolves wrapper markers that the llguidance trie treats as special tokens (an added token that is flagged special or wrapped in <...>, which is how Qwen ships <tool_call>) so they are referenced by id (<[151657]>); a byte literal there masks out the model's own token, which is exactly what the first real-model run showed. Before anything is cloned, tool_schemas_fit measures the selected tools' names and schemas against MAX_SCHEMA_BYTES with a counting sink and count_refs applies MAX_SCHEMA_REFS, so a request cannot buy runtime-worker time or transient allocation proportional to a body sized for base64 images; either budget exceeded is the instruction-only fallback.
  • src/server/structured.rs: build_lark_constraint(tokenizer, lark) next to build_json_schema_constraint, sharing TOK_ENV_CACHE, the tightened ParserLimits, and the MAX_SCHEMA_BYTES cap applied to the grammar text. Nothing else in the file changes (issue perf(server): apply structured-output token masks as a packed u32 bitmask instead of a full f32 bias #1316 owns the rest).
  • src/server/routes/chat.rs: build_chat_constraint builds either the response_format constraint or the forced tool-call grammar on the blocking pool and is shared by the chat, Responses, and Anthropic routes; forced_constraint_or_instruction_only turns a grammar compile failure into the instruction-only fallback with a warn (a response_format the client asked for explicitly still yields a 400); validate_chat_tool_inputs delegates to ToolChoice::validate and rejects response_format plus a forced choice; both finish paths log at warn when a forced choice ends without a call (format name included), and the streaming path sets finish_reason: "tool_calls" only when at least one tool-call delta reached the client (previously it claimed tool_calls even when the named-function filter had dropped every call). The name filter for the named form stays as the last line of defence.
  • src/server/routes/responses.rs and src/server/routes/anthropic.rs: run the shared validation and constraint build, so text.format plus a forced choice is a 400 on Responses and the Anthropic {"type": "any"} / {"type": "tool"} mappings (already present in anthropic_translator.rs) get the same enforcement; the constraint is threaded into both Anthropic generation paths.
  • src/server/router_front.rs: a forced choice is accepted as before and enforced through the prompt only, with a warn saying the grammar cannot travel to the decode node; router_front_tests.rs pins that the router forwards such a request instead of rejecting it the way it rejects response_format.
  • src/server/routes/chat.rs streaming finish gate: tool_call_matches_choice and count_tool_calls_reaching_client are extracted from the spawn_blocking closure so the finish_reason: "tool_calls" gate has unit coverage for the required, named-match, and named-miss cases; the SSE emission flow is unchanged.
  • Docs: docs/responses-api.md (tool_choice row plus a "Tool choice enforcement" section), docs/server-features.md ("Tool calling and tool_choice"), and docs/CONTINUOUS_BATCHING.md (the disaggregated router's instruction-only behaviour next to its existing response_format limitation); the repository has no src/server/README, so the server feature doc is the closest equivalent to the README section the issue names.

Validation

All commands ran under DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer with --profile test-fast --features metal,accelerate on Apple Silicon (M1, Metal + Accelerate).

  • cargo fmt --all -- --check: clean.
  • cargo check --lib --tests: clean, no warnings.
  • cargo clippy --lib --tests -- -D warnings: clean.
  • cargo test --lib -- server::chat_request server::types server::tool_calls server::chat_template server::structured server::anthropic_translator server::routes::chat server::request_options server::responses_translator server::routes::anthropic server::routes::responses server::router_front: all passing, including the new tests effective_tools_narrows_to_named_function, tool_choice_instruction_appends_to_system_message, tool_choice_instruction_appends_to_last_text_user_message, tool_choice_instruction_inserts_system_when_no_system_and_no_text_user, named_tool_choice_changes_rendered_prompt_and_template_sig, tool_choice_required_without_tools_is_rejected, tool_choice_unknown_function_is_rejected, tool_choice_object_without_function_type_is_rejected, tool_choice_grammar_hermes_required_is_anyof_over_all_tools, tool_choice_grammar_named_pins_name_const, tool_choice_grammar_is_none_for_atem_and_gemma4, tool_choice_grammar_references_special_wrapper_tokens_by_id, tool_choice_grammar_is_none_when_the_declared_schemas_exceed_the_size_cap, tool_choice_grammar_is_none_when_the_declared_schemas_exceed_the_ref_cap, special_token_id_follows_the_trie_classification, forced_tool_call_format_detects_hermes_marker, forced_tool_call_format_is_none_for_atem_template, lark_constraint_forces_hermes_wrapper (token-by-token consume_token with compute_mask on every step, stopped at the end, prose masked out as the first token), lark_constraint_named_choice_refuses_other_tool_names, a_grammar_that_does_not_compile_degrades_to_instruction_only, anthropic_tool_choice_any_maps_to_required, anthropic_tool_choice_tool_maps_to_named, the streaming finish-gate cases, and router_chat_forwards_forced_tool_choice_instead_of_rejecting_it (972 tests in the filter at the final commit).
  • Real checkpoint mlx-community/Qwen3-4B-4bit (Hermes format, grammar-capable) served by target/test-fast/mlxcel-server, 5 runs per request at temperature: 0.7: tool_choice: "required" returned a get_time call with finish_reason: "tool_calls" on 5 of 5 runs; the named get_weather form with two tools declared returned get_weather on 5 of 5 runs and get_time on 0 of 5; required with "tools": [] returned HTTP 400, an undeclared named function returned HTTP 400, and required plus response_format: json_schema returned HTTP 400; required with stream: true streamed the tool-call start and arguments deltas and the final chunk carried finish_reason: "tool_calls"; /v1/messages with tool_choice: {"type": "any"} ended with stop_reason: "tool_use" and a get_time block. The server log carried no forced-choice warning across these runs. The review cycle re-ran the same checkpoint after the $ref relocation: a tool whose parameters carry $defs returned book_trip({"to":{"city":"Seoul"}}) with finish_reason: "tool_calls" on 3 of 3 runs and over SSE, an unresolvable external $ref degraded to instruction-only with one fallback warning and still returned 200, and the original cases were unchanged.

Changes during review

  • The first real-model run failed: llguidance's trie marks every added token of the form <...> as special, so a byte-literal "<tool_call>" masked out Qwen's own token. The grammar now references such markers by token id.
  • Nested tool schemas ($defs + #/$defs/...) failed to compile inside the wrapper and turned a request that worked on main into a 400; the schema's root-relative pointers are now relocated, and a grammar that still does not compile falls back to instruction-only enforcement instead of failing the request.
  • The grammar builder ran on a Tokio runtime worker with work proportional to the declared tool schemas (a 36 MB tools array cost about 350 ms and 72 MB of transient allocation); the size and $ref budgets are now applied before anything is cloned (133 us for the same array).
  • A padded function name passed validation and then rendered no tool; the name is now matched exactly as sent.

Not verified on this host

  • mlx-community/Muse-Glimmer-30B-4bit (ATEM, instruction-only path) is not available locally, so the "named form yields get_weather on at least 9 of 10 runs" acceptance for the instruction-only path was not run. The ATEM detection (forced_tool_call_format() == None with default_tool_call_format() == Some(Atem)) is unit-tested.
  • Mistral Nemo and Llama 3 grammar forcing is covered by the grammar-text and matcher unit tests only; no checkpoint of either family is present on this host.
  • cargo test --workspace and cargo clippy --workspace --all-targets (the issue's full-workspace gates) were not run here; the narrow module runs above and the path-filtered CI cover the touched surface. No CUDA code is touched.

Follow-ups (not in this PR)

  • The Responses API spells a named choice as {"type": "function", "name": "f"}; ToolChoice only deserializes the Chat Completions nesting, so that shape is rejected at deserialization as it was before this PR. required and the string modes work on /v1/responses.
  • The required grammar admits exactly one call; parallel calls on grammar-capable templates and parallel_tool_calls: false enforcement are out of scope per the issue.

Notes

PR for #1314 touches the same file; whichever merges second needs a rebase. The routes/chat.rs edits here are scoped to validation, constraint setup, and the finish-path warning.

`/v1/chat/completions` accepted `tool_choice: "required"` and the named-function object but only `none` changed behaviour: `required` was validated and then ignored, and a named function still rendered every declared tool and only filtered the parsed calls afterwards, so a model that picked another tool answered with an empty `tool_calls` array and `finish_reason: "stop"`.

Both forms now steer generation. `ToolChoice::validate` rejects the unsatisfiable shapes with 400 (`required` without tools, a named function that is undeclared, malformed, or empty) and is shared by the chat route, the Responses and Anthropic Messages routes, and the disaggregated router front. `effective_tools` narrows the template's tool list to the named function, and `prepare_chat_request_with_cache` renders from a cloned message list carrying the forced-choice instruction (first system message, else last user message, else a new leading system message), so the history-boundary render and the next-turn warm-up see the same prompt while the request itself stays untouched.

On templates whose tool-call wire shape is a JSON object in a fixed wrapper, the call is grammar-forced through the existing llguidance path: `ChatTemplateProcessor::forced_tool_call_format` reads Hermes (`<tool_call>`), Mistral Nemo (`[TOOL_CALLS]`) and Llama 3 (`<|python_tag|>` / `"parameters":`) off the template text at construction, excluding the XML-body dialects that reuse those tags; `tool_calls::tool_choice_grammar_with` spells the wrapper around `%json` schemas built from the tool definitions (`anyOf` for `required`, the single schema for a named function); and `structured::build_lark_constraint` compiles it with the same limits and tokenizer cache as the schema path. Wrapper markers the tokenizer carries as special tokens are referenced by id (`<[151657]>`) because the trie hides those behind a marker byte and a byte literal would mask out the very token the model emits. A forced choice combined with a constraining `response_format` is a 400, and a forced choice that finishes without a call is logged at `warn`; the streaming path now reports `tool_calls` only when at least one delta actually reached the client.

Validation: `cargo fmt --all -- --check`, `cargo check` and `cargo clippy --lib --tests -- -D warnings` under `--profile test-fast --features metal,accelerate`, plus the unit tests for `server::chat_request`, `server::types`, `server::tool_calls`, `server::chat_template`, `server::structured`, `server::anthropic_translator` and `server::routes::chat`. On `mlx-community/Qwen3-4B-4bit` (Hermes), `required` returned a `get_time` call with `finish_reason: "tool_calls"` on 5 of 5 runs at temperature 0.7, the named form returned `get_weather` and never `get_time` on 5 of 5 runs, the three 400 cases were rejected, the streaming form carried tool-call deltas and a `tool_calls` finish chunk, and the Anthropic `{"type": "any"}` mapping ended with `stop_reason: "tool_use"`.

Refs #1319
@adrysn adrysn added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:inference Generation, sampling, decoding (incl. speculative, DRY) area:cli Command-line interface / CLI flags modeltype:text Text-only language model labels Sep 2, 2026
The forced-call grammar embedded each tool's `parameters` schema verbatim under `properties/arguments` of a synthesized wrapper object. A tool schema written as its own document then lost its own definitions: `{"$defs": {"Addr": ...}, "properties": {"to": {"$ref": "#/$defs/Addr"}}}`, which is exactly what Pydantic, the OpenAI SDK and LangChain emit for a nested model, resolves `#/$defs/Addr` against the wrapper's root, finds nothing, and fails to compile. Because a compile failure was returned to the client, `tool_choice: "required"` with any such tool answered HTTP 400 on a request that returned 200 before the choice was enforced at all.

`relocate_root_refs` now re-points a tool schema's root-relative pointers at the place the schema comes to rest, `#/properties/arguments/...` for a named choice and `#/anyOf/<i>/properties/arguments/...` for `required`, before the schema is embedded. Per-branch relocation also keeps two tools' identically-named definitions apart, since each branch's pointers stay inside that branch.

A grammar that still does not compile no longer fails the request. The client asked for a tool call, not for a grammar, and the grammar is only how the server delivers one; a schema past llguidance's reach, a nesting depth past its limits or a tool set whose combined grammar exceeds the size cap now falls back to the instruction-only enforcement every non-grammar-capable template already gets, logged at `warn`. A `response_format` schema, which the client did ask for explicitly, still turns a compile failure into a 400.

Verified on `mlx-community/Qwen3-4B-4bit` under `--profile test-fast --features metal,accelerate`: the nested `$defs` tool with `tool_choice: "required"` returns `finish_reason: "tool_calls"` with `book_trip({"to":{"city":"Seoul"}})` on 3 of 3 runs and over SSE, an unresolvable external `$ref` degrades to instruction-only with the fallback warning and still returns 200, and the existing acceptance cases are unchanged (required to get_time 3/3, named get_weather 3/3, and the three 400 cases). `cargo fmt --all -- --check`, `cargo clippy --lib --tests -- -D warnings` and the `server::chat_request server::types server::tool_calls server::chat_template server::structured server::anthropic_translator server::routes::chat server::request_options server::responses_translator server::routes::anthropic server::routes::responses server::router_front server::prompt_cache` filter (1139 passing) are clean.

Refs #1319

Claude-Session: https://claude.ai/code/session_01FXxGfASHG7ju369cFEpHjS
@adrysn

adrysn commented Sep 2, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Make tool_choice: "required" and the named-function form actually steer generation on /v1/chat/completions and the Responses / Anthropic translations of it: narrow the rendered tool list, inject a prompt instruction, reject unsatisfiable requests with 400, and grammar-force the call on JSON-wire tool formats.

The implementation matches the issue's specification closely. All eight deliverables are present and wired into the request path, all sixteen mandated unit tests exist under the names the issue gives, effective_tools / forced_tool_call_format / tool_choice_grammar / build_lark_constraint are each reached from a real handler, and the change to structured.rs stays inside the build_lark_constraint addition that issue #1316 leaves free. Extending the enforcement to routes/responses.rs and routes/anthropic.rs goes past the literal deliverable list but is what the "Anthropic any and tool map to the same enforcement" acceptance criterion needs, so it is in scope rather than drift.

Findings addressed

  • HIGH — a forced tool_choice returned 400 for any tool whose parameters schema carries its own $defs. tool_call_schema embedded the tool schema verbatim under properties/arguments of a synthesized wrapper, so {"$defs": {"Addr": ...}, "properties": {"to": {"$ref": "#/$defs/Addr"}}} resolved #/$defs/Addr against the wrapper's root, found nothing, and failed to compile. That is the exact shape Pydantic, the OpenAI SDK and LangChain emit for a nested model, and because the compile failure was returned to the client, tool_choice: "required" with such a tool answered HTTP 400 on a request that returned 200 before the choice was enforced at all. Confirmed by feeding the schema through build_lark_constraint (failed to compile grammar), not inferred. Fixed in fa7332f by relocate_root_refs, which re-points a tool schema's root-relative pointers at where the schema comes to rest (#/properties/arguments/... for a named choice, #/anyOf/<i>/properties/arguments/... for required, which also keeps two tools' identically-named definitions apart), plus a fallback: a grammar that still does not compile now degrades to the instruction-only path with a warn instead of failing the request, while a response_format schema the client did ask for explicitly still turns a compile failure into a 400. Covered by lark_constraint_compiles_tool_schemas_that_use_defs_refs and a_grammar_that_does_not_compile_degrades_to_instruction_only, and documented in both docs pages.

Remaining items (reported, not changed)

  • MEDIUM — ToolChoice::validate matches a trimmed name against untrimmed tool names (src/server/types/request.rs). name is choice.function.name.trim() for the empty check and then reused for the declared-tool lookup, so {"function": {"name": " get_weather "}} validates against a declared get_weather. Every consumer afterwards compares the untrimmed string: effective_tools renders no tool, tool_choice_grammar builds no constraint, and build_tool_call_responses filters out every parsed call, so the request answers 200 with an empty tool_calls array instead of a 400. Using the raw name for the declared lookup makes a padded name a clean rejection.
  • MEDIUM — the Llama 3 marker "parameters": is the loosest of the three detectors (src/server/chat_template.rs). Any template that is not Hermes, Mistral Nemo or ATEM but happens to render "parameters": anywhere, which a generic tools preamble that dumps the OpenAI function JSON does, is classified as Llama 3 and gets a wrapper-less bare-JSON grammar its model was never trained to emit. The issue names this marker, so the code is spec-conformant; pairing it with a Llama-family identity check, or requiring <|python_tag|>, would narrow the blast radius.
  • MEDIUM — grammar forcing suppresses the reasoning block. The Lark grammar applies from the first generated token, so a thinking-enabled template cannot emit <think> ... </think> before the call. This matches the existing response_format path (both pass lazy: None to build_constraint), so it is at least consistent, but there the client asked for constrained decoding and here it did not. build_constraint already accepts a LazyGate; a trigger on the thinking close marker would let both coexist. Worth a documented limitation either way.
  • MEDIUM — required promises "one or more" calls and the grammar admits exactly one. On a grammar-capable template a required request can never produce parallel calls, which diverges from the instruction text the same request injects. parallel_tool_calls enforcement is out of scope for this issue, but the divergence deserves a line in the docs.
  • LOW — with_tool_choice_instruction deep-clones the whole request when only messages needs a copy. One extra allocation per forced request, proportional to conversation length.
  • LOW — the streaming finish_reason correction is untested. Gating "tool_calls" on emitted > 0 fixes a real prior bug (the stream claimed tool_calls even when the named-function filter had dropped every call), but it sits inside the finish closure with no unit test; only the real-model streaming run exercises it.

Verification

  • All stated requirements implemented (eight deliverables, four tool_choice shapes, three grammar-capable formats, the 400 cases)
  • No placeholder, mock, or stub code remaining
  • Integrated into the project code flow (chat, Responses, Anthropic Messages, the disaggregated router front, and /apply-template all reach ToolChoice::validate; build_chat_constraint feeds options.structured on every generating path)
  • Project conventions followed (thiserror-style error plumbing, inline format arguments, // Used by: markers, doc comments carrying the reasoning)
  • Existing modules reused (build_constraint, TOK_ENV_CACHE, ParserLimits, MAX_SCHEMA_BYTES, structured_error_to_response, validate_chat_tool_inputs, template_sig)
  • No unintended structural changes (structured.rs limited to the new build_lark_constraint; routes/chat.rs limited to validation, constraint setup and the finish-path warning)
  • Tests pass: cargo fmt --all -- --check, cargo clippy --profile test-fast --features metal,accelerate --lib --tests -- -D warnings, and the module filter covering chat_request, types, tool_calls, chat_template, structured, anthropic_translator, request_options, responses_translator, router_front, prompt_cache and the three routes: 1139 passing
  • Real checkpoint re-run on mlx-community/Qwen3-4B-4bit after the fix: nested $defs tool with required returns finish_reason: "tool_calls" with book_trip({"to":{"city":"Seoul"}}) 3 of 3 and over SSE; an unresolvable external $ref degrades to instruction-only with the fallback warning and still returns 200; required to get_time 3 of 3; named get_weather with two tools 3 of 3 and never get_time; the empty-tools, undeclared-function and response_format combinations each return 400

Not verified on this host: the ATEM instruction-only checkpoint (Muse-Glimmer-30B-4bit is not present), Mistral Nemo and Llama 3 grammar forcing against a real checkpoint of either family, and any CUDA path.

`ToolChoice::validate` compared a trimmed choice name against the declared tools, while `effective_tools`, the grammar builder and the response filter all compare the raw string. A padded name such as `" get_weather "` therefore passed validation and then rendered no tool, forced no grammar and filtered every parsed call, answering 200 with an empty `tool_calls` array instead of the 400 the named form promises. The declared-tool check now uses the name exactly as sent; blank names are still rejected on the trimmed form.

Validation: `cargo fmt --all -- --check` and `cargo test --profile test-fast --features metal,accelerate --lib -- server::types::request server::routes::chat::tests` (68 passing, including the new padded-name case).

Refs #1319
`forced_tool_choice_grammar` runs on the caller's thread, which for every HTTP route is a Tokio runtime worker: `build_chat_constraint` computes the Lark text before it enters `spawn_blocking`, and the Messages and Responses routes call it the same way. `tool_choice_grammar_with` then deep-clones every selected tool's `parameters`, walks the clone recursively to relocate its root-relative `$ref`s, and re-serializes the result. All of that is proportional to the tool schemas the request declared, and none of it was bounded: `tools` is capped by count (`MAX_TOOLS`) and not by size, and `build_lark_constraint`'s `MAX_SCHEMA_BYTES` cap only sees the finished text, on the blocking pool, after the work is already done and about to be discarded.

The JSON body limit is sized for base64 image payloads (roughly 1.3 GB at the default image knobs), so a single `tool_choice: "required"` request could buy a long stall on a runtime worker plus a multiple of the body size in transient allocation, for a grammar that was never going to compile. Measured on an M-series host, a 36 MB `tools` array cost 352 ms and about 72 MB of transient allocation inside the builder, scaling linearly with the body; Tokio's worker count is the core count, so a handful of concurrent requests stalls the HTTP surface, `/health` and in-flight SSE included.

Measure the selected tools' names and `parameters` against a `MAX_SCHEMA_BYTES` budget first, using a counting sink that fails once the budget is exhausted. `serde_json::to_writer` stops at the first writer error, so an oversized schema costs the budget rather than its own size, and the same 36 MB array now leaves the builder in 133 us. Exceeding the budget returns `None`, which is the instruction-only fallback a grammar that fails to compile already takes, so no request that worked before is newly refused. The pre-flight is a lower bound on the finished text and does not replace the cap; `build_lark_constraint` stays the authority on the final size.

Verified with `cargo fmt --all -- --check`, `cargo clippy --lib --tests -- -D warnings`, and the chat / tool-call / structured-output / translator / route test filters (967 passed, 0 failed).

Refs #1319
@adrysn

adrysn commented Sep 2, 2026

Copy link
Copy Markdown
Member Author

Security and performance review

Scope: the changed surface of this PR, with attention on the request-controlled JSON schemas that now flow from tools[].function.parameters into a Lark grammar, the constraint build on the chat / Messages / Responses routes, and the shared tool_choice validation.

Fixed in 4933f6f

HIGH -- unbounded reactor-thread work and transient allocation in the forced-grammar build. build_chat_constraint computes forced_tool_choice_grammar before entering spawn_blocking, so tool_choice_grammar_with ran on a Tokio runtime worker: it deep-clones every selected tool's parameters, walks the clone recursively in relocate_root_refs, and re-serializes the result. Nothing bounded that work -- tools is capped by count (MAX_TOOLS) and not by size, and build_lark_constraint's 64 KiB MAX_SCHEMA_BYTES cap only sees the finished text, on the blocking pool, after the work is done and about to be discarded. The JSON body limit is sized for base64 images (roughly 1.3 GB at the default image knobs), so one tool_choice: "required" request could stall a runtime worker and allocate a multiple of the body size. Measured on an M-series host: a 36 MB tools array cost 352 ms and about 72 MB of transient allocation inside the builder, scaling linearly with the body. Tokio's worker count is the core count, so a handful of concurrent requests stalls the HTTP surface including /health and in-flight SSE. The fix measures the selected tools' names and parameters against a MAX_SCHEMA_BYTES budget with a counting sink that fails once the budget is exhausted, before anything is cloned; the same 36 MB array now leaves the builder in 133 us. Over-budget returns None, the same instruction-only fallback a grammar that fails to compile already takes, so no request that worked before is newly refused.

Reported, not changed

MEDIUM -- build_lark_constraint applies only one of the three pre-compilation guards the response_format path applies. build_json_schema_constraint runs validate_schema_bounds, which enforces MAX_SCHEMA_BYTES, MAX_SCHEMA_DEPTH (32) and MAX_SCHEMA_REFS (64). build_lark_constraint enforces the size cap only, so tools[].function.parameters reaches llguidance without the $ref-count guard whose stated rationale is exactly this attack ("a tiny schema that references itself 10k times to explode compilation cost"). Measured: 64 $refs compile in 4.2 ms, 1000 $refs (49 KB of Lark, inside the cap) in 101 ms. The 64 KiB cap keeps this bounded and the compile is on the blocking pool, so it is an amplification factor rather than an outage, but the asymmetry is worth closing -- tools is a far more commonly attacker-reachable field than response_format. Depth is not a practical concern: serde_json's own 128-level recursion limit rejects a properties chain past roughly 40 levels before the schema is ever built.

MEDIUM -- the disaggregated router front silently drops the forced grammar. router_front.rs rejects response_format with a 400 on the stated principle that PrefillRequestFrame cannot carry a compiled constraint and the router must not "return unconstrained output for a request that explicitly asked for structured output". It now runs the shared validate_chat_tool_inputs, so tool_choice: "required" is accepted -- and then always degrades to instruction-only, with no constraint and no warning, on every grammar-capable model. On the single-node path that degradation is the compile-failure exception; on the router it is the rule. At minimum this deserves the same warn the compile-failure path emits, and a line in the docs.

MEDIUM -- the named tool_choice form is unreachable on /v1/responses. The Responses API spells it {"type": "function", "name": "f"}, but ToolChoice is #[serde(untagged)] over Mode(String) and Specific(ToolChoiceFunction), and ToolChoiceFunction requires the Chat Completions nesting (function.name). A Responses-shaped named choice matches neither variant, so the request fails at deserialization with a generic untagged-enum 400 before any of the new validation runs. The route now wires validation and constraint building for a shape it cannot receive.

LOW -- lark_string is not a general-purpose escaper. It escapes ", \, \n, \t and \r but passes other C0/C1 control bytes and DEL through, which the Lark string-literal lexeme rejects. Today it only ever sees the &'static str wrapper markers, so this is safe, and grammar injection is not possible either way (the JSON payload is serde_json-serialized, so it carries no raw newline or unescaped quote, and llguidance's %json is parsed by parse_json_prefix rather than by the comment-stripping lexer). The risk is a future caller passing a tool name or description and getting a silent compile failure. A debug assertion or a doc note that the input must be a fixed marker would pin the invariant.

LOW -- MAX_TOOLS is checked after ToolChoice::validate. The named-choice branch does a linear scan over tools before the count guard runs. Pre-existing ordering and negligible next to parsing the body, but the cheap guard should come first.

LOW -- with_tool_choice_instruction clones the whole request twice per turn. Once in prepare_chat_request_with_cache and once in render_next_turn_history's warm-up probe. Already noted in the implementation review; the second copy is the part worth remembering.

Checked and clear

  • No grammar injection through tools[].function.name or parameters: the schema is embedded as serde_json output, which cannot contain a raw newline or an unescaped quote, and llguidance hands %json to parse_json_prefix without applying its # / // comment skip inside the value.
  • No prompt-cache cross-contamination: template_sig already hashes tool_choice and tools, so a forced render and an unforced render of the same conversation cannot share a bucket.
  • No stack-overflow path through relocate_root_refs: serde_json's 128-level deserializer recursion limit bounds the input depth.
  • Error messages stay sanitized: a forced-grammar compile failure is swallowed by forced_constraint_or_instruction_only and never reaches the client, and the StructuredOutputError variants that do surface carry fixed strings.
  • No log forging through the tool name in warn_unmet_tool_choice or the debug in forced_tool_choice_grammar: the default tracing_subscriber::fmt visitor records &str fields through Debug, which escapes newlines.
  • special_token_id borrows the added-token map rather than cloning it (AddedVocabulary::get_added_tokens_decoder returns a reference in tokenizers 0.22), so the per-request marker lookup is cheap.
  • The Llama 3 grammar emits a bare JSON object with no <|python_tag|> prefix, and try_llama3 accepts exactly that shape, so the forced output still parses.

Validation

cargo fmt --all -- --check, cargo clippy --profile test-fast --features metal,accelerate --lib --tests -- -D warnings, and the chat / tool-call / structured-output / translator / route test filters: 967 passed, 0 failed. The measurements above come from throwaway probes run against this branch and removed before the commit.

The `response_format` path guards a schema with three pre-compilation limits (size, nesting depth, `$ref` count) because each `$ref` expands into its own sub-grammar and a small schema that references itself many times buys compile time out of proportion to its size. The forced tool-call grammar enforced the size cap only, so 1000 references inside a 49 KB tool schema still cost about 100 ms of grammar compilation on the blocking pool. `tool_choice_grammar_with` now counts `$ref` entries across the selected tools' `parameters` the same way `validate_schema_bounds` does and takes the instruction-only fallback past `MAX_SCHEMA_REFS`, with a `warn` naming the reason. Depth needs no separate guard: serde_json's recursion limit rejects deeper documents at parse time.

The disaggregated router front cannot carry a compiled constraint to the decode node, so a forced choice there is enforced through the narrowed tool list and the injected instruction only. It keeps accepting those requests, as it did before the choice was enforced at all, and logs the limitation at `warn` once per request instead of silently dropping the grammar.

Validation: `cargo fmt --all`, `cargo test --profile test-fast --features metal,accelerate --lib -- server::tool_calls server::router_front server::structured` (435 passing, including the new ref-cap case), and `cargo clippy --profile test-fast --features metal,accelerate --lib --tests -- -D warnings`.

Refs #1319
The streaming finish path's `emitted > 0` gate, which decides whether `finish_reason` may claim `"tool_calls"`, lived only inside `stream_chat_completion`'s `spawn_blocking` closure, so it had no unit coverage of its own; extract `tool_call_matches_choice` and `count_tool_calls_reaching_client` as plain functions that the emission loop now calls through the same predicate, without touching the SSE emission flow itself, and add tests pinning the `"required"`, named-match, and named-miss cases so a future change to the filter cannot silently let `finish_reason` claim a call the client never received.

Validation:
- cargo test --profile test-fast --features metal,accelerate --lib -- server::routes::chat (52 passed)
- cargo fmt --all -- --check and cargo clippy --profile test-fast --features metal,accelerate --lib --tests -- -D warnings both clean

Refs #1319
`route_chat` gained a branch (#1319) that lets a forced `tool_choice` ("required" or a named function) proceed past validation on the disaggregated router instead of being rejected the way `response_format` is, since the narrowed tool list and the injected prompt instruction still reach the rendered prompt even without a grammar constraint; nothing exercised that branch, so a future regression that turned it back into a 400 would have gone unnoticed by every existing router test. Add a test that posts a "required" tool_choice with a declared tool through a template that raises once rendering is reached, so getting the template's own rejection (not the tool_choice/response_format guard's 400) proves the request passed the new branch.

Validation:
- cargo test --profile test-fast --features metal,accelerate --lib server::router_front (27 passed)
- cargo fmt --all -- --check and cargo clippy --profile test-fast --features metal,accelerate --lib --tests -- -D warnings both clean

Refs #1319
…ion-only

The disaggregated-serving scope-and-limitations list already documents that `response_format` is rejected with 400 because the wire protocol cannot carry a compiled structured-output constraint to the decode node, but said nothing about the new forced `tool_choice` handling (#1319) added right next to it in `route_chat`, which takes the opposite path: it is accepted and enforced through the narrowed tool list and injected prompt instruction alone, logged once at `warn` instead of failing the request, since the grammar constraint has the same wire-protocol limitation but a forced tool_choice is still meaningfully served without one.

Refs #1319
@adrysn adrysn added status:done Completed and removed status:review Under review labels Sep 2, 2026
@inureyes
inureyes merged commit fe3b213 into main Sep 2, 2026
12 checks passed
inureyes added a commit that referenced this pull request Sep 2, 2026
## Summary

`build_template_context` inserted the `tools` key into the minijinja context unconditionally, and both render paths substituted an empty `Vec<Tool>` when the request carried no tools. Every template that selects its tool branch with `tools is defined` or `tools is not none` therefore took that branch on a plain chat request and rendered a tool-calling preamble with an empty function list. transformers passes `tools=None` and llama-server leaves the key unset, so neither of them does this. The key is now absent unless the request carries at least one tool.

Measured on the two shipped families, for `{"messages":[{"role":"user","content":"The Fibonacci sequence begins with"}]}` with no `tools` key:

| Checkpoint | Guard | Before | Oracle |
|---|---|---|---|
| `models/mlx/youtu-llm-2b-4bit` | `tools is defined and tools is not none` | 76 tokens, empty `<\|begin_of_tool_description\|>` block | 8 tokens |
| `models/mlx/llama-3.2-1b-4bit` | `set tools = none` default, then `tools is not none` | 97 tokens, `Environment: ipython` plus the functions preamble | 40 tokens |

## What changed

`src/server/chat_template.rs`: `build_template_context` takes `tools: Option<minijinja::Value>` and inserts the key only for `Some`. `apply_raw_inner` and `apply_inner` build that value as `tools.filter(|t| !t.is_empty()).map(minijinja::Value::from_serialize)`, so a request with no tools and a request with an explicit `"tools": []` both leave the key undefined. The tests-module render helper mirrors the same expression so it keeps reproducing what the server renders.

Normalizing inside the two inner functions covers every render in the tree at once: `/v1/chat/completions`, `/v1/messages`, `/v1/responses`, `/apply-template`, both `input_tokens` routes, the Muse ATEM stream path, the prompt cache's history-boundary render, and the offline `generate` and `chat` CLI commands. No caller was patched, no standalone helper was introduced, and `effective_tools` in `src/server/chat_request.rs` is untouched (it already maps `tool_choice: "none"` to `None`), so this PR does not overlap #1581.

Undefined rather than `none` is the required value, not a stylistic choice. minijinja 2.24's `iterable` test is `Value::try_iter().is_ok()`, which succeeds for `none`, while `| length` of `none` errors; the Nemotron / MiMo guard `tools is iterable and tools | length > 0` would therefore abort the render and degrade the prompt to the simple fallback. That family defaults an undefined `tools` to `[]` itself, so an absent key is the one value all three shipped guard shapes agree on. `tools` stays in `RESERVED_KEYS`, so a `chat_template_kwargs` entry still cannot fill the slot the request left empty.

The two stale comments that attributed the old empty-list workaround to minijinja short-circuiting are replaced with the actual `iterable` / `length` facts and a pointer to this issue.

`docs/llama-server-compat.md` gains a subsection under "Chat templates, reasoning, and output parsing" stating that llama-server defines `tools` only for a non-null tool array, that mlxcel now matches, that transformers' `tools=None` renders identically for every guard shape shipped, and that upgrading costs one cold prompt-cache miss per affected model.

## Context-key audit

Requested by the issue; also recorded as a comment on the insert block so the invariant travels with the code. `build_template_context` inserts exactly these keys:

- `messages`, `bos_token`, `eos_token`, `add_generation_prompt`: stay unconditional. Templates read them for their value and never test them with `is defined`; a missing one would change the rendered conversation rather than select a branch.
- `enable_thinking`: stays unconditional and stays defined. It is the tested per-request override point from #686 and #1114, and changing its definedness would change that contract. No shipped template was found where `enable_thinking is defined` alone flips a branch; if one turns up it is a follow-up issue, not a widening of this fix.
- `tools`: now conditional. This is the key the invariant was written for.
- `thinking` (#512) and `thinking_mode` (#775, #819): already conditional before this PR.
- `tool_choice` and `documents`: never inserted anywhere (`ctx.insert` / `owned.insert` in `chat_template.rs`), so there is nothing to audit.

## Prompt cache

The change alters `tokens[..prefix_len]` and the history-boundary render for affected models, so the first request per model after upgrading misses once and rebuilds. That is a one-time cold miss, not a compatibility break: no key digest version changes and no migration is needed.

## Test plan

- [x] `cargo test --profile test-fast --features metal,accelerate --lib server::chat_template` (154 passed), including four new tests: the DeepSeek/Youtu guard, the Llama guard, the Nemotron guard rendering without error, and the history-boundary render. `test_apply_with_tools_none_still_works`, `test_kwargs_cannot_override_reserved_tools_key`, `test_supports_tools_detection` and `test_supports_tools_caching` pass unchanged.
- [x] `cargo test --profile test-fast --features metal,accelerate --lib server::chat_request` (104 passed), plus `server::routes` (387), `server::tool` (384), `server::prompt_cache` (173), `server::reasoning_effort_tests` (28), `server::anthropic_translator` (33), `server::muse_atem_roundtrip_tests` (5), `server::muse_glimmer_template_tests` (6).
- [x] `cargo test --profile test-fast --features metal,accelerate --lib server::chat_template::tests::local_checkpoint_templates_render -- --ignored`: renders `models/mlx/youtu-llm-2b-4bit` and `models/mlx/llama-3.2-1b-4bit` through `from_model_path`, which reads only the template files, and both match the transformers oracle string exactly. This is the weight-free half of the gate and it runs in milliseconds; it caught that the Youtu template primes an empty `<think></think>` block unless `enable_thinking` is true, which `server::startup` derives from the tokenizer's think markers.
- [x] `cargo test --profile test-fast --features metal,accelerate --test apply_template_tools_parity` compiles and registers the gated HTTP test.
- [x] `cargo clippy --profile test-fast --lib --tests --features metal,accelerate -- -D warnings`
- [x] `cargo fmt --all -- --check`
- [x] `python3 scripts/ci/check_cross_repo_refs.py`
- [x] Static audit of the 196 chat templates under `models/`: every one of the 8 that computes `tools | length` guards it with a definedness or none test first, so no local template can error under an undefined `tools`.
- [ ] Real-checkpoint gate on `models/mlx/youtu-llm-2b-4bit` and `models/mlx/llama-3.2-1b-4bit` (`cargo test --test apply_template_tools_parity --release -- --ignored`, or the `/apply-template` and `input_tokens` curls in the issue). Run centrally; this PR did not start a server.

Closes #1597
@inureyes
inureyes deleted the feature/issue-1319-tool-choice-enforcement branch October 6, 2026 12:12
@inureyes inureyes added this to the 0.7 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Command-line interface / CLI flags area:inference Generation, sampling, decoding (incl. speculative, DRY) modeltype:text Text-only language model priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(server): enforce tool_choice required and named-function semantics on chat completions

2 participants