From 76c50158854f0249d85588c11195b7f88a0d4304 Mon Sep 17 00:00:00 2001 From: "Brandon M. Music" <266531604+brandonmmusic-max@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:58:45 -0500 Subject: [PATCH 1/3] helios/output: fail TML turns that close a nonempty model header without a content kind Why: When a TMLv0 model emits a reasoning frame followed by <|message_model|> and non-empty header text (such as a tool name and partial arguments where <|content_invoke_tool_json|> was dropped) and then closes the frame on <|end_message|> or <|content_model_end_sampling|>, TmlOutput discarded the header text and returned Ok on Termination::Eos. Before this change, /v1/responses emitted response.output_item.done(reasoning) followed by response.completed(output=[reasoning]) with status completed and no error. What changed: - Add AnswerState (Empty, HeaderWithoutContent, Emitted) to TmlOutput in helios/src/output/tml.rs. - Record HeaderWithoutContent when a non-empty model header closes on <|end_message|> or <|content_model_end_sampling|> before any visible content or tool call has been emitted. - Mark answer as Emitted whenever non-thinking visible content or a non-empty tool invocation body is emitted. - Return an error from TmlOutput::finish() on Termination::Eos when answer is HeaderWithoutContent while preserving existing behavior for empty model headers, non-model role frames, external terminations, and turns that emit visible text or a tool call. - Add unit tests in helios/src/output/tml.rs and a real tokenizer snapshot regression test in helios/src/server/request/tml_tests.rs. Claimed result: Malformed TMLv0 turns whose non-empty model header closes without a content kind and without any visible output or tool call fail at EOS and surface response.failed on /v1/responses instead of completing with reasoning only. Supporting evidence: - output::tml::tests and server::request::tml_tests (with FLARE_INKLING2_TEST_SNAPSHOT) pass on upstream main ee49d850. - Limitation: non-model role frames (<|message_tool|>, <|message_user|>, <|message_system|>) remain ignored per tml-renderers semantics. Design-Signed-Off-By: Brandon M. Music; design-review=1af4 Signed-off-by: Brandon M. Music <266531604+brandonmmusic-max@users.noreply.github.com> --- helios/src/output/tml.rs | 94 +++++++++++++++++++++++++- helios/src/server/request/tml_tests.rs | 38 +++++++++++ 2 files changed, 129 insertions(+), 3 deletions(-) diff --git a/helios/src/output/tml.rs b/helios/src/output/tml.rs index 5bd5d7a28..2ff009277 100644 --- a/helios/src/output/tml.rs +++ b/helios/src/output/tml.rs @@ -75,6 +75,13 @@ enum State { Closed, } +#[derive(Clone, Copy, PartialEq)] +enum AnswerState { + Empty, + HeaderWithoutContent, + Emitted, +} + /// The parser start after a prompt, from the last framing control token in it. pub(crate) fn prompt_start(prompt: &[u32], control_tokens: &[(u32, String)]) -> OutputStart { let marker = prompt.iter().rev().find_map(|id| { @@ -94,6 +101,7 @@ pub(crate) fn prompt_start(prompt: &[u32], control_tokens: &[(u32, String)]) -> pub struct TmlOutput { state: State, + answer: AnswerState, /// Escaped generated text with framing markers inserted only for control tokens. buffer: String, name: Option, @@ -128,6 +136,7 @@ fn first(buffer: &str, markers: &[&'static str]) -> Option<(usize, &'static str) impl TmlOutput { pub fn new(config: OutputConfig, control_tokens: Vec<(u32, String)>) -> Self { Self { + answer: AnswerState::Empty, state: match config.start { OutputStart::RecipientHeader => State::Header { model: true }, OutputStart::RecipientFrame => State::Frame, @@ -207,6 +216,7 @@ impl TmlOutput { if kind == Body::Thinking { events.push(Event::Reasoning(text)); } else { + self.answer = AnswerState::Emitted; self.spans.push(Some(start..start + text.len())); events.push(Event::Content(text)); } @@ -269,6 +279,13 @@ impl TmlOutput { }; let name = unescape(&self.buffer[..at]); self.buffer.drain(..at + marker.len()); + if model + && at > 0 + && matches!(marker, END | TURN_END) + && self.answer == AnswerState::Empty + { + self.answer = AnswerState::HeaderWithoutContent; + } self.state = match marker { MODEL => State::Header { model: true }, USER | SYSTEM | TOOL => State::Header { model: false }, @@ -315,12 +332,13 @@ impl TmlOutput { /// A registered invocation, or its payload as visible text when TMLv0 rejects it. fn call_or_text(&mut self, body: &str, start: usize) -> Vec { - if let Some(events) = self.call(body) { - return events; - } if body.is_empty() { return vec![]; } + self.answer = AnswerState::Emitted; + if let Some(events) = self.call(body) { + return events; + } self.spans.push(Some(start..start + body.len())); vec![Event::Content(body.to_owned())] } @@ -378,6 +396,9 @@ impl TmlOutput { // An unterminated header carries no content. self.buffer.clear(); self.state = State::Closed; + if cause == Termination::Eos && self.answer == AnswerState::HeaderWithoutContent { + return Err("TML model header closed without a content kind and the turn produced no answer or tool call".into()); + } Ok(events) } } @@ -565,6 +586,73 @@ mod tests { assert_eq!(run(frame, &[MODEL, "lookup"], Termination::Eos), Parsed::default()); } + #[test] + fn nonempty_model_header_closed_without_a_content_kind_fails_at_eos() { + for fragmented in [false, true] { + for deliver_turn_end in [false, true] { + let mut p = parser(OutputStart::RecipientFrame); + let mut events = vec![]; + for piece in [MODEL, THINK, "Inspect the branch.", END, MODEL, + r#"bash"description":"Inspect branch"}}"#, END] { + if CONTROL_MARKERS.contains(&piece) { + events.extend(feed(&mut p, piece, fragmented).unwrap()); + } else { + events.extend(p.push(Input::Text(piece)).unwrap()); + } + } + if deliver_turn_end { + events.extend(feed(&mut p, TURN_END, fragmented).unwrap()); + } + assert_eq!(events, vec![Event::Reasoning("Inspect the branch.".into())]); + let error = p.finish(Termination::Eos).unwrap_err(); + assert!(error.to_string().contains("without a content kind"), "{error}"); + } + let mut p = parser(OutputStart::RecipientFrame); + let mut events = vec![]; + for piece in [MODEL, THINK, "Inspect the branch.", END, MODEL, + r#"bash"description":"Inspect branch"}}"#, TURN_END] { + if CONTROL_MARKERS.contains(&piece) { + events.extend(feed(&mut p, piece, fragmented).unwrap()); + } else { + events.extend(p.push(Input::Text(piece)).unwrap()); + } + } + assert_eq!(events, vec![Event::Reasoning("Inspect the branch.".into())]); + let error = p.finish(Termination::Eos).unwrap_err(); + assert!(error.to_string().contains("without a content kind"), "{error}"); + } + } + + #[test] + fn a_closed_untyped_header_allows_visible_content_and_completed_calls() { + let frame = OutputStart::RecipientFrame; + let header = [MODEL, "untyped", END]; + let answer = [MODEL, TEXT, "done", END]; + let call = [MODEL, "lookup", JSON_CALL, r#"{"name":"lookup","args":{}}"#, END]; + let invalid_call = [MODEL, JSON_CALL, "invalid JSON", END]; + for valid in [&answer[..], &call[..], &invalid_call[..]] { + let expected = run(frame, valid, Termination::Eos); + for order in [[&header[..], valid], [valid, &header[..]]] { + assert_eq!(run(frame, &order.concat(), Termination::Eos), expected); + } + } + } + + #[test] + fn empty_model_headers_other_roles_and_external_stops_keep_their_termination() { + let frame = OutputStart::RecipientFrame; + for pieces in [vec![MODEL, END], vec![USER, "name", END], vec![TOOL, "lookup", END], + vec![SYSTEM, "name", END]] { + assert_eq!(run(frame, &pieces, Termination::Eos), Parsed::default()); + } + for cause in [Termination::OutputLimit, Termination::UserStop, Termination::Cancelled, + Termination::ExecutionError] { + assert_eq!(run(frame, &[MODEL, "untyped", END], cause), Parsed::default()); + } + assert_eq!(run(frame, &[MODEL, THINK, "t", END, TURN_END], Termination::Eos), + ("t".into(), String::new(), vec![])); + } + #[test] fn prompt_tail_selects_the_parser_start() { let controls: Vec<_> = CONTROL_MARKERS diff --git a/helios/src/server/request/tml_tests.rs b/helios/src/server/request/tml_tests.rs index bfbfa18f5..3c78b40e6 100644 --- a/helios/src/server/request/tml_tests.rs +++ b/helios/src/server/request/tml_tests.rs @@ -243,6 +243,44 @@ fn parse(inkling: &Inkling, case: &Value) -> (String, String, Vec<(String, Value (reasoning, content, calls) } +#[test] +#[ignore = "requires FLARE_INKLING2_TEST_SNAPSHOT with the Inkling 2 tokenizer"] +fn a_model_frame_without_a_content_kind_reports_a_failed_response() { + use crate::server::output::Decoder; + use crate::server::protocol::{Encoder, PromptUsage}; + + let inkling = Inkling::load(&golden()); + let request = inkling.request(Protocol::Responses, json!({ + "input": "Inspect the branch.", + "tools": [{"type":"function","name":"bash","parameters":{"type":"object"}}] + })).unwrap(); + let prepared = prepare_inference(&inkling.frontend, None, &inkling.compiler, &inkling.config, + &request, 0, false).unwrap(); + let mut decoder = Decoder::::new( + &inkling.frontend, &inkling.config.eos_token_ids, prepared.output); + let mut encoder = Encoder::new(Protocol::Responses, "test".into(), inkling.config.model_id.clone(), + 0, 1, vec![PromptUsage { tokens: prepared.prompt.tokens.len(), image_tokens: 0 }], + request.tools, request.tool_choice, true, true, json!({})); + + let mut tokens = vec![200001, 200008]; // Model reasoning frame + tokens.extend(inkling.frontend.encode("Inspect the branch.", false).unwrap()); + tokens.extend([END_MESSAGE, 200001]); + // Captured ordinary IDs between the second model-frame opener and its end. + tokens.extend([33131, 1, 70469, 1, 25, 1, 3960, 150309, 12, 68206, 155417, 152664, 1, 92, 92]); + tokens.extend([END_MESSAGE, 200006]); + for id in tokens { + let events = decoder.push(id).unwrap(); + assert!(events.iter().all(|event| matches!(event, Event::Reasoning(_)))); + encoder.apply(0, events).unwrap(); + } + let error = decoder.finish(Termination::Eos).unwrap_err(); + let frame = encoder.failure(&error); + assert_eq!(frame.event.as_deref(), Some("response.failed")); + assert_eq!(frame.data["response"]["status"], "failed"); + assert_eq!(frame.data["response"]["error"]["code"], "server_error"); + assert!(error.to_string().contains("without a content kind"), "{error}"); +} + #[test] #[ignore = "requires FLARE_INKLING2_TEST_SNAPSHOT with the Inkling 2 tokenizer"] fn outputs_match_reference_parses() { From 9b2f2f6ac84255705debf2099d41ef37337898a3 Mon Sep 17 00:00:00 2001 From: "Brandon M. Music" <266531604+brandonmmusic-max@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:58:45 -0500 Subject: [PATCH 2/3] helios/grammar: allow unnamed tool headers and answer-then-tool in TMLv0 grammars Why: Two mismatches existed between TmlOutput (helios/src/output/tml.rs) and GrammarCompiler::compile_content_headers (helios/src/grammar.rs): 1. TmlOutput treats the tool name in a <|message_model|> header before <|content_invoke_tool_json|> as optional, and Inkling 2 models natively emit <|message_model|><|content_invoke_tool_json|> with no header name. Before this change, compile_content_headers required self.marker(name) before <|content_invoke_tool_json|>, masking out <|content_invoke_tool_json|> after <|message_model|> and preventing grammar-constrained runs from invoking tools natively. 2. Before this change, compile_content_headers compiled tool-enabled envelopes as (answer | tools), rejecting a visible text preamble followed by tool calls even though TmlOutput parses that sequence. What changed: - Add a factored tool_unnamed rule (<|content_invoke_tool_json|> @payload_any <|end_message|>) using a single JSON schema enum over registered tool names, avoiding N-way Earley ambiguity across large tool sets while keeping named headers paired with matching @payload_i schemas. - Change the tool-enabled ending from (answer | tools) to (answer ({restart} thinking* tool)* | tools), matching XTML's wrapped_answer (ws tool)* framing while keeping at most one @answer frame. - Add content_headers_grammar_allows_preamble_before_tools in helios/src/grammar.rs and inkling_stress_* snapshot regression tests in helios/src/server/request/tml_tests.rs. Claimed result: TMLv0 grammar-constrained requests with declared tools accept unnamed and named tool headers as well as a visible preamble frame followed by tool calls, while still rejecting unregistered tools, mismatched header names, invalid tool arguments, duplicate @answer frames, and reasoning-only terminations. Supporting evidence: - grammar::tests, output::tml::tests, frontend::tml::tests, and all 8 FLARE_INKLING2_TEST_SNAPSHOT tests in server::request::tml_tests pass on upstream main ee49d850. - Live SM120 GPU verification against TML-d24-varloop-research with grammar start: /(?s:.+)/ and 178 tools moved from 0/5 to 5/5 tool calls and 6/6 preamble-plus-tool responses. - Limitation: non-TMLv0 model families were verified through unit tests only, not live GPU serving. Design-Signed-Off-By: Brandon M. Music; design-review=1af4 Signed-off-by: Brandon M. Music <266531604+brandonmmusic-max@users.noreply.github.com> --- helios/src/grammar.rs | 83 +++++++++++++++++++++++- helios/src/server/request/tml_tests.rs | 87 ++++++++++++++++++++++++++ 2 files changed, 168 insertions(+), 2 deletions(-) diff --git a/helios/src/grammar.rs b/helios/src/grammar.rs index f7ca11ebc..2ba8c3d34 100644 --- a/helios/src/grammar.rs +++ b/helios/src/grammar.rs @@ -375,6 +375,17 @@ impl GrammarCompiler { self.marker("<|content_thinking|>"), self.marker("<|content_text|>"))); grammar.grammars[0].name = Some("answer".into()); let mut tools = vec![]; + if !envelope.tools.is_empty() { + let mut payload = TopLevelGrammar::from_json_schema(serde_json::json!({ + "type":"object", "properties":{"name":{"enum":&envelope.tools},"args":{"type":"object"}}, + "required":["name","args"], "additionalProperties":false, + })).grammars.remove(0); + payload.name = Some("payload_any".into()); + grammar.grammars.push(payload); + rules.push_str(&format!("tool_unnamed: {} @payload_any {end}\n", + self.marker("<|content_invoke_tool_json|>"))); + tools.push("tool_unnamed".into()); + } for (index, name) in envelope.tools.iter().enumerate() { let mut payload = TopLevelGrammar::from_json_schema(serde_json::json!({ "type":"object", "properties":{"name":{"const":name},"args":{"type":"object"}}, @@ -386,9 +397,9 @@ impl GrammarCompiler { self.marker(name), self.marker("<|content_invoke_tool_json|>"))); tools.push(format!("tool_{index}")); } - let ending = if tools.is_empty() { "answer" } else { + let ending = if tools.is_empty() { "answer".to_owned() } else { rules.push_str(&format!("tool: {}\ntools: tool ({restart} thinking* tool)* ({restart} thinking* answer)?\n", tools.join(" | "))); - "(answer | tools)" + format!("(answer ({restart} thinking* tool)* | tools)") }; rules.push_str(&format!("tail: thinking* {ending}\n")); match envelope.start { @@ -1894,6 +1905,74 @@ mod tests { } } } + + #[test] + fn content_headers_grammar_allows_preamble_before_tools() { + use crate::model::contract::ToolParserKind; + use crate::output::tagged::OutputStart; + + let markers = [ + "<|message_model|>", + "<|content_thinking|>", + "<|content_text|>", + "<|content_invoke_tool_json|>", + "<|end_message|>", + ]; + let tokenizer = byte_tokenizer_with(&markers); + let controls: Vec<_> = markers + .iter() + .map(|marker| (tokenizer.token_to_id(marker).unwrap(), (*marker).to_owned())) + .collect(); + let compiler = GrammarCompiler::new(&tokenizer, 320, &[256, 257], &controls).unwrap(); + let envelope = OutputEnvelope { + recipient: Some(RecipientEnvelope { + syntax: ToolParserKind::TmlJson, + start: OutputStart::RecipientFrame, + tools: vec!["bash".into()], + }), + reasoning_end: None, + tool: None, + function: None, + tool_ends_reasoning: false, + tool_body_start: false, + response: None, + message_close: None, + }; + let thinking = "<|message_model|><|content_thinking|>Plan.<|end_message|>"; + let answer = "<|message_model|><|content_text|>Checking branch.<|end_message|>"; + let named_call = "<|message_model|>bash<|content_invoke_tool_json|>{\"name\":\"bash\",\"args\":{\"cmd\":\"git status\"}}<|end_message|>"; + let unnamed_call = "<|message_model|><|content_invoke_tool_json|>{\"name\":\"bash\",\"args\":{\"cmd\":\"git status\"}}<|end_message|>"; + let bad_unnamed_call = "<|message_model|><|content_invoke_tool_json|>{\"name\":\"other\",\"args\":{}}<|end_message|>"; + let bad_named_call = "<|message_model|>other<|content_invoke_tool_json|>{\"name\":\"bash\",\"args\":{}}<|end_message|>"; + for (text, valid) in [ + (answer.to_owned(), true), + (named_call.to_owned(), true), + (unnamed_call.to_owned(), true), + (format!("{named_call}{answer}"), true), + (format!("{unnamed_call}{answer}"), true), + (format!("{answer}{named_call}"), true), + (format!("{answer}{unnamed_call}"), true), + (format!("{thinking}{answer}{unnamed_call}"), true), + (format!("{answer}{thinking}{named_call}{unnamed_call}"), true), + (bad_unnamed_call.to_owned(), false), + (bad_named_call.to_owned(), false), + (thinking.to_owned(), false), + (format!("{answer}{unnamed_call}{answer}"), false), + ] { + let mut grammar = compiler + .compile_lark_in("start: /(?s:.+)/", Some(&envelope)) + .unwrap(); + let accepted = tokenizer + .encode(text.as_str(), false) + .unwrap() + .get_ids() + .iter() + .copied() + .chain([256]) + .all(|id| grammar.advance(id).is_ok()); + assert_eq!(accepted, valid, "{text}"); + } + } } #[cfg(all(test,feature="server"))] diff --git a/helios/src/server/request/tml_tests.rs b/helios/src/server/request/tml_tests.rs index 3c78b40e6..07c5cab4a 100644 --- a/helios/src/server/request/tml_tests.rs +++ b/helios/src/server/request/tml_tests.rs @@ -389,3 +389,90 @@ fn structured_output_grammars_constrain_frames() { assert_eq!(accepted, valid, "{text}"); } } + +#[test] +#[ignore = "requires FLARE_INKLING2_TEST_SNAPSHOT with an Inkling 2 tokenizer"] +fn inkling_stress_untyped_closed_header_must_surface_failure() { + use crate::server::output::Decoder; + use crate::server::protocol::{Encoder, PromptUsage}; + + let inkling = Inkling::load(&golden()); + let request = inkling.request(Protocol::Responses, json!({ + "input":"Inspect the branch.", + "tools":[{"type":"function","name":"bash","parameters":{"type":"object"}}], + "tool_choice":"auto" + })).unwrap(); + let prepared = prepare_inference( + &inkling.frontend, None, &inkling.compiler, &inkling.config, &request, 0, false, + ).unwrap(); + let mut decoder = Decoder::::new( + &inkling.frontend, &inkling.config.eos_token_ids, prepared.output, + ); + let mut encoder = Encoder::new( + Protocol::Responses, "stress".into(), inkling.config.model_id.clone(), 0, 1, + vec![PromptUsage { tokens: prepared.prompt.tokens.len(), image_tokens: 0 }], + request.tools, request.tool_choice, true, true, json!({}), + ); + + // A short valid reasoning frame, then the exact captured 18-token suffix. + let mut ids = vec![200001, 200008]; + ids.extend(inkling.frontend.encode("Inspect the branch.", false).unwrap()); + ids.push(END_MESSAGE); + ids.extend([ + 200001, 33131, 1, 70469, 1, 25, 1, 3960, 150309, 12, 68206, 155417, + 152664, 1, 92, 92, END_MESSAGE, 200006, + ]); + let decoded: crate::Result<()> = (|| { + for id in ids { + let events = decoder.push(id)?; + assert!(events.iter().all(|e| matches!(e, Event::Reasoning(_)))); + encoder.apply(0, events)?; + } + let last = decoder.finish(Termination::Eos)?; + assert!(last.iter().all(|e| matches!(e, Event::Reasoning(_)))); + Ok(()) + })(); + let error = decoded.expect_err("malformed terminal header silently disposed of the action"); + let terminal = encoder.failure(&error); + assert_eq!(terminal.event.as_deref(), Some("response.failed")); + assert_eq!(terminal.data["response"]["status"], "failed"); +} + +#[test] +#[ignore = "requires FLARE_INKLING2_TEST_SNAPSHOT with an Inkling 2 tokenizer"] +fn inkling_stress_custom_grammar_preamble_then_tool() { + let inkling = Inkling::load(&golden()); + let preamble = "I'll start by exploring the workspace and the PR."; + let text = format!("<|message_model|><|content_text|>{preamble}<|end_message|>"); + let call = concat!( + "<|message_model|>bash<|content_invoke_tool_json|>", + r#"{"name":"bash","args":{"command":"git status","description":"Inspect branch"}}"#, + "<|end_message|>", + ); + let preamble_then_call = format!("{text}{call}"); + let mut ids = inkling.frontend.encode(&preamble_then_call, false).unwrap(); + ids.push(200006); + let fixture = json!({"output_ids":ids,"tools":["bash"],"finish":"eos"}); + let (_, parsed_text, calls) = parse(&inkling, &fixture); + assert_eq!(parsed_text, preamble); + assert_eq!(calls, vec![("bash".to_owned(), + json!({"command":"git status","description":"Inspect branch"}))]); + + let request = inkling.request(Protocol::Responses, json!({ + "input":"Inspect the branch.", + "tools":[{"type":"function","name":"bash","parameters":{"type":"object"}}], + "tool_choice":"auto","grammar":"start: /(?s:.+)/" + })).unwrap(); + let accepts = |frames: &str| { + let mut prepared = prepare_inference( + &inkling.frontend, None, &inkling.compiler, &inkling.config, &request, 0, false, + ).unwrap(); + let grammar = prepared.prompt.grammar.as_mut().unwrap(); + inkling.frontend.encode(frames, false).unwrap().into_iter().chain([200006]) + .all(|id| grammar.advance(id).is_ok()) + }; + assert!(accepts(&text)); + assert!(accepts(call)); + assert!(accepts(&format!("{call}{text}"))); + assert!(accepts(&preamble_then_call), "answer before a valid tool call rejected"); +} From aacbca18206cd37d727e35f5ed49bdfa0c379a8e Mon Sep 17 00:00:00 2001 From: "Brandon M. Music" <266531604+brandonmmusic-max@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:57:54 -0500 Subject: [PATCH 3/3] helios/grammar: allow unnamed tool headers and preamble-then-tool in strict TMLv0 grammars Why: PR #418 (0b09434d) added GrammarCompiler::compile_strict_tml in helios/src/grammar/strict.rs with the same two constraints stricter than TmlOutput that compile_content_headers had before this branch: 1. Each tool rule required self.marker(&tool.name) before <|content_invoke_tool_json|>, even though Inkling 2 natively emits unnamed <|message_model|><|content_invoke_tool_json|> tool headers and TmlOutput treats the header name as optional. 2. Non-required tool envelopes compiled as (answer | tools), rejecting a visible text preamble followed by tool calls even though TmlOutput parses that frame sequence directly. What changed: - Added a factored tool_unnamed rule (<|content_invoke_tool_json|> (@payload_0 | ... | @payload_k) <|end_message|>) in compile_strict_tml so unnamed tool headers validate against each active tool's strict or default wrapper schema while named headers keep per-tool pairing. - Updated the non-required ending in compile_strict_tml from (answer | tools) to (answer ({restart} thinking* tool)? | tools) when single_call is set and (answer ({restart} thinking* tool)* | tools) otherwise. - Added a TML_unnamed case to strict_tool_wire_grammars_enforce_constraints and a new strict_tml_grammar_allows_unnamed_headers_and_preamble_before_tools unit test covering multi-tool unnamed headers, schema and undeclared-tool rejection, named header mismatch rejection, and preamble-then-tool framing with both parallel and single_call limits. Claimed result: Strict function-tool requests ("strict": true) on TMLv0 models accept both unnamed and named tool headers as well as a visible text preamble followed by tool calls while enforcing each tool's strict JSON schema. Supporting evidence: - output::tml::tests, frontend::tml::tests, grammar::tests, grammar::strict::tests, server::protocol::tests, and server::output::tests pass (124 passed, 0 failed) and all 8 real Inkling 2 tokenizer snapshot tests in server::request::tml_tests pass on NVIDIA/hyperflare-inference main (b9cac839). - Live SM120 GPU verification on RTX PRO 6000 Blackwell with a strict get_weather function tool ("strict": true) returned HTTP 200 and a valid schema-conforming function_call on /v1/responses. - Limitation: non-TMLv0 strict tool families (Qwen, GLM, DSML) were verified through existing grammar::strict::tests only, not live GPU serving. Design-Signed-Off-By: Brandon M. Music; design-review=1af4 Signed-off-by: Brandon M. Music <266531604+brandonmmusic-max@users.noreply.github.com> --- helios/src/grammar/strict.rs | 136 ++++++++++++++++++++++++++++++++++- 1 file changed, 134 insertions(+), 2 deletions(-) diff --git a/helios/src/grammar/strict.rs b/helios/src/grammar/strict.rs index d7435c46b..638b76460 100644 --- a/helios/src/grammar/strict.rs +++ b/helios/src/grammar/strict.rs @@ -1563,6 +1563,7 @@ impl GrammarCompiler { )); } let mut tool_rules = Vec::new(); + let mut payload_refs = Vec::new(); for (index, tool) in plan.tools.iter().enumerate() { let wrapper = match &tool.strict_schema { Some(schema) => embed_schema_in_tml_wrapper(&tool.name, schema), @@ -1582,6 +1583,7 @@ impl GrammarCompiler { .remove(0); payload.name = Some(format!("payload_{index}")); subgrammars.push(payload); + payload_refs.push(format!("@payload_{index}")); rules.push_str(&format!( "tool_{index}: {} {} @payload_{index} {end}\n", self.marker(&tool.name), @@ -1594,6 +1596,12 @@ impl GrammarCompiler { "strict tool grammar requires at least one active tool", )); } + rules.push_str(&format!( + "tool_unnamed: {} ({}) {end}\n", + self.marker("<|content_invoke_tool_json|>"), + payload_refs.join(" | "), + )); + tool_rules.push("tool_unnamed".into()); rules.push_str(&format!("tool: {}\n", tool_rules.join(" | "))); if plan.single_call { rules.push_str(&format!("tools: tool ({restart} thinking* answer)?\n")); @@ -1603,9 +1611,11 @@ impl GrammarCompiler { )); } let ending = if plan.require_call { - "tools" + "tools".to_owned() + } else if plan.single_call { + format!("(answer ({restart} thinking* tool)? | tools)") } else { - "(answer | tools)" + format!("(answer ({restart} thinking* tool)* | tools)") }; rules.push_str(&format!("tail: thinking* {ending}\n")); match recipient.start { @@ -4121,6 +4131,16 @@ mod tests { valid: "weather<|content_invoke_tool_json|>{\"name\":\"weather\",\"args\":{\"value\":2}}<|end_message|>", invalid: "weather<|content_invoke_tool_json|>{\"name\":\"weather\",\"args\":{\"value\":4}}<|end_message|>", }, + Case { + name: "TML_unnamed", + kind: ToolParserKind::TmlJson, + separator: "", + start: OutputStart::RecipientHeader, + controls: &CONTROL_MARKERS, + constraint: Constraint::NumericRange, + valid: "<|content_invoke_tool_json|>{\"name\":\"weather\",\"args\":{\"value\":2}}<|end_message|>", + invalid: "<|content_invoke_tool_json|>{\"name\":\"weather\",\"args\":{\"value\":4}}<|end_message|>", + }, ]; for case in cases { @@ -4501,4 +4521,116 @@ mod tests { false, ); } + + #[test] + fn strict_tml_grammar_allows_unnamed_headers_and_preamble_before_tools() { + use crate::model::contract::{ToolParser, ToolParserKind}; + use crate::output::{ + OutputConfig, OutputPipeline, + tagged::{OutputConfig as TaggedConfig, OutputStart}, + tml::CONTROL_MARKERS, + }; + + let weather_schema = json!({ + "type": "object", + "properties": {"value": {"type": "integer", "minimum": 1, "maximum": 3}}, + "required": ["value"], + "additionalProperties": false + }); + let lookup_schema = json!({ + "type": "object", + "properties": {"query": {"type": "string", "minLength": 2}}, + "required": ["query"], + "additionalProperties": false + }); + let tokenizer = byte_tokenizer_with(&CONTROL_MARKERS); + let controls: Vec<_> = CONTROL_MARKERS + .iter() + .map(|marker| (tokenizer.token_to_id(marker).unwrap(), (*marker).to_owned())) + .collect(); + let compiler = GrammarCompiler::new(&tokenizer, 320, &[256, 257], &controls).unwrap(); + let mut syntax = crate::model::testing::metadata().frontend; + syntax.reasoning = None; + syntax.tools = Some(ToolParser { + kind: ToolParserKind::TmlJson, + wrapping_newlines: 0, + tag_separator: String::new(), + }); + let config = OutputConfig { + syntax, + control_tokens: controls.clone(), + content: TaggedConfig { + structured: false, + start: OutputStart::RecipientHeader, + tools: vec![ + json!({"type":"function","function":{"name":"weather","parameters":weather_schema}}), + json!({"type":"function","function":{"name":"lookup","parameters":lookup_schema}}), + ], + }, + }; + let envelope = OutputPipeline::grammar_envelope(&config).unwrap(); + let encode = |wire: &str| { + let mut tokens = Vec::new(); + let mut rest = wire; + while let Some((at, id, marker)) = controls + .iter() + .filter_map(|(id, marker)| { + rest.find(marker).map(|at| (at, *id, marker.as_str())) + }) + .min_by_key(|(at, _, _)| *at) + { + tokens.extend(rest[..at].bytes().map(u32::from)); + tokens.push(id); + rest = &rest[at + marker.len()..]; + } + tokens.extend(rest.bytes().map(u32::from)); + tokens + }; + let accepts = |single_call: bool, wire: &str| { + let plan = ToolGrammarPlan { + tools: vec![ + StrictToolSpec { + name: "weather".into(), + strict_schema: Some(&weather_schema), + }, + StrictToolSpec { + name: "lookup".into(), + strict_schema: Some(&lookup_schema), + }, + ], + syntax: Some((ToolParserKind::TmlJson, 0, String::new())), + dsml_token: None, + allow_undeclared: false, + require_call: false, + single_call, + }; + let mut g = compiler + .compile_with_strict_tools(None, Some(&envelope), &plan) + .unwrap(); + encode(wire) + .into_iter() + .chain([256]) + .all(|token| g.advance(token).is_ok()) + && g.is_stopped() + }; + + // Multi-tool unnamed strict headers accept valid arguments for either tool + assert!(accepts(false, r#"<|content_invoke_tool_json|>{"name":"weather","args":{"value":2}}<|end_message|>"#)); + assert!(accepts(false, r#"<|content_invoke_tool_json|>{"name":"lookup","args":{"query":"ok"}}<|end_message|>"#)); + // Unnamed strict headers reject schema violations and undeclared tools + assert!(!accepts(false, r#"<|content_invoke_tool_json|>{"name":"weather","args":{"value":9}}<|end_message|>"#)); + assert!(!accepts(false, r#"<|content_invoke_tool_json|>{"name":"lookup","args":{"query":"x"}}<|end_message|>"#)); + assert!(!accepts(false, r#"<|content_invoke_tool_json|>{"name":"other","args":{}}<|end_message|>"#)); + // Named strict headers reject header/body mismatch + assert!(!accepts(false, r#"weather<|content_invoke_tool_json|>{"name":"lookup","args":{"query":"ok"}}<|end_message|>"#)); + // Visible preamble before unnamed strict tool calls is accepted; single_call caps at one tool + let preamble_one = r#"<|content_text|>Checking now.<|end_message|><|message_model|><|content_invoke_tool_json|>{"name":"weather","args":{"value":2}}<|end_message|>"#; + let preamble_two = r#"<|content_text|>Checking both.<|end_message|><|message_model|><|content_invoke_tool_json|>{"name":"weather","args":{"value":2}}<|end_message|><|message_model|><|content_invoke_tool_json|>{"name":"lookup","args":{"query":"ok"}}<|end_message|>"#; + let preamble_bad = r#"<|content_text|>Checking now.<|end_message|><|message_model|><|content_invoke_tool_json|>{"name":"weather","args":{"value":9}}<|end_message|>"#; + assert!(accepts(false, preamble_one)); + assert!(accepts(false, preamble_two)); + assert!(!accepts(false, preamble_bad)); + assert!(accepts(true, preamble_one)); + assert!(!accepts(true, preamble_two)); + } }