Correctness and contracts report · NVIDIA/hyperflare-inference #652

Raw Markdown for agents: https://autobot.eidonix.com/p/7a247427-9e5e-4966-986d-8846e80a36c7.md

Correctness, Contracts & System-Level Consequences — PR #652

heliopause: prune unreferenced kernels from exported CUDA ELF64 cubins, @lukealonso, head 9ea2491, base main, +937/−5 in two files: heliopause/src/export/cubin.rs (+927/−1) and heliopause/src/export/capture.rs (+10/−4). No wire/proto/runtime change is in the diff.

Key findings

  1. Major — the pruned image is internally inconsistent for auxiliary symbol tables and unrecognised sh_info. Only the single SHT_SYMTAB is rebuilt; .nv.merc.symtab (kind 0x70000085, which the file itself handles at cubin.rs:145) is copied verbatim with pre-compaction section indices, and any section whose sh_info sh_info_is_section does not recognise keeps a stale index into the old table (cubin.rs:849-856).
  2. Major — two silent all-or-nothing passthroughs. One captured symbol name without a matching .text.<name> section (cubin.rs:451-457), or a module with no surplus .text.* sections (cubin.rs:434-436), disables pruning for the whole module with no log, no error, and no counter. This is the plausible explanation for "35 multi-kernel modules pruned" out of 123 and is not in the PR's list of fallbacks.
  3. Major — the rewritten ELF is never loaded through the driver at export time, and no CI lane runs the tests. The only check is a bounds-only Elf::parse(&pruned)? (cubin.rs:365, parser at cubin.rs:69-107); the first real validation is cuModuleLoadData on the serving machine (helios/src/runtime_core/mod.rs:790-798). search_code("heliopause", path=".github") returns no matches, so all five export::cubin tests are manual-only.
  4. Major — charter hardware matrix unverified for an unconditional export change. Every measured number is SM87/AGX Orin; the PR states SM103/SM120/SM121 were not run, while the change applies unconditionally at capture.rs:3288 to exactly the CUTLASS/FlashInfer cubins it targets.
  5. Minor — design docs now contradict the code and were not updated (docs/core-format-design.md:380-381, docs/runtime-core-design.md:76).
  6. Minor — per-module export-time peak memory roughly triples, with no export-time cost claim (the PR's timing claim is load-time).

Areas I verified as sound are listed at the end; I found no concurrency hazard, no contract break, and no metric-span change.


1. Correctness & Safety

1.1 Major — auxiliary symbol tables and unrecognised sh_info keep pre-compaction section indices

Citations: heliopause/src/export/cubin.rs:145, :261-280, :426-431, :694-722, :772-795, :849-856; consumer helios/src/runtime_core/mod.rs:790-798.

(a) Symbol tables. The layout gate accepts any section kind; only duplicates of SHT_SYMTAB abort:

            } else if s.kind == SHT_SYMTAB {
                if symtab_idx.is_some() {
                    return Ok(None);
                }
                symtab_idx = Some(si);
            }

(cubin.rs:426-431)

Rebuilding touches only that one table (cubin.rs:694-722); every other surviving section is copied byte-for-byte:

        if let Some(owned) = payloads.get(&old_si) {
            new_sizes[old_si] = owned.len();
            out.extend_from_slice(owned);
        } else {
            let slice = elf.contents(old_si)?;
            new_sizes[old_si] = slice.len();
            out.extend_from_slice(slice);
        }

(cubin.rs:786-793)

The CUDA "merc" symbol table (kind 0x70000085) is a case the codebase already knows about — strip_debug handles it explicitly:

            if s.kind != 2 && !(alternate && s.kind == 0x70000085) {
                continue;
            }

(cubin.rs:145)

Its entries are 24-byte ELF-style symbols carrying st_shndx. Those indices point into the old section table; after compaction (cubin.rs:652-659 builds old_to_new_sec and drops every non-kept section) they designate different sections, and no code path rewrites them.

