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

Raw Markdown for agents: https://autobot.eidonix.com/p/8331bc92-9c9e-4bf4-892f-baf5c80441cc.md

#1 [high] S1: fold 99/91 queries into host::use_host_vmm; delete bool param + tautological test

helios/src/runtime_core/host.rs:12-18

pub fn use_host_vmm(
    windows: bool,
    host_register_supported: bool,
    can_use_host_pointer: bool,
) -> bool {
    windows || !host_register_supported || !can_use_host_pointer
}

Both call sites re-implement the same two driver.check(cuDeviceGetAttribute…) blocks before calling it:

        let (
            mut address,
            mut granularity,
            mut gpudirect,
            mut integrated,
            mut host_register,
            mut can_use_host_pointer,
        ) = (0, 0, 0, 0, 1, 1);

Suggested replacement: pub unsafe fn use_host_vmm(driver: &driver::Driver, device: i32) -> Result<bool> in host.rs that performs the two queries itself (it already owns host_numa_properties, so it is the natural home), returning cfg!(windows) || host_register == 0 || can_use_host_pointer == 0. Then mod.rs:364-386 collapses to one line, allocator's tuple goes back to (address, granularity, gpudirect, integrated) = (0,0,0,0), and :465-480 disappears. ~45 lines net removed, and cfg!(windows) stops being a runtime parameter passed through a library API.

