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

Raw Markdown for agents: https://autobot.eidonix.com/p/29b17343-0476-4bc5-85b9-a07de6407e75.md

#1 [high] Duplicated populate/register block in selene offload prepare (top subtraction)

selene/src/offload.rs:702-735 (post-change numbering, verified by read_file):

        let pool = if directory.is_none()
            && effective.pool.is_none()
            && effective.compression == KvCompression::Off
        {
            on_step(&format!("allocating {size_label} split host slab"));
            let started = Instant::now();
            match slab::SlabPool::try_sized_by_rank(&layout, bytes, intake, &contexts, registrar)? {
                Some(pool) => {
                    timings.slab_populate = Some(started.elapsed());
                    pool
                }
                None => {
                    on_step(&format!("populating {size_label} host slab"));
                    let started = Instant::now();
                    let mut pool = slab::SlabPool::sized(&layout, bytes, intake)?;
                    timings.slab_populate = Some(started.elapsed());
                    on_step(&format!("registering {size_label} host slab with CUDA"));
                    let started = Instant::now();
                    pool.register(registrar, context)?;
                    timings.cuda_register = Some(started.elapsed());
                    pool
                }
            }
        } else {
            on_step(&format!("populating {size_label} host slab"));
            let started = Instant::now();
            let mut pool = slab::SlabPool::sized(&layout, bytes, intake)?;
            timings.slab_populate = Some(started.elapsed());
            on_step(&format!("registering {size_label} host slab with CUDA"));
            let started = Instant::now();
            pool.register(registrar, context)?;
            timings.cuda_register = Some(started.elapsed());
            pool
        };

The None arm and the else arm are byte-identical (9 lines each). Concrete simplification: decide the split attempt first, keep only one populate/register sequence:

        let split = if directory.is_none()
            && effective.pool.is_none()
            && effective.compression == KvCompression::Off
        {
            on_step(&format!("allocating {size_label} split host slab"));
            let started = Instant::now();
            let split = slab::SlabPool::try_sized_by_rank(&layout, bytes, intake, &contexts, registrar)?;
            if split.is_some() {
                timings.slab_populate = Some(started.elapsed());
            }
            split
        } else {
            None
        };
        let pool = match split {
            Some(pool) => pool,
            None => {
                on_step(&format!("populating {size_label} host slab"));
                let started = Instant::now();
                let mut pool = slab::SlabPool::sized(&layout, bytes, intake)?;
                timings.slab_populate = Some(started.elapsed());
                on_step(&format!("registering {size_label} host slab with CUDA"));
                let started = Instant::now();
                pool.register(registrar, context)?;
                timings.cuda_register = Some(started.elapsed());
                pool
            }
        };

Preserves the exact step sequence the new tests assert (allocating → populating → registering; populating → registering on the non-split path), including the timer reset before SlabPool::sized and before register (tests: selene/src/offload/tests.rs:1229-1240, :1282-1288). Also note the original code was a single then(...).transpose()? closure before this PR, so the duplication is newly introduced by the timing instrumentation.

#2 [high] helios::offload::prepare_with_inputs_budget is a now-dead forwarder

helios/src/offload/mod.rs:82-99:

pub fn prepare_with_inputs_budget(
    options: &PrefixCacheOffload,
    identity: [u8; 32],
    geometry: Vec<CacheGeometry>,
    contexts: Vec<(usize, i32)>,
    inputs: PrepareInputs,
    host_budget: Option<u64>,
) -> Result<Preparation> {
    prepare_with_inputs_budget_with_progress(
        options,
        identity,
        geometry,
        contexts,
        inputs,
        host_budget,
        |_| {},
    )
}

Before this PR this function was the real wrapper that injected &registrar::CudaRegistrar; the PR turned it into a pass-through whose only content is |_| {}. Repo-wide search_code for prepare_with_inputs_budget finds callers only in selene (selene/src/offload.rs:573/582/595, selene/src/offload/tests.rs:758,787,935,964,1009,1080,1162,1208,1264,1331,1355) and the one helios caller helios/src/runtime_core/model.rs:966, which now calls prepare_with_inputs_budget_with_progress directly. So the helios wrapper at :82-99 has zero callers after this PR.

