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

Raw Markdown for agents: https://autobot.eidonix.com/p/ba9ff3da-9dd6-4e0a-962d-eb366b9d4595.md

PR #609 — Subtraction, Simplicity & Conventions review

Key findings

The diff is lean in direction: no new flags, config knobs, feature gates, fallback layers or public API (every new item — Staging::region, rdma::Device::open, Engine::quarantine, ptr_mut — is pub(crate)/crate-private), so AGENTS.md's "no unsupported abstractions or churn" rule is respected. The waste is concentrated in three constructs the PR adds as twins of constructs that already exist, plus three smaller items. No finding here is a correctness bug; every one is a delete-or-collapse.

Ranked:

  1. HIGH — scatter_disjoint is a line-for-line copy of the existing scatter (selene/src/shared/slice.rs:214-248 vs slice.rs:180-206). Make scatter a 3-line wrapper and delete ~18 lines.
  2. MED-HIGH — the new Windows IOCP attach is the third verbatim copy of the same #[cfg(windows)] ring.queue.attach(&file).map_err(...) block (selene/src/disk.rs:2031-2035; pre-existing twins at disk.rs:986-990 and 1296-1300). One cfg'd helper removes two of the three #[cfg] attributes.
  3. MED — MemoryStore::close recomputes the codec-idleness predicate it already has ten lines above (selene/src/memory.rs:3095-3098 duplicating memory.rs:3077-3086). One compressor_busy() method lets close lose both cfg pairs and the mem::forget cfg.
  4. MED-LOW — LocalRegions::ptr_mut is a pass-through alias of the private range (selene-manager/src/regions.rs:30-40, 58-66), and it echoes the caller's own length back as the "validated length".
  5. LOW — the take + mem::forget idiom is now at 7 sites with no helper (selene/src/pool/engine/mod.rs:555-566, selene/src/pool/agent.rs:1729-1737), and the Arc rewrite leaves a stale field-order comment at selene/src/pool/net.rs:61-63 that the PR invalidated but did not update.
  6. LOW — checked-add hardening in SliceLayout::new (slice.rs:69-74) imposes a rigour the sum's actual producer, Layout::new, does not (selene/src/geometry.rs:177-178), and the description never mentions it.

What the diff already simplifies (explicitly not flagged)

Credit where due — these are net subtractions and should stay:

1. HIGH — scatter_disjoint copies scatter body-for-body; make scatter a wrapper

selene/src/shared/slice.rs:180-206 (existing, safe):

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

selene/src/shared/slice.rs:214-248 (new) repeats the identical prologue — self.check(rank, window_len, pages, row)?, the identical slice_bytes guard with the identical error string at slice.rs:224-226 — and the identical for page in 0..pages { … page_at … at += len } loop with only copy_nonoverlapping in place of copy_from_slice:

        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;
            let len = r.page_len as usize;
            // SAFETY: `check` verified the slice bounds inside `window_len`, and
            // rank `rank`'s slices are disjoint from every other rank's slices.
            unsafe {
                std::ptr::copy_nonoverlapping(packed.as_ptr().add(at), window.add(to), len);
            }
            at += len;
        }

Concrete simplification: delete slice.rs:189-205 and make scatter delegate:

        // 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) }

One implementation, one iteration order, one error string. All existing scatter callers (selene/src/pool/agent.rs:1145, selene/src/pool/engine/outbound.rs:79 (not opened), selene/src/shared/slice.rs:395 and :409) are unaffected; scatter_disjoint's two callers (selene-manager/src/data/channel.rs:941, slice.rs:458) stay as they are. Net ≈ 18 lines deleted.

This is also the charter-conformance point: "Solve the right problem in the right place … look for the smallest footprint in shared code, or a way to solve it without new code at all." The aliasing fix belongs inside scatter's existing body, not beside it.

2. MED-HIGH — third verbatim Windows IOCP attach block; extract one helper

New, selene/src/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, selene/src/disk.rs:986-990:

        #[cfg(windows)]
        self.ring
            .queue
            .attach(&file)
            .map_err(|e| io_failure("attach record writer", e))?;

Pre-existing, selene/src/disk.rs:1296-1300: the same block again with "attach record reader". A fourth variant exists at disk.rs:1846 (self.queue.attach(…)).

Concrete simplification: one cfg'd free function next to Ring:

