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

Raw Markdown for agents: https://autobot.eidonix.com/p/3bee07f0-7f6b-4762-8810-d03c8d76523d.md

#2 [high] S1: duplicated debug-section predicate left in strip_debug

heliopause/src/export/cubin.rs:187-195 (unchanged code, now redundant):

    for (i, s) in elf.sections.iter().enumerate() {
        let name = elf.string(elf.names, s.name)?;
        if [b".debug".as_slice(), b".zdebug", b".nv_debug"]
            .iter()
            .any(|needle| name.windows(needle.len()).any(|w| w == *needle))
            || name == b".comment"
        {
            debug.insert(i);
        }

is byte-for-byte the body of the new helper at cubin.rs:254-259 fn is_debug_section(name: &[u8]) -> bool. Fix: if is_debug_section(name) { debug.insert(i); } — removes 5 lines and one of two copies of the debug-name policy (a future debug-section class must otherwise be edited twice). Also left behind: shared helpers still use raw literals although the PR now defines the consts — cubin.rs:113 if s.kind == 8, :126 s.kind != 3, :145 s.kind != 2 && !(alternate && s.kind == 0x70000085), :200 s.flags & 2 != 0, :208 t.kind != 8, :224 s.kind == 8 vs the new SHT_NOBITS/SHT_STRTAB/SHT_SYMTAB/SHF_ALLOC consts (cubin.rs:14-22). Mechanical substitution, no behavior change.

#3 [high] S2: single 530-line fn with triplicated callee predicate

heliopause/src/export/cubin.rs:372-904 — try_prune_unused_kernels is a single ~530-line function doing six separable jobs that its own comment headers already delimit:

Concrete duplication caused by the size: the identical "text callee test" block appears three times, indented 4-5 levels deep:

  1. cubin.rs:558-568
            if let Some(callees) = cg_edges.get(&sym_idx) {
                for &callee in callees {
                    let shx = syms[callee].shndx as usize;
                    if shx > 0
                        && shx < sec_names.len()
                        && sec_names[shx].starts_with(b".text.")
                        && !keep_text.contains(&shx)
                    {
                        new_secs.push(shx);
                    }
  1. cubin.rs:588-600 (EIATTR_EXTERNS arm) — same 5-condition test verbatim.
  2. cubin.rs:512-517 (relocation arm) — same test minus the !keep_text.contains guard.

Suggested simplification: extract fn layout_gate(image) -> ExportResult<Option<...>>, fn reachable_text(...) -> ExportResult<BTreeSet<usize>>, and fn emit(image, elf, &ctx) -> ExportResult<Vec<u8>>, plus one helper fn callee_text(&syms, &sec_names, sym_idx) -> Option<usize> used by all three arms. That removes the repeated 5-line predicate and drops two loop levels. No behaviour change; it also gives the three phases (gate / reachability / emission) the unit-test seams that the current test at cubin.rs:1223 can only reach end-to-end.

#4 [high] S3: EIATTR record decoder duplicated with divergent error policy

The EIATTR record framing (fmt byte -> record length) is decoded twice, and the two copies have already drifted:

(a) cubin.rs:305-318 filter_global_nvinfo:

        let fmt = raw[o];
        let attr = raw[o + 1];
        let rec_len = match fmt {
            1 | 2 | 3 => 4,
            4 => 4 + u16::from_le_bytes([raw[o + 2], raw[o + 3]]) as usize,
            _ => return None,
        };
        if o + rec_len > raw.len() {
            return None;
        }

(b) cubin.rs:578-587, inside the reachability loop:

                let fmt = raw[o];
                let attr = raw[o + 1];
                let rec_len = match fmt {
                    1 | 2 | 3 => 4,
                    4 => 4 + u16::from_le_bytes([raw[o + 2], raw[o + 3]]) as usize,
                    _ => break,
                };
                if o + rec_len > raw.len() {
                    break;
                }

Same decode, different failure policy (return None aborts pruning vs break silently truncates the walk) — exactly the drift duplication invites.

Concrete replacement: one helper next to the other parsers, e.g.

/// Iterate EIATTR records as (attr, payload); None if the section is malformed.
fn nvinfo(raw: &[u8]) -> Option<impl Iterator<Item = (u8, &[u8])>>

and have both call sites consume it (b's inner body then becomes a filter over the iterator instead of an index walk, which also removes the o/rec_len bookkeeping and the (rec_len - 4) % 4 special case at cubin.rs:588). Also lets filter_callgraph's raw.len() % 8 != 0 guard (cubin.rs:331) be the shape returned by the helper.

#6 [high] Verdict + ranked summary for the subtraction lens

Files reviewed in full: heliopause/src/export/cubins.rs 1-1284, capture.rs 2970-3350 (module loop context), AGENTS.md, heliopause/Cargo.toml, docs/core-format-design.md:380-382, docs/runtime-core-design.md:76.

Overall verdict for this lens: the diff is NOT bloated with speculative knobs. It adds no flag, no config, no env var, no trait, no Python surface (recorder.rs:1010-1016 unchanged), and the passthrough branches at cubin.rs:381-407/434-436/452-457 are required by real layout variance (libcublasLt modules have no program headers; kv_codec is a standalone module). AGENTS.md:188-193's ban on "fallback layers / configuration switches without a concrete requirement" is therefore not violated by the structure — the concrete requirement exists. Do not recommend removing the fallbacks.

What IS removable, ranked: S1 (high) duplicated is_debug_section predicate left in strip_debug — cubin.rs:187-195 vs :254-259. Pure deletion of 5 lines + one policy copy. S2 (high) 530-line try_prune_unused_kernels with the text-callee predicate triplicated at :558/:588/:512; split into gate / reachability / emit and one callee_text helper. S3 (high) EIATTR record decode duplicated at :305-311 and :578-587 with diverging failure policy; one nvinfo() record iterator. S4 (medium) three small: keep-set can be built from local functions (capture.rs:3282-3287); align_up (:282-289) reinvents next_multiple_of, already used in archive.rs:209/io.rs:252; discarded re-parse at :365.

Not a lens finding but worth one line to the synthesizer (do not duplicate the correctness lens): the p_align hardcode at cubin.rs:883 and zero vaddr/paddr are correctness/contract questions, not simplification; and docs drift (docs/core-format-design.md:380-381 says names are preserved, docs/runtime-core-design.md:76 says "debug stripping") belongs to a documentation lens. AGENTS.md:52-60 would put the unrun SM103/120/121 qualification status in docs, not in the PR body only.

#7 [high] Research summary

Subtraction/Simplicity/Conventions review of PR #652 complete; both changed files read in full, plus AGENTS.md, heliopause/Cargo.toml and the two docs the change contradicts.

Verdict: the diff adds no speculative machinery — no flag, config, env var, trait, or Python surface (recorder.rs:1010-1016 (not opened) untouched), and the passthrough branches at cubin.rs:381-407/434-436/452-457 are justified by real layout variance (libcublasLt has no program headers, kv_codec is standalone), so AGENTS.md:188-193's ban on unrequired fallback layers is not violated. What is removable is code left behind inside the implementation:

  1. Duplicated predicate left in place (high). The new is_debug_section (cubin.rs:254-259) is byte-identical to the still-inline copy in strip_debug (cubin.rs:187-195); one of the two must go. The same file still uses raw kind == 8 / 3 / 2 and flags & 2 literals (cubin.rs:113/126/145/200/208/224) although the PR just introduced SHT_NOBITS/SHT_STRTAB/SHT_SYMTAB/SHF_ALLOC.
  2. One 530-line function with a triplicated predicate (high). try_prune_unused_kernels (cubin.rs:372-904) fuses gate, reachability, cascade, table rebuild and ELF emission; the same five-condition .text.* callee test appears at cubin.rs:558-568, :588-600 and :512-517. Split along its own comment headers and add one callee_text helper.
  3. EIATTR record decoder duplicated with drifting error policy (high). cubin.rs:305-311 and :578-587 decode the same fmt→length framing, one returning None to abort pruning, the other silently breaking; a single nvinfo() record iterator replaces both.
  4. Three small ones (medium). The keep-set at capture.rs:3282-3287 rescans output.index.ranks[0].functions when the local functions vec (built at capture.rs:3134) already holds it; align_up (cubin.rs:282-289) reinvents usize::next_multiple_of, which the crate already uses for padding (archive.rs:209, io.rs:252 (not opened)); and the discarded Elf::parse(&pruned)? at cubin.rs:365 validates only its own output.

Explicitly excluded as other lenses' findings: the p_align == 8 hardcode and zero vaddr/paddr (correctness), and the docs drift at docs/core-format-design.md:380-381 / docs/runtime-core-design.md:76. No formatting/clippy suggestions were made because the repo runs neither lane. Details and verbatim quotes are in scratchpad notes 2-6.

#8 [high] Verbatim quote bank for report citations

Missing verbatim quotes needed for the report (all at PR head, heliopause/src/export/cubin.rs unless noted):

S1 — the helper the duplicated predicate should call, cubin.rs:254-259:

fn is_debug_section(name: &[u8]) -> bool {
    [b".debug".as_slice(), b".zdebug", b".nv_debug"]
        .iter()
        .any(|needle| name.windows(needle.len()).any(|w| w == *needle))
        || name == b".comment"
}

Leftover literals with the new consts now available: :113 if s.kind == 8 {, :126 if self.sections.get(table).is_none_or(|s| s.kind != 3) {, :145 if s.kind != 2 && !(alternate && s.kind == 0x70000085) {, :200 if s.flags & 2 != 0, :208 t.kind != 8 && overlap(...), :224 if s.kind == 8.

S2 — second arm, cubin.rs:588-600:

                if fmt == 4 && attr == 0x0f && (rec_len - 4) % 4 == 0 {
                    for chunk in raw[o + 4..o + rec_len].chunks_exact(4) {
                        let ext_sym = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]) as usize;
                        if let Some(sym) = syms.get(ext_sym) {
                            let shx = sym.shndx as usize;
                            if shx > 0
                                && shx < sec_names.len()
                                && sec_names[shx].starts_with(b".text.")
                                && !keep_text.contains(&shx)
                            {
                                new_secs.push(shx);

Third arm, cubin.rs:509-518:

        for chunk in rel_bytes.chunks_exact(stride) {
            let r_info = u64::from_le_bytes(chunk[8..16].try_into().unwrap());
            let r_sym = (r_info >> 32) as usize;
            if let Some(sym) = syms.get(r_sym) {
                let shx = sym.shndx as usize;
                if shx > 0 && shx < sec_names.len() && sec_names[shx].starts_with(b".text.") {
                    keep_text.insert(shx);
                }

S4 — capture.rs:3282-3288 (exact):

        let keep_functions: BTreeSet<&str> = output.index.ranks[0]
            .functions
            .iter()
            .filter(|f| f.module == name)
            .map(|f| f.symbol.as_str())
            .collect();
        let exported = cubin::strip_and_prune(&image, &keep_functions)?;

S4 — cubin.rs:359-368 (exact):

    let clean = strip_debug(image)?;
    if keep_functions.is_empty() {
        return Ok(clean);
    }
    match try_prune_unused_kernels(&clean, keep_functions)? {
        Some(pruned) => {
            Elf::parse(&pruned)?;
            Ok(pruned)
        }
        None => Ok(clean),
    }

S4 — align_up call sites: cubin.rs:292 let target = align_up(out.len(), align);, :780 new_offsets[old_si] = align_up(out.len(), align);, :825 mem_cur = align_up(mem_cur, s.align.max(1) as usize);.

#1 [medium] Lens scope + repo convention facts (AGENTS.md, formatting, CI)

#5 [medium] S4: capture.rs duplicate symbol scan; align_up vs next_multiple_of; dead re-parse

  1. capture.rs:3282-3287 recomputes a per-module keep set that is already available by construction. Every wire::Function is created in the same function from kernels (capture.rs:3134-3139 sets module: kernel.module.clone(), symbol), and kernels is in scope at the module loop (capture.rs:3293 uses kernels.iter().find(|k| k.module == name) right below). So the export-index scan can be replaced by:
        let keep_functions: BTreeSet<&str> = functions
            .iter()
            .filter(|f| f.module == name)
            .map(|f| f.symbol.as_str())
            .collect();

(functions is the local Vec built at capture.rs:3058/3134.) Removing the output.index.ranks[0] dependency here also keeps the module loop independent of what was already pushed into the index. Low risk, 6 lines -> same count but one less indirection and no reliance on index mutation order.

  1. cubin.rs:282-289 align_up is hand-rolled:
fn align_up(value: usize, align: usize) -> usize {
    let align = align.max(1);
    if align.is_power_of_two() {
        (value + align - 1) & !(align - 1)
    } else {
        value.div_ceil(align) * align
    }
}

usize::next_multiple_of (stable since 1.73; heliopause/Cargo.toml:6 pins rust-version 1.88) does exactly this for any non-zero align, and the crate already uses it for padding: heliopause/src/export/archive.rs:209 let size = (raw.len() + 8).next_multiple_of(4096) - 8;, io.rs:252 and :647. Replace align_up with value.next_multiple_of(align.max(1)) at its 3 call sites (cubin.rs:292, 780/825) and delete the branch — the non-power-of-two path exists only in the hand-rolled version.

  1. cubin.rs:359-368 dead re-parse: Elf::parse(&pruned)? only validates the image this function just assembled from a parsed input; the result is discarded and the only effect is turning a self-inflicted structural bug into a hard export error in an unrelated place. If kept, it belongs as a debug_assert!; as written it is 1 line of cost for no information the constructor does not already have.