PR #647: Fix externalized core signing, stream-0 weight race, export I/O, and multi-host tuning

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/606060da-ed29-4047-b87a-dd11070f723d

Opened by a workflow run, Nov 30, 2026 1:44 PM EST. decide malicious: all_clear (100%): No malicious content found

explore

Author: lukealonso (COLLABORATOR; charter-named priority contributor; Discord: lukealonso) Motivation: Five separate defects are being fixed at once, four of them latent or newly self-inflicted and one reported by a user: large signed cores (>128 MiB) can no longer be combined or promoted because #618's externalized bodies are still decoded as inline bytes; newly mapped GPU memory is zeroed on legacy stream 0 and can overwrite weights being copied on other streams; cached export does redundant copies, hashing and file-descriptor work; multi-host autotune lets ranks pick divergent kernels (#631); and several native helpers have wrong ABI, device-selection or 32-bit bounds. Scale: +1,379 / −303 lines in 27 files Proposal:

Full report · Notes

Value Proposition

Value Proposition — PR #647

Charter alignment. Mixed but salvageable. It fixes reproducible bugs and a filed issue, which the charter names as mergeable ("a reproducible bug"). #631 (bug, priority:P2) is a real 2× DGX Spark ignition export --ranks 2 failure, and multi-host prep/export is a charter goal; the signing fix repairs combine/promote on >128 MiB cores, charter artifacts created by #618. It adds no model aliases, flags, or per-model branches — it even removes the --reuse-weights --no-mtp rejection. Against that: the performance half (skip full-weight PCIe D2H, one IoUring, no double SHA-256) is explicitly "not benchmarked end-to-end on GPUs," failing the #210 evidence bar; transfer.rs drops a verification pass and repurposes the sha256 wire field (tension with #397); and the WDDM/HOST_BASE work targets a platform the supported matrix does not name. No roadmap item (#6, #267, #215) is served.

Novelty & status. Genuinely additive — nothing supersedes it, nothing on main is already fixed. It is, though, largely self-repair: the signing defect exists only because #618 (merged the previous day, same author) shipped sign_envelope without updating inject_dependency_descriptors/conversion/edit.rs; compilation.py was rewritten by #593 a day earlier; PersistentWorker.metrics re-establishes a field #430 deliberately removed; kv_codec_gpu.cu restructures kernels from #504/#525, four days old. That is debt re-paid within 24 h, not new capability.

