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
- Verdict first: the diff is not bloated with speculative machinery. It adds no flag, no config key, no env var, no trait, no new public surface (
recorder.rs:1010-1016(not opened) still registers onlystrip_debug/strip_global_source/global_symbols, so there is no Python API to trim). The passthrough branches atcubin.rs:381-407,:434-436,:452-457are required by real cubin variance (libcublasLt has no program headers;kv_codecis a standalone module), so AGENTS.md:188-193's ban on "fallback layers … without a concrete requirement" is not violated. Do not recommend removing them. - S1 (high, pure deletion): the PR introduces
is_debug_section(cubin.rs:254-259) but leaves the identical inline copy instrip_debug(cubin.rs:187-195). Five lines and one duplicate policy copy to delete. - S2 (high):
try_prune_unused_kernelsis one ~530-line function (cubin.rs:372-904) fusing six phases that its own comments already delimit, and the identical.text.*callee test is triplicated atcubin.rs:512-517,:558-568,:588-600. - S3 (high): the EIATTR record framing decode is duplicated at
cubin.rs:305-311and:578-587and the two copies have already drifted in failure policy (return Nonevsbreak). Onenvinfo()record iterator removes both. - S4 (medium, three):
capture.rs:3282-3287rescans the export index when the localfunctionsvec already holds the data;align_up(cubin.rs:282-289) reinventsusize::next_multiple_of, which the crate already uses for padding (archive.rs:209,io.rs:252(not opened)); the re-parse atcubin.rs:365validates only the image the function just produced and its result is dropped.
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:
- 372-407 layout gate →
Ok(None) - 409-457 section-name scan,
text_by_fn,keep_textseeds - 459-614 symtab parse + relocation / callgraph /
EIATTR_EXTERNSreachability closure - 616-650
keep_seccascade - 652-748
.shstrtab/.strtab/symtab rebuild and global-payload filters - 750-903 section placement, section headers, program headers, ELF header patch
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)
- AGENTS.md:188-193 ("Do not add frameworks, extension points, speculative compatibility, fallback layers, or configuration switches without a concrete requirement"): met — every fallback has an identified real-world trigger. The findings above are internal duplication, not new abstraction.
- AGENTS.md:194-199 ("Tests must exercise the affected behavior… Identify missing hardware, inputs, and unrun checks explicitly… Keep each PR focused on one coherent outcome"): the PR stays one coherent outcome and the Limitations paragraph names the unrun hardware. This lens adds nothing.
- AGENTS.md:52-60 (state support as present qualification; unresolved defects and unrun checks go to
docs/TODO.txt, not design documents): the SM103/120/121 unrun status lives only in the PR body. That is a documentation lens point, noted here once rather than duplicated. - Formatting/lint: no rustfmt or clippy workflow exists under
.github(only a release version check), and no docs requirecargo fmt. No formatting suggestions are made; only the structural items above. - Existing helper reuse: the file already had
Section/Elf/number/putand now hasis_debug_section,sh_info_is_section,align_up,pad_to,filter_global_nvinfo,filter_callgraph. Apart from the alignment helper (b), these are new logic, not duplicates of existing repo helpers — I found no prior ELF-emission helper elsewhere inheliopause/src/export/. (module_images.py:21-36andrecorder.rs:1010-1016(not opened) mirror only the three pre-existing cubin functions, so no Python-side wrapper was added either.)
Not this lens (recorded so the synthesizer does not lose them)
p_alignhardcoded to 8 incubin.rs:883(put(&mut ph, 48, 8, 8);) andp_vaddr/p_paddrleft zero, never exercised on SM120/121 CUTLASS cubins — correctness/contract question, not simplification. Likewise whether ap_alignof 8 is even a simplification worth keeping versus copying the input header.- Docs drift:
docs/core-format-design.md:380-381("The exporter preserves kernel and global symbol names in cubins") versus the dead-slot name clearing atcubin.rs:716-720(dead_syms.insert(idx); entry[4] = sym.info & 0xf0;), anddocs/runtime-core-design.md:76still describing cubin handling as debug stripping. Documentation lens. - Whether pruning should be unconditional rather than gated on
text_by_fn.len() > keep_functions.len()(cubin.rs:434-436) or on a fully matching keep set (cubin.rs:452-457) is a behaviour/coverage question (the dossier's "35 of 123 modules pruned"), not a subtraction one — unless the review concludes the unmatched-name fallback exists to paper over a name-normalisation defect, in which case that defect should be fixed and the branch deleted rather than documented.
Open questions / what I could not verify
- Whether the 5-line predicate triplication at
:512/:558/:588was deliberate (e.g. to keep the closure loop allocation-free) — I found no comment justifying it, and the three copies differ only in the!keep_text.contains(&shx)guard, which the outerkeep_text.insert(shx)makes redundant anyway. - Whether
capture.rs's keep set is intentionally read from the exported index as a self-check that the index was populated correctly; no comment or test establishes either intent, so S4(a) is a judgement call rather than a defect. - I did not build or run the crate (no Rust toolchain in this review), so all counts (
+927/−1, 5export::cubintests) come from the diff/dossier, not from execution. No CI lane runs these tests, so the simplifications above cannot be validated by CI either way.