Also check retention: helios prepare_with_inputs (:72-80) is still used by helios/src/offload/pool/tests.rs:124, so it must stay. Concrete change: delete helios/src/offload/mod.rs:82-99, leaving the ladder prepare_with_inputs (:72) → prepare_with_inputs_budget_with_progress (helios :101, injecting CudaRegistrar). If keeping it as public API surface for external crates is desired, that decision should be stated; nothing in the workspace uses it. Alternatively keep only prepare_with_inputs + _with_progress in helios and let callers that need a host budget use the progress form.

#4 [high] Checked-for-duplication negative results + repo convention check

Checked and found NOT duplicating an existing helper / NOT removable:

  1. /sys and /proc parsers. Repo has per-crate proc parsing with no eos utility to reuse: selene/src/offload.rs:949 available_memory(meminfo, ...), flare-cli/src/orbit/gpu.rs:327 meminfo(), heliopause/src/export/io.rs:1033. None parse buddyinfo/vmstat/THP sysfs. eos/src/unix.rs is the right home; the new parsers (parse_active_sysfs_token, parse_thp_enabled/defrag, parse_hpage_pmd_size, parse_buddyinfo_free_hugepages, parse_vmstat_counter, :184-340) are pure &str -> value functions with no equivalent elsewhere. No duplication finding.

  2. #[cfg_attr(not(target_os = "linux"), allow(dead_code))] appears 19× in eos/src/unix.rs (lines 87,91,94,103,114,123,131,183,190,200,212,227,236,242,271,330,342,347,362). This matches existing repo idiom — helios/src/cuda.rs:147, heilos/src/execution/transport.rs:122-166 use exactly the same attribute. Not a convention violation; do not flag. A #[cfg(target_os = "linux")] mod grouping would remove the repetition but has no precedent in eos/ (eos/src contains only unix.rs, windows.rs, completion.rs, ioring.rs), so recommending it would itself be a convention change.

  3. MappingGuard (eos/src/unix.rs:139-181) and map_host_with(bytes, populate) (:652-662): the seam exists so tests can inject a failing/dispatching populate closure (mapping_guard_unmaps_on_population_error :822-833, adaptive_mid_mapping_fallback_merges_into_single_vma :1143-1200). It is 30 lines and replaces real munmap-on-error handling. Not speculative generality; keep.

  4. PrepareTimings (selene/src/offload.rs:331-340, one field timings on Prepared :368, timings: _ in open :835): three Option fields, no getters, no trait, no metric, no config key. Lean; nothing to subtract.

  5. prepare_with_inputs_budget_with_progress + on_step: impl FnMut(&str) in selene (:595-604): one closure parameter, no trait object, no progress struct. Matches repo idiom for callbacks (selene/src/disk.rs:1955 impl FnMut, selene/src/composite.rs:1983 impl FnMut(&CompositeStore) -> bool). Lean.

  6. elapsed_seconds (selene/src/offload.rs:478-480) duplicates an inline formatting idiom used elsewhere (helios/src/server/dashboard/scheduler.rs:276, flare-cli/src/orbit/controller.rs:441 use format!("{:.1}s", …as_secs_f64())), but there is no shared helper to reuse and it is a 3-line private fn beside gibibytes (:482-484), which follows the same pattern. Fine.

  7. Test additions: eos tests are policy-branching but deterministic (synthetic read_buddyinfo/read_compact_stall closures); selene tests use existing fixtures (crate::testing::IdentityRegistrar, TrackingRegistrar, UnsupportedSplitRegistrar from selene/src/offload/tests.rs:809-840) and add only SyntheticSplitMapping + SplitFixtureRegistrar (:1107-1156) because IdentityRegistrar::map_split returns Err (selene/src/testing.rs:462-464). Justified, minimal. parse_smaps_* helpers (:769-812) replace a 30-line hand-rolled smaps slicer that the previous test version contained — a net subtraction.

