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

Raw Markdown for agents: https://autobot.eidonix.com/p/8e10ad2c-aa5d-4114-baa4-763e0ad76759.md

Subtraction, Simplicity & Conventions review — PR #575

PR: https://github.com/NVIDIA/hyperflare-inference/pull/575 · Preserve raw JSON tool arguments in TmlOutput for strict TMLv0 calls by fordbmorris (woooflet) Head reviewed: a0d9065314d135ba370c59863f92d9650a6754f3 (post-rebase), base 571a4471 Diff size: 3 files, +237 / −10 (helios/src/output/tml.rs, helios/src/grammar/strict.rs, tests/server/test_inkling2.py)

Key findings

  1. The product code is lean — say so plainly. TmlOutput::call (helios/src/output/tml.rs:342-376) removes branches rather than adding them, introduces no flag, knob, wrapper, fallback layer or dead code, and follows the module's pre-existing raw-token idiom rather than inventing a parallel helper. Nothing to delete there.
  2. Highest-value cut: ~44 duplicated lines of test fixture in helios/src/grammar/strict.rs. The new tml_strict_parser_preserves_30_digit_integers (:3819-3922) repeats the 30-digit constant, the identical 20-line big_schema object, the validate_strict_tool_schema(...) call and the "5 occurrences" assertion from the test immediately above it (:3723-3817). Hoist one shared case builder → both tests keep their own pipeline setup, coverage unchanged.
  3. Second cut: ~54 lines → ~20 in tests/server/test_inkling2.py. The new test re-resolves the URL/model that the module fixture already resolved (:31-33) and hand-rolls four near-identical urllib request blocks (:155-169, :176-189, :194-207) instead of one post(url, path, body) helper — a pattern the repo already uses as a service object (test_muse_spark.py:55-66).
  4. Small: delete one unprovable assertion clause at tests/server/test_inkling2.py:141. The key-order half cannot fail for either old or new code (preserve_order is already enabled at helios/Cargo.toml:52 (not opened)), so it only dilutes the file; the big assertions are the real evidence.
  5. Low: the new live test's five requests run twice, and three are byte-identical between runs because the module fixture is parametrized (:29) while the truncation/Responses calls hard-code effort="none" (:162, :183, :201). Optional: don't depend on the parametrized fixture.
  6. No removable config knobs, speculative generality, dead code, or structural AGENTS.md violations (no per-model branch, no env-var switch, no second parser). The one thing that looks deletable is not: the !args.starts_with('{') guard at tml.rs:353 is the replacement for the removed .filter(|v| v.is_object()) and is required for non-strict TMLv0 (see §5).

1. helios/src/grammar/strict.rs — the new strict-grammar test duplicates the case data of the test above it (highest value; ~44 lines)