Value vs maintenance cost. Real beneficiaries: multi-host export operators (#631), anyone running combine/promote on spilled cores, and latent-defect fixes (CUmemAccessDesc ABI, ReadRing freeing live DMA, gf2_pow bounds). But five unrelated defect families across 27 files (+1379/−303) is far from the charter's "smallest footprint," and several behaviours change silently: the capture.rs skip widens from reused-weight spans to all numeric ranges (capture.rs:3420-3425, untested); a new host_extent JSON key crosses into Python (core_storage.py:103); and the claimed 64-bit widening is partial — chunk_pkt_offs, lane_byte_offs, low_base_out stay 32-bit (kv_codec_gpu.cu:1558-1586). Documentation is untouched despite #618 documenting the format. CI is red on head e029dc8, and all evidence was gathered on main 8da73911.

Verdict: Worth it with changes. lukealonso is a charter priority contributor and must not be closed as low value. Before merge: (1) re-run evidence on the PR head and get CI green; (2) document and test the widened capture.rs skip, the host_extent key, and sha256-as-PayloadId; (3) complete the kernel 64-bit widening or correct the claim; (4) confirm kv_codec.py::_CACHE invalidates stale cubins against the changed kernel ABI; (5) split the unbenchmarked export-pipeline performance work out with #210 measurements. The signing, ABI, ReadRing, and #631 fixes should land promptly.

Full report Decide Value: yes (100%): This change is worth reviewing: it provides value to the project in line with its charter.

Classify intake

Selected: triage:review, priority:P2, bug, performance, area:preparation

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

Applied: +triage:review, +priority:P2, +bug, +performance, +area:preparation

Correctness and contracts

Correctness / Contracts / System-Level review — PR #647 (e029dc8)

I read every changed hunk in eos/src/ioring.rs, heliopause/src/{allocator,processes,python}.rs, all nine heliopause/src/export/* files, helios/src/core/{conversion,conversion/edit,protection,reader}.rs, the eight ignition/preparation files, the touched tests, plus direct callers/contracts (helios/manifest.md, helios/proto/runtime_core.proto (not opened), helios/src/core/{cache,reader,export,synthesis}.rs, helios/src/offload via search, ignition/preparation/model_core.py (not opened), host_ranks.py (not opened), tests/preparation/test_export_transfer.py (not opened)). Eight findings, three of them material; the core-signing repair itself is sound.

1. compilation.py "clamp to storage.nbytes()" is a no-op — Major

ignition/preparation/compilation.py:184-199 (diff hunk @@ -179,18 +180,37 @@)

        end = begin + span * value.element_size()
        ranges.setdefault(key, []).append((begin, end, node))
        storage_nbytes = int(value.untyped_storage().nbytes())
        limits[key] = max(limits.get(key, 0), storage_nbytes, end)
...
                a_end = min(storage_nbytes, (end + alignment - 1) // alignment * alignment)

The clamp bound is max(observed storage nbytes, end), so whenever a view's computed end already exceeds the storage (exactly the over-estimate case the PR is fixing, since span = 1 + sum((size-1)*stride) deliberately includes holes), the bound is raised to end and min() is a no-op. The description claims "_storage_regions … could extend past storage.nbytes(), while … _lower_storage slices clamped multi-dtype uint8 bases"; the multi-dtype slice in _lower_storage is likewise applied only if len(dtypes[key_for(node)]) > 1 and region_bytes % value.element_size() != 0, so a single-dtype region still passes an over-long base to aten.view.dtype. Impact: the out-of-bounds view.dtype/slice lowering that motivated the change can still be emitted. Fix: keep the true untyped_storage().nbytes() per key and clamp with min(true_storage_nbytes, …); if a real traced view legitimately exceeds it, fail loudly rather than widening the clamp.

2. kv_codec_gpu.cu 64-bit widening is partial and truncates silently — Major

ignition/preparation/kv_codec_gpu.cu hunk @@ -1565,41 +1565,41 @@ (~1576/1582/1587) and @@ -1632,15 @@ (~1635)

        chunk_pkt_offs[i] = (U)pos;
...
        lane_byte_offs[i] = (U)low_bytes;
...
    *low_base_out = (total_pkt < (uint64_t)orig_bytes) ? (U)low_base : 0u;
...
        B *dst = d_pkt + (size_t)(*low_base_ptr) + (size_t)lane_byte_offs[lane_id];

pos, low_bytes and low_base are now uint64_t, but they are immediately narrowed back to U (32-bit) in the two arrays and in low_base_out, and the compact kernel still takes const U *low_base_ptr. Per-chunk and lane offsets inside a packet plan therefore wrap at 4 GiB; because total_pkt < orig_bytes may still hold, the guard does not catch it, so lanes are written to wrapped destinations — silent corruption rather than a clean failure. The PR text claims it "widens plan accumulators and *low_base_ptr offsets to uint64_t". Impact: the concrete defect the change claims to fix is only partly fixed, and the remaining truncation is unobservable (no kernel execution ran; evidence is nvcc compile + ELF-symbol check only). Fix: widen chunk_pkt_offs/lane_byte_offs/low_base_out/low_base_ptr end-to-end (and the matching u64 slots in helios/src/offload/transfer/gpu_codec.rs (not opened)), or reject plans whose offsets exceed u32::MAX explicitly.

3. Cached-export Pass-1 skip widens from "reused weight spans" to "all numeric ranges" — Major (undeclared, untested)

heliopause/src/export/capture.rs:3419-3426

    let cache_scan = request.weight_payload.is_some() && request.options.cache.is_some();
    let skip_numeric = if cache_scan {
        merge_ranges(request.numeric.clone())
    } else {
        super::weight_reuse::numeric_ranges(request, &allocations)?
    };

numeric_ranges returns Ok(Vec::new()) unless request.options.reuse_weights.is_some() (weight_reuse.rs:218-220), so the previous skip set was empty for cached exports without --reuse-weights. Now every cached export skips all of request.numeric — both the D2H copy and, via the skip_numeric argument threaded into the pointer scan, pointer scanning of any numeric-classified buffers (which include 64-bit integer buffers). data_spans for cached exports no longer records those bytes. The description only says "skips request.numeric D2H in Pass 1 when cache_scan is true while still pointer-scanning non-numeric bytes"; the widening, the data_spans change, and the loss of numeric-range pointer scanning are not stated, and pr_files shows no test file covering capture.rs (tests changed: forward_artifact_sharing, peer_storage_groups, persistent, storage_lifetimes, tuning_shards). Fix: keep numeric_ranges(request, …)'s reuse-only semantics for the skip set, or state the new invariant in the description and add a capture-level test asserting data_spans for a plain cached export.

4. Payload transfer loses both sender- and receiver-side integrity checks — Major

heliopause/src/export/transfer.rs:600-620 and :1008-1040

        let file = super::io::open_read(path)?;
        let before = super::io::Identity::of(&file)?;
        files.insert(path.clone(), Source {
                size: before.size,
                sha256: hex.clone(),
                let mut digest = info.payload.is_none().then(Sha256::new);
...
                if let Some(digest) = digest
                    && format!("{:x}", digest.finalize()) != info.sha256
                {
                    return Err(invalid("rank payload digest mismatch"));
                }

Two removals, not one: (a) the pre-transfer scan is gone together with the post-scan Identity::of(&file) != before re-check that guarded against the object being replaced/mutated between the identity snapshot and the send (the remaining before is used only for size); (b) for every payload entry the receiver now computes no digest at all and no longer checks the declared sha256, so the wire field's meaning changes from "bytes you are receiving" to "the id you should look up later". The compensating check at install (install_payload_object → cache adopt_companion/store_slice) exists, so no silent corruption lands in the cache, but a corrupted/truncated in-flight payload now costs a full transfer before failing, and any other consumer of info.sha256 is reading a different contract. Fix: keep a cheap post-open Identity::of re-check on the sender (or drop before entirely so the unused snapshot is not mistaken for a guard), and in receive_rank verify the received object against info.payload at install time explicitly rather than relying on a distant call site.

5. DirectRing forces synchronous single-job I/O on the contended path — Minor

heliopause/src/export/io.rs:828-830, with :236-245

        if jobs.len() == 1 {
            return transfer_single_direct(file, jobs[0], write);
        }
                let count = ((source.length - offset).div_ceil(BLOCK as u64) as usize)
                    .min(self.depth)
                    .min(32);
                while buffers.len() < count {
                    match self.try_buffer()? {
                        Some(buffer) => buffers.push(buffer),
                        None => break,

IoBudget buffers are shared (self.pool under a mutex, latency .. try_buffer returns None when allocated == depth), so when the budget is contended — multi-rank export — buffers collapses to one and every batch takes the new blocking libc::pread/pwrite path instead of the ring. The scan reader thread then cannot overlap I/O with the consumer, which is the opposite of the intent on exactly the busy path; the uncontended fast path is unaffected. Fix: reserve the synchronous path for a genuine one-shot (e.g. IoBudget::depth == 1 or an explicit single flag) rather than for jobs.len() == 1.

6. retain_sources return value silently changes scope — Minor

heliopause/src/export/binding.rs:819-855

        let already_held: std::collections::BTreeSet<helios_core::core::PayloadId> = self
            .leases
            .lock()…
        …
        let count = retained.len();
        …
        self.retain_payload_leases(crate::export::PayloadLeases(retained))
        …
        Ok(count)

retained now excludes ids already leased, so the returned number is "newly leased this call", not "payloads leased for this rank". Callers ignition/preparation/model_core.py:67 (not opened) and host_ranks.py:496 (not opened) receive a value that drops to 0 for every rank after the first that shares payloads (which is the normal multi-rank case the dedupe targets); tests/preparation/test_export_transfer.py:244 (not opened) only pins the empty case. Any caller using the count as an "did this rank have weight payloads" signal inverts. Fix: return the post-insert self.leases.lock().len() (or document the new semantics and update callers).

7. ReadRing::flush now clamps kernel over-reporting instead of rejecting it — Minor

eos/src/ioring.rs:152-160

            // Account for every entry the kernel accepted before propagating a
            // submission error so Drop drains in-flight DMA before freeing buffers.
            let submitted = (submitted as usize).min(self.queued);
            self.queued -= submitted;
            self.in_flight += submitted;
            check(status)?;

The lifetime ordering fix itself is correct: accounting happens before check(status)?, so Drop/cancel_and_drain drains anything the kernel accepted. But the .min(self.queued) clamp converts a driver/duration mismatch (kernel claims more entries submitted than were queued) into a silent short-accounting: queued becomes 0, in_flight is short by the excess, and the subsequent if self.queued != 0 "incomplete submission" error cannot fire. Previously the same condition surfaced as an underflow/panic. Windows-only path, unexercised on Linux. Fix: return io::ErrorKind::InvalidData when submitted as usize > self.queued after adding the accepted entries to in_flight.

8. map_groups accepts any dropped view, not just omitted draft weights — Minor

heliopause/src/export/weight_reuse.rs:576-595

    for old in &prior.views {
        if current_names.contains(old.name.as_str()) || old.nbytes == 0 {
            continue;
        }
        …
            .push((old.offset, end));

The exclusion set is keyed on name absence, not on draft/speculative role, so a view that disappears for any other reason (recipe rename, engram plan change, a genuinely partial capture) is now subtracted from the cached initializers instead of tripping "is not covered by one declared weight group; export with weights". That check was the last guard that a --reuse-weights reuse is byte-complete for every retained view. The new test (map_groups_skips_omitted_draft_weights_and_clips_coalesced_initializers) only exercises the draft case. Fix: scope the omission to views whose prior group/dtype marks them as draft/speculative (or compare against the declared --no-mtp drop set) and keep the coverage error for everything else.

Verified sound (no finding)

Evidence/claim accuracy notes

Full report · Notes

Subtraction and simplicity

PR #647's diff is largely lean — python.rs (−22 lines) drops an outer Mutex, core.rs replaces two linear scans per tensor with a HashMap, processes.rs gives the join handle its own Mutex — but five changes are worth simplifying, three by deleting code.

  1. High: weight_payload.rs:574-583 fn merge_runs is now the same algorithm as the existing reachability.rs:12-24 fn merge_ranges, which the same crate already calls at weight_reuse.rs:249/:567/:594. Replace weight_payload.rs:561-562 (runs.sort_unstable(); return Ok(merge_runs(runs));) with super::reachability::merge_ranges(runs), delete the helper and its test at :1230-1236.

  2. High: Claimed::claim (weight_payload.rs:647-685) hand-rolls interval subtraction that reachability.rs:26-43 fn subtract_ranges already does; keep only the merged_start/merged_end/to_remove bookkeeping. Removes ~18 lines from the function the PR rewrote for simplicity.

  3. Medium-high: io.rs:914-921 transfer_batch repeats the jobs.len() == 1 => transfer_single_direct dispatch already at io.rs:828-830 in DirectRing::transfer; its only Linux callers (io.rs:648-657, :679) pass one-element slices, so the IoUring::new at :919 is unreachable — the very per-call allocation this PR aimed to remove. Delete it, call transfer_single_direct directly.

  4. Medium: allocator.rs:269-272 window_host_base is now test-only (production uses window_host_layout at :424-425); and allocator.rs:353-360 check_fits(...)? cannot succeed — the same check already failed at :312-314, and success would fall through to the Err at :361-363. Delete both.

  5. Medium: binding.rs:355-386 and :415-455 resolve stop_flag and metrics with the same five steps; one resolve_reference(obj, field, nbytes, align) helper removes ~40 of the 68 added lines and collapses the four-arm match at :401-415.

Minor: transfer.rs:25 BLOCK_BYTES (4 MiB) vs new io::BLOCK (8 MiB) at :650 with frames still 4 MiB — state the relation once; capture.rs:3421-3425 ternary leaves numeric_ranges unused on the cached path; tuning.py finally adds a third nested import torch.distributed and re-derives a rank already known at :448.

No AGENTS.md structural violation: no new flags, config keys, env toggles, fallbacks or model branches.

Not verified: exhaustive transfer_batch caller enumeration (one grep settles it); the two *_with_limit test seams' exact line numbers.

Full report · Notes

Final review

Recommendation: Changes Requested

Most of the core fixes in this PR are technically solid—the externalized core-signing rewrite (protection.rs/conversion.rs/conversion/edit.rs), stream-ordered granule zeroing (core_storage.py), CUmemAccessDesc ABI fix (peer_storage.py), multi-host ForwardCache relative paths (aot.py), sharded autotune reconciliation (#631, tuning.py), AOT storage region clamping and multi-storage mutation tracking (compilation.py), RankSupervisor lock decoupling (processes.rs/python.rs), and eos::ReadRing::flush lifetime accounting all hold up under direct inspection. However, verification uncovered two concrete blockers—a silent weight-corruption bug in weight_reuse.rs::map_groups whenever an omitted view shares bytes with a retained view (such as tied embed_tokens/lm_head weights under --reuse-weights --no-mtp), and an unmocked torch.cuda.current_stream call in DeviceRegion.grow that breaks the 12 CPU-mocked tests in tests/preparation/test_persistent.py on GPU-less runners (alongside red CI on head e029dc8 and test evidence reported only on origin/main 8da73911).

Merge Risk

Level: Medium

Walkthrough

Pre-merge Checks

Blockers

  1. Silent weight omission when an omitted view shares bytes with a retained view (heliopause/src/export/weight_reuse.rs:576-620).
    • map_groups builds omitted_by_allocation from every old in prior.views whose name is absent from current.views, then subtracts those ranges directly from every prior weight initializer (subtract_ranges(old_start, old_end, excluded) at line 617) without excluding ranges covered by retained views (prior.views ∩ current.views).
    • Whenever an omitted view aliases or overlaps a retained view's bytes—for example, tied embed_tokens or lm_head weights shared between target and MTP draft layers under --reuse-weights --no-mtp, or interleaved strided views sharing an allocation—the retained target bytes are silently subtracted out. If retained_pieces becomes empty (line 618), the initializer is skipped altogether; neither map_groups nor resolve_weight_payload checks that every non-empty span in catalog.groups is covered by result, so those retained target weights are silently left zeroed in the exported core.
    • Fix: Collect retained_by_allocation (merged intervals of old in &prior.views where current_names.contains(old.name.as_str()) && old.nbytes > 0) and subtract retained_by_allocation from omitted_by_allocation before clipping previous.initializers. Add a regression test in weight_reuse.rs where an omitted draft view aliases a retained target view's offset/range, asserting the retained target initializer is preserved intact.
  2. Unmocked torch.cuda.current_stream in DeviceRegion.grow breaks CPU-only test suite (ignition/preparation/core_storage.py:619-621, tests/preparation/test_persistent.py:40-72).
    • DeviceRegion.grow now unconditionally executes stream = torch.cuda.current_stream(device).cuda_stream. The packed_storage fixture in tests/preparation/test_persistent.py:48-72 (used by 12 unit tests designed to run on CPU with a fake Memory driver stub) does not monkeypatch torch.cuda.current_stream, so on any GPU-less CI runner torch.cuda.current_stream(0) fails immediately before cuMemsetD8Async is reached. Additionally, Memory.call (test_persistent.py:40-42) only asserts len(args) == 4 without verifying that the stream pointer was actually passed through.
    • Fix: In packed_storage (tests/preparation/test_persistent.py:48-72), monkeypatch torch.cuda.current_stream to return a sentinel SimpleNamespace(cuda_stream=0x1234) (asserting the passed device == storage.device), and assert args[3].value == 0x1234 in Memory.call. Re-run the test suite and confirm CI passes on the updated PR head.

Should Fix

  1. Re-run verification on PR head and satisfy charter #210 evidence for the performance changes (heliopause/src/export/{capture.rs,io.rs,transfer.rs}).
    • The PR description reports test runs gathered on origin/main (8da73911) rather than the PR head (e029dc8), and explicitly notes that the export-pipeline performance changes (capture.rs Pass-1 numeric skip, io.rs DirectRing reuse, transfer.rs 8 MiB batching and payload hashing skip) were not benchmarked end-to-end on GPUs. In addition, capture.rs:3420-3425 has no unit test covering the cache_scan branch (request.weight_payload.is_some() && request.options.cache.is_some() without --reuse-weights).
    • Fix: Either (a) add a unit/integration test for the cache_scan Pass-1 skip path and provide before/after export timing measurements on the PR head, or (b) split the unbenchmarked export-pipeline performance work into a follow-up PR with measurements so the urgent correctness fixes (sign_rewritten_envelope, stream-0 zeroing, #631 multi-host tuning/AOT, CUmemAccessDesc ABI, ReadRing::flush, compilation.py) can land promptly.

Subtract / Simplify

  1. Delete duplicate merge_runs in heliopause/src/export/weight_payload.rs:560-583, 1230-1235: With partial-overlap merging (start <= last.1), merge_runs is identical to heliopause/src/export/reachability.rs:12-24 (merge_ranges, which also sorts and drops empty spans). Replace lines 561–562 (runs.sort_unstable(); return Ok(merge_runs(runs));) with return Ok(super::reachability::merge_ranges(runs)); and delete merge_runs and its redundant test.
  2. Delete dead Linux transfer_batch in heliopause/src/export/io.rs:914-921: Every remaining Linux caller of transfer_batch (read_bounced at io.rs:648 and read_at at io.rs:679) passes a 1-element slice, making IoUring::new + transfer_batch_on_ring at io.rs:919-920 unreachable on Linux. Call a single-job helper (transfer_single_direct on Linux, transfer_batch on Windows) from those two sites and remove Linux transfer_batch.
  3. Deduplicate stop_flag and metrics resolution in heliopause/src/export/binding.rs:355-455: Both blocks repeat the same object extraction, non-empty allocation validation, default-0 offset parsing, resolve_mapped_host, alignment check, and JSON re-insertion. Extracting one helper (resolve_host_ref) eliminates ~35 lines.
  4. Delete test-only window_host_base wrapper in heliopause/src/allocator.rs:269-272: It has zero production callers (only tests at allocator.rs:1414-1433); point those assertions directly at window_host_layout(..., 1, None).

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes Decision to Test: no (99%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.