Subtraction and simplicity scratchpad · NVIDIA/hyperflare-inference #677

Raw Markdown for agents: https://autobot.eidonix.com/p/a455abc7-f071-4927-a970-02945a838dba.md

#1 [high] Research summary

Subtraction, Simplicity & Conventions review — PR #677 (head c897437)

The parser half of this PR (the Candidate enum replacing Option) is well shaped and mostly lean: it removes a boolean-mode flag in favour of a sum type, keeps one scan_value_end hook per dialect, and deletes dead match arms. The effort half is where the removable complexity sits. Five suggestions below, ordered by value; none are correctness bugs (already covered elsewhere).

1. scan_value_end's default arm is speculative generality and unsafe — make it fail-closed or delete it

helios/src/output/tagged.rs:56-63:

    /// ... Returns `Ok(advance)` when a value-ending
    /// boundary appears at `tail[..advance]` ... or `Err(safe_advance)` ...
    fn scan_value_end(_tail: &str) -> std::result::Result<usize, usize> {
        Ok(0)
    }

Only three dialects ever produce Candidate::IncompleteValue (argument_tags.rs:86, chatml.rs:207, gemma_call.rs:148), and all three override this. The default therefore exists for the four dialects that can never trigger it, and it is actively wrong: TaggedTools::push treats Ok as "the value ended" (tagged.rs:350-361), so Ok(0) adds zero progress, clears in_value, leaves search_from untouched, and the next loop iteration re-selects the same closer — an infinite loop the 1 MiB bound (tagged.rs:330) cannot catch. Minimum fix: change the default body to Err(0) ("no progress, wait for input"), which is correct and one line. Better: drop the default entirely and give MiniMaxXml, which never returns IncompleteValue, nothing to implement by making the hook Option-free only for the three dialects — but the one-token Err(0) default is the smallest correct answer.

2. The Chat effort normalization repeats its own vocabulary and its own predicate four times

helios/src/server/protocol/decode.rs:596-598, :622-627, :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")
            ));

The same six level names now live in two places: the match effort.as_str() arms at :614-628 and this matches! list, which a future editor must keep in sync by hand (add a name to the match, silently leak it to the template). The protocol == Protocol::Chat && !chat_nested_effort predicate is likewise spelled out at :596-598, :622, :627 and again at :677-682. Collapse both: bind let chat_top_level = protocol == Protocol::Chat && !chat_nested_effort; once, and have the match return (native, normalized) — e.g. Some("medium") if chat_top_level => (Some(Effort::Medium), true), _ if chat_top_level => (None, false), _ => (None, true) — then withheld_chat_effort = chat_nested_effort || normalized. That deletes the duplicated name list and three of the four predicate copies, and makes drift impossible.

3. Effort::Medium is a one-backend enum variant in shared code

helios/src/server/inference.rs:120-122 and helios/src/server/request.rs:521:

    /// Between low and high. Prompt formats without a distinct medium level render high effort.
    Medium,
                Effort::Medium => &["medium", "high"],

Effort is shared across Responses, Messages and the native DeepSeek encoders, but Frontend::resolve_effort already hard-restricts non-TML, non-Jinja encoders to low|high|xhigh|max (frontend/mod.rs:836-841), so &["medium", "high"] collapses to "high" everywhere except PromptEncoder::TmlV0 (frontend/mod.rs:829-835). Net effect: a new variant in a shared enum whose only distinguishable consumer is one prompt encoder — close to the "no per-model special cases; keep the runtime model-agnostic" line in AGENTS.md:338-364. A variant-free expression exists: keep Chat medium at Effort::High (decode.rs:625) and let request.rs:515-530, which already branches on frontend.prompt_encoder(), prefer the "medium" candidate for TMLv0 (its tml::effort_level already maps medium→0.7 per frontend/mod.rs:833). That removes inference.rs:120-122, the decode.rs:622-624 special arm, and the &["medium","high"] ladder, while keeping the documented 0.7/0.9 split.

4. The Candidate→error mapping is copied six times; hoist it onto Candidate

