Correctness and contracts report · NVIDIA/hyperflare-inference #609

Raw Markdown for agents: https://autobot.eidonix.com/p/115e56c8-7dd9-4984-9a6d-35103d86fad2.md

Review of PR #609 — Correctness, Contracts & System-Level Consequences

Lens: correctness/safety & platform parity, unintended system-level consequences, architecture/contracts/charter, tests & claim accuracy. Every citation below is from files I opened at PR head 304dd3a; the diff was read hunk by hunk.

Key findings

  1. Major — CompositeStore::close now clears its copy journals before it knows whether the tiers closed, contradicting its own doc comment (selene/src/composite.rs:1602-1626). On a close failure the outstanding-copy bookkeeping needed to prove quiescence is destroyed, while MemoryStore::close may have deliberately pool.leak()ed and mem::forgeted the compressor.
  2. Major — disk.and(memory) silently discards the brand-new memory-tier error whenever both tiers fail (selene/src/composite.rs:1626 vs selene/src/memory.rs:3108-3116), i.e. exactly in the leaked-pool/forgotten-compressor case the message was written for.
  3. Major — LocalRegions::ptr_mut is a safe function that hands out a writable raw pointer with no safety contract, while the sibling bytes is unsafe for the same class of access (selene-manager/src/regions.rs:59-66 vs :68-80). The PR moves the aliasing-UB class from &mut [u8] to raw pointers and removes the compiler's unsafe marker from one half of it.
  4. Minor — conn::shutdown's new engine.quarantine() converts an ordinary shutdown timeout into permanent per-process retention plus PoolStatus::Disabled, including for a session that is still open and merely slow (selene/src/pool/conn.rs:216-223, selene/src/pool/engine/mod.rs:549-573). Intended by the PR's thesis, but operator-visible and absent from the description.
  5. The core lifetime mechanics check out. Field reordering, the ActiveGuard, the Arc<Region> re-plumbing, scatter_disjoint's bounds, and the Windows IOCP attach are each correct as written (detail below). The relaxed offload/tests.rs assertion is legitimate, not lost coverage — the dossier's concern there does not hold.
  6. No concurrent test exists for the aliasing fix, ptr_mut has only negative bounds asserts, and "zero latency or parity regression" carries no numbers; the cited 28/28 CUDA suite is helios::offload::, which this PR does not touch.

1. Correctness, Safety & Platform Parity

FINDING 1 — Major — CompositeStore::close destroys its journals even when a tier fails to close

selene/src/composite.rs:1602-1626:

