Recommendation: Ready To Merge
PR #607 fixes six concrete, verified memory-safety, DoS, state-corruption, and offload lifecycle defects across selene-manager, selene, and helios with a lean production footprint (~60 non-test lines) and targeted regression tests for each fix. No correctness regressions, wire/on-disk format breaks, or blockers were found after inspecting every modified path and its surrounding concurrency/lifecycle invariants at 4f12cae. Two defence-in-depth / robustness polish items (claims.rs gRPC validation order and composite.rs transient I/O vs corruption quarantine) and two small simplifications are noted below as optional follow-ups.
Merge Risk
Level: Low
- Small, localized production surface: Every fix is 1–10 lines inside existing state machines with no wire protocol (
selene.proto(not opened)), on-disk record format, Cargo dependency, or public API changes. - Safety-critical paths touched: Pool staging/DMA release (
selene-manager/src/pool/claims.rs,selene/src/pool/agent.rs,selene/src/pool/engine/requester.rs), manager store-bridge transfer IDs and linked multi-process puts (selene-manager/src/pool/store_bridge.rs), and offload lifecycle (selene/src/memory.rs,selene/src/composite.rs,helios/src/server/runtime.rs). All 11 invariants are verified in unit tests and Helios formal checks; live GPU/RDMA/multi-process runs were not executed on this PR alone (declared in the PR limitations, though downstream PRs#609/#610/#612rebased onto#607include SM120/GB10 hardware qualification). - Blast radius of edge cases: The two non-blocking caveats (accepting stray gRPC
WindowReleasedon channel claims as a no-op; quarantining an unpacked disk ancestor on a transient OS open/read error) cannot corrupt data or cause UB—at worst, a transient disk error triggers a cache miss/recompute until recapture.
Walkthrough
- Remote data-channel staging UAF (
selene-manager/src/pool/claims.rs:1513-1516): GuardsCore::window_releasedwithif claim.channel().is_some() { return Ok(()); }so a remote gRPCWindowReleasedcannot clear reader bit 0 and dropwindow.extentwhile the data-channel handler still holds references; release remains exclusively driven bychannel::Event::Sent/Closed(claims.rs:1794-1795). - Chain-walk CPU DoS (
selene-manager/src/pool/mod.rs:113-117,selene-manager/src/pool/index.rs:171-227): Rejects zero or non-decreasingparent.consumed_tokensin bothentry_fromandwalk_chain, rejectsmax_nodes == 0, and bounds total visited entries (including zero-page checkpoints) bymax_nodes. - Staging slot aliasing & premature peer window release (
selene/src/pool/agent.rs:1561-1565,selene/src/pool/net.rs:163,selene/src/pool/engine/requester.rs:1177):Agent::window_drainedcallsforget_windowafterrelease_sloton failedchannel.send, preventingAgent::drive(agent.rs:1638-1642) from double-releasing the slot;Staging::releaseadds a duplicate-slotdebug_assert!;Engine::withdraw_queuednow checksw.jobs_left == 0 && w.peers_left.is_empty() && !w.released, matching the other three release sites (requester.rs:739, 790, 898). - Store transfer IDs & linked multi-process puts (
selene-manager/src/pool/{core,claims,store_bridge}.rs): Allocates monotonic manager-side transfer IDs viaStoreHandle::next_transfer(store_bridge.rs:122-126) for everyStoreCommand(preventing concurrentput_id == claim_idcollisions in the store's per-connectionopsmap), and hoists the record-relativefirst_pagecalculation inCore::put_answer(store_bridge.rs:643-647) soPutWin.first_pagematchesWindowSpec.first_pageandput_commit. - Helios & Selene offload lifecycle (
helios/src/server/runtime.rs:2117-2121,selene/src/memory.rs:2346-2349,selene/src/composite.rs:1125-1134,selene/src/shared/index.rs:503-511,docs/prefix-cache-offload.md:625-631): Clears stale pre-park admission/pool fields inWorker::parkbefore re-planning the extended prompt; removes theif !refillguard inMemoryStore::drain_compressedso deferred children wake after async CPU-codec row refills; releases incomplete memory copies and quarantines unreadable v1/v2/v3 disk records inCompositeStore::disk_read; replacestake_whilewithfilterinIndex::expired(fixing#439) and updates the docs accordingly.
Pre-merge Checks
- [PASS] Security / malicious screen: Fixes two remote security/DoS vectors (data-channel staging UAF and cyclic/zero-page
walk_chainCPU hang) with no unsafe additions or credential/protocol exposure; minor gRPC validation tightening noted in Should Fix. - [PASS] Charter & value fit: Directly advances the Selene prefix-cache sharing goal from priority contributor
@lukealonso, includes all four required PR description sections, and introduces no model-specific branches, config knobs, or non-goal scope. - [PASS] Related / duplicate / conflict check: Companion PRs
#609,#610,#611, and#612byyatesdrhave already been rebased onto#607(removing the overlapping hunks and referencing#607explicitly);#439is linked and closed. - [WARN] Tests & verification evidence: All 11 added regression tests exist, compile cleanly under the reported commands (
selene/Cargo.toml:20includescodecintest-support), and CI is green on4f12cae; live GPU/RDMA/multi-process tests (FLARE_RUN_CUDA_TESTS=1) were not run on this branch (explicitly disclosed in Limitations), and twostore_bridge.rstests seed internalClaim/PutRecfixtures rather than drivingclaim_begin/put_beginend-to-end.
Blockers
None.
Should Fix
- Preserve gRPC window/phase validation on channel claims (
selene-manager/src/pool/claims.rs:1513-1531): ReturningOk(())at line 1513 before looking upclaim.windowsand checkingwindow.phasemakes the twoErr(Violation)checks at:1517-1529unreachable for data-channel requesters on this untrusted gRPC entry point. (This mirrorswindow_filledat:1437-1440, so it is consistent with existing style, and a channel requester cannot trigger UAF here.) To keep defence-in-depth validation without extra complexity, hoistlet channelled = claim.channel().is_some();beforeclaim.windows.get_mutand gate only thePhase::RequesterReadrelease arm:Phase::RequesterRead if channelled => return Ok(())(or reject any gRPCWindowReleasedon a channel claim as aViolation, since compliant clients never emit it perselene/src/pool/engine/requester.rs:918-924). - Distinguish transient OS open/read errors from corruption before permanent quarantine (
selene/src/composite.rs:1130-1132): Callingself.disk.quarantine_corrupt(&node)on anyerror.is_record_read()fixes corrupt unpacked v1/v2/v3 pages (Operation::ReadPages/ReadRow), corrupt headers, and deleted files (Operation::Openinselene/src/disk.rs:1088-1111), all of which setwith_record_read()(selene/src/disk_store.rs:1103, 1131, 1160). However, transient OS errors duringdirect_fileopen or read (e.g.,EMFILEor temporaryEIO) also setis_record_read()and will mark a healthy ancestorlocation.failed = true(disk_store.rs:3099-3105), hiding all descendants until recaptured (whereas the packed v4 path atcomposite.rs:1090-1103narrows quarantine topacked::Checksum). Consider gatingquarantine_corrupton content/missing-file errors (checksum/header invalidation andENOENT) rather than transient I/O errors, or document that permanent quarantine on any record-read error is intentional.
Subtract / Simplify
- Remove redundant bound in
walk_chain(selene-manager/src/pool/index.rs:171, 184, 194, 211, 214):stepsincrements on every loop iteration whilenodesonly appends whenparent.tail_pages > 0(:217), sonodes.len() <= stepsalways holds and|| nodes.len() >= max_nodesat:211is unreachable aftersteps >= max_nodesat:194. Replace|| max_nodes == 0,steps, and|| nodes.len() >= max_nodeswith a singlevisitedcounter checked at the top of the loop (visited += 1; if visited > max_nodes { return None; }). - Use
Option<u64>instead of a0sentinel forManagerGet.transfer(selene-manager/src/pool/claims.rs:225-227,selene-manager/src/pool/store_bridge.rs:1208-1234): Manager-allocated store transfers start at1(store_bridge.rs:122-126), so0is only an "unstarted" sentinel that forces.filter(|&transfer| transfer != 0)instore_cancel_get(:1232). ChangingManagerGet.transfertoOption<u64>removes the magic sentinel and the.filter.
Nits
selene-manager/src/pool/store_bridge.rs:643-647:grant.page_first as u32 - rec.accepted.expect("put accepted").1was hoisted verbatim from the existingWindowSpecconstruction (:683), now running just before thelet Some(region) = region else { ... }check (:652-655). Moving it below the region check and usingchecked_subwould make malformed/out-of-order internal store grants fail cleanly instead of panicking in debug builds.selene/src/shared/index.rs:503-511: SwitchingIndex::expiredfromtake_whiletofilterscans all entries inself.ordered()once every 60s when--prefix-cache-max-ageis enabled (off by default). Fine for workstation caches; worth keeping in mind if manager indexes grow very large with expiry enabled.- PR description wording: "All 11 added regression tests verify each invariant directly on production entry points" slightly overstates
put_and_get_with_same_client_id_use_disjoint_store_transfers(store_bridge.rs:1739-1753) andlinked_multi_process_put_stores_record_relative_window_first_page(store_bridge.rs:1891-1942), which seedClaim::new_for_test/PutRecfixtures and drivemanager_get/put_answer/put_commitdirectly rather thanclaim_begin/put_begin.
Dropped on verification
- False — "
async_cpu_codec_refill_wakes_deferred_childis#[cfg(feature = "codec")]and skipped by--features test-support" (Correctness Lens & Dossier): Disproved inselene/Cargo.toml:14, 20, where bothdefault = ["codec"]andtest-support = ["codec"]enablecodec. - False — "clearing
pool_planat park while keepingpublic_prefixletsbegin_pool_lookupadopt the pre-park plan viatokens_agree" (Correctness Lens Key Finding #2): Hallucinated;public_prefixandtokens_agreedo not exist anywhere inhelios/src, andbegin_pool_lookup(helios/src/server/runtime.rs:2758-2765) replans fromincoming.spec()wheneverpool_planisNone. - False — "
MemoryStore::drain_compressedErr(msg)refill path setsset_ready(true)with no row, stranding/corrupting deferred children" (Correctness Lens Finding 2): Disproved inselene/src/memory.rs:737-746, 1560-1594. A row refill runs on an already-stored record whose pages are intact; on row-refill failure, only the newly allocatedrowslots are released andreadyis intentionally restored totrue(matching the synchronous refill paths at:1564-1574and:1590-1593) so deferred children can link to the parent's intact pages. - False — "
CompositeStore::disk_readquarantine wipes both tiers and strands linked children instart_deferred" (Correctness Lens Key Finding #1): Fabricated;disk_readonly runs when fetching a record not resident in memory (complete_record(&node, false)frees only the incomplete fetch allocation), andstart_deferredis an unrelated outboundMemoryStorepath. - False — "Limit
quarantine_corrupttoReadPages | ReadRow | ReadPackedonly" (Correctness Lens Finding 1 proposed fix): Incorrect;selene/src/disk.rs:1088-1111performs v3 header decoding/verification and file-open insideOperation::Open, so excludingOperation::Openentirely would fail to quarantine corrupt-header or deleted v3 files. - False — "Delete
drop(free);inStaging::releaseas redundant" (Subtraction Lens S5): Harmful suggestion; inselene/src/pool/net.rs:162-166, dropping theMutexGuardbeforeself.permits.add_permits(1)prevents lock contention with a task woken byadd_permitsthat immediately locksself.freeinacquire()(:147-152). - False — "
withdraw_queuedleaves windows/slots leaked if a peer never reports done" (Correctness Lens Finding 6): Verified intentional DMA-safety behavior; if a peer rank disconnects or fails without draining,selene/src/pool/engine/mod.rs:731-769(rank_lost) transitions toself.quarantine(), intentionally retaining shared regions/slots rather than releasing memory an un-drained peer may still DMA into. - False — "Resetting
RestoreWaitonWorker::parkwrongly restarts its budget" (Correctness Lens Finding 7):Worker::parkextendsincoming.prompt.tokenswith generated tokens (helios/src/server/runtime.rs:2100-2114), starting a new admission episode for a longer prefix; resettingRestoreWait::default()matches its documented contract ("charged once per admission episode",runtime.rs:215). - False — "Hallucinated summary items (
claims.rstruncated,PINNED after RESET,corrupt_a_v1_record_is_dropped_and_recaptured, 1-in-10^9 underflow)" (Correctness Lens top summary): None exist in the codebase at4f12cae. - Stale — "Five of six headline defects conflict with open
#609/#610/#612" (Discovery Dossier & Value Prop): Verified viaread_itemthat#609,#610, and#612were already updated and rebased onto#607, removing the overlapping hunks. - Low-signal — "Consolidate 5 reset lists in
helios/src/server/runtime.rsintoIncoming::reset_admission()" (Subtraction Lens S3): Dropped because the other four sites (runtime.rs:1584-1588, 2586-2587, 2598-2599, 2627-2630) intentionally clear different field subsets (e.g., preserving pending pool answers on active requests or ready lookups onrequeue(..., true)). - Low-signal — "
corrupt_ancestor_v3_page_is_quarantined_and_replaceablecan return early iftest_directoryyieldsNone" (Correctness Lens Finding 10): Standard repo pattern (selene/src/testing.rs:415-441) used across disk tests solely to skip when a test filesystem returnsEINVALonO_DIRECT. - Low-signal — "
PutAnswer::Acceptdoes not assertaccept.transfer == rec.transfer" (Correctness Lens Finding 9):answersis an in-process per-putmpsc::channelcreated input_begin(store_bridge.rs:438), so answers cannot cross-route between puts.