helios/src/output/gemma_call.rs:166-188 (both bodies identical but for the eos bool):

    fn parse(body: &str, tools: &[Value]) -> Result<Vec<(String, String)>> {
        match Self::parse_body(body, tools, false)? {
            Candidate::Complete(calls) => Ok(calls),
            Candidate::IncompleteValue => Err("unterminated tool call string".into()),
            Candidate::InJsonString => Err("incomplete JSON argument".into()),
        }
    }

and again at argument_tags.rs:107-113, :124-131, chatml.rs:129-134. Add one method on the type that already owns the variants (tagged.rs:31-37), e.g. impl Candidate { fn into_calls(self, incomplete: &str) -> Result<Vec<(String, String)>> }, and call Self::parse_body(..)?.into_calls("unterminated GLM argument value") at all six sites. The per-variant Complete/IncompleteValue/InJsonString triples collapse to one line each and the two Gemma bodies become one-liners, deleting ~30 lines and one whole class of copy-paste divergence.

5. ChatML now has two implementations of "where does the parameter value end"

helios/src/output/chatml.rs:30-47 (scan_value_end) and chatml.rs:197-208 (the in-parse_tool_candidate search):

        for (at, _) in tail.match_indices('<') {
            let suffix = &tail[at..];
            if let Some(rest) = parameter_end(suffix) {
                return Ok(at + suffix.len() - rest.len());
            }
            if parameter_start(suffix).is_some() || suffix.starts_with("</function>") {
                return Ok(at);
            }
        let Some((end, consumed)) = tail.match_indices('<').find_map(|(at, _)| {
            let suffix = &tail[at..];
            if let Some(rest) = parameter_end(suffix) {
                Some((at, suffix.len() - rest.len()))
            } else if parameter_start(suffix).is_some() || suffix.starts_with("</function>") {
                Some((at, 0))

The second copy only differs by folding possible_parameter_end/possible_parameter_start/</function> incompleteness into the same walk. Keep one function fn find_value_end(tail: &str) -> Result<(usize, usize), usize> and have parse_tool_candidate map its Err to Candidate::IncompleteValue; scan_value_end becomes find_value_end(tail).map(|(_, consumed)| consumed). Removes ~20 lines and the standing risk that the streaming scan and the batch parse disagree about what terminates a value. (While there: possible_parameter_end at chatml.rs:100-119 restates possible_parameter_start's <///parameter ladder; a shared prefix matcher would cut it in half.)

Lower-priority notes

Everything else I checked — the Candidate enum itself, the JSON_BODY/partial_marker reuse (tagged.rs:46-48, :959 now pub(super)), the Kani in_value extension, minimax_xml.rs:200-201 staying on the default parse_candidate — is lean and idiomatic; no dead code or leftover mutable-tracking flag remains from the earlier head.

#2 [high] PR #677 Subtraction/Simplicity lens — final findings (head c897437)

PR #677 (head c897437) — Subtraction, Simplicity & Conventions review

Verdict shape: parser half (Candidate enum) is lean and idiomatic; effort half carries the removable complexity. 5 ranked suggestions, no pure-correctness bugs (other lens).

1. scan_value_end default is speculative generality AND unsafe — helios/src/output/tagged.rs:56-63

    /// ... Returns `Ok(advance)` when a value-ending
    /// boundary appears at `tail[..advance]` ... or `Err(safe_advance)` ...
    fn scan_value_end(_tail: &str) -> std::result::Result<usize, usize> {
        Ok(0)
    }

Only 3 dialects ever return Candidate::IncompleteValue (argument_tags.rs:86, chatml.rs:207, gemma_call.rs:148) and all 3 override. Default Ok(0) is wrong: TaggedTools::push treats Ok as "value ended" (tagged.rs:350-361) → advance 0, clears in_value, doesn't move search_from, next iteration re-selects same closer = infinite loop; 1 MiB bound (tagged.rs:330) can't catch it (no bytes added). Fix: default body Err(0) (one line, correct) or drop default and require override on the 3 dialects.

2. Chat effort vocabulary + predicate duplicated 4x — decode.rs:596-598, :622-627, :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")
            ));

Six level names in 2 places (match arms :614-628 + this matches!) — must be hand-synced; add a name to the match and it silently leaks to the template. Predicate protocol == Chat && !chat_nested_effort spelled out at :596-598, :622, :627, :677-682. Fix: bind let chat_top_level = ... once; make the match return (native, normalized) e.g. Some("medium") if chat_top_level => (Some(Effort::Medium), true), _ if chat_top_level => (None, false), _ => (None, true); then withheld_chat_effort = chat_nested_effort || normalized. Deletes dup name list + 3 of 4 predicate copies.

3. Effort::Medium is a one-backend variant in shared code — inference.rs:120-122 + request.rs:521

    /// Between low and high. Prompt formats without a distinct medium level render high effort.
    Medium,
                Effort::Medium => &["medium", "high"],

resolve_effort restricts non-TML/non-Jinja encoders to low|high|xhigh|max (frontend/mod.rs:836-841), so &["medium","high"] collapses to "high" except for PromptEncoder::TmlV0 (frontend/mod.rs:829-835). Shared enum variant whose only distinguishable consumer is one prompt encoder — close to AGENTS.md:338-364 "no per-model special cases". Variant-free alternative: keep Chat medium → Effort::High (decode.rs:625) and let request.rs:515-530 (already branches on prompt_encoder()) prefer the "medium" candidate for TMLv0 (tml::effort_level already maps medium→0.7, frontend/mod.rs:833). Removes inference.rs:120-122, decode.rs:622-624, and the ladder; keeps documented 0.7/0.9 split.

4. Candidate→error mapping copied 6x — gemma_call.rs:166-188 (twice, identical but eos bool), argument_tags.rs:107-113 & :124-131, chatml.rs:129-134

    fn parse(body: &str, tools: &[Value]) -> Result<Vec<(String, String)>> {
        match Self::parse_body(body, tools, false)? {
            Candidate::Complete(calls) => Ok(calls),
            Candidate::IncompleteValue => Err("unterminated tool call string".into()),
            Candidate::InJsonString => Err("incomplete JSON argument".into()),
        }
    }

Fix: add impl Candidate { fn into_calls(self, incomplete: &str) -> Result<Vec<(String,String)>> } next to tagged.rs:31-37; call Self::parse_body(..)?.into_calls("...") at all 6 sites. ~30 lines gone, removes copy-paste divergence class.

5. ChatML has two implementations of "where the parameter value ends" — chatml.rs:30-47 vs chatml.rs:197-208

        for (at, _) in tail.match_indices('<') {
            let suffix = &tail[at..];
            if let Some(rest) = parameter_end(suffix) {
                return Ok(at + suffix.len() - rest.len());
            }
            if parameter_start(suffix).is_some() || suffix.starts_with("</function>") {
                return Ok(at);
        let Some((end, consumed)) = tail.match_indices('<').find_map(|(at, _)| {
            let suffix = &tail[at..];
            if let Some(rest) = parameter_end(suffix) {
                Some((at, suffix.len() - rest.len()))
            } else if parameter_start(suffix).is_some() || suffix.starts_with("</function>") {
                Some((at, 0))

Differ only by folding possible_parameter_end/possible_parameter_start/</function> incompleteness into the walk. Fix: one fn find_value_end(tail: &str) -> Result<(usize, usize), usize>; parse_tool_candidate maps Err→IncompleteValue, scan_value_end = find_value_end(tail).map(|(_, consumed)| consumed). ~20 lines + removes scan/parse disagreement risk. Also possible_parameter_end (chatml.rs:100-119) restates possible_parameter_start's <///parameter ladder — share a prefix matcher.

Lower priority

Confirmed lean (do not flag)

Candidate enum itself (tagged.rs:31-37); JSON_BODY/partial_marker reuse (tagged.rs:46-48, :959 pub(super)); Kani in_value extension (kani_proofs.rs diff +9/−3); minimax_xml.rs:200-201 stays on default parse_candidate; no leftover mutable-tracking flag from earlier head; minimax_xml.rs:460 test is new coverage not duplication-critical.