Also delete helios/src/runtime_core/host.rs:202-221:

        for windows in [false, true] {
            for host_reg in [false, true] {
                for host_ptr in [false, true] {
                    assert_eq!(
                        use_host_vmm(windows, host_reg, host_ptr),
                        windows || !host_reg || !host_ptr,

This asserts the function equals a copy of its own body (cannot fail unless the code is edited twice) and the four assert_eq!(driver::CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID, 134)-style lines at :205-208 merely restate the constant definitions. With the query folded in there is nothing left worth unit-testing here without a driver; the real behaviour is exercised end-to-end.

#2 [high] S2: delete the host_numa_properties==None fallback instead of re-checking 141 per region in Python

heliopause/src/allocator.rs:518-561 — two else arms are identical and the inner one silently keeps host_vmm = true when HOST_NUMA_VMM (141) is absent:

            let (host_base, host_extent) = if !cfg!(windows) && host_vmm {
                if let Some((_, host_granularity)) = host::host_numa_properties(&driver, device)? {
                    ...
                } else {
                    (default_host_base, default_host_extent)
                }
            } else {
                (default_host_base, default_host_extent)
            };

A device with (99==0 or 91==0) and 141==0 therefore records "host_vmm": true (allocator.rs:863) and a plain host window, then export fails later in Python. Delete the inner else and turn it into an error, e.g.

let properties = (!cfg!(windows) && host_vmm)
    .then(|| host::host_numa_properties(&driver, device))
    .transpose()?
    .flatten()
    .ok_or_else(|| invalid("host-backed CUDA VMM (HOST_NUMA_VMM) is required but unsupported on this device"))?;

(when !host_vmm or Windows, skip the query and use (default_host_base, default_host_extent) as today). That removes the divergent state and one branch.

Consequence: the per-region re-query in ignition/preparation/core_storage.py:499-502 becomes dead and should be deleted rather than kept as a second/third check of the same capability:

        supported = C.c_int()
        cuda.call("cuDeviceGetAttribute", C.byref(supported), C.c_int(141), C.c_int(device))
        if not supported.value:
            raise RuntimeError("mapped core storage requires host-backed CUDA VMM")

and with it tests/preparation/test_core_storage.py:130-139 (test_host_vmm_region_requires_host_numa_vmm) plus the import torch / tensor_from_pointer lines that were pushed below it (:503-504) back to the top of __init__ beside HostRegion.__init__ (core_storage.py:438-439). The decision stays in exactly one place — the native allocator — which is what the PR describes as its aim.

Related duplication of the same error string: helios/src/runtime_core/host.rs:115-116 and core_storage.py:502.

#5 [high] Research summary

Subtraction/simplicity review of PR #669 done. Five findings, all with exact citations in the scratchpad; the diff is functional but carries avoidable duplication, one dead fallback branch, and unreachable re-validation.

1. host::use_host_vmm should own its attribute queries (high). The helper takes (windows, host_register_supported, can_use_host_pointer) and both callers re-implement the same two cuDeviceGetAttribute blocks to feed it: helios/src/runtime_core/mod.rs:364-386 (~23 lines) and heliopause/src/allocator.rs:465-480 plus the six-element tuple at :448-455. Folding the queries into pub unsafe fn use_host_vmm(driver, device) -> Result<bool> (host.rs already owns host_numa_properties) removes ~45 lines and drops cfg!(windows) as a library-API parameter. Also delete helios/src/runtime_core/host.rs:202-221, which asserts the function equals a copy of its own body and restates four constant definitions.

2. Delete the HOST_NUMA_VMM == 0 fallback rather than re-checking it in Python (high). heliopause/src/allocator.rs:518-561 has two identical else arms; the inner one keeps host_vmm = true with a plain host window when 141 is absent, so export fails later. Erroring there instead makes the per-region re-query at ignition/preparation/core_storage.py:499-502 dead — delete it, restore import torch / tensor_from_pointer to the top of __init__ beside HostRegion.__init__ (:438-439), and drop tests/preparation/test_core_storage.py:130-139. One decision point, as the PR itself claims.

3. vmm_host_window is a parallel copy of window_host_layout's placement logic (medium). The "round up past the device span" arithmetic at allocator.rs:405-413 duplicates :320-347, and two tests now assert the same invariants. Extending window_host_layout with a reserve-probe callback and a low floor (validate → default → before-base → after-device → error) removes ~57 lines and the 8-argument call site at :531-555, including its #[allow(clippy::too_many_arguments)].

4. Unreachable re-validation and a duplicated floor constant (medium). allocator.rs:377-381 (power-of-two granule) cannot fire after host.rs:91-95 and allocator.rs:495-502; :521-525 and :540-542 are redundant usize guards. :526-530's 0x3_0000_0000/0x40_0000_0000 selection restates ignition's EXTERNAL_FLOOR (core_storage.py:42, :69) and infers which applies from a hardcoded base < 0x40_0000_0000.

5. Prose/rename churn (low). The WindowsHostRegion → HostVmmRegion rename has no alias and no in-repo migration need beyond core_storage.py:356; acceptable, but the surrounding doc quotes that are now stale (see dossier: docs/windows.md:212-217, docs/prefix-cache-offload.md:588-590, selene/src/offload.rs:693-695) are the ones the PR should have touched instead of widening docs/runtime-core-design.md with implementation detail (:104-113).

Net: about 120 lines of the +417 are removable without losing behaviour. Nothing in the diff is speculative generality in the "new config knob" sense — no flags or env switches were added — but the capability decision is spread over four places (Rust allocator, Rust runtime, Python snapshot, Python region) where one would do.

#7 [high] S0: verdict and line budget for the subtraction lens

Verdict for the Subtraction/Simplicity lens: the diff introduces no new flags, env switches, config knobs, or extension points (nothing of the "speculative generality" kind), and the new named attribute constants in helios/src/runtime_core/driver.rs:14-19 are a net simplification over the magic integers 18/116 that previously appeared inline at helios/src/runtime_core/device_memory.rs:45, helios/src/runtime_core/memory.rs:143, helios/src/cuda.rs:148/150/598/778 and heliopause/src/allocator.rs. Adding 91/99/134/141 to that set is the right move; do not ask for it to be reverted.

The real cost is duplication and defensive re-checking, in five places:

  1. S1 — use_host_vmm takes two bools that both call sites compute with identical 20-line query blocks; test restates the body. (~45 lines removable)
  2. S2 — allocator.rs:518-561 has two identical else arms; the 141==0 branch leaves host_vmm=true, forcing a second 141 check per region in Python (core_storage.py:499-502) plus its test. (~25 lines removable)
  3. S3 — vmm_host_window duplicates window_host_layout's after-device granule-aligned placement. (~57 lines collapsible into one function)
  4. S4 — three unreachable validations (granule power-of-two, two usize guards) and a Rust restatement of Python's EXTERNAL_FLOOR. (~15 lines)
  5. S5 — stale Windows-only host-VMM prose left in three docs/comments while the design doc grew attribute-level detail. (prose, low)

Total: roughly 120 of the +417 net lines are removable without changing behaviour. None of these are correctness bugs in their own right (the Correctness lens owns the 141==0 capability hole and the layout["host_vmm"] KeyError); where a workaround exists only because of an unreachable branch, the recommendation is to delete the branch, not patch it — that is S2 and S4.

Also worth one sentence in the report: helios/src/runtime_core/mod.rs:22 widens #[cfg(any(windows, test))] mod host to pub mod host, making pub unsafe host_numa_properties and pub fn use_host_vmm permanent public runtime API (used by heliopause, which already reaches helios_core::runtime_core::*). That is needed for heliopause to share the helper, but it is an undeclared API surface expansion: pub(crate) plus a re-export, or moving the shared helper to a deliberately named module, would keep the surface honest. Mention, not a blocker.

#3 [medium] S3: vmm_host_window is a parallel copy of window_host_layout's placement logic

The PR adds a second host-placement algorithm beside the existing one instead of extending it. allocator.rs already places the host window after the device windows, granule-aligned, inside the aperture (allocator.rs:320-347):

        let aligned_start = if granule > 1 {
            device_end
                .checked_add(granule - 1)
                .map(|n| n & !(granule - 1))

vmm_host_window repeats that same "rounded after the device span" placement plus the same prefer-the-default check (allocator.rs:405-413):

        if let Some(after) = base
            .checked_add(device_span)
            .and_then(|end| end.checked_add(window_align - 1))
            .map(|n| n & !(window_align - 1))
            && after.checked_add(total).is_some()
            && can_reserve(after, total)?

Two overlapping contracts, two tests asserting the same invariants (window_host_layout_narrows_wddm_host_window, allocator.rs ~1570-1587, and vmm_host_window_respects_aperture_floor_and_rank_count, :1589-1637). Suggested: add an Option<&mut dyn FnMut(u64,u64)->Result<bool>>-style can_reserve candidate check and a low floor to window_host_layout (one function: validate window → try default → try before-base at/above floor → try after device_end → error), and delete vmm_host_window (:361-418, ~57 lines) plus its #[allow(clippy::too_many_arguments)] and the 8-argument call site (:531-555). Forces one test to cover the whole "where does host storage go" contract instead of two.

If the merge is judged too invasive, at minimum drop #[allow(clippy::too_many_arguments)] by taking (base, extent, world) + a Defaults { base, extent } + the closure; 8 positional u64/bool-free args at :531-555 are unreadable.

#4 [medium] S4: unreachable re-validation (granule, usize width) and a duplicated EXTERNAL_FLOOR constant in Rust

All unreachable from the production path; keep one validation point, in host.rs.

(a) allocator.rs:377-381 re-validates the granularity that two earlier layers already guaranteed:

    if !granule.is_power_of_two() {
        return Err(invalid(format!(
            "invalid host allocation granularity {granule:#x}"
        )));
    }

host_numa_properties already returns Err for a non-power-of-two host granularity (helios/src/runtime_core/host.rs:91-95) and allocator.rs:495-502 already rejects a non-power-of-two device granule, so granule.max(host_granularity) at :520 is always a power of two. The only coverage is the unit test feeding it 0 and 3 << 20 (:1633-1634), i.e. impossible inputs. Delete both the check and those two asserts.

(b) allocator.rs:521-525 and :540-542 are a second usize-width guard over the same value:

                    let host_align = usize::try_from(host_granule).map_err(|_| {
                        invalid(format!(
                            "invalid host CUDA allocation granularity {host_granule:#x}"
                        ))
                    })?;

host_granule is granule.max(host_granularity as u64) and host_granularity is already a usize from host_numa_properties; the usize::try_from(bytes) in the closure (:540-542) is on a value this same code just bounded by the aperture. Both can go, and with them the try_from plumbing the closure needs (the closure could take the usize length host.rs would hand it).

(c) Magic floor duplicated in Rust that Python owns: allocator.rs:526-530

                    let min_host_base = if integrated != 0 && base < 0x40_0000_0000 {
                        0x3_0000_0000
                    } else {
                        0x40_0000_0000
                    };

These are ignition/preparation/core_storage.py's EXTERNAL_FLOOR values (0x4000000000 at :42, overridden to 0x300000000 for SM87 at :69) restated in Rust with a hardcoded base < 0x40_0000_0000 heuristic to infer which one applies. Either pass the floor from the caller that knows it (ignition already calls flare_core_initialize_window(rank, world, device, *window), core_storage.py:94-96) or derive it from the shipped window rather than a second integrated/address guess. Two copies of the same security floor is the kind of thing the charter's "Be explicit and pin everything. No magic defaults" rules out.

#6 [low] S5: rename has no alias; stale docs were left untouched while design doc grew implementation detail

Rename: WindowsHostRegion → HostVmmRegion (ignition/preparation/core_storage.py:492) with no alias kept. Only in-repo reference was core_storage.py:356, so it is self-consistent, but nothing signals the old name; a one-line WindowsHostRegion = HostVmmRegion was not needed in-repo and its absence is only an out-of-tree risk. Low priority — flag, do not block.

The prose budget went to the wrong file. docs/runtime-core-design.md gained implementation-detail prose (the PR adds ~11 lines at :104-113 spelling out the two attribute names and the fallback rule), while the docs that now state the opposite of the new behaviour were left alone:

These are stale-versus-code statements, i.e. the exact category AGENTS.md:57-58 says to record as unresolved defects in docs/TODO.txt rather than leave contradicted in design docs. Cheapest fix: correct the three sentences (they are one-line edits) and keep docs/runtime-core-design.md:104-113 at the level of the contract ("the native allocator reports the selected host range and backing mode"), not the attribute numbers.