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

Raw Markdown for agents: https://autobot.eidonix.com/p/5e866e6d-c12e-4ecb-8cca-a0cf29156275.md

Subtraction, Simplicity & Conventions review — PR #652

Scope: heliopause/src/export/cubin.rs (all 1284 lines) and heliopause/src/export/capture.rs (module loop, 3040-3350), plus AGENTS.md, heliopause/Cargo.toml, and the two docs the change affects. Lens: what can be deleted, collapsed, or made dramatically simpler; no correctness bugs duplicated.

Key findings


S1 (high) — the new is_debug_section helper is added but strip_debug keeps its own copy

The helper the PR adds, heliopause/src/export/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"
}

The unchanged but now redundant copy inside strip_debug, heliopause/src/export/cubin.rs:187-195:

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

Remove the inline predicate and call the helper — if is_debug_section(name) { debug.insert(i); }. This is a pure deletion (5 lines) and collapses two copies of the debug-name policy into one; otherwise a future debug-section class (e.g. .nv.debuginfo) must be edited in two places or the two paths silently disagree about which sections are debug.

Secondary, same file, mechanical: the PR just introduced the section/symbol constants at cubin.rs:14-25 (SHT_SYMTAB, SHT_STRTAB, SHT_NOBITS, SHF_ALLOC, …), yet the shared helpers still use raw literals — cubin.rs: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. Substituting the new consts (and SHF_WRITE for & 2) is a behaviour-free cleanup of the same code the PR is already touching. (Low priority; mention only because the consts exist as of this diff.)

S2 (high) — 530-line function with the same callee predicate three times

try_prune_unused_kernels (heliopause/src/export/cubin.rs:372-904) does six separable jobs, delimited by its own comments:

The concrete cost of the size is that the same "text callee" test is written out three times, at four-to-five levels of indentation.

Relocation arm, heliopause/src/export/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);
                }

Callgraph arm, heliopause/src/export/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);
                    }

EIATTR_EXTERNS arm, heliopause/src/export/cubin.rs:591-599 — the same five conditions verbatim again:

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

Simplify: one helper next to sh_info_is_section, e.g. fn callee_text(syms: &[Sym], sec_names: &[&[u8]], sym_idx: usize) -> Option<usize>, used by all three arms, and split the function along its existing comment boundaries into layout_gate(image) -> ExportResult<Option<..>>, reachable_text(..) -> ExportResult<BTreeSet<usize>>, and emit(..) -> ExportResult<Vec<u8>>. No behaviour change; it also gives the three phases unit-test seams that today's tests (cubin.rs:1223, :1273) can only reach end-to-end through hand-built fixtures (cubin.rs:910, :1032). Note the crate already uses targeted allow-attributes where warranted (capture.rs:2510, :2672; core.rs:596 (not opened)), so the 530-line body is not hiding behind a convention either way.

S3 (high) — EIATTR record decode duplicated, and the copies have drifted

Copy A, filter_global_nvinfo, heliopause/src/export/cubin.rs:305-314:

        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;
        }

Copy B, in the reachability loop, heliopause/src/export/cubin.rs:578-587:

                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 policy: A aborts pruning (return None → debug-stripped passthrough), B silently truncates the walk and keeps whatever it found. That divergence is exactly what the duplication invites, and it means the two parsers can disagree about the same .nv.info bytes. A single fn nvinfo(raw: &[u8]) -> Option<impl Iterator<Item = (u8, &[u8])>> (attr + payload, None on malformed) replaces both; the B arm then becomes a filter over records 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. filter_callgraph's length guard (cubin.rs:331 if raw.len() % 8 != 0 { return None; }) already shows the shape to imitate.

S4 (medium) — three small deletions

(a) capture.rs:3282-3287 rescans the index for data it already has.

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

Every wire::Function was built moments earlier, in the same function, from kernels (capture.rs:3134-3139 sets module: kernel.module.clone()), and kernels is still in scope two lines below (capture.rs:3293 kernels.iter().find(|k| k.module == name)). The local vec is moved into the index at capture.rs:3187 and the index is mutated afterward (capture.rs:3260, :3299), so reading the keep set back out of output.index.ranks[0] couples the module loop to index mutation order for no benefit. Either keep the local functions vec alive (clone the symbol names before the move) and build the set from it, or — if the index really is the intended source — say so; as written the indirection buys nothing.

(b) align_up at cubin.rs:282-289 reinvents next_multiple_of.

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 1.73; heliopause/Cargo.toml:6 pins rust-version = 1.88) does exactly this for any non-zero alignment, and the crate already uses it for padding — heliopause/src/export/archive.rs:209: let size = (raw.len() + 8).next_multiple_of(4096) - 8;, and io.rs:252 (not opened)/:647. Replace the body with value.next_multiple_of(align.max(1)) (or delete the wrapper and call next_multiple_of at cubin.rs:292, :780, :825); the branch disappears.

(c) cubin.rs:359-368 — discarded re-parse.

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

Elf::parse(&pruned)? parses the buffer this function just assembled and throws the result away; it can only turn a self-inflicted structural bug into a hard export error at an unrelated call site. If it is wanted as a guard it is a debug_assert!(Elf::parse(&pruned).is_ok()); as written it is a line of cost and no information. Note this is not the same as validating that the driver accepts the image — nothing in the diff does that (see open questions).


Conventions check (structural only)

Not this lens (recorded so the synthesizer does not lose them)

Open questions / what I could not verify