Deep Correctness, Invariants & Hot-Path Performance Audit — PR #728 @ 71af7c9
Scope partitioned (24 files, ~1,600 changed lines, 2 subsystems) into two disjoint slices audited concurrently in Turn 1: (A) heliopause/ Rust (reachability.rs, binding.rs, capture.rs, source_identity.rs, build.rs), (B) ignition/preparation/ Python (aot.py, capture.py, source_identity.py, inductor_tuning.py, compile_pool.py, core_storage.py, forward_metadata.py, rebuild_manifest.py) plus the 8 changed test files. I independently re-read every diff site and callee behind each reported claim (citations below are from my own reads; two sub-agent claims that did not survive my verification are listed at the end as rejected).
Verdict: 2 Major + 3 Minor verified defects. The largest change, reachability.rs (+738), is clean.
FINDING 1 — Major: forward_source_identity silently hashes no FlashInfer native sources for a legitimate install layout, silently re-opening the stale-cache bug the PR set out to fix
Diff site: ignition/preparation/source_identity.py:104-125. Divergent sibling callee (same file): source_identity.py:188-192.
104 if data.exists():
105 for name in ("include", "csrc"):
106 native = (data / name).resolve()
107 if not native.is_dir():
108 raise RuntimeError(
109 f"FlashInfer native source directory is unavailable: {data / name}; "
110 "install the selected FlashInfer package before preparation"
111 )
...
116 elif (flashinfer_package.parent / "include").is_dir() and (
117 flashinfer_package.parent / "csrc"
118 ).is_dir():
119 for name in ("include", "csrc"):
The if/elif has no else. If neither the data/{include,csrc} layout nor the both-siblings-present layout matches — i.e. no data/ directory at all, or a data/ dir that exists but lacks include/csrc, or a parent layout with only one of the two — control falls straight through to return digest.hexdigest() at :136 with zero native FlashInfer bytes mixed in and no error. The sibling function that must agree on FlashInfer identity, source_identity() (used for rebuild metadata), raises loudly for the identical condition (source_identity.py:188-192: if !source.is_dir(): raise RuntimeError(...)).
Concrete counterexample: FlashInfer installed at site-packages/flashinfer/ with no data/ subdirectory (a valid layout for older/source-tree installs), and a site-packages/include, site-packages/csrc pair where only include exists. Edit include/flashinfer/attention.cuh. ForwardCache.__init__ (aot.py:905-919) computes an identical self.root before and after the edit, so _restore → _load finds and restores the stale compiled forward — the exact Python-only ForwardCache hashing gap the PR description claims to close, merely relocated to a different install layout. Note the elif is also all-or-nothing: the include-only case skips include too, even though it is present and hashable.
Fix: resolve the native trees up front and fail loudly, mirroring _source_identity:
for name in ("include", "csrc"):
native = (data / name)
if not native.is_dir():
native = flashinfer_package.parent / name
if not native.is_dir():
raise RuntimeError(
f"FlashInfer native source directory is unavailable: {data / name}; "
"install the selected FlashInfer package before preparation")
mix_hex(f"flashinfer.{name}", flare_heliopause.export_source_identity([native.resolve()]))
FINDING 2 — Major: async_transfer.alignment is validated twice with contradictory upper bounds, so the same manifest's validity flips on an orthogonal request field, and the permissive path defers a real misalignment failure to load time
Diff sites: heliopause/src/export/capture.rs:2932-2944 (new validate_external_extents) vs heliopause/src/export/binding.rs:629-637 (new async_transfers block in execution()).
// capture.rs:2906-2907
let container_align = helios_core::core::container::ALIGNMENT; // == 4096
let min_align = u64::from(helios_core::async_transfer::MIN_ALIGNMENT); // == 4096
// capture.rs:2932-2944
let align = u64::from(channel.alignment);
if align < min_align || !align.is_power_of_two() { return Err(...); }
if align > container_align {
return Err(invalid(format!(
"external_extents channel {:?} alignment {align} exceeds core container alignment {container_align}",
// binding.rs:630-637
if alignment < 4096 || alignment > u32::MAX as u64 || !alignment.is_power_of_two() {
return Err(super::invalid(
"async transfer alignment must be a power of two >= 4096",
));
}
Guard-domain resolution (protocol §1): container_align == min_align == 4096, so capture.rs:2933-2944 together admit exactly one value, 4096. binding.rs:633 admits every power of two in [4096, 2³²).
Concrete counterexample — proven from the read code: validate_external_extents is driven by for ext in external_extents (capture.rs:2909), so with request.external_extents == [] it validates nothing. Manifest {"async_transfers":[{"name":"experts","alignment":8192, ...}]}:
external_extents == []→ onlybinding.rs:633runs → 8192 accepted, written intooutput.index.ranks[0].execution.external_extents == [{"channel":"experts", ...}]→ the same alignment is rejected with "alignment 8192 exceeds core container alignment 4096".
A field with no causal relationship to alignment (external_extents) flips the verdict. In the permissive branch the exported core carries alignment: 8192 while the payload container base is only guaranteed 4096-aligned (container.rs:39 (not opened)), so the load-time absolute-offset alignment check in decode_extent_directory (ring.rs:529-536, if (abs_offset & align_mask) != 0 { return Err(...) }) can reject at load a core that export declared valid — precisely the "export accepts, runtime rejects" class this PR targets.
Fix: apply the bound unconditionally where the channel is first validated, at binding.rs:633 (alignment != helios_core::core::container::ALIGNMENT → error, or thread the real payload base alignment through), keeping validate_external_extents as the second line of defence. Better: replace both hand-derived predicate sets with a single call to helios_core::async_transfer::validate_control_layout / a shared validate_channel_alignment so the two sites cannot drift.
FINDING 3 — Minor: export accepts completion_slots == u32::MAX, which the loader's validate_control_layout always rejects
Diff site: heliopause/src/export/binding.rs:620-628. Callee: helios/src/async_transfer/ring.rs:293-295 with NO_COMPLETION_SLOT = u32::MAX at ring.rs:27.
if completion_slots == 0 || completion_slots > u32::MAX as u64 {
return Err(super::invalid(
"async transfer completion_slots must be a positive uint32",
));
}
// ring.rs:293-295
if completion_slots == 0 || completion_slots == NO_COMPLETION_SLOT { return false; }
4294967295 passes the export guard (> u32::MAX as u64 is false) and is then rejected at load. Fix: add || completion_slots == u64::from(helios_core::async_transfer::NO_COMPLETION_SLOT), or delegate to validate_control_layout (which also subsumes Finding 2).
FINDING 4 — Minor: append_planes now silently accepts "weights": null / "scales": null, which previously failed export
Diff site: heliopause/src/export/binding.rs:886-891.
for name in ["weights", "scales"] {
if let Some(parts) = value.get_mut(name) {
if parts.is_null() {
continue;
}
let sources: Vec<super::FileSource> = serde_json::from_value(parts.clone())?;
Order-of-operations trace (protocol §2): the continue fires before the plane rewrite *parts = serde_json::json!({"offset":start,"nbytes":*cursor-start}) at binding.rs:915, so a null plane is neither rejected nor rewritten — it survives verbatim into message("Engram", &data) where prost-reflect treats null as unset. Previously serde_json::from_value::<Vec<FileSource>>(Value::Null) errored, so {"tables":[{"weights": null, "scales": null}]} was a hard failure and is now silently accepted into an engram table with absent weight/scales descriptors. Silent acceptance of previously-rejected input, no diagnostic. Fix: if let Some(parts) = value.get_mut(name).filter(|v| !v.is_null()), or emit a zero-length {offset, nbytes: 0} descriptor so downstream shape is unchanged.
FINDING 5 — Minor: the absolute-offset alignment assertion in validate_external_extents is unsatisfiable (dead validation) and its explanatory comment is false
Diff site: heliopause/src/export/capture.rs:2973-2980. Callee: helios/src/async_transfer/ring.rs:321-324 and :529-536.
2973 // Payload containers guarantee `container::ALIGNMENT` (4 KiB) base alignment;
2974 // validating at `container_align` exercises the real nonzero container offset.
2975 resolved_segments.push((seg_idx as u32, container_align, len));
From Finding 2, align == container_align == 4096 is forced by :2933-2944; validate_extent_entry forces each relative entry offset to a multiple of align = 4096; and the fabricated base is the constant container_align = 4096. Hence abs_offset = 4096 + k*4096 = (k+1)*4096, so abs_offset & 0xFFF == 0 for every k: the abs_offset branch of decode_extent_directory (ring.rs:529-536) can never trigger. Because the base is fabricated rather than read from the real payload plan, the check cannot detect the load-time misalignment it was written to catch (Finding 2 is exactly the case it misses). Fix: thread the actual segment base offset from the payload planner into resolved_segments, or delete the fabricated base and state that only relative entry alignment is validated.
Verified-clean (explicit negative results, so these need no re-audit)
heliopause/src/export/reachability.rs(+738) — no defect found. Hand-traced every new construct:pointer()→candidate()(:162-179) preserves the exactreference()and inactive-shadows-live ordering of the oldreturn Ok(());blob()caching (:205-228) is keyed on(data, numeric)whose miss set is a pure function of immutableReachability::newstate, and the insert moved after the successful scan so a failed scan no longer poisons the cache (a fix vs. the old insert-before-scan);record_unresolved(:181-203) makesorderunique so thesort_unstable_by_keyat:264is total and deterministic despite theHashMap;unresolved_report(:246-324) keepsselected.len() == UNRESOLVED_EXAMPLES.min(examples.len())and never double-counts occurrences, sooccurrences - shown_occurrencescannot underflow;(base + offset).is_multiple_of(8)(:343) is correctly argument-relative, which is what makes an unaligned numeric prefix still report a genuinely 8-aligned pointer;subtract_ranges/merge_rangespreconditions hold (excludedsorted viamerge_ranges, which dropsstart >= end); boundary semantics are end-exclusive and verified against the existing kernel-argument-boundary test. Cold path only (single caller, post-graph-loop) — O(U log U), no allocations×args×buffers nesting, so no hot-path regression. All new tests recomputed by hand and consistent; none vacuous or failing.ForwardCache.__init__hashing rewrite (aot.py:905-919) — the suspected Blocker does NOT hold. The old exclusion semantics are preserved exactly:_COMMAND_SOURCES/_PUBLICATION_SOURCESsplit cleanly into real directories (ignition/cli,ignition/direct) and real files (six plus__main__.py(not opened)), and the Rust side applies exact-PathBufequality to both files (source_identity.rs:42-43) and directories (:19-22), so passing files is meaningful and no exclusion silently no-ops. I explicitly rejected the sub-agent's contrary claim that this breaks on relative/absolute paths:forward_source_identityresolves bothignition_root(:79) and every excluded path (:93-94) before calling Rust, and Rust'sread_diryields paths rooted at that same resolved root, so==matches. The only behavioural change is a superset (.rs/.c/.cpp/.cu/.cuh/.h/.hpp, FlashInferdata/{include,csrc}, bound extra roots) — intended by the PR._seed_warmup_workspacespool threading (capture.py:53-79) — the nestedif pool is None: pool = _warmup_pools.get(index)only rebinds when the caller passed nothing, so aCoreStorage.warmup_pool()is used and_warmup_poolsstays empty; the 2-argument fallback and thehasattr(warmup_storage, "warmup_pool")gate (:151-157) are both correct forwarmup_storage is None.CoreStorage.warmup_pool()retains theMemPoolonself, so exitinguse_mem_pooldoes not release the cached workspace._warmup_streamcontext ordering is unchanged._loadcorrupt-artifact path (aot.py:1366-1390) — safe:if required: raiseprecedes the warn+unlink, so required loads (the peer-transfer_load(..., required=True)and the post-save reload) never delete a file;_atomic_write_filepublishes viaos.replaceso no reader sees a partial file; a correct peer's file cannot be damaged because only a rank that itself failed to parse it unlinks. Worst case is redundant recompiles, not corruption._atomic_write_file/_save_compiled_function(aot.py:87-109) — handle closed beforeos.replace/ before the callee reopens the path; thefinally: temporary.unlink(missing_ok=True)preserves the target if the writer raises. No double-close, no leak, no*.tmpresidue._prune_static_compile_results/_sanitize_static_bundle(inductor_tuning.py:21-65) — linear, not O(N·M); the non-frozen prune only drops non-static results when static ones remain and does not touch launchers/freeze state, and_snapshotre-prunes withrequire_single=Truebeforecopy.deepcopy, so the new non-frozen_sanitize_static_bundle(bundle, frozen=frozen)call cannot leavefreezewith a state it rejects. Invariants complementary, not contradictory.prepared_module_roots/is_prepared_object_module(source_identity.py:31-58),forward_metadata.py:39-47,rebuild_manifest.py:369,compile_pool.py:129,138-145,180-183—_EXTRA_ROOTSis aContextVarwithdefault=()of(str, Path)pairs so both.get()consumers work; dedup byseenprevents double counting; missing bound roots still raiseValueError(:127-130); the workerbind_source_roots(extra_roots)wraps bothloadsandaot_forwardand resets afterwards. The widening fromstartswith('ignition.')to matching the bareignition/b12xmodules is harmless and matches the docstring.- Changed tests — the ones I re-derived (
test_source_identity.pyexact file+dir exclusion with a positive and negative digest case,test_guard_code.pyCompiledKernelTypeErroragainst a real__new__instance plus the negative-without-binding case,test_compile_pool.pypositional-arg-6 + contextvar reset,test_inductor_prepared_winners.pyprune-vs-raise plus a realpickle.dumps(bundle),test_core_storage.pypool reuse,test_forward_cache_sources.pycorrupt-bin andB12X_*env identity) all assert the new behaviour and none is vacuous or self-contradictory. - Two sub-agent claims I rejected after verification: (a) that
excluded_filesbreaks on path-normalization mismatches — refuted bysource_identity.py:79,93-94resolving both sides; (b) that_seed_warmup_workspaces's nestedif pool is Nonecan override a caller-supplied pool — refuted by readingcapture.py:53-79(it only rebinds whenpoolisNone).
Hot-path performance
No regression found. The only newly-hot code is warmup_storage.seal_low_window() called once per exported graph name (capture.py:266-267), which is O(names × span_count) with an early skip of already-reserved spans (core_storage.py:180-184); it is not dead — the first capture legitimately reopens the low window — and it runs N times by design during a cold export, not per served token. ForwardCache.__init__'s Rust tree hash runs once per export per rank, not per forward. unresolved_report is a cold-path diagnostic. _b12x_forward_env adds ~14 constant names to the key.