#1 [high] Research summary
Correctness, Contracts & System-Level Consequences review — PR #677 (head c897437)
Scope inspected: full diff of all 11 changed files, plus callers/neighbours read in context — helios/src/output/tagged.rs (trait 39–72, TaggedTools::push 323–413, finish 414–429, eos_decision 283–297, TaggedOutput 439–620, 820–957), argument_tags.rs:24–131, chatml.rs:16–247, gemma_call.rs:120–190, minimax_xml.rs:142–206, frontend/mod.rs:782–891 (+1573–1780 test), server/protocol/decode.rs:14–40, 177–228, 560–709, 2430–2761, server/request.rs:458–568, server/inference.rs:110–161, docs/api.md diff. (No scratchpad notes were written before the turn limit; findings are recorded here in full.)
1. scan_value_end's trait default is fail-open and silently reintroduces quadratic reparsing — Major
helios/src/output/tagged.rs:56–63:
/// Advances linearly across an open non-JSON argument value after
/// `Candidate::IncompleteValue`. Returns `Ok(advance)` when a value-ending
/// boundary appears at `tail[..advance]` ...
fn scan_value_end(_tail: &str) -> std::result::Result<usize, usize> {
Ok(0)
}
helios/src/output/tagged.rs:350–361 treats Ok as "the value ended":
if self.in_value {
match D::scan_value_end(&self.buffer[self.search_from..]) {
Ok(advance) => {
self.search_from += advance;
self.in_value = false;
}
Impact (traced, not guessed): with the default, Ok(0) clears in_value and adds zero advance, so the loop re-selects the next closer at tagged.rs:367–374 and calls parse_candidate(&self.buffer[..end], …) again (:395), which re-runs parse_body from byte 0 and rescans the value with value.split_once("</arg_value>") — i.e. one full body parse per inner closing tag, O(N·K). Progression is guaranteed (:377 sets search_from = prev + consumed), so this is not a hang, but the PR's central "O(N)" guarantee evaporates with no compile error, no test failure, and no Kani failure for any dialect that returns IncompleteValue without also overriding scan_value_end. Today only the three production dialects override it (argument_tags.rs:117–123, chatml.rs:30–47, gemma_call.rs:176), so the hazard is latent — but the default contradicts the documented contract (Ok = boundary found).
Fix: make the method required (remove the default) so a dialect that emits IncompleteValue cannot compile without a scanner; if a default must exist, it should be Err(tail.len())-style fail-closed only together with a compile-time assertion, or the Ok(0) sentinel should be rejected in push (advance == 0 ⇒ treat as Err).
2. The resolve_effort sentinel heuristic can drop a level the template genuinely accepts — Major
helios/src/frontend/mod.rs:863–879:
let fallback = render("__flare_unknown_effort__");
let rendered: Vec<(&str, String)> = ["low", "medium", "high", "xhigh", "max"] …
let has_distinct = fallback
.as_deref()
.is_some_and(|fb| rendered.iter().any(|(_, out)| out != fb));
rendered
.into_iter()
.filter(|(effort, out)| {
!has_distinct
|| *effort != "medium"
|| fallback.as_deref() != Some(out.as_str())
})
Impact: the test is "does medium render the same as an unknown string". A template that clamps unknown values to its own default and whose default is medium — e.g. {% set eff = reasoning_effort if reasoning_effort in ['low','medium','high'] else 'medium' %} — renders medium and the sentinel identically, so medium is removed from the accepted vocabulary even though the template explicitly lists it. Effort::Medium then resolves to "high" (request.rs:521) and the prompt for a top-level Chat medium request silently changes to high. The inverse blind spot also holds: a template that maps medium onto another valid level (rendering differently from the sentinel) keeps medium in the set, and no other level is ever dropped. The only in-tree vocabulary test (frontend/mod.rs:1742–1777) uses raise-on-unknown templates, where render() returns None, has_distinct is false, and the filter never fires — i.e. the code path is untested where it actually acts. The magic sentinel is also undocumented in docs/api.md:988–991, which describes plain vocabulary matching.
Fix: make acceptance explicit rather than inferred from render equality — e.g. require the recipe to declare its effort vocabulary, or probe with the absence of reasoning_effort plus a value that the template must reject, and assert on the raise rather than on string equality; add a test with a fallback-to-medium template.
3. Unknown / non-string top-level Chat reasoning_effort is forwarded verbatim and untested — Minor
helios/src/server/protocol/decode.rs:606–607, 627, 677–682:
body.get("reasoning_effort").filter(|v| v.is_string())
…
_ if protocol == Protocol::Chat && !chat_nested_effort => None,
…
let withheld_chat_effort = protocol == Protocol::Chat
&& (chat_nested_effort
|| matches!(
body.get("reasoning_effort").and_then(Value::as_str),
Some("none" | "minimal" | "low" | "medium" | "high" | "max")
));
"bogus", true, or {} at the top level on /v1/chat/completions neither errors nor is normalized; it lands in options.template raw at :693–695. docs/api.md:984–987 claims only "xhigh, numeric scores, and chat_template_kwargs overrides" pass through directly, so the documented contract and the code disagree, and this is exactly the "accept it and quietly drop/forward it" pattern the charter's #417 guidance forbids. The only negative tests added are for the nested spelling (decode.rs:2643–2650). Fix: reject unknown top-level strings on Chat with the same unsupported reasoning effort error already produced for the nested path, or document the raw pass-through explicitly and add a test pinning it.
4. Same OpenAI field, two spellings, two different prompts on Inkling 2 — Minor
helios/src/server/protocol/decode.rs:622–625 + helios/src/server/request.rs:521–522:
Some("medium") if protocol == Protocol::Chat && !chat_nested_effort => {
Some(Effort::Medium)
}
Some("medium" | "high") => Some(Effort::High),
Effort::Medium => &["medium", "high"],
Effort::High => &["high", "medium"],
Top-level "medium" → Effort::Medium → TMLv0 0.7; nested reasoning.effort:"medium" on the same Chat endpoint → Effort::High → 0.9 (asserted decode.rs:2716 vs :2723–2726). For any Jinja template that accepts both medium and high, the ladder order also flips the result (medium vs high) purely by spelling. The divergence is deliberate and documented (docs/api.md:991–993) but it is an internal contract inconsistency introduced by this PR, so it deserves an explicit maintainer sign-off rather than a docs footnote. Fix options: normalise top-level medium to Effort::High and give TMLv0 a Chat-specific level mapping inside the encoder, or make the nested spelling match the top-level one on Chat only.
5. Undeclared behaviour change: a missing value terminator is now omitted instead of erroring on stop/cancel/length — Minor
helios/src/output/tagged.rs:283–296:
if matches!(
cause,
Termination::Cancelled
| Termination::ExecutionError
| Termination::UserStop
| Termination::OutputLimit
) {
EosDecision::Omit
} else if !self.confirmed || self.in_json_string || self.in_value {
EosDecision::Reject
Before this PR ArgumentTags::parse_candidate returned Err("unterminated GLM argument value") (argument_tags.rs:85–87 old form) the moment the body ended inside an open <arg_value>, so a </tool_call> seen inside a value aborted the request; now IncompleteValue defers to EOS. On OutputLimit/UserStop/Cancelled/ExecutionError that yields an empty tool-call list (the new test asserts exactly this, argument_tags.rs diff tail) instead of the previous hard error. That is arguably the better outcome, but it is a user-visible change on the error/stop paths that the PR's "Compatibility notes" (a)/(b)/(c) do not mention. Fix: add it to the description, and consider whether OutputLimit truncation should still surface as an incomplete-call signal rather than silently vanishing.
6. Test coverage gaps for the new effort path — Minor
- No test exercises
Effort::Mediumthrough a Jinja template that lists bothmediumandhigh; the onlyMediumassertion is TMLv0 (decode.rs:2716).request.rs:521is therefore untested in the branch where the ladder order actually matters. - No test for unknown/non-string top-level Chat
reasoning_effort(see finding 3); thefor bad in [json!("bogus"), json!(50)]loop atdecode.rs:2643–2650covers only the nested spelling. kani_proofs.rs(not opened) was extended only foreos_decision/in_value;scan_value_end(the new non-default trait method that every dialect now depends on) has no proof or exhaustive-split test of its own, and the description confirmscargo kaniwas not run.- The 40,000-tag stress tests assert wall-clock-free behaviour (they complete), which is a reasonable proxy but does not pin the O(N) property against a future regression.
Areas checked and found sound
- Hot path / contention:
resolve_effort's six renders happen once perFrontendinsideOnceLock::get_or_init(frontend/mod.rs:843, field:799); per-request cost is a linear scan over ≤5 strings. No per-request render, no lock held across I/O, no new allocation inpushbeyond the existingStringbuffer. - Buffering / memory: the 1 MiB bound is retained and still evaluated on every push (
tagged.rs:328–331);buffer.drain(..search_from)onComplete(:397) andstd::mem::takeonfinish(:416) keep retention unchanged.in_valueadds onebooland never adds bytes. - Strictness preserved:
parse/parse_eosstill reject unterminated values (argument_tags.rs:107–113, 124–131;chatml.rs:129–135;gemma_call.rs:166–187), strict tools are still rejected at EOS, andin_valuefeedsEosDecision::Reject(tagged.rs:292). Effortvariant completeness: a repo-wide search showsEffortis matched exhaustively in exactly one place (request.rs:518–524); the newMediumvariant is handled there (:521) andOptions.effortis not serialized, so no wire/JSON contract changes.- Adjacent observation (not a blocker):
ToolDialect::JSON_BODY(tagged.rs:46–48) is stillfalsefor every dialect (only two occurrences repo-wide: the constant and:378), so JSON-string-embedded closing tags still reparse from byte 0 per candidate. The new docs sentence is correctly scoped to non-JSON values (docs/api.md:621–625), but the PR title's "O(N)" claim covers only that path.
Metric/rate/admission-pricing span check: this PR samples no rate, latency, or admission metric; the only admission error touched is the existing AdmissionError::Feature("prepared chat template does not accept the requested reasoning effort") (frontend/mod.rs:885–890, surfaced as unsupported_feature at server.rs:748 (not opened)), whose trigger set narrows (previously-rejected Qwen high/max now resolve) — a user-visible reduction in 400/unsupported responses, consistent with the description.
#2 [high] Finding 1 (Major): scan_value_end trait default is fail-open (Ok(0)), silently restores quadratic reparsing
Severity: Major. File: helios/src/output/tagged.rs:56-63 (trait default) + :350-361 (consumer).
Quote 1 (tagged.rs:56-63):
/// Advances linearly across an open non-JSON argument value after
/// Candidate::IncompleteValue. Returns Ok(advance) when a value-ending
/// boundary appears at tail[..advance] (resuming closer scanning at
/// tail[advance..]), or Err(safe_advance) to advance search_from past
/// bytes that cannot start a value-ending boundary and wait for more input.
fn scan_value_end(_tail: &str) -> std::result::Result<usize, usize> {
Ok(0)
}
Quote 2 (tagged.rs:350-361): if self.in_value { match D::scan_value_end(&self.buffer[self.search_from..]) { Ok(advance) => { self.search_from += advance; self.in_value = false; }
Verified trace: with the default, Ok(0) clears in_value and adds zero advance, so the loop re-selects the next closer at tagged.rs:367-374 and calls D::parse_candidate(&self.buffer[..end], ...) at :395 -> parse_body rescans from byte 0 and re-runs value.split_once("</arg_value>") (argument_tags.rs:85) = one full body parse per inner closing tag => O(N*K). Progression is guaranteed because :377 sets search_from = prev + consumed, so it is NOT an infinite loop (this corrects dossier key-finding 5's "spin forever" wording).
Why it matters: the default contradicts the documented contract (Ok = boundary found) and destroys the PR's central O(N) claim with no compile error, no failing test, and no Kani failure. Latent only because all three IncompleteValue dialects override: argument_tags.rs:117-123, chatml.rs:30-47, gemma_call.rs:176.
Fix: make the method required (no default) so a dialect emitting IncompleteValue cannot compile without a scanner; or fail closed (Err(tail.len())) and have push() treat advance==0 as Err.
Area checks that came out sound (for the report's "sound" section): 1 MiB bound still checked every push (tagged.rs:328-331); drains at :397 / mem::take at :416 unchanged; in_value adds one bool and never adds bytes; JSON_BODY is false for every dialect (only tagged.rs:46-48 and :378 repo-wide), so the docs sentence at docs/api.md:621-625 is correctly scoped to non-JSON values and the title's O(N) claim covers only that path.
#3 [high] Finding 2 (Major): resolve_effort sentinel-render heuristic can drop a genuinely accepted medium
Severity: Major. File: helios/src/frontend/mod.rs:843 (OnceLock get_or_init), :853-879 (probe), quote from :863-879.
Quote: let fallback = render("flare_unknown_effort"); let rendered: Vec<(&str, String)> = ["low", "medium", "high", "xhigh", "max"] .into_iter() .filter_map(|effort| render(effort).map(|out| (effort, out))) .collect(); let has_distinct = fallback .as_deref() .is_some_and(|fb| rendered.iter().any(|(_, out)| out != fb)); rendered .into_iter() .filter(|(effort, out)| { !has_distinct || *effort != "medium" || fallback.as_deref() != Some(out.as_str()) })
Impact A (false negative): a template that clamps unknown values to a default of medium — e.g. "{% set eff = reasoning_effort if reasoning_effort in ['low','medium','high'] else 'medium' %}" — renders medium and the sentinel identically, so medium is removed from the accepted set even though it is explicitly listed. Effort::Medium then resolves via request.rs:521 (&["medium","high"]) to "high", silently changing the prompt for a top-level Chat medium request. Impact B (false positive): a template mapping medium onto another valid level renders differently from the sentinel and keeps medium in the set; no level other than medium is ever dropped.
Test gap: the only vocabulary test is frontend/mod.rs:1742-1777 and uses raise-on-unknown templates, where render() returns None (frontend/mod.rs:853-862), has_distinct is false, and the filter never fires — i.e. the acting path is untested. docs/api.md:988-991 documents plain vocabulary matching and never mentions the flare_unknown_effort sentinel.
Fix: make acceptance explicit (recipe-declared vocabulary) or probe by absence + a value the template must reject, asserting on the raise rather than render equality; add a fallback-to-medium template test.
Perf contention note: the six renders run once per Frontend behind OnceLock; per-request cost is a linear scan of <=5 strings. No new lock held across I/O, no per-request render.