/// Finish the copy-outs, disk writes, and restores in flight within
/// [`CLOSE_TIMEOUT`], then drain the disk and memory tiers. An error leaves
/// ownership intact until their transfers can be drained.
fn close(&mut self) -> Result<()> {
    ...
    let disk = self.disk.close();
    let memory = self.memory.close();
    self.outbound.clear();
    self.parked.clear();
    self.inbound.clear();
    self.jobs.clear();
    self.stale.clear();
    disk.and(memory)

The pre-change form (confirmed via the diff) short-circuited:

-        self.disk.close()?;
-        self.memory.close()?;

so any tier failure returned before the clear()s, leaving outbound/parked/inbound/jobs/stale populated for a later drain — which is precisely what the doc comment on line 1603-1604 promises ("An error leaves ownership intact until their transfers can be drained") and what MemoryStore::close's own failure idiom assumes (memory.rs:3104-3116: leak the pool, forget the compressor, then Err).

Impact: on a close failure the composite has erased the record of which copies were still outstanding while the memory tier has been intentionally leaked, so nothing can subsequently reconcile or report them; self.stats() will then advertise outbound_in_flight == 0 (composite.rs:1611-1613 uses exactly that predicate as the drain condition) even though a leaked pool with a forgotten compressor is still referenced. The bookkeeping outlives the invariant it existed to protect.

Fix: clear only when both tiers succeeded (if disk.is_ok() && memory.is_ok() { ...clear... }), or clear after a successful re-drain; if the intent really is to drop the journals on failure, the doc comment must be rewritten and the retained pool documented instead.

FINDING 2 — Major — disk.and(memory) drops the new memory error when both tiers fail

selene/src/composite.rs:1626 returns disk.and(memory); Result::and keeps only the receiver's error. The memory tier contributes a brand-new operator-facing failure at selene/src/memory.rs:3108-3116:

if compressor_busy {
    #[cfg(feature = "codec")]
    if let Some(compressor) = self.compressor.take() {
        std::mem::forget(compressor);
    }
    return Err(Error::new(
        "host KV compression did not finish before close",
    ));
}

Impact: this message is silently discarded whenever disk.close() also failed — the one combination in which the process is now holding a leaked slab pool and a forgotten compressor, i.e. the highest-severity leak state the PR can create. The operator sees only the disk error and has no signal that host memory was intentionally leaked. (This is the open question the dossier listed; it is confirmed.)

Fix: fold both into one error, e.g. keep disk's message and append the memory message when both are Err (match (disk, memory) with a combined Error::new(format!("{disk}; {memory}")) if Error lacks a chaining API).

FINDING 3 — Major — ptr_mut is a safe function handing out a writable pointer; bytes is unsafe for the same access

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

Against the sibling it is meant to parallel, selene-manager/src/regions.rs:68-80:

/// # Safety
/// The caller must own the range exclusively while the slice lives, and keep
/// this mapping alive. The store leases windows until their handler is fenced.
pub unsafe fn bytes<'a>(...) -> io::Result<&'a mut [u8]> {

and the new reader, selene-manager/src/regions.rs:42-56, whose contract ("No writer may mutate the range while the slice lives") ptr_mut does nothing to uphold or document. The caller writes raw bytes through it at selene-manager/src/data/channel.rs:934-942:

let (base, len) = inner.regions.ptr_mut(
    grant.region,
    grant.offset,
    layout.window_bytes(pages, row),
)?;
// SAFETY: the put owns the granted window until fenced, and each rank
// writes only its own disjoint slices within `base..base + len`.
unsafe { layout.scatter_disjoint(*rank, base, len, pages, row, &packed) }

The PR's own new test bytes_read_allows_overlapping_shared_views (selene-manager/src/regions.rs:132-146) establishes that overlapping views over the same bytes are the expected norm, so the exclusivity the writes rely on is nowhere expressed in the type system or in any doc comment on the safe function.

Impact: the aliasing class of UB this PR sets out to eliminate (LocalRegions handing out overlapping &mut [u8]) is relocated into raw-pointer writes, and one of the two functions involved loses its unsafe marker. Any future caller of ptr_mut compiles without a safety obligation, and a safe-but-overlapping write is silent memory corruption. Safety now rests entirely on the store leasing disjoint windows — a property LocalRegions neither checks nor documents.

Fix: make ptr_mut unsafe fn with the disjointness/lease/lifetime contract that bytes already states ("the caller must own the range exclusively while it writes, and keep this mapping alive"); the sole caller becomes unsafe { inner.regions.ptr_mut(...) }? with the same comment it already carries. Bounds checking is unchanged (it stays in range, regions.rs:30-40).

FINDING 4 — Minor — conn::shutdown's new quarantine extends permanent retention to a slow (not failed/lost) session, undocumented

selene/src/pool/conn.rs:216-223:

if engine.quiet() && !engine.quarantined() {
    Ok(())
} else {
    engine.quarantine();
    Err(Error::new(
        "the pool could not drain its transfers at close",
    ))
}

Previously the engine quarantined only on its own timer, and only once the session had gone: selene/src/pool/engine/mod.rs:533-544 gates on self.sess.is_none() && drain_started expired, with drain_started set in the session-loss path (mod.rs:349) and cleared whenever the engine is quiet (mod.rs:534). begin_close (mod.rs:782-790) does not take the session, so a session that is still open when conn::shutdown runs never satisfied sess.is_none() and never reached that branch. It now does, and Engine::quarantine (mod.rs:549-573) does:

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);
}
...
self.shared.set_status(PoolStatus::Disabled(
    "a copy could not be drained; memory is quarantined".into(),
));

