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

Raw Markdown for agents: https://autobot.eidonix.com/p/c0674c4a-bf6a-4745-9768-fa7561773948.md

Subtraction, Simplicity & Conventions review — PR #647

Key findings

The diff is mostly lean, and several changes are genuine net simplifications: heliopause/src/python.rs (−22 lines) drops the outer Mutex around the rank supervisor instead of adding lock discipline; export/core.rs::convert_prepared replaces two linear scans per tensor with one HashMap; processes.rs moves the join handle into its own Mutex so finish_shutdown can take &self. No AGENTS.md structural violation was found: no new flags, config knobs, environment toggles, fallback execution paths or model-specific branches are introduced, and the PR removes the --reuse-weights --no-mtp rejection rather than adding a switch.

Five changes are worth simplifying; three of them delete code rather than add it, and two are pure duplication of helpers that already exist in the same module tree:

  1. High — weight_payload.rs::merge_runs is now byte-for-byte the same algorithm as the existing reachability::merge_ranges, already called elsewhere in the crate.
  2. High — Claimed::claim hand-rolls the interval subtraction that reachability::subtract_ranges already implements.
  3. Medium-high — io.rs::transfer_batch gained a jobs.len() == 1 dispatch that duplicates the identical check in DirectRing::transfer, leaving an unreachable IoUring::new path on Linux.
  4. Medium — allocator.rs keeps a test-only window_host_base wrapper and an address_space::check_fits tail that can only return the error the next line returns anyway.
  5. Medium — binding.rs resolves stop_flag and metrics with the same five steps written out twice (~40 of 68 added lines removable with one helper).

1. High — weight_payload.rs::merge_runs duplicates reachability::merge_ranges

heliopause/src/export/weight_payload.rs:574-583:

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, and more completely (it also drops empty ranges and sorts):

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) {
            last.1 = last.1.max(end);

The only reason the local copy existed is that it merged adjacent-only runs; this PR widens it to partial overlaps (start <= last.1), which is precisely merge_ranges' behaviour. The crate already uses the shared helper in three places: weight_reuse.rs:249, :567, :594 (Ok(super::reachability::merge_ranges(ranges))).

Concrete simplification. At weight_payload.rs:560-563 the call site is:

            if dimension == outer.len() {
                runs.sort_unstable();
                return Ok(merge_runs(runs));
            }

Replace both lines with return Ok(super::reachability::merge_ranges(runs)); (the local runs.sort_unstable() becomes redundant — merge_ranges sorts), delete merge_runs (574-583) and its test merge_runs_merges_partially_overlapping_and_adjacent_intervals (weight_payload.rs:1230-1236), whose cases vec![(0,10),(5,15),(15,20),(18,19),(30,40),(35,50)] are all covered by the existing merge_ranges tests. Net: one interval-merging algorithm in the crate instead of two, and roughly −15 lines.

2. High — Claimed::claim re-implements reachability::subtract_ranges

heliopause/src/export/weight_payload.rs:647-685 (the pieces computation, 652-679):

        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();
        ...
        for (&taken_start, &taken_end) in claimed.range(start..) {
            if taken_start > end {
                break;
            }
            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));
        }

"the parts of [start, end) not already claimed, against a sorted disjoint interval list" is exactly heliopause/src/export/reachability.rs:26-43:

pub(crate) fn subtract_ranges(start: u64, end: u64, excluded: &[(u64, u64)]) -> Vec<(u64, u64)> {
    let mut cursor = start;
    let mut spans = Vec::new();
    let first = excluded.partition_point(|&(_, stop)| stop <= start);
    for &(begin, stop) in &excluded[first..] {
        if begin >= end {
            break;
        }
        if cursor < begin {
            spans.push((cursor, begin.min(end)));
        }
        cursor = cursor.max(stop.min(end));
    }
    if cursor < end {
        spans.push((cursor, end));
    }
    spans
}