(b) sh_info. Anything sh_info_is_section does not recognise is passed through raw:

            let sh_info = if sh_info_is_section(s, sec_names[old_si]) && s.info != 0 {
                let Some(mapped) = old_to_new_sec.get(s.info as usize).copied().flatten() else {
                    return Ok(None);
                };
                mapped as u32
            } else {
                s.info
            };

(cubin.rs:849-856)

sh_info_is_section (cubin.rs:261-280) recognises SHT_REL/SHT_RELA, SHF_INFO_LINK, .nv.info.*, .nv.shared.*, .nv.local.*, and .nv.constant<digits>.<fn>. The author's own comment records that NVIDIA omits SHF_INFO_LINK on such sections:

    // Per-kernel constant banks (e.g. .nv.constant0.<fn>, .nv.constant2.<fn>) carry
    // the target .text.<fn> section index in sh_info even when SHF_INFO_LINK is omitted.
    if let Some(rest) = name.strip_prefix(b".nv.constant") {
        return rest.contains(&b'.');
    }

(cubin.rs:274-278)

The same omission anywhere else the predicate does not cover — a bare .nv.constant0, .nv.global.init, .nv.weak, .nv.merc.* — leaves sh_info pointing at whatever section now occupies that slot.

Impact: strip_and_prune's output check is Elf::parse(&pruned)? (cubin.rs:365), which validates the ELF magic, e_shentsize == 64, names < count, and that the section table lies inside the image (cubin.rs:69-107) — nothing about cross-references. The image therefore reaches cuModuleLoadData on the serving host (helios/src/runtime_core/mod.rs:790-798) with dangling internal references. In the .nv.info/.nv.constant* case this can also bind per-kernel metadata to the wrong kernel rather than failing loudly. Because the whole change is unconditional, this is a new failure class on any cubin the gate accepts but the remap does not fully cover.

Fix: make the remap exhaustive: return Ok(None) (debug-stripped passthrough) when any surviving section has kind 0x70000085 / SHT_SYMTAB_SHNDX / any second symbol-table-like kind, and when any kept section's non-zero sh_info cannot be proven to be a section index; or remap all of them.

1.2 Major — two silent all-or-nothing passthroughs

Citations: cubin.rs:363-369, :434-436, :451-457; capture.rs:3282-3291.

    if text_by_fn.len() <= keep_functions.len() {
        return Ok(None);
    }

(cubin.rs:434-436)

    let mut keep_text: BTreeSet<usize> = BTreeSet::new();
    for &fn_name in keep_functions {
        let Some(&si) = text_by_fn.get(fn_name) else {
            return Ok(None);
        };
        keep_text.insert(si);
    }

(cubin.rs:451-457)

    match try_prune_unused_kernels(&clean, keep_functions)? {
        Some(pruned) => {
            Elf::parse(&pruned)?;
            Ok(pruned)
        }
        None => Ok(clean),
    }

(cubin.rs:363-369)

None is debug-stripped passthrough: no error, no log, no counter. I read cubin.rs:355-545, 600-730, 760-905 and found no logging or status return on any of these branches.

Impact:

  1. A single mismatch between a captured wire::Function.symbol (obtained from cuFuncGetName in capture.rs) and a .text.<name> section suffix zeroes pruning for the whole module, including its other, genuinely dead kernels. That is the classic silent-degradation shape: correct output, absent benefit, invisible cause.
  2. The only observable signal is an aggregate byte count: module_bytes += exported.len() as u64; module_phase.advance_bytes(exported.len() as u64); (capture.rs:3289-3291). Neither pruned-vs-skipped nor a reason is reported per module.
  3. The PR text enumerates fallbacks only for "stripped section names, no program headers …, SHN_XINDEX symbol tables, or non-zero section/segment virtual addresses" and reports "35 multi-kernel modules pruned" out of 123 without accounting for the other 88. These two guards are the most likely explanation and untestable from the description — an operator cannot distinguish intended passthrough from a broken keep-set.

Fix: return a decision enum (Pruned { dropped_kernels } / Skipped(reason)) from strip_and_prune, and surface counts in module_phase.finish; at minimum count modules where a captured name had no .text. section and report it.