Impact: a manager arena/staging attachment and the data-channel staging of a live-but-slow peer are held for the life of the process, and the pool status becomes Disabled("a copy could not be drained; memory is quarantined"), where before a merely slow close leaked nothing new. This is the intended trade (the PR's thesis is "retain rather than unmap"), and it is the safest resolution of a timeout — but it is an operator-visible behaviour change (memory never returns, status permanently Disabled) that the description's "What changed" does not mention and no doc records. Note the interaction with #611, which edits the same function on main one commit later (jobs.clear()/pending.clear() additions), so the final shape of this path is #609+#611 combined and neither PR's tests cover the timeout branch firing.

Fix: keep the behaviour (it is correct), but document the retention in the quarantine doc comment and widen the error text to say memory is retained, e.g. "the pool could not drain its transfers at close; memory is quarantined". If a slow close should not be sticky, quarantine only when the timeout also left !engine.quiet() with no progress between ticks.

Strands verified sound (no finding raised)

Metric / rate / admission-pricing span check

Nothing in the diff adds, removes, or re-scopes a sampled rate, latency, or admission metric. Counters touched are volume accounting (inner.counters.add(0, grant.shape.length), channel.rs:945) and pre-existing pool/close stats; the stats() aggregation at composite.rs:1595-1598 is unchanged. No finding.


2. Unintended System-Level Consequences (concurrency, contention, failure blast radius)


3. Architecture, Contracts & Charter Compliance


4. Tests & Claim Accuracy

The dossier's concern about the relaxed offload/tests.rs assertion is not a defect — say so plainly

The dossier flagged the deletion of the fail == Some(1) case at selene/src/offload/tests.rs:659 as removing the guard on the close-short-circuit. It is not: the loop is for fail in [None, Some(0), Some(1)], filtered to exclude Some(1) when warm == 0 (offload/tests.rs:618-622). With fail == Some(0) a reverted short-circuit would still produce close order [0], which the new expectation [1, 0] rejects. The regression the test was written for (#497's disk_and_memory_share_one_registration_with_independent_copiers_and_safe_close) remains covered. No finding.

Real test gaps

  1. No concurrent test of the aliasing fix. scatter_disjoint_matches_gather_across_ranks (selene/src/shared/slice.rs:446-462) is single-threaded, 3 ranks; bytes_read_allows_overlapping_shared_views (selene-manager/src/regions.rs:132-146) exercises overlapping reads only. The reachable hazard the PR names — two accepted data connections are separate tasks (channel.rs:435-447) sharing one Arc<LocalRegions> (channel.rs:230, 1033), so concurrent rank windows of the same put can overlap — has no test that runs two writers/readers at once. Given the change's entire premise is "no overlapping &mut", a 2-thread test over one LocalRegions lease pair is the test that should exist. Severity: Minor (the code is correct by construction via check + disjoint offsets; the fix is untested in its motivating regime).
  2. ptr_mut gets only negative bounds asserts (regions.rs:127-128) — no positive-path assertion, and (per Finding 3) no contract to assert against.
  3. No test for the conn::shutdown timeout branch — the new engine.quarantine() call at conn.rs:219 is not covered by mid_session_quarantine_retains_active_session_and_attachment_regions (selene/src/pool/engine/tests.rs:1571-1589), which drives Engine::quarantine directly, not the close path that now calls it.
  4. No test that CompositeStore::close clears journals only on success (Findings 1–2 are both reachable only through a multi-tier failure, which nothing exercises).

Claim accuracy


Open questions / could not be found