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

Raw Markdown for agents: https://autobot.eidonix.com/p/af895c99-02f2-4e3f-88da-c5e72430a304.md

#1 [high] Simplification findings for PR #609 (Subtraction lens)

PR #609 — Subtraction / Simplicity / Conventions

S1 (HIGH) scatter_disjoint is a line-for-line copy of scatter; delete one body

The PR adds scatter_disjoint (selene/src/shared/slice.rs:208-248) whose body is the exact mirror of the existing scatter (slice.rs:180-206) — same check, same slice_bytes guard, same page_at/row_at loop, differing only in copy_from_slice vs ptr::copy_nonoverlapping.

Existing (slice.rs:180-206):

    /// The inverse of [`gather`](Self::gather): write packed bytes into rank `rank`'s slices.
    pub fn scatter(
        &self,
        rank: usize,
        window: &mut [u8],
        pages: u32,
        row: bool,
        packed: &[u8],
    ) -> Result<()> {
        self.check(rank, window.len(), pages, row)?;
        if packed.len() as u64 != self.slice_bytes(rank, pages, row) {
            return Err(Error::new("a packed slice's length does not fit its pages"));
        }
        let r = &self.ranks[rank];
        let mut at = 0usize;
        for page in 0..pages {
            let to = self.page_at(rank, page) as usize;
            window[to..to + r.page_len as usize]
                .copy_from_slice(&packed[at..at + r.page_len as usize]);
            at += r.page_len as usize;
        }
        if row {
            let to = self.row_at(rank, pages) as usize;
            window[to..to + r.row_len as usize].copy_from_slice(&packed[at..]);
        }
        Ok(())
    }

New (slice.rs:214-248) repeats all of it with raw pointers.

Simplification: keep scatter as the safe API and make it a 3-line wrapper, deleting slice.rs:189-205:

        // SAFETY: `&mut [u8]` gives exclusive access to the whole window, so no other
        // thread can read or write any rank's slices during this call.
        unsafe { self.scatter_disjoint(rank, window.as_mut_ptr(), window.len(), pages, row, packed) }

Callers of scatter (selene/src/pool/agent.rs:1145, selene/src/pool/engine/outbound.rs:79, slice.rs tests) are unaffected. Net: ~18 lines deleted, one iteration order to maintain.

S2 (MEDIUM-HIGH) Third copy of the Windows IOCP attach dance — extract one helper

The PR adds a third verbatim copy of a 5-line #[cfg(windows)] block in selene/src/disk.rs:

new (disk.rs:2031-2035):

        let ring = Ring::new()?;
        #[cfg(windows)]
        ring.queue
            .attach(&file)
            .map_err(|e| io_failure("attach read-ahead file", e))?;

pre-existing (disk.rs:986-990): #[cfg(windows)] self.ring.queue.attach(&file).map_err(|e| io_failure("attach record writer", e))?; pre-existing (disk.rs:1296-1300): #[cfg(windows)] self.ring.queue.attach(&file).map_err(|e| io_failure("attach record reader", e))?;

Simplification: one cfg'd free function next to Ring, e.g.

#[cfg(windows)]
fn attach(ring: &Ring, file: &File, what: &str) -> Result<()> {
    ring.queue.attach(file).map_err(|e| io_failure(format!("attach {what}"), e))
}
#[cfg(not(windows))]
fn attach(_: &Ring, _: &File, _: &str) -> Result<()> { Ok(()) }

then three one-line calls with no #[cfg] at the call sites. Removes two of three cfg attributes and makes the new site identical to the reviewed Windows contract.

S3 (MEDIUM) MemoryStore::close computes the codec idleness predicate twice

