Subtraction and simplicity scratchpad · NVIDIA/hyperflare-inference #647

Raw Markdown for agents: https://autobot.eidonix.com/p/0c085cd0-9d09-4782-b4c0-76f3db66e196.md

#1 [high] Research summary

Subtraction, Simplicity & Conventions review — PR #647

The diff is mostly lean and a genuine net simplification in places (python.rs −22 lines by dropping the outer Mutex on RankSupervisor; core.rs replaces two linear scans per tensor with one HashMap; processes.rs moves the join handle into its own mutex instead of a new lock discipline). Five changes are worth simplifying; three of them delete code rather than add it.

1. weight_payload.rs::merge_runs is now a byte-for-byte duplicate of reachability::merge_ranges (high value)

heliopause/src/export/weight_payload.rs:574-583 (post-image), after this PR:

fn merge_runs(runs: Vec<(u64, u64)>) -> Vec<(u64, u64)> {
    let mut merged: Vec<(u64, u64)> = Vec::with_capacity(runs.len());
    for (start, end) in runs {
        match merged.last_mut() {
            Some(last) if start <= last.1 => last.1 = last.1.max(end),
            _ => merged.push((start, end)),
        }
    }
    merged
}

heliopause/src/export/reachability.rs:12-24 already implements exactly this merge (plus retain(start<end) and sort_unstable):