Concrete simplification. Keep only the merge bookkeeping (merged_start/merged_end/to_remove), and compute the pieces as let pieces = super::reachability::subtract_ranges(start, end, &self.ranges(allocation)); (the Claimed::ranges accessor at :687-692 already materialises the sorted Vec<(u64,u64)>). That deletes the cursor/pieces loop, the range(..=start)/range(start..) pair and the early start >= end guard, i.e. ~18 of the ~38 lines the PR just rewrote — noteworthy because the stated benefit of this change was that Claimed became simpler.

3. Medium-high — io.rs: duplicated single-job dispatch, leaving an unreachable ring path

heliopause/src/export/io.rs:914-921 (added by this PR):

#[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 dispatch the new DirectRing::transfer performs at io.rs:828-830:

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

After the PR, the scan and write workers route through ring.transfer(...) (io.rs:262, :417), and 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, e.g.:

            transfer_batch(&file, &[(output.as_mut_ptr(), bulk, position, bulk)], false)?;

So on Linux transfer_batch can only ever take the shortcut branch; the IoUring::new(...) on line 919 is dead, and it is the exact per-call ring allocation this PR set out to eliminate. Concrete simplification: delete io.rs:914-921 and call transfer_single_direct(&file, job, false)? at :648 (inside read_bounced) and :679 (inside read_at). Worth a grep -n transfer_batch heliopause/src before landing to confirm no other Linux caller passes more than one job; the Windows transfer_batch (io.rs:1038+) and DirectRing stay untouched.

4. Medium — allocator.rs: test-only wrapper plus an unreachable validation tail

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

The PR moved its body into the new window_host_layout and left the old signature behind. The production caller now uses window_host_layout(base, extent, world, granule, bits) directly (allocator.rs:424-425); the only remaining users are tests (allocator.rs:1414, :1422-1425, :1433). A production-looking function kept alive solely for old test call sites should go: delete it and point those assertions at window_host_layout(..., 1, None), which the new test at :1436-1446 already demonstrates.

(b) heliopause/src/allocator.rs:353-360, the tail of the if let Some(bits) narrow-address-space branch:

        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",
    ))

This statement cannot succeed. Control reaches it only after the default placement was rejected — either default_fits_bits was already false at :312-314, which is computed by calling address_space::check_fits with the same candidate_base and span, so this call returns the same error again — or the narrow fallback at :325-352 failed. And if it could succeed, execution would fall straight through to the unconditional Err at :361-363 and report failure anyway. Delete :353-360; the Err on the next lines is the only outcome, and dropping it removes a misleading "this might work" branch from a function that is already the most branchy addition in the PR.

5. Medium — binding.rs: stop_flag and metrics reference resolution written out twice

heliopause/src/export/binding.rs:355-386 resolves stop_flag:

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

and :415-455 resolves metrics with the identical five steps (object lookup → non-empty allocation name → default offset to 0 → resolve_mapped_host(name, off, nbytes) → alignment check → reinsert):

                         let metrics_bytes = count.checked_mul(8).ok_or_else(|| {
                             super::invalid("persistent worker metrics size overflow")
                         })?;
                         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",
                             ));
                         }

Concrete simplification: extract one helper, e.g. fn resolve_reference(worker_obj: &mut serde_json::Map<..>, field: &str, nbytes: u64, align: u64, label: &str) -> Result<()>, and call it for "stop_flag" (nbytes 4, align 4) and "metrics" (nbytes count * 8, align 8). With that, the four-arm match (metrics_val, metrics_count) at :401-415 also collapses to reading metrics_count as Option<u64> and simply not calling the helper when it is absent — the three error arms exist only because both values are resolved a second time. This removes roughly 40 of the 68 lines the PR added to this function while still rejecting all four cases (None/0, Some/0, None/Some, Some/Some) that the new unit test checks.


6. Smaller items (fold into the above if touched anyway)

Conventions check

No AGENTS.md/module-convention violation of substance was found. No new CLI flags, config keys, env toggles, dual code paths or model-specific branches; the one new cross-language contract surface, the host_extent JSON key published at heliopause/src/allocator.rs:724-726 and consumed at ignition/preparation/core_storage.py:103 (not opened), is undocumented in docs/, which is a documentation/compatibility gap rather than a simplicity one. New unit tests in tests/preparation/ and the crate tests assert behaviour, not source text.

Open questions / not verified in this pass