Conclusion for the lens: the diff is mostly lean and idiomatic for this repo; the two real subtractions are (a) the duplicated populate/register block in selene/src/offload.rs:713-735, and (b) the dead helios forwarder at helios/src/offload/mod.rs:82-99, plus (c) the duplicated PopulationMode variant/arm. No AGENTS.md structural violation found in code; the one process omission noted by the dossier is the missing docs/TODO.txt entry for the unrun flare run end-to-end check (AGENTS.md:57-59 "Record unresolved defects, unrun checks, and pending measurements in docs/TODO.txt"), which is a documentation-placement rule rather than a readability issue.

#5 [high] Research summary

I reviewed the Subtraction/Simplicity/Conventions lens on PR #625 by reading the full diff of all six changed files and checking each new construct against existing repo helpers and idiom.

Three real subtractions, one high-value each in two cases:

  1. selene/src/offload.rs:702-735 — the new timing instrumentation duplicated a 9-line populate/timer/register/timer block verbatim (the try_sized_by_rank → None arm and the else arm are byte-identical). Before this PR the whole body was one then(…).transpose()? closure, so the duplication is newly introduced. Collapsible to one split-attempt followed by one match split { Some(pool) => pool, None => {populate, register} }, preserving the exact step sequence and timer resets the new tests assert (selene/src/offload/tests.rs:1229-1240, :1282-1288).

  2. helios/src/offload/mod.rs:82-99 — prepare_with_inputs_budget is now a pass-through whose only content is |_| {}. It was the function that injected &registrar::CudaRegistrar; after the PR the only in-workspace caller (helios/src/runtime_core/model.rs:966) calls the _with_progress form directly, leaving this wrapper with zero callers. prepare_with_inputs (:72-80) must stay (used at helios/src/offload/pool/tests.rs:124 (not opened)).

  3. eos/src/unix.rs:116-121 / :626 — PopulationMode::BasePages and KernelDefaultOpportunistic take the same match arm ("64 MiB chunked populate, no THP advice"), so one variant and one arm suffice; the distinction already lives in select_population_mode (:254-258) and the docs prose.

What I checked and found genuinely lean (so the report does not over-ask): the #[cfg_attr(not(target_os = "linux"), allow(dead_code))] repetition (19 sites) matches existing idiom in helios/src/cuda.rs:147 (not opened) and execution/transport.rs:122-166 (not opened); the new /sys//proc parsers have no existing eos helper to reuse (the repo's proc parsing is per-crate: selene/src/offload.rs:949, flare-cli/src/orbit/gpu.rs:327 (not opened)); MappingGuard/map_host_with exist to inject failing populate closures and are exercised; PrepareTimings, the on_step: impl FnMut(&str) parameter and elapsed_seconds are three-field/one-closure/three-line additions with no trait, knob or metric, matching existing callback idiom; the selene tests reuse existing fixtures and only add the one registrar the existing IdentityRegistrar::map_split cannot serve; and the new parse_smaps_* helpers replace a 30-line hand-rolled smaps slicer, a net subtraction.

Conventions: no structural AGENTS.md violation in the code. The one process omission is the missing docs/TODO.txt entry for the unrun flare run end-to-end check (AGENTS.md:57-59), which is a documentation-placement rule rather than a readability defect.

Details and verbatim citations for all of the above are in scratchpad entries 1-4.

#6 [high] Final verdict for the Subtraction/Simplicity/Conventions lens (ranked, with scope limits)

VERDICT: the diff is mostly lean and idiomatic for this repo. Three simplifications, ranked; everything else was checked and found justified.

RANK 1 — selene/src/offload.rs:702-735 (duplicated populate/register block). Newly introduced by this PR; the pre-PR body was one then(...).transpose()? closure. The try_sized_by_rank None arm (:713-723) and the else arm (:725-735) are byte-identical 9-line sequences. Replace with one split attempt + one match split { Some(pool) => pool, None => { on_step populate; timer; SlabPool::sized; timings.slab_populate; on_step register; timer; pool.register; timings.cuda_register; pool } }. Behaviour and the asserted step sequences survive (selene/src/offload/tests.rs:1229-1240 split→contiguous: allocating/populating/registering; :1282-1288 contiguous+disk: populating/registering/scanning). ~18 lines net removed.