pub(crate) fn merge_ranges(mut ranges: Vec<(u64, u64)>) -> Vec<(u64, u64)> {
    ranges.retain(|(start, end)| start < end);
    ranges.sort_unstable();
    let mut merged: Vec<(u64, u64)> = Vec::new();
    for (start, end) in ranges {
        if let Some(last) = merged.last_mut().filter(|last| start <= last.1) {

The only reason the local copy existed was that it merged adjacent-only runs; this PR widens it to partial overlaps, which is precisely what reachability::merge_ranges already did, and weight_reuse.rs:249 and :567 already call super::reachability::merge_ranges in the same crate. Replace line 562's return Ok(merge_runs(runs)); with super::reachability::merge_ranges(runs) (the runs.sort_unstable() on line 561 is then redundant too), delete merge_runs (574-583) and its new test at weight_payload.rs:1230-1236, and assert the merge behaviour through merge_ranges' existing cases. One interval-merging algorithm instead of two.

2. Claimed::claim's piece walk duplicates reachability::subtract_ranges (high value)

heliopause/src/export/weight_payload.rs, new claim body (post-image ≈643-690):

        let claimed = self.ranges.entry(allocation.to_string()).or_default();
        let mut pieces = Vec::new();
        let mut cursor = start;
        let mut merged_start = start;
        let mut merged_end = end;
        let mut to_remove = Vec::new();
        ...
            if taken_start > cursor {
                pieces.push((cursor, taken_start.min(end)));
            }
            cursor = cursor.max(taken_end);
            merged_end = merged_end.max(taken_end);
            to_remove.push(taken_start);
        }
        if cursor < end {
            pieces.push((cursor, end));
        }

Computing "the parts of [start,end) not already claimed" against a sorted disjoint interval list is exactly reachability::subtract_ranges (reachability.rs:26-43), whose body is the same loop with pending & mutations style bookkeeping removed:

pub(crate) fn subtract_ranges(start: u64, end: u64, excluded: &[(u64, u64)]) -> Vec<(u64, u64)> {
    let mut cursor = start;
    let mut spans = Vec::new();

Replace the cursor/pieces loop with let pieces = super::reachability::subtract_ranges(start, end, &ordered_claimed); (collecting the BTreeMap keys into a Vec once, which Claimed::ranges already does), keeping only the merged_start/merged_end insertion and to_remove maintenance. That removes ~18 hand-rolled lines from a function whose whole point in this PR was to be simpler.

3. io.rs: the Linux transfer_batch is a duplicate dispatch whose only callers pass one job (medium-high value)

heliopause/src/export/io.rs:914-921:

#[cfg(target_os = "linux")]
fn transfer_batch(file: &File, jobs: &[(*mut u8, usize, u64, usize)], write: bool) -> Result<()> {
    if jobs.len() == 1 {
        return transfer_single_direct(file, jobs[0], write);
    }
    let mut ring = io_uring::IoUring::new(jobs.len().next_power_of_two() as u32)?;
    transfer_batch_on_ring(&mut ring, file, jobs, write)
}

This is the same single-job dispatch that DirectRing::transfer performs at io.rs:828-830:

        if jobs.len() == 1 {
            return transfer_single_direct(file, jobs[0], write);
        }

The only remaining Linux callers of transfer_batch are read_bounced (io.rs:648-657) and read_at (io.rs:679), each passing a one-element slice (&[(...)]), so the IoUring allocation on line 919 is unreachable from production code — i.e. this PR leaves behind a ring-creating path nobody uses. Delete io.rs:914-921 and call transfer_single_direct(&file, job, false)? directly at 648 and 679. The Windows transfer_batch (1038) and DirectRing stay as they are.

4. allocator.rs: window_host_base is test-only, and the tail of window_host_layout is dead (medium value)

heliopause/src/allocator.rs:269-272:

fn window_host_base(base: u64, extent: u64, world: u32) -> Result<u64> {
    let (host_base, _) = window_host_layout(base, extent, world, 1, None)?;
    Ok(host_base)
}

After the change every caller is a test (allocator.rs:1414, 1422-1433); the production caller at :425 uses window_host_layout. A production wrapper that exists only to keep old test call sites compiling should go: delete it and point the five test assertions at window_host_layout(..., 1, None).

Immediately below, allocator.rs:353-360 is a branch that cannot succeed:

        address_space::check_fits(
            "native core host window",
            candidate_base,
            u64::from(world).saturating_mul(default_extent),
            Some(bits),
        )
        .map_err(invalid)?;
    }
    Err(invalid(
        "core host reservations would overlap or overflow the virtual address space",
    ))

On reaching this point default_fits_bits (computed at :312-314 from the same candidate_base) has already been false and the narrow-address-space placement at :325-352 has already failed, so check_fits here can only return Err — and if it ever returned Ok the function would fall through to the Err below anyway. Delete lines 353-360; the existing Err at 361-363 is the only outcome.

5. binding.rs: the metrics resolution repeats the stop-flag resolution line for line (medium value)

heliopause/src/export/binding.rs:355-386 resolves stop_flag and then :387-455 resolves metrics with the identical five steps — read allocation name, default offset to 0, resolve_mapped_host(name, off, nbytes), an alignment check, reinsert the resolved object:

                 let (stop_alloc, stop_final_off) = resolve_mapped_host(&stop_name, stop_off, 4)?;
                 if stop_final_off % 4 != 0 {
                     return Err(super::invalid(
                         "persistent worker stop flag offset must be 4-byte aligned",
                     ));
                 }
                 worker_obj.insert(
                     "stop_flag".into(),
                     serde_json::json!({"allocation": stop_alloc, "offset": stop_final_off}),
                 );

versus

                         let (metrics_alloc, metrics_final_off) =
                             resolve_mapped_host(&metrics_name, metrics_off, metrics_bytes)?;
                         if metrics_final_off % 8 != 0 {
                             return Err(super::invalid(
                                 "persistent worker metrics offset must be 8-byte aligned",
                             ));
                         }
                         worker_obj.insert(
                             "metrics".into(),
                             serde_json::json!({
                                 "allocation": metrics_alloc,

Extract one closure resolve_reference(obj: &serde_json::Value, field: &str, nbytes: u64, align: u64, label: &str) and call it for "stop_flag" (nbytes 4, align 4) and "metrics" (nbytes count*8, align 8); the match (metrics_val, metrics_count) three-arm validation at :401-414 can then collapse into reading metrics_count as Option<u64> and skipping the call when it is None. That removes roughly 40 of the 68 added lines without losing any of the four rejection cases the new test checks.

Smaller items, worth folding into the above

No AGENTS.md structural violation was found: no new flags, config knobs, environment toggles, fallback execution paths, or model-specific branches are introduced (the PR removes the --reuse-weights --no-mtp rejection rather than adding a switch), and the new unit tests in tests/preparation/ and the crate tests exercise behaviour rather than source text. The host_extent JSON key added without documentation in allocator.rs:722-726 is a docs/compatibility gap rather than a simplicity one.

#2 [high] Sub/Simplicity review PR #647 — final findings

Verdict: diff mostly lean; python.rs (−22, drops outer Mutex), core.rs (HashMap view lookup), processes.rs (join handle in own Mutex) are net simplifications. Five substantive simplifications + minor items.

  1. DUPLICATE merge helper (high). weight_payload.rs:574-583 post-image fn merge_runs(runs) -> Vec<(u64,u64)> with Some(last) if start <= last.1 => last.1 = last.1.max(end) is now identical to reachability.rs:12-24 pub(crate) fn merge_ranges (which also does retain(start<end) + sort_unstable). Call sites already use reachability::merge_ranges: weight_reuse.rs:249, weight_reuse.rs:567. Fix: at weight_payload.rs:562 replace return Ok(merge_runs(runs)); with super::reachability::merge_ranges(runs) (line 561 runs.sort_unstable() then redundant), delete 574-583 and new test weight_payload.rs:1230-1236.

  2. DUPLICATE range subtraction (high). weight_payload.rs Claimed::claim new body (~643-690 post-image): let mut cursor = start; ... if taken_start > cursor { pieces.push((cursor, taken_start.min(end))); } cursor = cursor.max(taken_end); ... if cursor < end { pieces.push((cursor, end)); } == reachability.rs:26-43 subtract_ranges(start,end,excluded). Fix: let pieces = super::reachability::subtract_ranges(start, end, &ordered_claimed); keeping merged_start/merged_end + to_remove. Removes ~18 lines.

  3. Dead/duplicate dispatch in io.rs (med-high). io.rs:914-921 transfer_batch re-implements the jobs.len() == 1 => transfer_single_direct dispatch already at io.rs:828-830 in DirectRing::transfer; its only remaining Linux callers are read_bounced (io.rs:648-657) and read_at (io.rs:679), each passing a 1-element slice, so the IoUring::new at :919 is unreachable. Fix: delete 914-921, call transfer_single_direct(&file, job, false)? at 648 and 679. Windows transfer_batch (1038) + DirectRing unchanged.

  4. allocator.rs test-only wrapper + unreachable tail (med). allocator.rs:269-272 fn window_host_base(...) now only used by tests (1414, 1422-1433); production uses window_host_layout at :425. Delete it, point tests at window_host_layout(..., 1, None). Also allocator.rs:353-360 trailing address_space::check_fits(... default_extent ...).map_err(invalid)?; cannot succeed: default_fits_bits (:312-314) is already false, narrow placement (:325-352) failed, and success would fall through to the Err at 361-363. Delete 353-360.

  5. binding.rs duplicate reference resolution (med). binding.rs:355-386 stop_flag resolution (resolve_mapped_host(&stop_name, stop_off, 4), % 4 != 0 check, reinsert) vs :387-455 metrics (same 5 steps, nbytes count*8, % 8). Extract one closure resolve_reference(obj, field, nbytes, align, label); collapse match (metrics_val, metrics_count) arms :401-414 into Option metrics_count + skip when None. Removes ~40 of 68 added lines; the 4 rejection cases in the new test still covered.

Minor:

AGENTS.md: no structural violation — no new flags/config/env toggles/fallback paths/model branches; PR removes the --reuse-weights --no-mtp rejection. host_extent JSON key undocumented (allocator.rs:722-726) is a docs/compat gap, not simplicity.