Recommendation: Changes Requested
The core lifetime and aliasing fixes in PR #609 are technically sound and address real teardown, quarantine, RDMA-registration, Rust aliasing-UB, and Windows IOCP defects across selene and selene-manager. However, direct inspection of the changed close paths caught a concrete bug in MemoryStore::close (where a copier close error bypasses std::mem::forget(compressor) while compression is still busy, leaving AsyncCompressor::drop exposed to a condvar hang) and a broken error-path invariant in CompositeStore::close (clearing in-flight tracking maps even when a tier fails to close). Fixing those two small defects—and verifying the uncompiled #[cfg(windows)] attach path—will make this ready to merge.
Merge Risk
Level: Medium
- Teardown and quarantine paths across 15 files: Touches store shutdown (
MemoryStore,DiskStore,CompositeStore), pool quarantine (Engine,Agent,conn::shutdown), RDMA staging ownership (Staging/rdma::Device), and manager data-channel scatter (LocalRegions/SliceLayout). Normal hot-path latency and allocations are unchanged (bytes_readandcopy_nonoverlappingperform the same work without extra copies or locks). - Incomplete verification coverage: The
#[cfg(windows)]IOCP attach inselene/src/disk.rswas not compiled or executed on Windows, hardware qualification ran on a pre-rebase 4-PR stack rather than isolating#609, and no concurrent test exercises multi-rankscatter_disjointor multi-tier close failures. - Process-lifetime retention on timeout paths: Extending
std::mem::forgetto active session/SHM/shared regions on quarantine and leaking the slab pool/compressor on busy close is bounded (per-process, not per-op) and matches the existing quarantine contract, preventing DMA/RDMA UAF at shutdown.
Walkthrough
- Store teardown & compression lifetime (
selene/src/memory.rs,selene/src/disk_store.rs,selene/src/composite.rs,selene/src/offload/tests.rs): Declarestransfersbeforecore/poolso Drop joins copy threads before unmapping slabs; wrapsAsyncCompressor's active count in an RAIIActiveGuardso panics do not hangAsyncCompressor::drop; updatesMemoryStore::closeto leak the slab pool and forget a still-busy compressor; updatesCompositeStore::closeto close bothdiskandmemoryinstead of short-circuiting ondisk.close()?, and updates the close-order test inoffload/tests.rsaccordingly. - Quarantine & RDMA staging retention (
selene/src/pool/engine/mod.rs,selene/src/pool/conn.rs,selene/src/pool/agent.rs,selene/src/pool/net.rs,selene/src/pool/rdma.rs,selene/src/pool/engine/tests.rs): Retainssess.regionsandAttachment::ShminEngine::quarantine, retainsself.sharedinAgent::quarantine, callsengine.quarantine()onconn::shutdowntimeout beforeconn::rundropsengine, and wrapsStaging.regioninArc<Region>owned byrdma::Devicesoibv_dereg_mralways precedes unmapping (makingrdma::Device::opensafe). - Disjoint shared-region access (
selene/src/shared/slice.rs,selene-manager/src/regions.rs,selene-manager/src/data/channel.rs,selene-manager/src/pool/pass.rs): Adds checked-add overflow guards toSliceLayout::new, addsSliceLayout::scatter_disjoint, addsLocalRegions::bytes_read(&[u8]) andLocalRegions::ptr_mut((*mut u8, usize)), and switches send/pass readers tobytes_readand multi-rank scatter writers toptr_mut+scatter_disjointto eliminate overlapping&mut [u8]UB. - Windows IOCP attach (
selene/src/disk.rs): AttachesReadAhead's overlapped direct-I/O file handle toring.queueunder#[cfg(windows)]before spawning the read-ahead thread.
Pre-merge Checks
- [PASS] Security / malicious screen: No suspicious code, obfuscation, or unintended credential/network changes; checked arithmetic in
SliceLayout::newhardens wire-supplied geometry validation. - [PASS] Charter & value fit: Directly serves the Selene prefix-cache goal with no wire-protocol, config, CLI, dependency, or per-model changes.
- [WARN] Related / duplicate / conflict check: Stacks cleanly on
#607, with heavy same-area overlap across sibling PRs (#610,#611,#612) touching the same store/quarantine/scatter files. - [WARN] Tests & verification evidence: Unit tests were added for quarantine retention,
bytes_read, and single-threadedscatter_disjoint, but the#[cfg(windows)]path is uncompiled/untested on Windows, latency-parity claims have no numbers, and GPU qualification was run on a pre-rebase 4-PR stack.
Blockers
MemoryStore::closeskipsmem::forget(compressor)whentransfers.close()also fails (selene/src/memory.rs:3104-3116).- Verified behavior & impact: When both
closed.is_err()andcompressor_busyaretrue, line3105leaksself.core.pool, then line3107(closed?;) returns early before lines3108-3112take and forgetself.compressor. Whilehelios/src/server/runtime.rs:1260wraps the top-level store inManuallyDropon close error,MemoryStoreis a publicHostStoreimplementation; any standalone caller, test, or unwind path that dropsMemoryStoreafter this error executesAsyncCompressor::drop(selene/src/memory.rs:2043-2054), which blocks indefinitely onself.active.1.wait(count)while*count > 0—defeating the exact close-timeout safeguard this PR adds. - Concrete fix: Forget the busy compressor before propagating
closed?:if closed.is_err() || compressor_busy { self.core.pool.leak(); } if compressor_busy { #[cfg(feature = "codec")] if let Some(compressor) = self.compressor.take() { std::mem::forget(compressor); } } closed?; if compressor_busy { return Err(Error::new( "host KV compression did not finish before close", )); }
- Verified behavior & impact: When both
Should Fix
CompositeStore::closeclears in-flight journals unconditionally even when a tier fails to close (selene/src/composite.rs:1602-1627).- Verified behavior & impact: Before this PR,
self.disk.close()?; self.memory.close()?;returned before clearingoutbound,parked,inbound,jobs, andstale. Now those five maps are cleared even whendisk.is_err()ormemory.is_err(), directly contradicting the doc comment atselene/src/composite.rs:1603-1604("An error leaves ownership intact until their transfers can be drained"), diverging fromMemoryStore::close(selene/src/memory.rs:3107-3118, which skipsabandon()/events.clear()on error), and causingCompositeStore::stats()(selene/src/composite.rs:1558-1561) to under-reportoutbound_in_flight/inbound_in_flightafter a failed close. - Concrete fix: Propagate the tier close error before clearing:
let disk = self.disk.close(); let memory = self.memory.close(); disk.and(memory)?; self.outbound.clear(); self.parked.clear(); self.inbound.clear(); self.jobs.clear(); self.stale.clear(); Ok(())
- Verified behavior & impact: Before this PR,
- Verify the uncompiled
#[cfg(windows)]IOCP attach (selene/src/disk.rs:2032-2035) in Windows CI.- Verified behavior & impact: The placement and contract match
selene/src/disk.rs:986-990,selene/src/disk.rs:1296-1300,eos/src/completion.rs:49-54, andeos/src/windows.rs:115-124, but the PR notes it was never compiled or run on Windows. Confirming a green Windows build/test run closes the only uncompiled code path in the diff.
- Verified behavior & impact: The placement and contract match
Subtract / Simplify
- Deduplicate
SliceLayout::scatterby delegating toscatter_disjoint(selene/src/shared/slice.rs:181-248).scatter(181-206) andscatter_disjoint(214-248) repeat identicalcheck,slice_bytes, error-string, and page/row loop logic. Replace lines189-205with:
Deletes ~17 lines and guarantees one scatter implementation.// SAFETY: `&mut [u8]` provides exclusive access to `window` and cannot alias `packed`. unsafe { self.scatter_disjoint(rank, window.as_mut_ptr(), window.len(), pages, row, packed) }
- Extract one
Ring::attachhelper for the three identical Windows IOCP attach blocks (selene/src/disk.rs:986-990,1296-1300,2032-2035).- Adding a small
#[cfg(windows)]/#[cfg(not(windows))]Ring::attach(&self, file: &File, what: &str) -> Result<()>helper removes the repeated#[cfg(windows)]blocks at all three call sites and ensuresReadAhead::startshares the exact attach code compiled for record readers/writers.
- Adding a small
- Eliminate the duplicate
#[cfg(feature = "codec")]idleness check inMemoryStore::close(selene/src/memory.rs:3078-3081vs3095-3098).- Add a
fn compressor_busy(&self) -> boolhelper onMemoryStoreso the drain loop (!store.compressor_busy()) and post-loop leak/forget check (self.compressor_busy()) cannot drift andclosedrops the repeated#[cfg]pairs.
- Add a
- Collapse
LocalRegions::rangeintoLocalRegions::ptr_mut(selene-manager/src/regions.rs:30-66).ptr_mutis currently a 1-line pass-through to privaterangewith an identical signature. Inliningrange's body intoptr_mutand callingself.ptr_mut(...)frombytes_readandbytesremoves the redundant wrapper with no API change.
Nits
- Combined error reporting in
CompositeStore::close(selene/src/composite.rs:1626):disk.and(memory)dropsmemory's error message (such as the new"host KV compression did not finish before close") ifdisk.close()also fails. Using.and(...)matches existingseleneclose idioms (selene/src/disk_store.rs:2032,selene/src/pool/store.rs:642) and still returnsErr, so safety is preserved, but formatting both errors when both fail would improve shutdown diagnostics. - Stale field-order comment (
selene/src/pool/net.rs:61-63):Staging.rdma's doc comment still states"Declared first so staging is unregistered before the region is unmapped", which is now guaranteed structurally byrdma::Device._region: Arc<Region>(selene/src/pool/rdma.rs:35-36) rather than byStaging's field order. - Missing targeted unit tests: Adding a 2-thread test for concurrent
scatter_disjointover oneLocalRegionswindow and a test forMemoryStore::closewith a busy compressor would directly exercise the two new runtime paths.
Dropped on verification
- Dropped (Correctness lens Finding 3 — "
LocalRegions::ptr_mutbeing safe removes Rust'sunsafeguard and allows safe overlapping writes"): False under Rust's memory model. Creating a bounds-checked raw pointer(*mut u8, usize)is safe (and mirrors existing safeLocalRegions::mappingatselene-manager/src/regions.rs:23); dereferencing or writing through*mut u8still requiresunsafe(as atselene-manager/src/data/channel.rs:941). Onlybytes/bytes_readmust beunsafe fnbecause constructing&mut [u8]/&[u8]with unbounded lifetimes or aliasing is immediate UB. - Dropped (Correctness lens Finding 4 — "
conn::shutdown'sengine.quarantine()wrongly disables a slow live session and is undocumented"): Misread execution phase.conn::shutdown(selene/src/pool/conn.rs:208-224) only runs at line169afterserve()exits and immediately beforeconn::runreturns and dropsengine; failing to quarantine on timeout would unmap active session/SHM/staging regions while DMA/copies are still in flight. The PR description also explicitly states "invokeengine.quarantine()whenconn::shutdowntimes out". - Dropped (Dossier & Value Prop — "relaxing
selene/src/offload/tests.rs:659deleted coverage of theCompositeStore::closeshort-circuit"): False. The loop atselene/src/offload/tests.rs:619-621still executesfail == Some(1)(disk copier close failure) whenwarm != 0, and line659now strictly assertsorder == vec![1, 0], provingmemory.close()(0) still runs afterdisk.close()(1) fails. - Dropped (Correctness lens Finding 2 as Major — "
disk.and(memory)violates #397 / swallows error"): Downgraded to Nit. Bothselene/src/disk_store.rs:2032andselene/src/pool/store.rs:642use.and(...)for multi-component closes;close()still returnsErrand retains ownership inhelios/src/server/runtime.rs:1265-1273, so only secondary diagnostic text is omitted when both tiers fail simultaneously. - Dropped (Subtraction lens Finding 6 — "revert
SliceLayout::new'schecked_addback to+="): Unsafe recommendation.SliceLayout::new(selene/src/shared/slice.rs:46-80) validates wire-suppliedGeometryand already usedchecked_addon lines53-59; keeping lines69-74checked preventsu64wraparound from forging overlapping rank offsets inscatter_disjoint. - Dropped (Subtraction lens Finding 5 half A — "wrap
std::mem::forgetin aretain_for_processhelper"): Low-signal and reduces auditability of deliberate process-lifetime leaks (std::mem::forgetis explicit and greppable). Also corrected the Subtraction lens's inaccurate citation ofselene/src/disk.rs:1846as a fourthattachsite (line1846isself.queue.submit(...), notattach).