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

Raw Markdown for agents: https://autobot.eidonix.com/p/bdc6725c-a204-4258-a177-aeaae8eda5b0.md

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

Key findings

The output/parser half of this PR is already lean and idiomatic — the Candidate enum replaces a boolean mode flag with a sum type, one scan_value_end hook per dialect, dead match arms deleted, the #670 helpers (JSON_BODY, partial_marker) reused rather than re-implemented, and no leftover mutable tracking flag from the earlier head. Nothing there needs deleting.

The effort half carries all the removable complexity. Five ranked simplifications, none of which is a pure correctness bug (those belong to the Correctness & Contracts lens), but two of which (1 and 2) also happen to remove a latent hazard, so they double as cleanups:

  1. scan_value_end's trait default is speculative generality and wrong — delete or make it fail-closed (one line).
  2. Chat effort normalization spells its six-name vocabulary and its protocol == Chat && !chat_nested_effort predicate twice/四 times — collapse into one binding and one match returning (native, normalized).
  3. Effort::Medium is a new variant in a shared enum whose only distinguishable consumer is one prompt encoder (TmlV0) — expressible without a variant.
  4. The Candidate→Err mapping is hand-copied six times — one Candidate::into_calls method deletes ~30 lines.
  5. ChatML now has two near-identical implementations of "where does a parameter value end" — fold into one find_value_end.

Lower priority: ~250 lines of triplicated parser test scaffolding, and the PR still bundles two independent defects.


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:

    /// 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)
    }

Only three dialects ever produce Candidate::IncompleteValue — ArgumentTags (output/argument_tags.rs:86), FunctionTags (output/chatml.rs:207) and GemmaCall (output/gemma_call.rs:148) — and all three already override scan_value_end (argument_tags.rs:117-123, chatml.rs:30-47, gemma_call.rs:176-181). The default therefore exists solely for the dialects that can never trigger it.

It is also actively wrong. TaggedTools::push treats Ok as "the value ended", helios/src/output/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;
                    }
                    Err(advance) => {
                        self.search_from += advance;
                        return Ok(Progress::default());
                    }
                }
            }

With the default Ok(0): search_from advances by zero, in_value is cleared, the next loop iteration re-finds the same closer, and push spins forever. The 1 MiB bound at tagged.rs:329-330 cannot catch it because no bytes are appended on the looping iterations. It is safe today only by convention.

Concrete simplification: change the default body to Err(0) — "no progress, wait for input" — which is correct for any dialect that never emits IncompleteValue (it is unreachable for them) and fail-closed for any that does. Alternatively drop the default entirely and require the three dialects to implement it; then MiniMaxXml, which stays on the default parse_candidate (output/minimax_xml.rs:200-201), has nothing to add. The one-token Err(0) is the smallest correct answer.

2. Chat effort normalization repeats its own vocabulary and its own predicate

helios/src/server/protocol/decode.rs: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 also live in the match arms at decode.rs:613-629:

        let native = match effort.as_str() {
            Some("none") => {
                options
                    .template
                    .insert("enable_thinking".into(), false.into());
                None
            }
            Some("minimal") => Some(Effort::Minimal),
            Some("low") => Some(Effort::Low),
            Some("medium") if protocol == Protocol::Chat && !chat_nested_effort => {
                Some(Effort::Medium)
            }
            Some("medium" | "high") => Some(Effort::High),
            Some("xhigh" | "max") => Some(Effort::Max),
            _ if protocol == Protocol::Chat && !chat_nested_effort => None,
            _ => return Err("unsupported reasoning effort".into()),
        };

A future editor who adds a name to the match must hand-sync the matches! list, and if they miss it the level silently leaks verbatim into options.template at decode.rs:690-695; conversely the protocol == Protocol::Chat && !chat_nested_effort predicate is spelled out four times (decode.rs:596-598, :622, :627, :677-682).

Concrete simplification: bind the predicate once — let chat_top_level = protocol == Protocol::Chat && !chat_nested_effort; (replacing decode.rs:596-598 and the two guards) — and have the match return a pair:

Some("medium") if chat_top_level => (Some(Effort::Medium), true),
_ if chat_top_level => (None, false),
_ => (None, true),

with withheld_chat_effort = chat_nested_effort || normalized at :677. That deletes the duplicated name list and three of the four predicate copies, and makes drift structurally impossible.

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

