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:
- HIGH —
scatter_disjointis a line-for-line copy of the existingscatter(selene/src/shared/slice.rs:214-248vsslice.rs:180-206). Makescattera 3-line wrapper and delete ~18 lines. - 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 atdisk.rs:986-990and1296-1300). One cfg'd helper removes two of the three#[cfg]attributes. - MED —
MemoryStore::closerecomputes the codec-idleness predicate it already has ten lines above (selene/src/memory.rs:3095-3098duplicatingmemory.rs:3077-3086). Onecompressor_busy()method letscloselose bothcfgpairs and themem::forgetcfg. - MED-LOW —
LocalRegions::ptr_mutis a pass-through alias of the privaterange(selene-manager/src/regions.rs:30-40,58-66), and it echoes the caller's ownlengthback as the "validated length". - LOW — the
take+mem::forgetidiom 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 atselene/src/pool/net.rs:61-63that the PR invalidated but did not update. - 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:
selene/src/offload/tests.rs:659: an 8-line nestedif/else if/elsecollapses toassert_eq!(order, if warm == 0 { vec![0] } else { vec![1, 0] });. SinceCompositeStore::closenow runs both closes (selene/src/composite.rs:1619-1626), thefail == Some(1)case genuinely yields[1, 0], so the branch was dead. (The dossier notes separately that the assertion no longer proves the old short-circuit — that is a coverage observation, not a subtraction complaint.)selene/src/pool/rdma.rs:44-63+35-36:unsafe fn open(base: *mut u8, len: usize, …)→ safefn open(region: Arc<Region>, …)with_region: Arc<Region>deletes a safety contract, a SAFETY comment at the call site (selene/src/pool/net.rs:111-114) and theabsent-moduleunsafestub. Fewer invariants, not more.selene/src/memory.rs:2024-2035: localActiveGuardRAII replaces manual decrement/notify and closes a panic hole. Localstruct … impl Dropinside a fn has precedent (selene/src/input.rs:1390(not opened),ModeGuard).selene-manager/src/regions.rs:30-40: factoring the bounds check intorangede-duplicates thechecked_add/mappingblock frombytes— good.selene/src/disk_store.rs:206-211,selene/src/memory.rs:2237-2246: the fix is a one-line field reorder plus a comment; nothing to delete.bytes_readis not duplication ofselene/src/pool/shm.rs:125(Region::bytes) — different crate side; the manager previously had only a&mutaccessor.
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
docs/TODO.txtentry for the unverified Windows path. AGENTS.md requires "Record unresolved defects, unrun checks, and pending measurements indocs/TODO.txt". The PR body states the IOCP attach was never compiled or run on Windows. I greppeddocs/TODO.txtfor Windows entries and found several existing ones (lines 88-102, 288-314) but did not confirm whether one covers this specific seleneReadAheadattach, so I am not asserting a violation — it is worth one grep by the merger.- Whether the relaxed
selene/src/offload/tests.rs:659assertion leaves any test covering theCompositeStore::closeshort-circuit it used to prove (dossier open question; ownership is #497's test). - No CI job identity for the failing head commit
304dd3acould be established from here; if the failing job is the Windows selene job, finding 2 becomes materially more valuable. - I did not run a build; every citation is from reading the head tree.