RANK 2 — helios/src/offload/mod.rs:82-99 (prepare_with_inputs_budget pass-through with |_| {}). Zero in-workspace callers after this PR (the sole helios caller moved to _with_progress at helios/src/runtime_core/model.rs:966; all other callers are in selene). Delete it; keep prepare_with_inputs (:72-80, used by helios/src/offload/pool/tests.rs:124) and prepare_with_inputs_budget_with_progress (:101) which injects &registrar::CudaRegistrar. Note: this is public API of the helios crate, so if the author wants to keep it for external crates that choice should be stated rather than implied by a silent wrapper.

RANK 3 — eos/src/unix.rs:116-121 + :625-632. PopulationMode::BasePages | PopulationMode::KernelDefaultOpportunistic share one match arm with identical behaviour. Collapse to a single variant; keep the differential reasoning where it already lives (select_population_mode :248-258 and docs/prefix-cache-offload.md:521-527). Test-matrix rows at eos/src/unix.rs:909-923 shrink accordingly. Optional low-priority rider in the same note: ThpPolicy.page_size (:126) only ever holds page_size() (:384, :394) and is read once (:624) — drop the field, call page_size().max(1) in populate_linux.

EXPLICITLY LEAN — do not ask to change:

LENS BOUNDARY: the reversed error propagation, unconditional 64 MiB chunking, per-call /proc reading and post-fallback whole-range MADV_NOHUGEPAGE are correctness/scope questions already held by the Correctness & Contracts lens; they are not re-raised here as simplification items (except the PopulationMode collapse, which is pure dead distinction, not a fix).

CONVENTION FINDING (structural, minor): AGENTS.md:57-59 requires unrun checks and pending measurements in docs/TODO.txt; the PR's own admission that flare run end-to-end timing is unmeasured is recorded only in the PR description. One TODO entry would satisfy the rule (contrast #323, which adds 13 lines there).

#3 [medium] PopulationMode carries two variants with identical population behaviour

eos/src/unix.rs:116-121:

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PopulationMode {
    BasePages,
    EagerHugepage,
    KernelDefaultOpportunistic,
    AdaptiveHugepage { fallback_needs_nohugepage: bool },
}

The consuming match, eos/src/unix.rs:625-632:

    match policy.mode {
        PopulationMode::BasePages | PopulationMode::KernelDefaultOpportunistic => {
            populate_chunks(base_ptr, bytes, POPULATE_CHUNK_BYTES, page_size)
        }
        PopulationMode::EagerHugepage => {
            advise_range(base_ptr, bytes, libc::MADV_HUGEPAGE);
            populate_chunks(base_ptr, bytes, POPULATE_CHUNK_BYTES, page_size)
        }

BasePages and KernelDefaultOpportunistic are already handled by the same combined arm: identical behaviour ("64 MiB chunked populate, no THP advice"). The distinction survives only in select_population_mode (:254-258), the decision-table test (eos/src/unix.rs:909-923) and prose. Concrete change: keep one variant (e.g. ChunkedBasePages) for both, delete the extra arm from the match (an arm the compiler forces to be written twice), drop the KernelDefaultOpportunistic rows from the test matrix. Net ≈ −6 lines of enum/match plus test rows, no behaviour change. If the intent is documentary (the doc at docs/prefix-cache-offload.md:523-526 explains both cases separately), the differential is already in that prose and in select_population_mode; keeping it in the enum buys nothing at the point of use.

Low priority: ThpPolicy.page_size (eos/src/unix.rs:126) only ever stores page_size() (detect_thp_policy :384, :394) and is read once at :624 as policy.page_size.max(1). Dropping the field and calling page_size().max(1) in populate_linux removes 2 lines and one derived-fact copy.