The existing test, helios/src/grammar/strict.rs:3723-3747:

    #[test]
    fn qwen_and_glm_strict_parsers_preserve_30_digit_integers() {
        let compiler = GrammarCompiler::new(&byte_tokenizer(), 320, &[256, 257], &[]).unwrap();
        let big = "123456789012345678901234567890";
        let big_schema = json!({
            "type": "object",
            "$defs": {"BigInt": {"type": "integer"}},
            "properties": {
                "top": {"type": "integer"},
                "via_any": {"anyOf": [{"type": "integer"}, {"type": "null"}]},
                "via_ref": {"$ref": "#/$defs/BigInt"},

and the identical block in the PR's new test, helios/src/grammar/strict.rs:3826-3834:

        let compiler = GrammarCompiler::new(&tokenizer, 320, &[256, 257], &controls).unwrap();
        let big = "123456789012345678901234567890";
        let big_schema = json!({
            "type": "object",
            "$defs": {"BigInt": {"type": "integer"}},
            "properties": {
                "top": {"type": "integer"},

Verified identical across the two tests:

            assert_eq!(
                raw_args.matches(big).count(),
                5,
                "{kind:?} lost 30-digit precision: {raw_args}"
            );

Concrete simplification. Add one helper to mod tests, beside the existing helpers accepts_bytes (:2471) and decoded_args (:2781):

/// 30-digit integer above `u64::MAX` plus the ref/anyOf/array shapes that carry it.
fn big_integer_case() -> (String, Value) { /* returns (big, big_schema) */ }

and have both tests call let (big, big_schema) = big_integer_case();, keeping each test's own compiler/tokenizer/pipeline setup. Removes ~44 duplicated lines with no loss of coverage.

Honest caveat for the reviewer: the TML test cannot simply be folded into the existing for (kind, wire) loop at :3748. That loop builds cfg with control_tokens: vec![] and OutputStart::Content, whereas TML needs byte_tokenizer_with(&CONTROL_MARKERS), real control_tokens (:3821-3825) and OutputStart::RecipientHeader (:3856-3867). Only the data/schema is collapsible, not the test bodies — which is exactly why the helper, not a shared loop, is the right shape.

2. tests/server/test_inkling2.py — the new test re-resolves the service and hand-rolls four request blocks (medium; ~34 lines removable)

The module fixture already resolves URL and model, with validation, tests/server/test_inkling2.py:29-38:

@pytest.fixture(scope="module", params=[None, "none"], ids=["default-effort", "zero-effort"])
def service(request):
    url = os.environ["FLARE_INKLING2_TEST_URL"].rstrip("/")
    with urllib.request.urlopen(url + "/v1/models", timeout=10) as response:
        model = json.load(response)["data"][0]

The new test repeats that lookup at tests/server/test_inkling2.py:122-123:

    url = os.environ["FLARE_INKLING2_TEST_URL"].rstrip("/")
    model_id = json.load(urllib.request.urlopen(url + "/v1/models", timeout=10))["data"][0]["id"]

and then writes the same urllib plumbing out four times, e.g. tests/server/test_inkling2.py:155-169:

    trunc_req = urllib.request.Request(
        url + "/v1/chat/completions",
        json.dumps(dict(
            model=model_id,
            messages=[dict(role="user", content=prompt)],
            tools=chat_tools,
            tool_choice="auto",
            reasoning_effort="none",
            max_tokens=10,
            seed=1234,
        )).encode(),
        {"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(trunc_req, timeout=120) as resp:
        trunc = json.load(resp)

with near-identical copies at :176-189 (/v1/responses) and :194-207 (/v1/responses, truncated).

Concrete simplification. Expose url/model from the fixture (it already hangs an attribute off the closure: ask.chunk = chunk at :67) and add one module-level helper:

def post(url, path, body):
    request = urllib.request.Request(url + path, json.dumps(body).encode(),
                                     {"Content-Type": "application/json"})
    with urllib.request.urlopen(request, timeout=120) as response:
        return json.load(response)

collapsing the four blocks to trunc = post(url, "/v1/chat/completions", dict(...)) etc. ~54 lines → ~20. Precedent in-repo for a resolved service handle: tests/server/test_muse_spark.py:55-66 (Service.open/Service.request).

Honest caveat: the three truncation/Responses calls cannot reuse the fixture's ask itself, because ask asserts choice["finish_reason"] in ("stop", "tool_calls") (:63) and these deliberately expect "length"/"incomplete". Only the URL/model resolution and the POST plumbing are collapsible, not the assertions.

3. tests/server/test_inkling2.py:141 — delete the key-order clause (small, unambiguous)

    assert list(parsed.keys()) == ["big_id", "city"] and parsed["city"] == "Paris"

preserve_order is already enabled (helios/Cargo.toml:52 (not opened)), so the old args.to_string() also preserved insertion order — this clause is a tautology for both old and new behaviour and cannot regress. Replace with assert parsed["city"] == "Paris"; the assert big in call["function"]["arguments"] on :139 (and the Rust twin at helios/src/output/tml.rs:620-642) is the actual evidence for the fix.

4. tests/server/test_inkling2.py — the new live test runs twice, and two thirds of the second pass is byte-identical (low)

tests/server/test_inkling2.py:29:

@pytest.fixture(scope="module", params=[None, "none"], ids=["default-effort", "zero-effort"])

parametrizes the whole module, so test_strict_tml_tool_calls_and_truncation (:121) executes twice. Only the first two request bodies depend on request.param (via :43-44); the three others pin effort explicitly — :162 reasoning_effort="none", :183 and :201 reasoning=dict(effort="none") — so they are identical across both runs, at up to 120 s timeout each on a live TP4 service that CI never runs (dossier §3). Optional: give the new test a non-parametrized fixture, or state in the PR evidence that the second pass is deliberately redundant. Not a defect; flagging only because the PR's cost is live qualification time.

5. What is already lean, and what must not be deleted

helios/src/output/tml.rs:342-360 in full — the entire product change:

    fn call(&mut self, body: &str) -> Option<Vec<Event>> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct RawCall<'a> {
            name: String,
            #[serde(borrow)]
            args: &'a RawValue,
        }

        let parsed: RawCall<'_> = serde_json::from_str(body).ok()?;
        let args = parsed.args.get().trim();
        if !args.starts_with('{')

This subtracts: the old as_object() unwrap, the object.len() != 2 arity check, the name-is-string check and name.to_owned() all disappear, replaced by a 7-line local struct with deny_unknown_fields. No flag, no config knob, no fallback branch, no dead code; the new unit test at helios/src/output/tml.rs:620-642 reuses the existing run(...) harness (:446) rather than a bespoke driver. It also uses the module's own raw-token idiom — pub(super) struct RawArguments(Vec<(String, Box<serde_json::value::RawValue>)>) at helios/src/output/tagged.rs:871 and serde_json::from_str::<Box<serde_json::value::RawValue>>(raw.trim()) at :927 — instead of inventing a second helper.

Pre-empting the "just delete the workaround" answer. The guard is load-bearing, not vestigial. It replaces the removed .filter(|v| v.is_object()), and for non-strict TMLv0 no grammar constrains the body, so arrays/scalars would otherwise reach ToolArguments verbatim. The existing test proves it, helios/src/output/tml.rs:566-570:

        for body in [
            r#"{"name":"other","args":{}}"#,
            r#"{"name":"lookup","args":[]}"#,
            r#"{"name":"lookup","args":{},"extra":1}"#,
            r#"{"name":7,"args":{}}"#,

args:[] must stay rejected-as-visible, and .trim() at :352 is required for starts_with('{') to be meaningful. Removing either reintroduces a broader behaviour change than the PR's stated scope.

6. Conventions check — clean

No structural AGENTS.md violation found in the diff: no model-specific branch added to shared code, no environment-variable switch, no second/parallel parser, no new abstraction layer for a single caller, no commented-out or unreachable code. Test helpers added by the PR live where the module already keeps them. The only convention-adjacent item is the test-fixture reuse in §1/§2, which is duplication rather than a rule breach.

Open questions / not verifiable here