selene/src/memory.rs:3077-3086 (existing busy closure):

        let busy = |store: &Self| {
            #[cfg(feature = "codec")]
            let compressor_idle = store.compressor.as_ref().is_none_or(|c| c.is_idle());
            #[cfg(not(feature = "codec"))]
            let compressor_idle = true;
            !(store.core.outbound.is_empty()

and the PR repeats the same cfg-gated check 10 lines later (memory.rs:3095-3098):

        #[cfg(feature = "codec")]
        let compressor_busy = self.compressor.as_ref().is_some_and(|c| !c.is_idle());
        #[cfg(not(feature = "codec"))]
        let compressor_busy = false;

Simplification: one method on the store (fn compressor_busy(&self) -> bool, with a #[cfg(not(feature = "codec"))] body returning false), used by both places; busy then reads !store.compressor_busy(). Kills the second cfg pair, and lets the #[cfg(feature = "codec")] on the mem::forget(compressor) at memory.rs:3109-3112 move with it into a #[cfg]-gated stop_compressor helper, so close has no cfg attributes at all.

S4 (MEDIUM-LOW) LocalRegions::ptr_mut is a pass-through alias of range

selene-manager/src/regions.rs:30-40 (private) and 58-66 (public) are the same signature and the same body:

    fn range(&self, region: Region, offset: u64, length: u64) -> io::Result<(*mut u8, usize)> {
        let (base, size) = self.mapping(region);
        let end = offset
            .checked_add(length)
            .ok_or_else(|| invalid("window range overflow"))?;
        if end > size as u64 {
            return Err(invalid("a window lies outside its region"));
        }
        // SAFETY: `offset <= end <= size`, so the pointer stays within the mapped region.
        Ok((unsafe { base.add(offset as usize) }, length as usize))
    }
...
    /// Raw writable pointer to a validated range for concurrent disjoint sub-writes.
    pub fn ptr_mut(
        &self,
        region: Region,
        offset: u64,
        length: u64,
    ) -> io::Result<(*mut u8, usize)> {
        self.range(region, offset, length)
    }

Also note the returned length is literally the caller's own length echoed back (length as usize), and the only call site (selene-manager/src/data/channel.rs:934-938) immediately feeds it to scatter_disjoint as window_len, which re-derives the expected value from pages/row anyway. Simplification: drop ptr_mut and make range pub (or return just *mut u8 and let bytes/bytes_read supply length as usize), so one name and one bounds check exist instead of two names.

S5 (LOW) Quarantine now repeats the same take + mem::forget idiom 7 times

selene/src/pool/engine/mod.rs:555-566:

        for regions in self.draining.drain(..) {
            std::mem::forget(regions);
        }
        if let Some(regions) = self.sess.as_mut().and_then(|sess| sess.regions.take()) {
            std::mem::forget(regions);
        }
        if let Some(super::shm::Attachment::Shm { regions, .. }) = self.attachment.take() {
            std::mem::forget(regions);
        }
        if let Some(staging) = self.net.take() {
            std::mem::forget(staging);
        }

plus selene/src/pool/agent.rs:1729-1737 (three more). The idiom has no helper anywhere in selene (all 20 mem::forget sites are raw). A single fn retain<T>(value: Option<T>) (or fn retain_for_process<T>(…)) used at all seven sites would encode "this mapping is kept for the life of the process" once; the two new hunks are what pushed the count from 3 to 7. Related stale comment the Arc now makes moot: selene/src/pool/net.rs:61-63 still says /// Registrations by local data socket address. Declared first so staging is /// unregistered before the region is unmapped. — after _region: Arc<Region> in rdma::Device (selene/src/pool/rdma.rs:35-36) a forgotten device keeps its own Arc, so field order is no longer what protects that case; the memory.rs/disk_store.rs comments were updated by this PR, this one was not.

S6 (LOW) checked-add hardening in SliceLayout::new duplicates unchecked arithmetic in Layout::new

selene/src/shared/slice.rs:69-74 (new):

            page = page
                .checked_add(page_len)
                .ok_or_else(|| Error::new("page record size overflow"))?;
            row = row
                .checked_add(row_len)
                .ok_or_else(|| Error::new("row record size overflow"))?;

The same two accumulations are plain += in the function that actually builds the geometry the value is compared against — selene/src/geometry.rs:177-178 (page_record_bytes += offset; row_record_bytes += rank.row_record_bytes();). Either drop the new checks (slice.rs:76 already rejects any disagreement with geometry.page_record_bytes) or put the overflow check where the sums are formed; two disciplines for one sum is churn the PR description does not mention.

#3 [high] Research summary

I reviewed all 15 changed hunks for removable code, duplication and repo-convention violations, reading each against the surrounding code and existing helpers in selene / selene-manager.

Six findings are in the scratchpad, ranked. The top three: (1) the new SliceLayout::scatter_disjoint (selene/src/shared/slice.rs:208-248) is a line-for-line copy of the existing safe scatter (slice.rs:180-206) — same check, same slice_bytes guard, same page_at/row_at loop — so scatter should become a 3-line wrapper over it and ~18 lines should go; (2) the new Windows IOCP attach in ReadAhead::start (selene/src/disk.rs:2031-2035) is the third verbatim copy of the same #[cfg(windows)] ring.queue.attach(&file).map_err(...) block (pre-existing at disk.rs:986-990 and 1296-1300) and belongs in one cfg'd helper; (3) MemoryStore::close recomputes the codec-gated idleness predicate it already has ten lines above (memory.rs:3077-3086 vs 3095-3098), which should be one compressor_busy() method so close loses both cfg pairs. Lower-value: LocalRegions::ptr_mut is a pass-through alias of the private range that also echoes the caller's own length back (selene-manager/src/regions.rs:30-66); the quarantine hunks bring the take + mem::forget idiom to seven sites with no shared helper and leave net.rs:61-63's field-order comment stale now that _region: Arc<Region> protects the case; and the new checked-add in SliceLayout::new (slice.rs:69-74) imposes a rigour the sum's actual producer, Layout::new (geometry.rs:177-178), does not.

I also recorded (scratchpad note 2) what the diff already simplifies and should not be flagged: the collapsed offload test assertion, rdma::Device::open losing its unsafe, the local ActiveGuard, the range factoring, and the absence of any new flag, cfg gate or public API. The diff is broadly lean; the waste is concentrated in the three duplicated constructs above.

#4 [high] Report framing: verdict, ranked list, convention citations, unverified item

Report framing (Subtraction / Simplicity / Conventions lens, PR #609)

Verdict paragraph (use this shape)

The diff is lean in direction and contains no new flags, cfg knobs, feature gates, fallback layers or public API (all new items are pub(crate)), so the AGENTS.md "no unsupported abstractions" rule is met. The waste is concentrated in three duplicated constructs the PR adds where an existing construct already existed, plus three smaller items. No finding is a correctness bug; each is a delete-or-collapse.

Charter / AGENTS.md hooks to cite:

Ranked list (details in note 1)

  1. S1 HIGH — scatter_disjoint duplicates scatter body; make scatter a wrapper. ~18 lines deleted.
  2. S2 MED-HIGH — third verbatim #[cfg(windows)] ring.queue.attach(&file).map_err(...) copy; extract one helper; two of three cfg attributes disappear.
  3. S3 MED — MemoryStore::close recomputes the codec idleness predicate it already has in busy; one compressor_busy() removes both cfg pairs and lets the mem::forget cfg attribute move out of close.
  4. S4 MED-LOW — LocalRegions::ptr_mut is a pass-through alias of the private range and echoes back the caller's own length.
  5. S5 LOW — take + mem::forget now at 7 sites (engine/mod.rs:555-566, agent.rs:1729-1737) with no helper; plus stale field-order comment at net.rs:61-63.
  6. S6 LOW — checked-add in SliceLayout::new (slice.rs:69-74) vs unchecked += in Layout::new (geometry.rs:177-178); two disciplines for the same sum, unmentioned in the description.

Verified call-site inventory (supports S1)

scatter callers, all safe-API, none need raw pointers:

mem::forget sites in selene/src: 20 total (grep mem::forget), none routed through a helper — pool/engine/mod.rs:556,559,562,565; pool/agent.rs:1725,1730,1733,1736; pool/net.rs:711,713; pool/rdma.rs:107; shared/rdma.rs:418; offload/sharded.rs:71,80; slab.rs:408; shard.rs:1304; disk_store/coalesce.rs:316; engine/{requester,source,writer}.rs. This is the evidence that the idiom is unabstracted and that #609 raises the count.

is_idle callers (supports S3): only memory.rs:3079 (inside busy) and memory.rs:3096 (the new duplicate). No other consumer, so a single compressor_busy() on MemoryStore has exactly two call sites.

Convention item I could not verify (state honestly if used)

AGENTS.md:58-60 requires "Record unresolved defects, unrun checks, and pending measurements in docs/TODO.txt, not in design documents." The PR body states the Windows #[cfg(windows)] IOCP attach was "not compiled or executed on Windows" — by that rule it needs a docs/TODO.txt entry. I did NOT open docs/TODO.txt (a grep with an invalid regex consumed the check, and no read followed), so I cannot say whether an entry exists. Report as "unverified / worth a grep", not as a violation.

What I did not do (scope honesty)

#2 [medium] What #609 already simplifies (do not re-flag)

Already lean / net subtraction — say so plainly