1.3 Major — no driver validation at export time, and no CI gate

Citations: cubin.rs:365, :69-107; helios/src/runtime_core/mod.rs:790-798, :825-831; .github has no heliopause match.

    match try_prune_unused_kernels(&clean, keep_functions)? {
        Some(pruned) => {
            Elf::parse(&pruned)?;
            Ok(pruned)
        }

(cubin.rs:363-367)

The first real validation is on the serving machine:

                let image = files.read(core, &module.file)?;
                if !image.starts_with(b"\x7fELF") {
                    return Err(invalid("module image is not a compiled cubin"));
                }
                let mut handle = null_mut();
                driver.check(
                    "cuModuleLoadData",
                    (driver.module_load)(&mut handle, image.as_ptr().cast()),
                )?;

(helios/src/runtime_core/mod.rs:790-798)

search_code("heliopause", path=".github") → "No matches", so no CI workflow compiles or tests the crate that contains this 900-line ELF rewriter. The 5 export::cubin tests (pre-existing at cubin.rs:977/995/1015, new at cubin.rs:1223/1273) and the PR's cargo test --lib result are therefore manual-only evidence for a binary-format rewrite.

Impact: an export that produces an ELF which parses but is not loadable converts a build-time failure into a served-start failure on the user's GPU, and CI cannot catch it. The new tests are self-consistent by construction — they build synthetic ELFs (multi_kernel_cubin, cubin()) and re-parse the output with the same parser, so they cannot detect the class of bug in 1.1.

Fix: (a) add a heliopause cargo test job to the CI that builds this crate; (b) add an in-export assertion set that is independent of Elf::parse — after pruning, verify every captured name still resolves to a surviving .text. section, every surviving sh_link/sh_info resolves, and (cheaply) that the driver accepts the image when a CUDA context is already live in capture_rank.

1.4 Platform-parity note (checked, no defect found)

The gate requires EM_CUDA, phentsize == 56, zero p_vaddr/p_paddr, zero sh_addr, exactly one SHT_SYMTAB, stride == 24, and < 0xff00 sections (cubin.rs:381-449), rejecting non-standard layouts to passthrough. p_align is hardcoded to 8 (cubin.rs:883) rather than copied from input, and emitted headers leave p_vaddr/p_paddr zero. That is internally consistent with the zero-vaddr gate, and the emitted PT_LOADs need no page alignment for CUDA's loader — I do not report it as a standalone defect, only as an unverifiable-under-SM103/120/121 detail inside finding 2 of the key list.


2. Unintended system-level consequences

2.1 Minor — export-time peak memory per module roughly triples, unmeasured

Citations: capture.rs:3280-3291; cubin.rs:197, :355-370, :409-470, :652-770, :768.

    for (index, (name, image)) in modules.into_iter().enumerate() {
        let file = format!("module-{index}.cubin");
        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)?;

(capture.rs:3280-3288)

strip_and_prune keeps the stripped clone and the rebuilt image live at once:

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

(cubin.rs:359-368)

strip_debug already clones the whole image (cubin.rs:197 let mut result = image.to_vec();), and try_prune_unused_kernels then allocates per-symbol Vecs, a BTreeMap of callgraph edges, seven O(sections) index vectors, a new .shstrtab, a new .strtab, a new symbol table, a BTreeMap<usize, Vec<u8>> of payloads, and the re-emitted out (cubin.rs:409-470, 652-770, 768). Peak live bytes per module move from ~1× to ~3× the input on modules reported to be tens of MiB (the PR cites 166.51 MiB total across 123 modules, so single-cubin sizes are bounded but the largest multi-kernel CUTLASS cubin dominates).

Impact: the PR makes no export-time cost claim, so this is an unmeasured regression risk on the export path, which is the one place where a whole-module image already exists in memory. It also compounds the concern raised on #585 about strip_debug's image.to_vec(). Fix: let try_prune_unused_kernels consume image by value, or drop clean before returning the pruned buffer.

2.2 No concurrency or failure-propagation hazard found

The module loop is sequential (for (index, (name, image)) in modules.into_iter().enumerate(), capture.rs:3280); downloader, keep_functions, and every working set in the pruner are per-iteration; the BTreeSet borrows output.index.ranks[0].functions immutably and nothing in the body mutates that vector while it is borrowed (the rank's modules vector is appended to, a different field). No shared/global state, no lock, no queue, no cross-module retention: exported is written to the staging file and dropped (capture.rs:3291). A per-module failure propagates as ExportResult out of capture_rank, which is the same shape as the pre-existing strip_debug call. Nothing here serializes a hot serving path — the cost is entirely export-time.

2.3 Metric / rate / admission-pricing span check

This PR does not change any rate, latency, or admission metric. The one progress-metric interaction is consistent: module_bytes accumulates the post-prune length and advance_bytes is called with the same number (capture.rs:3289-3291), so the "Capture compiled modules and globals" total shrinks with the artifact instead of disagreeing with it. No threshold downstream re-prices on that value.


3. Architecture, contracts & charter compliance

3.1 Major — the charter's supported matrix is the one matrix never exercised, and the change is unconditional

Citations: capture.rs:3288; PR Limitations paragraph; charter goals line ("Prepare supported model recipes with Ignition and serve captured CUDA graphs from Rust on SM103, SM120, and SM121").

The PR states verbatim: "SM103, SM120, SM121, and multi-rank TP core exports were not run for this PR." Every number in the description is from SM87: the "SM87 Inkling-2-Mini 9-graph (widths 1, 2, 4, 8) K4V8 + DSpark export", "Jetson Orin Nano 8 GB", and "needle recall on AGX Orin".

The call is unconditional:

        let exported = cubin::strip_and_prune(&image, &keep_functions)?;

(capture.rs:3288 — no flag, no per-module opt-out, replacing the previous strip_debug)

And the pruning decision depends on layout facts that vary by architecture and toolchain: per-kernel .text.<fn> naming (cubin.rs:421-425), EIATTR_EXTERNS in .nv.info.<fn> (cubin.rs:539-614), .nv.callgraph encoding (cubin.rs:521-537). On an architecture or toolchain that names kernel code differently, text_by_fn is empty and cubin.rs:434-436 silently disables pruning for every module — the same silent path as §1.2, and the likeliest reason only 35 of 123 modules pruned on SM87.

Impact: the highest-risk cubins the change targets (CUTLASS/FlashInfer, which the PR says pack "tens to over a thousand template instantiations") live on SM120/121, which the change is applied to unconditionally and which no one has run. The charter's served-workload evidence bar is met only on hardware outside the supported matrix.

Fix: run one SM120 or SM121 export plus flare run on a CUTLASS/FlashInfer-heavy module before merge, and report pruned/skipped module counts from that run; alternatively gate the prune to layouts actually validated.

3.2 Minor — design docs now contradict the code and are not updated by this PR

Citations: docs/core-format-design.md:380-381; docs/runtime-core-design.md:76; cubin.rs:716-720; test cubin.rs:1230.

The exporter preserves kernel and global symbol names in cubins and their
execution bindings. Cubin debug sections and assertion source paths are stripped.

(docs/core-format-design.md:380-381)

After this PR that is false for dead kernels:

        } else {
            // Preserve local/global binding so symtab.sh_info stays valid; clear type, section, and name.
            dead_syms.insert(idx);
            entry[4] = sym.info & 0xf0;
        }

(cubin.rs:716-720)

and the rebuilt .strtab never receives the name (add_str cache over surviving names only, cubin.rs:674-690). The new test asserts the name is gone: assert!(!pruned.windows(11).any(|w| w == b"dead_kernel")); (cubin.rs:1230).

docs/runtime-core-design.md:76 likewise still lists heliopause's cubin responsibility as only "cubin debug stripping".

Impact: core-format-design.md is the contract a core reader or auditor trusts for "symbol names are preserved". After this PR, two cores exported by different heliopause versions have materially different symbol content with no documented rule, which matters for anyone reasoning about artifact compatibility.

Fix: amend both docs in this PR: unreferenced kernels and their symbols are dropped and their .symtab slots zeroed, subject to the layout conditions, with debug-stripped passthrough otherwise.

3.3 Contracts verified unchanged

No schema, protobuf, Cargo.toml (not opened), CLI, or Helios runtime change is in the diff. core.modules[].file and core.modules[].globals are consumed exactly as before (helios/src/runtime_core/mod.rs:785-822), so previously exported cores still load. The PR correctly requires no owner sign-off for a new captured-graph op contract, since it adds none.


4. Tests & claim accuracy

4.1 Major (dependency of §1.3) — the new tests cannot catch the failure modes they sit next to

Citations: cubin.rs:1223-1284, :1233, :1269, :1276-1281.

The tests are good on their own terms — dead kernel removal, callee retention via callgraph/externs, sh_info remapping, global symbol preservation, and standalone/no-PT_PHDR passthrough:

            let original = multi_kernel_cubin(use_externs);
            let keep = BTreeSet::from(["live_kernel"]);
            let pruned = strip_and_prune(&original, &keep).unwrap();

(cubin.rs:1226-1228)

But verification is Elf::parse(&pruned) (cubin.rs:1233) — the same parser that produces the structure — and no fixture carries a 0x70000085 symbol table or an unrecognised sh_info, so §1.1 is invisible to the suite. pruning_preserves_standalone_and_no_phdr_modules covers only the two passthroughs it names (cubin.rs:1276-1281), not the two silent ones at cubin.rs:434-436 and :451-457 — the partial-keep-set case is untested.

Fix: add a fixture with a 0x70000085 table and one with a non-SHF_INFO_LINK, non-recognised companion section, plus a test asserting the unmatched-captured-name behaviour (currently a silent whole-module skip), so the chosen semantics are pinned either way.

4.2 Claim accuracy

Verified against the diff: the mechanism claims (reachability from captured symbols, relocation targets, .nv.callgraph, EIATTR_EXTERNS; symtab index preservation; sh_info cascade; global .nv.info/callgraph filtering; passthroughs) all match the code. The claims I could not verify — and that no artifact in the repo supports — are all the numeric ones: cubin 166.51 → 19.46 MiB (−88.3%), kernels.safetensors 9.93 → 1.5 MiB, "Prepare kernels" 0.5 s → 0.1 s, pre-cache 6.73 → 6.45 GiB (−287 MiB), KV 15,488 → 32,768 tokens. No script, log, or baseline accompanies them and no automated lane could reproduce them.

Two description statements are incomplete rather than wrong: the fallback list omits the two silent guards of §1.2, and "35 multi-kernel modules pruned" is presented without saying what happened to the other 88.


Verified sound (no findings)


Open questions and what I could not find

  1. Are the 88 unpruned modules intended passthrough or the silent fallback? The description does not say, and the code cannot tell you (§1.2). This determines whether the headline −88.3% is near the ceiling or near the floor for SM120/121.
  2. Does p_align = 8 (cubin.rs:883) and zero p_vaddr/p_paddr reproduce what NVIDIA's SM120/121 toolchain emits for CUTLASS cubins? No run exists to compare against; the gate only proves the input had zero vaddrs.
  3. Is a driver-level validation pass at export time feasible? capture_rank already holds a CUDA context (cuFuncGetModule at capture.rs:3308-3314), so an in-export cuModuleLoadData of the pruned bytes looks available; I did not find any existing helper that does this.
  4. Should the docs updates (§3.2) land in this PR or separately? No maintainer position is recorded; the design docs are the stated contract for core readers.
  5. I could not find any in-repo artifact, log, or script backing the PR's performance and memory figures, nor any CI job that would exercise heliopause, cubin.rs, or strip_and_prune (the Python cubin test in tests/preparation/test_cubin.py reaches only strip_debug/global_symbols, not the new function).