#[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 attach(&ring, &file, "read-ahead file")?; with no #[cfg] at any call site. This also directly addresses the PR's own stated weakness: the new site is the only unexercised code path, and the description concedes it "was reviewed against the existing Windows IOCP attach contract in disk.rs but not compiled or executed on Windows." Copying a contract by hand is what made that review necessary; sharing one helper makes the three sites identical by construction.

3. MED — MemoryStore::close computes the codec-idleness predicate twice

Existing closure, selene/src/memory.rs:3077-3086:

        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 new code repeats the same cfg-gated check 10 lines later, selene/src/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;

The two are exact negations (is_none_or(|c| c.is_idle()) vs is_some_and(|c| !c.is_idle())), so a future edit to one can silently diverge from the other — and this predicate now decides whether the slab pool is leaked and whether a new operator-visible error is returned (memory.rs:3113-3115).

Concrete simplification: one method on MemoryStore:

#[cfg(feature = "codec")]
fn compressor_busy(&self) -> bool { self.compressor.as_ref().is_some_and(|c| !c.is_idle()) }
#[cfg(not(feature = "codec"))]
fn compressor_busy(&self) -> bool { false }

busy then reads !store.compressor_busy() and close reads self.compressor_busy(); the #[cfg(feature = "codec")] on the mem::forget(compressor) at memory.rs:3109-3112 moves with it into a stop_compressor helper, so close — the function an operator will have to reason about when the new error fires — carries no cfg attributes at all. is_idle has exactly these two call sites in the tree, so the refactor has no other consumers to update.

4. MED-LOW — LocalRegions::ptr_mut is a pass-through alias of range

selene-manager/src/regions.rs:30-40 (private):

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

and the new selene-manager/src/regions.rs:58-66:

    /// 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)
    }

Same signature, same body: one name too many for one bounds check. Worse, the returned length is the caller's own length echoed back (length as usize), and the only call site immediately re-derives the authoritative value from the layout anyway (selene-manager/src/data/channel.rs:934-941 passes layout.window_bytes(pages, row) in and scatter_disjoint re-checks it against pages/row). Concrete simplification: since range is the only real implementation and bytes/bytes_read are its other two callers, either make range pub and delete ptr_mut (one name, one doc comment), or have it return just *mut u8.

5. LOW — take + mem::forget is now 7 sites with no helper; and one field-order comment went stale

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 three more in selene/src/pool/agent.rs:1729-1737. The idiom has no helper anywhere in selene — all ~20 mem::forget sites in the crate are raw (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 (not opened); offload/sharded.rs:71 (not opened),80; slab.rs:408; shard.rs:1304 (not opened); disk_store/coalesce.rs:316 (not opened)). This PR is what pushes the quarantine count from 3 to 7. A single fn retain_for_process<T>(value: Option<T>) used at all seven sites encodes the one policy ("keep this mapping for the life of the process") once instead of as seven look-alike statements, which matters because the policy is exactly the kind of thing a future reader must be able to audit in one place.

Related, and free to fix: 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 this PR, region: Arc<Region> (net.rs:64) is retained by rdma::Device (selene/src/pool/rdma.rs:35-36), so a forgotten device keeps its own Arc and field order is no longer what protects that case. This PR updated the equivalent field-order comments in memory.rs:2237-2246 and disk_store.rs:206-211 but left this one asserting an invariant the change made moot. Delete or rewrite the second sentence. (Note field-order invariants generally: they are the PR's main mechanism in memory.rs/disk_store.rs and no compiler check protects them — worth one sentence in review, not a change request.)

6. LOW — the checked-add hardening imposes a rigour the producer does not follow

selene/src/shared/slice.rs:69-74:

            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 forms the geometry these values are compared against — selene/src/geometry.rs:177-178 (page_record_bytes += offset; row_record_bytes += rank.row_record_bytes();) — and slice.rs:76 then rejects any disagreement with geometry.page_record_bytes. Two disciplines for one sum, and an overflow error string that, on the path where geometry wrapped first, would be unreachable or misleading. Also, this hardening is outside the DMA/RDMA-lifetime thesis the PR argues: "Refactoring must directly support the requested behavior" (AGENTS.md). Concrete simplification: either drop slice.rs:69-74 back to += (the slice.rs:76 cross-check already catches disagreement) or put the checked arithmetic where the sums are formed in geometry.rs and reuse it.

Open questions / not verified