Correctness, Contracts & System-Level Consequences review — PR #677 (head c897437)
Scope: the full diff of all 11 changed files plus the direct callers and contracts I could open in context — helios/src/output/tagged.rs (trait 39–72, eos_decision 283–297, TaggedTools::push 323–413, finish 414–429), output/argument_tags.rs:20–140, output/chatml.rs:1–140, output/gemma_call.rs:100–190, server/protocol/decode.rs:170–235, 590–710, server/request.rs:456–568, server/inference.rs:110–175, frontend/mod.rs:790–900 (+ diff), docs/api.md:600–640, 960–1010. Dossier items are used only where marked as such.
Key findings
- Major —
ToolDialect::scan_value_end's trait default isOk(0), i.e. fail-open: a dialect that emitsCandidate::IncompleteValuewithout overriding it silently reverts the parser to one full body re-parse per inner closing tag, destroying the PR's central O(N) claim with no compile error, no test failure, and no Kani failure. (helios/src/output/tagged.rs:56–63+:350–361) - Major — the new effort resolution is a sentinel-render heuristic:
mediumis dropped from the accepted vocabulary whenever its render equals the__flare_unknown_effort__render, so a template that clamps unknowns to amediumdefault loses a level it actually supports; the acting path is untested and the sentinel is undocumented. (helios/src/frontend/mod.rs:863–879) - Minor — unknown/non-string top-level Chat
reasoning_effortis forwarded verbatim intooptions.templatewhile the nested spelling returns 400, contradictingdocs/api.md:984–987and the charter's #417 "never accept and quietly forward/drop" rule. (decode.rs:606–607, 627, 677–682) - Minor — the same OpenAI field spelled two ways now produces two different prompts on Inkling 2: top-level
"medium"→Effort::Medium→ TMLv00.7, nestedreasoning.effort:"medium"on the same Chat endpoint →Effort::High→0.9. (decode.rs:622–625,request.rs:521–522) - Minor — with
IncompleteValuedeferring to EOS, an unterminated non-JSON argument value onOutputLimit/UserStop/Cancelled/ExecutionErrornow yields an empty tool-call list rather than an error; that behaviour is documented (docs/api.md:636–638) but absent from the description's compatibility notes. (tagged.rs:283–296) - Minor — test gaps: no test of
Effort::Mediumthrough a Jinja template, none for unknown top-level Chat effort, andkani_proofs.rs(not opened) was not executed. (decode.rs:2643–2650,frontend/mod.rs:1742–1777)
Everything else I checked — hot-path contention, buffer bounds, strict-tool rejection, Effort exhaustiveness, wire/schema stability, and the metric/admission span — is sound; see the last section.
1. Correctness, Safety & Platform Parity
1.1 scan_value_end's default is fail-open and silently restores quadratic re-parsing — 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]` (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)
}
helios/src/output/tagged.rs:350–361 consumes it, treating 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;
}
Err(advance) => {
self.search_from += advance;
return Ok(Progress::default());
}
}
}
Trace (verified against the surrounding loop, not inferred): with the default, Ok(0) clears in_value and adds nothing, the loop re-selects the next closer at tagged.rs:367–374, and calls D::parse_candidate(&self.buffer[..end], &self.tools)? at :395, which for GLM re-runs parse_body from byte 0 and re-scans the value with value.split_once("</arg_value>") (argument_tags.rs:85). One full body parse per inner closing tag ⇒ O(N·K), exactly the failure mode the PR claims to fix.
Correction to the dossier's key finding 5: this is not an infinite loop — :377 sets self.search_from = prev + consumed before parse_candidate, so the loop always advances. The real consequence is a silent performance regression for any future dialect, hidden behind a default that contradicts the documented contract (Ok = boundary found).
Why it can regress unnoticed: the three production dialects that can return IncompleteValue all override it today — argument_tags.rs:117–123, chatml.rs:30–47, gemma_call.rs:176–181 — so nothing fails, and the Ok(0) default means a fourth dialect compiles and passes tests.
Fix: remove the default so the method becomes required (a IncompleteValue-capable dialect then cannot compile without a scanner); if a default is kept, make it fail-closed (Err(tail.len())) and have push treat advance == 0 as Err.
1.2 resolve_effort's sentinel heuristic can drop a level the template genuinely accepts — Major
helios/src/frontend/mod.rs:863–879 (new in this PR):
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())
})
Acceptance is inferred from rendered-text equality with a magic unknown string, and only medium is ever filtered.
- False negative (the real hazard): a template that clamps unknown values to its own default — e.g.
{% set eff = reasoning_effort if reasoning_effort in ['low','medium','high'] else 'medium' %}— rendersmediumand__flare_unknown_effort__identically, somediumis removed fromacceptedeven though the template lists it.Effort::Mediumthen falls through the ladder&["medium","high"](request.rs:521) to"high", silently changing the prompt for a top-level Chatmediumrequest. This is the exact class of template the PR is trying to handle (aelse 'medium'fallback is as plausible as GLM'selse 'max'). - False positive: a template that maps
mediumonto another valid level renders differently from the sentinel, somediumstays accepted — the heuristic cannot distinguish "supported" from "aliased". - Untested where it acts: the only vocabulary test (
frontend/mod.rs:1742–1777, unchanged) uses raise-on-unknown templates, whererender()returnsNone(:853–862),fallbackisNone,has_distinctisfalse, and the filter never fires. - Undocumented:
docs/api.md:988–991describes plain vocabulary matching ("Qwen useslow/medium/xhigh… GLM and Kimi templates uselow/high/max") and never mentions render-equality probing.
A related behaviour worth naming: because accepted is a set of every level that renders without error, the PR's own guarantee only holds for templates that make unknown values fail or fall through — the description's claim that "fallback-branch templates … exclude fallback-only medium" is true only for fallbacks that are not medium.
Fix: make acceptance explicit (have the recipe declare its effort vocabulary, or probe by rendering with reasoning_effort absent plus a value the template must reject, asserting on the raise rather than string equality); add a fallback-to-medium template test; document the mechanism in docs/api.md.
1.3 Unknown / non-string top-level Chat reasoning_effort is forwarded verbatim — Minor
helios/src/server/protocol/decode.rs:606–607, 627:
body.get("reasoning_effort").filter(|v| v.is_string())
…
_ if protocol == Protocol::Chat && !chat_nested_effort => None,
_ => return Err("unsupported reasoning effort".into()),
and :677–682:
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" (string), true, or {} at the top level on /v1/chat/completions neither errors nor is normalized/withheld; it lands in options.template raw at :693–695, where it reaches the template verbatim. docs/api.md:984–987 says only "xhigh, numeric scores, and chat_template_kwargs overrides" pass through directly, so code and documentation disagree, and a garbled value silently poisons the prompt — the pattern the charter's #417 ("Don't silently ignore API fields … never accept it and quietly drop it") targets.
Fix: either return the existing unsupported reasoning effort error for unknown top-level Chat strings (matching the nested path), or document raw pass-through explicitly and add a test pinning it.
2. Unintended system-level consequences
2.1 Hot-path cost: sound. The six probe renders run once per Frontend inside OnceLock::get_or_init (frontend/mod.rs:843, field :799), so per-request work is a linear scan over ≤5 strings (:881–890). No per-request template render, no lock held across I/O, no new allocation in TaggedTools::push beyond the existing String buffer. Startup cost is six extra renders per core — negligible but unmeasured (see open questions).
2.2 Buffering / memory: unchanged. The 1 MiB bound is still evaluated on every push (tagged.rs:328–331); buffer.drain(..search_from) on Complete (:397) and std::mem::take on finish (:416) keep retention identical. in_value adds one bool and never adds bytes, so the bound cannot be evaded by the new state.
2.3 Failure-propagation blast radius: unchanged. in_value participates in EosDecision::Reject (tagged.rs:292), so a truncated call still fails the request rather than emitting a partial tool call, and parse/parse_eos still reject unterminated values (argument_tags.rs:107–113, 124–131; chatml.rs:129–135; gemma_call.rs:166–187). The new state is per-TaggedTools (per-request), not shared, so no cross-request poisoning.
2.4 Behaviour change on the stop/error paths — 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
IncompleteValue is a new state that defers the error to EOS, and EOS on OutputLimit/UserStop/Cancelled/ExecutionError is Omit. So a request truncated in the middle of a non-JSON argument value now returns an empty tool-call list with no error signal, where the erstwhile "parse everything before the closer" path surfaced an incomplete-call error. This is documented behaviour (docs/api.md:636–638: "unclosed arguments … and calls cut off by output limits or stop sequences are never recovered") and arguably the better outcome, but the description's Compatibility notes (a)/(b)/(c) do not mention it. (I could not diff the pre-PR argument_tags.rs directly because the file was rebased over #670; the claim is derived from the retained parse arm at argument_tags.rs:107–113, not from the old file.) Fix: add it to the compatibility notes; consider whether OutputLimit should still surface an incomplete-call signal rather than silently yielding zero calls.
2.5 Adjacent observation (not a blocker): ToolDialect::JSON_BODY (tagged.rs:46–48) remains false for every dialect, so closing tags inside JSON-string bodies still reparse from byte 0 per candidate. The 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.
3. Architecture, contracts & charter compliance
3.1 Wire/proto/captured-graph contracts: unchanged. Effort is matched exhaustively in exactly one place (request.rs:518–524), the new Medium variant is handled there (:521), and Options.effort is not serialized (inference.rs:153), so no wire schema or graph contract changes. The Effort::Medium doc comment is honest about degradation: "Between low and high. Prompt formats without a distinct medium level render high effort." (inference.rs:121–122).
3.2 Two spellings, two prompts — Minor. decode.rs:622–625:
Some("medium") if protocol == Protocol::Chat && !chat_nested_effort => {
Some(Effort::Medium)
}
Some("medium" | "high") => Some(Effort::High),
with request.rs:521–522:
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 at decode.rs:2716 vs :2723–2726 per the dossier/tests). For any Jinja template that accepts both medium and high, the ladder order also flips the resolved level purely by spelling. The divergence is deliberate and documented (docs/api.md:991–993), but it is a new internal contract inconsistency introduced here; it deserves explicit maintainer sign-off rather than a docs footnote, or the nested spelling should match the top-level one on Chat only.
3.3 Layer/charter fit: the change resolves effort against the prepared encoder vocabulary rather than adding model-specific branches in helios request handling, which is consistent with the charter's "keep the runtime model-agnostic" rule. The parser change is dialect-generic (Candidate + scan_value_end), also consistent. The outstanding fit concern from earlier reviews stands: two independent fixes (decode/effort and output/parser) remain bundled in one PR, which the author has not split.
3.4 Metric / rate / admission-pricing span check: this PR samples no rate, latency, or admission metric. The only admission surface touched is AdmissionError::Feature("prepared chat template does not accept the requested reasoning effort") (frontend/mod.rs:885–890), whose trigger set narrows (previously-rejected Qwen high/max now resolve) — a user-visible reduction in 400/unsupported responses, consistent with the description. No span shrinks from end-to-end to a sub-operation, and no rank/shard scoping changes.
4. Tests & claim accuracy
- No Jinja test of
Effort::Medium. The onlyMediumassertion is TMLv0 (decode.rs:2716per dossier; Chatmedium≡ numeric0.7).request.rs:521's ladder order — the branch wheremediumvshighactually matters — is untested for Jinja, which is precisely the path affected by finding 1.2. - Negative tests only cover the nested spelling.
decode.rs:2643–2650(for bad in [json!("bogus"), json!(50)]) wraps the value in"reasoning": {"effort": …}; the top-levelreasoning_effortequivalents described in finding 1.3 are untested. - Kani/mutants not run (stated in the description).
tagged/kani_proofs.rs(not opened) was extended forin_value/eos_decision, butscan_value_end— the new method every dialect depends on — has no proof and no case added to the proof harness. Given finding 1.1, that is the method most worth a proof or at least an exhaustive-split test. - The 40,000-tag stress tests ("linear-scan stress") assert completion, not asymptotic behaviour, so they do not pin O(N) against a future regression — notably they would not catch the
Ok(0)default of finding 1.1. - Claim accuracy: the description's behavioural before/after claims I could check against the diff are accurate — the alias precedence (
decode.rs:184–192), the withheld set (:677–682),xhighpassthrough (:627+ docs:984–987), and the TMLv0 0.7/0.9 split (docs/api.md:991–993) all match. External GPU/BFCL evidence claims were removed rather than substantiated; in-tree Rust tests back the behavioural claims.
Areas checked and found sound
- Concurrency/contention:
resolve_effort's probes run once perFrontendbehindOnceLock; no per-request renders, no new lock ordering, no shared mutable state introduced. - Memory amplification: 1 MiB bound checked every push (
tagged.rs:328–331); drain/mem::takediscipline unchanged;in_valueadds onebooland never bytes. - Strictness preserved:
parse/parse_eosstill reject unterminated values,in_valuefeedsEosDecision::Reject, and strict-schema rejection (strict_nonstring_raw,argument_tags.rs:40–46, 88–92) is untouched. - Alias scoping: assistant-only alias reads with
reasoning_contentfirst and non-null filtering (decode.rs:184–192) match the docs (docs/api.md:979–981); non-string aliases error naming the offending field, and the earlier "across roles" concern is correctly narrowed. Effortexhaustiveness: one match site, no serialized representation, no downstream match to update.
Open questions / could not verify
- Does the sentinel probe cost anything measurable at startup per core, and is a
__flare_unknown_effort__render safe for templates thatraise_exceptionon unknown values? (Code path saysrenderreturnsNoneon error,has_distinct = false, somediumis never dropped — the heuristic is inert precisely in the tested case.) - Should
scan_value_endbe a required method rather than defaulting toOk(0)? A reviewer should press this, or ask foradvance == 0⇒Errinpush. - Does docs PR #172 (which states named-effort resolution as Responses/Messages-only, GLM as
low/highelsemax) need rewriting before this merges, to avoid publishing two contradictory effort sections? - I did not run the test suite; the stated CPU counts (1,841 unit / 62 integration,
tml_tests6/6, flare 254, flare-cli 245) and the Kani gap are unverified here. - The pre-PR shape of
argument_tags.rs/chatml.rs(post-#670 rebase) was not directly comparable, so finding 2.4 is derived from the retainedparsearms rather than a diff of the old parsers.