helios/src/server/inference.rs:116-125:

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Effort {
    /// Below low. Prompt formats without a minimal level render low effort.
    Minimal,
    Low,
    /// Between low and high. Prompt formats without a distinct medium level render high effort.
    Medium,
    High,
    Max,
}

and helios/src/server/request.rs:518-524:

            let candidates: &[&str] = match effort {
                Effort::Minimal => &["minimal", "low"],
                Effort::Low => &["low"],
                Effort::Medium => &["medium", "high"],
                Effort::High => &["high", "medium"],
                Effort::Max => &["max", "xhigh", "high", "medium"],
            };

Effort is the shared request vocabulary for Responses, Messages and the native DeepSeek encoders, yet Frontend::resolve_effort already hard-restricts every non-TML, non-Jinja encoder to low|high|xhigh|max (helios/src/frontend/mod.rs:836-841):

        if self.prompt_encoder != PromptEncoder::Jinja {
            return candidates
                .iter()
                .copied()
                .find(|level| matches!(*level, "low" | "high" | "xhigh" | "max"))

so the &["medium", "high"] ladder can only ever yield "medium" for PromptEncoder::TmlV0, whose tml::effort_level already maps medium → 0.7 (frontend/mod.rs:829-835). Net: a new variant in a shared enum whose sole distinguishable consumer is one prompt encoder — close to the AGENTS.md:345 line against "per-model algorithms" and the AGENTS.md:356 warning about per-model flags in shared paths.

Concrete simplification: keep Chat medium → Effort::High (i.e. revert the special arm at decode.rs:622-624 to the existing Some("medium" | "high") => Some(Effort::High)) and let request.rs:515-530, which already branches on frontend.prompt_encoder() via resolve_effort, prefer the "medium" candidate when the encoder is TmlV0. That removes inference.rs:121-122, the decode.rs:622-624 arm and the &["medium","high"] ladder — three edits instead of a new shared-enum variant — while preserving the documented TMLv0 0.7 / Responses 0.9 split (docs/api.md:991-993).

4. The Candidate → error mapping is copied six times

helios/src/output/gemma_call.rs:166-188 — two 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 gemma_call.rs:182-188, argument_tags.rs:107-113, argument_tags.rs:124-131, chatml.rs:129-134 (parse_tool). Six copies, each a three-arm Complete/IncompleteValue/InJsonString triple differing only in message text.

Concrete simplification: add one method on the type that already owns the variants (helios/src/output/tagged.rs:31-37), e.g. impl Candidate { fn into_calls(self, incomplete: &str) -> Result<Vec<(String, String)>> } with the fixed InJsonString message, then write Self::parse_body(body, tools, false)?.into_calls("unterminated GLM argument value") at each site. ~30 lines go, and one whole class of copy-paste divergence (the GLM and ChatML parse_eos variants at argument_tags.rs:124-131, chatml.rs:48-50 already fold two variants together differently) disappears.

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

helios/src/output/chatml.rs:30-47 (streaming scan):

    fn scan_value_end(tail: &str) -> std::result::Result<usize, usize> {
        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);
            }
            if possible_parameter_end(suffix)

versus chatml.rs:197-208 (batch parse inside parse_tool_candidate):

        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))
            } else {
                None
            }
        }) else {
            return Ok(Candidate::IncompleteValue);
        };

Same walk over < occurrences, same parameter_end / parameter_start / </function> predicates; the second copy just folds the possible_parameter_* incompleteness cases into the same closure and can no longer report Err(safe_advance). Two implementations of one rule is the standing risk that the streaming scan and the batch parse disagree about what terminates a value.

Concrete simplification: one fn find_value_end(tail: &str) -> Result<(end, consumed), usize>; scan_value_end becomes find_value_end(tail).map(|(_, consumed)| consumed), and chatml.rs:197-208 becomes find_value_end(tail) with Err(_) => return Ok(Candidate::IncompleteValue). ~20 lines removed and one source of truth. While there: possible_parameter_end (chatml.rs:100-119) restates the same < / optional / / parameter ladder as possible_parameter_start (chatml.rs:85-98) — a shared prefix matcher (strip_prefix('<') → trim → optional strip_prefix('/') → "parameter".starts_with(..) / strip_prefix("parameter")) would halve both.


Lower-priority notes

Open questions

What I could not verify