Skip to content

selene,selene-manager,helios: fix pool staging UAF, chain walk DoS, multi-process put corruption, and offload lifecycle bugs - #607

Merged
yatesdr merged 1 commit into
mainfrom
selene-pool-uaf-infinite-loop-and-mp
Nov 29, 2026
Merged

yatesdr merged 1 commit into
mainfrom
selene-pool-uaf-infinite-loop-and-mp

Conversation

@lukealonso

Copy link
Copy Markdown
Collaborator

Why

Six memory-safety, remote-DoS, and state-corruption defects affect Selene pool transfers and prefix cache offload across selene-manager, selene, and helios:

  1. Remote data-channel staging UAF and cross-tenant KV leak (selene-manager/src/pool/claims.rs): Core::window_released omitted the claim.channel().is_some() guard that Core::window_filled enforces for source_channel(). A remote gRPC WindowReleased cleared reader bit 0 and dropped window.extent = None while selene-manager/src/data/channel.rs (which holds no Arc<Extent>) was still reading regions.bytes or issuing RDMA writes from that staging slice, permitting use-after-free and cross-tenant KV disclosure once the arena reallocated the extent.
  2. Remote 100% CPU hang in walk_chain (selene-manager/src/pool/mod.rs, selene-manager/src/pool/index.rs): entry_from accepted self-parenting or non-monotonic parent keys (parent.consumed_tokens >= key.consumed_tokens), and walk_chain skipped nodes.push when parent.tail_pages == 0, so nodes.len() >= max_nodes never triggered on zero-page cycles or long zero-page chains. A single self-parenting notice could freeze selene-manager at 100% CPU.
  3. Staging slot double-release aliasing UB and premature peer window release (selene/src/pool/agent.rs, selene/src/pool/engine/requester.rs): When channel.send(...) returned false in Agent::window_drained, the agent released the staging slot without removing the window from run.windows, causing Agent::drive to release the same slot a second time into Staging::free (enabling concurrent &mut [u8] aliasing). In Engine::withdraw_queued, rank 0 released windows whenever w.jobs_left == 0 without checking w.peers_left.is_empty(), emitting WindowReleased while a shared-memory peer rank still had in-flight DMA.
  4. Store transfer ID collision and broken linked multi-process puts (selene-manager/src/pool/store_bridge.rs, selene-manager/src/pool/claims.rs): Core passed raw client put_id and claim_id directly as StoreCommand::*::transfer into the store's single per-connection ops map, allowing concurrent puts and manager-backed claims with the same numeric client ID to collide or silently cross-cancel each other on StoreCommand::Cancel. Separately, Core::put_answer stored chain-absolute grant.page_first in PutWin.first_page instead of the record-relative offset used by WindowSpec.first_page and put_commit, so put_pass_done wrote mp.whole starting at the parent's page count and put_commit failed every linked multi-process put with missing page checksums.
  5. Stale pool plan on Worker::park, async CPU-codec refill pin leak, v3 disk quarantine gap, and expiry sweep hiding (Prefix-index sweep stops at a refreshed leaf whose access tick never advanced #439) (helios/src/server/runtime.rs, selene/src/memory.rs, selene/src/composite.rs, selene/src/shared/index.rs):
    • Worker::park extended incoming.prompt.tokens and called begin_pool_lookups without clearing surviving pre-admission pool_plan / pool_lookup, causing begin_pool_lookup to retain or refresh the shorter pre-park PrefixHistory.
    • MemoryStore::drain_compressed guarded start_deferred with if !refill, stranding child checkpoints deferred while a parent underwent an async CPU-codec row refill and leaking their VRAM checkpoint pins.
    • CompositeStore::disk_read only quarantined corrupt disk records on the packed v4 path; unpacked v1/v2/v3 read errors hit (Err(error), _) without releasing the incomplete memory record or quarantining damaged disk pages, causing repeated failing lookups on corrupt ancestors.
    • Index::expired used take_while over access-tick order and stopped at the first fresh leaf, so a leaf whose last_used was refreshed by touch_ancestors without advancing its access tick (Fixes Prefix-index sweep stops at a refreshed leaf whose access tick never advanced #439) hid expired leaves behind it.

What exactly changed

  • selene-manager/src/pool/claims.rs:
    • Before: Core::window_released called reader_done(key, m.index, 0) regardless of whether the claim used a rank-0 data channel.
    • After: Returns Ok(()) immediately when claim.channel().is_some(), so only the data-channel handler's Event::Sent or Event::Closed releases reader bit 0 and the staging extent.
  • selene-manager/src/pool/mod.rs and selene-manager/src/pool/index.rs:
    • Before: entry_from did not validate parent.consumed_tokens against key.consumed_tokens, and walk_chain checked only nodes.len() >= max_nodes (ignoring zero-page checkpoints).
    • After: entry_from rejects parent.consumed_tokens == 0 or parent.consumed_tokens >= key.consumed_tokens; walk_chain returns None for page_tokens == 0 || max_nodes == 0, requires strictly decreasing non-zero consumed_tokens on every step, and bounds total visited entries (including zero-page checkpoints) by max_nodes.
  • selene/src/pool/agent.rs, selene/src/pool/net.rs, and selene/src/pool/engine/requester.rs:
    • Before: Agent::window_drained called release_slot(slot) on !sent without removing the window from run.windows, and Engine::withdraw_queued released windows on w.jobs_left == 0 alone.
    • After: Agent::window_drained calls self.forget_window(xfer, index) right after self.release_slot(slot) on !sent; Staging::release adds a debug_assert! rejecting duplicate slot returns; Engine::withdraw_queued requires w.jobs_left == 0 && w.peers_left.is_empty() && !w.released.
  • selene-manager/src/pool/{store_bridge,core,claims}.rs:
    • Before: StoreCommand requests used raw client put_id / claim_id as transfer, and PutWin.first_page stored chain-absolute grant.page_first as u32.
    • After: StoreHandle::next_transfer allocates monotonic manager-side transfer IDs stored on PutRec::transfer and ManagerGet::transfer for all StoreCommand calls (PutBegin, GetBegin, WindowFilled, PutCommit, RequestWindow, Cancel), and Core::put_answer computes record-relative first_page once (grant.page_first as u32 - accepted.1 when page_count > 0, else 0) for both PutWin and WindowSpec.
  • helios/src/server/runtime.rs:
    • Before: Worker::park left blocked, pool_lookup, pool_lookup_started, pool_plan, and restore_wait intact before calling begin_pool_lookups.
    • After: Clears all five fields before calling begin_pool_lookups on the extended prompt tokens.
  • selene/src/memory.rs:
    • Before: MemoryStore::drain_compressed skipped start_deferred when rec.refill was true.
    • After: Calls self.core.start_deferred(&key, events) unconditionally after apply_compressed.
  • selene/src/composite.rs:
    • Before: CompositeStore::disk_read recorded inbound.error on (Err(error), _) without releasing the incomplete memory allocation or quarantining the disk record.
    • After: Releases the incomplete memory copy via complete_record(&node, false), resets the inbound node state to NodeState::Waiting, and calls self.disk.quarantine_corrupt(&node) when error.is_record_read().
  • selene/src/shared/index.rs and docs/prefix-cache-offload.md:
    • Before: Index::expired stopped at the first fresh leaf via take_while.
    • After: Filters self.ordered() for eligible expired leaves (children == 0 and age >= max_age) without mutating LRU ticks, and updates docs/prefix-cache-offload.md to match.

Claimed benefit and result

  • Observed in CPU unit tests: All 11 added regression tests verify each invariant directly on production entry points: data-channel extent retention across gRPC WindowReleased, rejection of self-parent/cyclic/oversized zero-page chains, single staging-slot release on failed channel send, peer-DMA gating in withdraw_queued, disjoint store transfer IDs for concurrent put_id == claim_id, successful linked multi-process put commit, fresh PrefixHistory planning after Worker::park, deferred child wakeup after async CPU-codec row refill, quarantine and replacement of corrupt v3 disk ancestors, and expiry past leaves refreshed without a new access tick.
  • Expected in production serving: Eliminates remote data-channel staging UAF and self-parenting CPU DoS in selene-manager, prevents staging slot aliasing and mid-DMA window release in multi-process selene clients, restores linked multi-process puts and concurrent put/get isolation in the manager store bridge, prevents stale pool prefix planning after parking in Helios, prevents VRAM pin leaks after async row refills, quarantines damaged v3 disk records, and fixes Prefix-index sweep stops at a refreshed leaf whose access tick never advanced #439. No model core re-export or wire protocol change is required.

Supporting evidence and limitations

  • Targeted regression tests (11/11 passed):
    • cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support --target-dir flare-cli/target --lib -- failed_channel_send_releases_staging_slot_once withdraw_queued_waits_for_peer_dma_before_releasing_window async_cpu_codec_refill_wakes_deferred_child corrupt_ancestor_v3_page_is_quarantined_and_replaceable expired_sweep_skips_leaf_refreshed_without_new_tick: 5 passed, 0 failed.
    • cargo test --locked --release --manifest-path selene-manager/Cargo.toml --features test-support --target-dir flare-cli/target --lib -- window_released_from_channel_requester_does_not_drop_extent entry_from_rejects_self_parent_and_non_monotonic_parent walk_chain_rejects_self_parent_cycles_and_zero_page_chains_beyond_max_nodes put_and_get_with_same_client_id_use_disjoint_store_transfers linked_multi_process_put_stores_record_relative_window_first_page: 5 passed, 0 failed.
    • cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target --lib -- worker_park_clears_stale_pool_plan_and_lookup: 1 passed, 0 failed.
  • Full crate and formal verification runs:
    • cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support --target-dir flare-cli/target: 510 passed, 0 failed.
    • cargo test --locked --release --manifest-path selene-manager/Cargo.toml --features test-support --target-dir flare-cli/target: 185 --lib tests and all 11 integration test binaries (builder, l0, offload, packed, pool_channel, pool_claims, pool_l0, pool_net, pool_relay, pool_store, rank_processes) passed; --test client passed 84/85, with a_record_put_into_a_manager_on_another_host_is_restored_over_tcp showing a pre-existing timing race against the 10 ms Core::tick() metrics refresh (stream: 2 windows when the second restore completes before the next tick; passed 1/5 isolated reruns).
    • cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target --lib -- server::runtime: 133 passed, 0 failed, 1 ignored.
    • python3 verification/helios-lifecycle/check.py --tlc-jar ~/.cache/flare-formal/tla2tools-1.7.4.jar --java ~/.cache/flare-formal/jdk-21.0.13+9-jre/bin/java --target-dir flare-cli/target: exited 0 (all TLC models and observed-edge Rust conformance checks passed, including ResponseLifecycle and reasoning continuation).
  • Limitations and unrun checks:
    • flare/Cargo.toml --locked failed on an unrelated upstream lockfile mismatch for deepseek-recipe (flare/ and flare-cli/ were not modified).
    • helios chat-template tests requiring FLARE_TEST_TEMPLATE_DIR and live GPU/RDMA execution (FLARE_RUN_CUDA_TESTS=1) were not run.

Discord: no username provided

…ulti-process put corruption, and offload lifecycle bugs

Why:
Six memory-safety, remote-DoS, and state-corruption defects exist across
`selene-manager`, `selene`, and `helios` in Selene pool transfers and prefix
cache offload:

1. Remote data-channel staging UAF (`selene-manager/src/pool/claims.rs`):
   `Core::window_released` omitted the `claim.channel().is_some()` guard that
   `Core::window_filled` applies for `source_channel()`. A remote gRPC
   `WindowReleased` message cleared reader bit 0 and dropped
   `window.extent = None` while `selene-manager/src/data/channel.rs` (which
   holds no `Arc<Extent>`) was still reading `regions.bytes` or issuing RDMA
   writes from that staging slice, allowing use-after-free and cross-tenant KV
   leakage when the arena reallocated the extent.
2. Remote 100% CPU hang in `walk_chain` (`selene-manager/src/pool/mod.rs`,
   `selene-manager/src/pool/index.rs`): `entry_from` accepted self-parenting or
   non-monotonic parent keys (`parent.consumed_tokens >= key.consumed_tokens`),
   and `walk_chain` skipped `nodes.push` when `parent.tail_pages == 0`, so
   `nodes.len() >= max_nodes` never triggered on zero-page cycles or long
   zero-page chains. A single self-parenting notice could freeze
   `selene-manager` at 100% CPU.
3. Staging slot aliasing UB and premature peer window release
   (`selene/src/pool/agent.rs`, `selene/src/pool/engine/requester.rs`):
   When `channel.send(...)` returned `false` in `Agent::window_drained`, the
   agent released the staging slot without removing the window from
   `run.windows`, causing `Agent::drive` to release the same slot a second time
   into `Staging::free` (allowing concurrent `&mut [u8]` aliasing). In
   `Engine::withdraw_queued`, rank 0 released windows as soon as
   `w.jobs_left == 0` without checking `w.peers_left.is_empty()`, emitting
   `WindowReleased` while a shared-memory peer rank still had in-flight DMA.
4. Store transfer ID collision and broken linked multi-process puts
   (`selene-manager/src/pool/store_bridge.rs`,
   `selene-manager/src/pool/claims.rs`): `Core` passed raw client `put_id` and
   `claim_id` directly as `StoreCommand::*::transfer` into the store's single
   per-connection `ops` map, allowing concurrent puts and manager-backed claims
   with the same numeric client ID to collide or silently cross-cancel each
   other on `StoreCommand::Cancel`. Separately, `Core::put_answer` stored
   chain-absolute `grant.page_first` in `PutWin.first_page` instead of the
   record-relative offset used by `WindowSpec.first_page` and `put_commit`, so
   `put_pass_done` populated `mp.whole` starting at the parent's page count and
   `put_commit` failed every linked multi-process put with missing page
   checksums.
5. Stale pool plan on `Worker::park`, async CPU-codec refill pin leak, v3 disk
   quarantine gap, and expiry sweep hiding (#439)
   (`helios/src/server/runtime.rs`, `selene/src/memory.rs`,
   `selene/src/composite.rs`, `selene/src/shared/index.rs`):
   - `Worker::park` extended `incoming.prompt.tokens` and called
     `begin_pool_lookups` without clearing surviving pre-admission
     `pool_plan` / `pool_lookup`, causing `begin_pool_lookup` to keep or
     refresh the shorter pre-park `PrefixHistory`.
   - `MemoryStore::drain_compressed` guarded `start_deferred` with
     `if !refill`, stranding child checkpoints deferred during an async
     CPU-codec row refill and leaking their VRAM checkpoint pins.
   - `CompositeStore::disk_read` only quarantined corrupt disk records on the
     packed v4 path; unpacked v1/v2/v3 read errors hit `(Err(error), _)`
     without releasing the incomplete memory copy or quarantining damaged disk
     pages, causing repeated failing lookups on corrupt ancestors.
   - `Index::expired` used `take_while` over access-tick order and stopped at
     the first fresh leaf, so a leaf whose `last_used` was refreshed by
     `touch_ancestors` without advancing its access tick (issue #439) hid
     expired leaves behind it.

What exactly changed:
- `selene-manager/src/pool/claims.rs`:
  - Before: `Core::window_released` called `reader_done(key, m.index, 0)` even
    when the claim used a rank-0 data channel.
  - After: returns `Ok(())` immediately when `claim.channel().is_some()`, so
    only the data-channel handler's `Event::Sent` or `Event::Closed` releases
    bit 0 and the staging extent.
- `selene-manager/src/pool/mod.rs` and `selene-manager/src/pool/index.rs`:
  - Before: `entry_from` did not compare `parent.consumed_tokens` against
    `key.consumed_tokens`, and `walk_chain` bounded only page-bearing nodes in
    `nodes.len()`.
  - After: `entry_from` rejects `parent.consumed_tokens == 0` or
    `parent.consumed_tokens >= key.consumed_tokens`; `walk_chain` returns
    `None` for `page_tokens == 0 || max_nodes == 0`, requires strictly
    decreasing non-zero `consumed_tokens` on every step, and counts every
    visited entry against `max_nodes`.
- `selene/src/pool/agent.rs`, `selene/src/pool/net.rs`, and
  `selene/src/pool/engine/requester.rs`:
  - Before: `Agent::window_drained` released `slot` on `!sent` while leaving
    the window in `run.windows`, and `Engine::withdraw_queued` released windows
    on `w.jobs_left == 0` alone.
  - After: `Agent::window_drained` calls `self.forget_window(xfer, index)`
    after `self.release_slot(slot)` on `!sent`; `Staging::release` adds a
    `debug_assert!` rejecting duplicate slot release; `Engine::withdraw_queued`
    requires `w.jobs_left == 0 && w.peers_left.is_empty() && !w.released`.
- `selene-manager/src/pool/{store_bridge,core,claims}.rs`:
  - Before: `StoreCommand` requests used raw client `put_id` / `claim_id` as
    `transfer`, and `PutWin.first_page` stored `grant.page_first as u32`.
  - After: `StoreHandle::next_transfer` allocates monotonic manager-side
    transfer IDs stored on `PutRec::transfer` and `ManagerGet::transfer` for
    all `StoreCommand` calls (`PutBegin`, `GetBegin`, `WindowFilled`,
    `PutCommit`, `RequestWindow`, `Cancel`), and `Core::put_answer` computes
    record-relative `first_page` once (`grant.page_first as u32 - accepted.1`
    when `page_count > 0`, else `0`) for both `PutWin` and `WindowSpec`.
- `helios/src/server/runtime.rs`:
  - Before: `Worker::park` left `blocked`, `pool_lookup`,
    `pool_lookup_started`, `pool_plan`, and `restore_wait` intact before
    calling `begin_pool_lookups`.
  - After: clears all five fields before calling `begin_pool_lookups` on the
    extended prompt tokens.
- `selene/src/memory.rs`:
  - Before: `MemoryStore::drain_compressed` skipped `start_deferred` when
    `rec.refill` was true.
  - After: calls `self.core.start_deferred(&key, events)` unconditionally after
    `apply_compressed`.
- `selene/src/composite.rs`:
  - Before: `CompositeStore::disk_read` recorded `inbound.error` on
    `(Err(error), _)` without completing/discarding the memory allocation or
    quarantining the disk record.
  - After: releases the incomplete memory record via
    `complete_record(&node, false)`, resets the inbound node state to
    `NodeState::Waiting`, and calls `self.disk.quarantine_corrupt(&node)` when
    `error.is_record_read()`.
- `selene/src/shared/index.rs` and `docs/prefix-cache-offload.md`:
  - Before: `Index::expired` stopped at the first fresh leaf via `take_while`.
  - After: filters `self.ordered()` for eligible expired leaves (`children == 0`
    and age `>= max_age`) without moving LRU ticks, and updates
    `docs/prefix-cache-offload.md` to match.

Claimed benefit and result:
- Observed in CPU unit tests: all 11 added regression tests verify each
  invariant directly on production entry points (data-channel extent retention
  across gRPC `WindowReleased`, rejection of self-parent/cyclic/oversized
  zero-page chains, single staging-slot release on failed channel send,
  peer-DMA gating in `withdraw_queued`, disjoint store transfer IDs for
  concurrent `put_id == claim_id`, successful linked multi-process put commit,
  fresh `PrefixHistory` planning after `Worker::park`, deferred child wakeup
  after async CPU-codec row refill, quarantine and repair of corrupt v3 disk
  ancestors, and expiry past leaves refreshed without a new access tick).
- Expected in production serving: eliminates remote data-channel staging UAF
  and self-parenting CPU DoS in `selene-manager`, prevents staging slot
  aliasing and mid-DMA window release in multi-process `selene` clients,
  restores linked multi-process puts and concurrent put/get isolation in the
  manager store bridge, prevents stale pool prefix planning after parking in
  Helios, prevents VRAM pin leaks after async row refills, quarantines damaged
  v3 disk records, and resolves #439. No model core re-export or wire protocol
  change is required.

Supporting evidence and limitations:
- Targeted regression tests (all 11 passed, 0 failed):
  - `cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support --target-dir flare-cli/target --lib -- failed_channel_send_releases_staging_slot_once withdraw_queued_waits_for_peer_dma_before_releasing_window async_cpu_codec_refill_wakes_deferred_child corrupt_ancestor_v3_page_is_quarantined_and_replaceable expired_sweep_skips_leaf_refreshed_without_new_tick` (5/5 passed).
  - `cargo test --locked --release --manifest-path selene-manager/Cargo.toml --features test-support --target-dir flare-cli/target --lib -- window_released_from_channel_requester_does_not_drop_extent entry_from_rejects_self_parent_and_non_monotonic_parent walk_chain_rejects_self_parent_cycles_and_zero_page_chains_beyond_max_nodes put_and_get_with_same_client_id_use_disjoint_store_transfers linked_multi_process_put_stores_record_relative_window_first_page` (5/5 passed).
  - `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target --lib -- worker_park_clears_stale_pool_plan_and_lookup` (1/1 passed).
- Full crate and formal verification runs:
  - `cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support --target-dir flare-cli/target`: 510 passed, 0 failed.
  - `cargo test --locked --release --manifest-path selene-manager/Cargo.toml --features test-support --target-dir flare-cli/target`: 185 `--lib` tests and all 11 integration test binaries (`builder`, `l0`, `offload`, `packed`, `pool_channel`, `pool_claims`, `pool_l0`, `pool_net`, `pool_relay`, `pool_store`, `rank_processes`) passed; `--test client` passed 84/85, with `a_record_put_into_a_manager_on_another_host_is_restored_over_tcp` exhibiting a pre-existing timing race against the 10 ms `Core::tick()` metrics refresh (`stream: 2 windows` when the second restore completes before the next tick; passed 1/5 isolated reruns).
  - `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target --lib -- server::runtime`: 133 passed, 0 failed, 1 ignored.
  - `python3 verification/helios-lifecycle/check.py --tlc-jar ~/.cache/flare-formal/tla2tools-1.7.4.jar --java ~/.cache/flare-formal/jdk-21.0.13+9-jre/bin/java --target-dir flare-cli/target`: exited 0 (all TLC models and observed-edge Rust conformance checks passed, including `ResponseLifecycle` and reasoning continuation).
- Limitations and unrun checks:
  - `flare/Cargo.toml --locked` failed on an unrelated upstream lockfile mismatch for `deepseek-recipe` (`flare/` and `flare-cli/` were not modified).
  - `helios` chat-template tests requiring `FLARE_TEST_TEMPLATE_DIR` and live GPU/RDMA execution (`FLARE_RUN_CUDA_TESTS=1`) were not run.

Signed-off-by: Luke Alonso <lalonso@gmail.com>
Design-Signed-Off-By: Antigravity (Gemini); design-review=c3a9
@yatesdr
yatesdr merged commit 5df8edd into main Nov 29, 2026
2 checks passed
@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 607.
Case File Intake Report

Future reviews will auto-run 90 minutes after code updates are pushed.

  • Re-review sooner: Call @flare-autobot after push.
  • Opt-out: Include #autobot:ignore in the PR or any comment.

@flare-autobot flare-autobot added area:caching Prefix/KV reuse, cache retention, and model or payload cache behavior. area:selene Selene shared prefix-cache pool, protocol, manager, and transfers. bug Something isn't working duplicate This issue or pull request already exists triage:review Proposed change needs code review; this does not imply merge readiness. labels Nov 29, 2026
yatesdr added a commit to yatesdr/flare-local-inference that referenced this pull request Nov 29, 2026
Active GPU DMA, host compression, NIC RDMA, and concurrent data-channel
workers can access mapped host or shared-memory ranges across close,
panic unwind, quarantine, and multi-rank scatter paths. Unmapping a
region before every local copier, RDMA queue pair, and compression
worker has drained causes use-after-unmap, and constructing overlapping
`&mut [u8]` slices in `LocalRegions` is undefined behavior under
concurrent readers or multi-rank writes.

- Declare `transfers` before `core`/`pool` in `MemoryStore` and
  `disk_store::Resources`, close both tiers in `CompositeStore::close`,
  guard `AsyncCompressor`'s active count with an RAII drop guard, and
  leak the slab pool and report an error if compression does not finish
  before `MemoryStore::close` (`selene/src/memory.rs`,
  `selene/src/disk_store.rs`, `selene/src/composite.rs`).
- Retain `sess.regions` and `Attachment::Shm` in `Engine::quarantine`,
  retain `self.shared` in `Agent::quarantine`, and invoke
  `engine.quarantine()` when `conn::shutdown` fails to drain
  (`selene/src/pool/engine/mod.rs`, `selene/src/pool/conn.rs`,
  `selene/src/pool/agent.rs`).
- Wrap `Staging.region` in `Arc<Region>` and retain it inside
  `rdma::Device` so quarantined RDMA queue pairs keep their registered
  staging mapped (`selene/src/pool/rdma.rs`, `selene/src/pool/net.rs`).
- Add `LocalRegions::bytes_read`, `LocalRegions::ptr_mut`, and
  `SliceLayout::scatter_disjoint` so concurrent read paths borrow
  `&[u8]` and multi-rank data-channel scatter writes only each rank's
  disjoint byte ranges without aliasing `&mut [u8]`
  (`selene/src/shared/slice.rs`, `selene-manager/src/regions.rs`,
  `selene-manager/src/pool/pass.rs`,
  `selene-manager/src/data/channel.rs`).
- Attach `ReadAhead`'s overlapped file handle to its IOCP queue on
  Windows (`selene/src/disk.rs`).

Every affected teardown, quarantine, RDMA, and concurrent region access
path now preserves backing mappings and disjoint ownership until all
DMA, RDMA, and worker accesses finish.

Validated on Linux (rebased onto post-NVIDIA#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene`, `selene-manager`, and `helios offload::`.

Design-Signed-Off-By: derek <derek.yates@live.com>; design-review=2e5b
yatesdr added a commit to yatesdr/flare-local-inference that referenced this pull request Nov 29, 2026
Local storage tiers, prepared-input caching, sharded disk ranks, direct
I/O loops, and KV-codec helpers had several correctness, durability, and
accounting bugs:

- Track `HashingState { in_flight, notice, rehash }` in `Announce::hashing`
  so interleaved `Ready`/`Gone`/`Ready` transitions neither leak DRAM
  pins nor announce stale hashes, and fast-path `allocate_slots(0, false)`
  (`selene/src/memory.rs`).
- Refuse direct-to-disk writes under unwritten DRAM-parked ancestors in
  `CompositeStore::store`, fix `Inbound::used_disk` NVMe attribution,
  and remove the `waiting_spills` head-of-line cap
  (`selene/src/composite.rs`).
- Require `!receive_profiles.is_empty()` for v4 packed files in
  `DiskStore::new`, prevent self-eviction loops in `make_room_inner`,
  fix `Reclaim::unlinked` `used` accounting after `Truncate`-then-`Unlink`,
  and reject v4 empty `ranks` and replication flags in `Header::decode`
  (`selene/src/disk_store.rs`, `selene/src/shared/record.rs`).
- Use an unbounded invalidation queue, generation epochs, `WaiterGuard`,
  pre-eviction `retain()` checks, and accurate `len()` vs `capacity()`
  in `InputStore` (`selene/src/input.rs`).
- Return `(drained, result)` from `Peer::shutdown`, return
  `with_record_read()` on v4 mismatch and refuse rank-0 truncate fallback
  on corrupt v4 files, prune page-only leaves in `shard::agree`, close
  peers concurrently in `Sharded::close`, filter unreadable v4 files when
  `KvCompression::Off`, propagate the global minimum disk limit across
  3+ ranks, and canonicalize peer IPs (`selene/src/shard.rs`,
  `selene/src/shard/tests.rs`, `selene/src/offload/sharded.rs`).
- Retry `EINTR` in `fallocate` and `io_uring`, retry block-aligned short
  transfers, and make `Worker::publish` directory sync Windows-safe
  (`selene/src/disk.rs`).
- Reject duplicate in-flight keys in `PooledStore::fetch`, start rate
  tracking only after accepted paged fetches, prefer faster equal-length
  local hits when a remote tier is degraded, guard `worth_transfer`
  against NaN, use `RefCell::take` across Rayon in `GpuPlan::decode_checked_cpu`,
  use checked arithmetic in `geometry.rs`, and reject unknown buffer
  names in `codec_layout.rs` (`selene/src/pool/store.rs`,
  `selene/src/levels.rs`, `selene/src/store.rs`,
  `selene/src/shared/gpu_codec.rs`, `selene/src/geometry.rs`,
  `selene/src/shared/codec_layout.rs`).

Local tiers, sharded disk ranks, prepared-input caches, and codec paths
no longer leak pins or disk accounting, desync disk limits across 3+
ranks, or panic on corrupt v4 headers.

Validated on Linux (rebased onto post-NVIDIA#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene`, `selene-manager`, and `helios offload::`.

Design-Signed-Off-By: derek <derek.yates@live.com>; design-review=2e5b
yatesdr added a commit to yatesdr/flare-local-inference that referenced this pull request Nov 29, 2026
Several `selene-manager` paths accepted unvalidated peer metadata or
multi-process packed operations that could cause out-of-bounds arena
reads/writes, panics, or permanent slot and resource leaks.

- Reject multi-process (`world >= 2`) packed `PutBegin` and `PinAck`
  grants cleanly instead of sizing an arena extent to compressed bytes
  and passing uncompressed window lengths to `pass::run` or concurrent
  rank writers (`selene-manager/src/pool/store_bridge.rs`,
  `selene-manager/src/pool/claims.rs`).
- Cap scopes at 64 ranks and 1 TiB record sizes in `validate_scope`,
  replace panicking `next_power_of_two` calls with
  `checked_next_power_of_two`, check `PinAck` page and reservation
  bounds before allocating `PlannedWindow` vectors, and use checked
  arithmetic in `windows::plan` (`selene-manager/src/pool/mod.rs`,
  `selene-manager/src/store.rs`, `selene-manager/src/pool/claims.rs`,
  `selene-manager/src/pool/windows.rs`).
- Reparent replaced nodes to root in `Index::reparent_to_root` when
  rootless fallback converts a linked replacement to a root record, and
  refuse evicting page-only ancestors with active readers in
  `evict_accounted` (`selene/src/shared/index.rs`,
  `selene-manager/src/store.rs`).
- Reclaim terminal remote-channel `Pinned` exports on source disconnect,
  resolve rank-agent fences by `aid`, verify scope and rank secrets
  before keeping peer agents across rank-0 reconnect, bound and prune
  idle scopes, fall back to `kill(pid, 0)` when `pidfd_open` is
  unavailable, cap and time out TLS handshakes on `--listen`, and call
  `hub.shutdown()` before aborting `pool_task`
  (`selene-manager/src/pool/claims.rs`,
  `selene-manager/src/pool/ranks.rs`,
  `selene-manager/src/pool/core.rs`, `selene-manager/src/local.rs`,
  `selene-manager/src/control.rs`).

The manager now rejects malformed or unsupported multi-process packed
requests safely, resists oversize-geometry DoS inputs, keeps `Tree`
topology consistent across rootless replacements, and reclaims remote
export slots and shutdown resources cleanly.

Validated on Linux (rebased onto post-NVIDIA#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene` and `selene-manager`.

Design-Signed-Off-By: derek <derek.yates@live.com>; design-review=2e5b
yatesdr added a commit to yatesdr/flare-local-inference that referenced this pull request Nov 29, 2026
Local storage tiers, prepared-input caching, sharded disk ranks, direct
I/O loops, and KV-codec helpers had several correctness, durability, and
accounting bugs:

- Track `HashingState { in_flight, notice, rehash }` in `Announce::hashing`
  so interleaved `Ready`/`Gone`/`Ready` transitions neither leak DRAM
  pins nor announce stale hashes, and fast-path `allocate_slots(0, false)`
  (`selene/src/memory.rs`).
- Refuse direct-to-disk writes under unwritten DRAM-parked ancestors in
  `CompositeStore::store`, fix `Inbound::used_disk` NVMe attribution,
  and remove the `waiting_spills` head-of-line cap
  (`selene/src/composite.rs`).
- Require `!receive_profiles.is_empty()` for v4 packed files in
  `DiskStore::new`, prevent self-eviction loops in `make_room_inner`,
  fix `Reclaim::unlinked` `used` accounting after `Truncate`-then-`Unlink`,
  and reject v4 empty `ranks` and replication flags in `Header::decode`
  (`selene/src/disk_store.rs`, `selene/src/shared/record.rs`).
- Use an unbounded invalidation queue, generation epochs, `WaiterGuard`,
  pre-eviction `retain()` checks, and accurate `len()` vs `capacity()`
  in `InputStore` (`selene/src/input.rs`).
- Return `(drained, result)` from `Peer::shutdown`, return
  `with_record_read()` on v4 mismatch and refuse rank-0 truncate fallback
  on corrupt v4 files, prune page-only leaves in `shard::agree`, close
  peers concurrently in `Sharded::close`, filter unreadable v4 files when
  `KvCompression::Off`, propagate the global minimum disk limit across
  3+ ranks, and canonicalize peer IPs (`selene/src/shard.rs`,
  `selene/src/shard/tests.rs`, `selene/src/offload/sharded.rs`).
- Retry `EINTR` in `fallocate` and `io_uring`, retry block-aligned short
  transfers, and make `Worker::publish` directory sync Windows-safe
  (`selene/src/disk.rs`).
- Reject duplicate in-flight keys in `PooledStore::fetch`, start rate
  tracking only after accepted paged fetches, prefer faster equal-length
  local hits when a remote tier is degraded, guard `worth_transfer`
  against NaN, use `RefCell::take` across Rayon in `GpuPlan::decode_checked_cpu`,
  use checked arithmetic in `geometry.rs`, and reject unknown buffer
  names in `codec_layout.rs` (`selene/src/pool/store.rs`,
  `selene/src/levels.rs`, `selene/src/store.rs`,
  `selene/src/shared/gpu_codec.rs`, `selene/src/geometry.rs`,
  `selene/src/shared/codec_layout.rs`).

Local tiers, sharded disk ranks, prepared-input caches, and codec paths
no longer leak pins or disk accounting, desync disk limits across 3+
ranks, or panic on corrupt v4 headers.

Validated on Linux (rebased onto post-NVIDIA#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene`, `selene-manager`, and `helios offload::`.

Design-Signed-Off-By: yatesdr; design-review=2e5b
yatesdr added a commit to yatesdr/flare-local-inference that referenced this pull request Nov 29, 2026
Active GPU DMA, host compression, NIC RDMA, and concurrent data-channel
workers can access mapped host or shared-memory ranges across close,
panic unwind, quarantine, and multi-rank scatter paths. Unmapping a
region before every local copier, RDMA queue pair, and compression
worker has drained causes use-after-unmap, and constructing overlapping
`&mut [u8]` slices in `LocalRegions` is undefined behavior under
concurrent readers or multi-rank writes.

- Declare `transfers` before `core`/`pool` in `MemoryStore` and
  `disk_store::Resources`, close both tiers in `CompositeStore::close`,
  guard `AsyncCompressor`'s active count with an RAII drop guard, and
  leak the slab pool and report an error if compression does not finish
  before `MemoryStore::close` (`selene/src/memory.rs`,
  `selene/src/disk_store.rs`, `selene/src/composite.rs`).
- Retain `sess.regions` and `Attachment::Shm` in `Engine::quarantine`,
  retain `self.shared` in `Agent::quarantine`, and invoke
  `engine.quarantine()` when `conn::shutdown` fails to drain
  (`selene/src/pool/engine/mod.rs`, `selene/src/pool/conn.rs`,
  `selene/src/pool/agent.rs`).
- Wrap `Staging.region` in `Arc<Region>` and retain it inside
  `rdma::Device` so quarantined RDMA queue pairs keep their registered
  staging mapped (`selene/src/pool/rdma.rs`, `selene/src/pool/net.rs`).
- Add `LocalRegions::bytes_read`, `LocalRegions::ptr_mut`, and
  `SliceLayout::scatter_disjoint` so concurrent read paths borrow
  `&[u8]` and multi-rank data-channel scatter writes only each rank's
  disjoint byte ranges without aliasing `&mut [u8]`
  (`selene/src/shared/slice.rs`, `selene-manager/src/regions.rs`,
  `selene-manager/src/pool/pass.rs`,
  `selene-manager/src/data/channel.rs`).
- Attach `ReadAhead`'s overlapped file handle to its IOCP queue on
  Windows (`selene/src/disk.rs`).

Every affected teardown, quarantine, RDMA, and concurrent region access
path now preserves backing mappings and disjoint ownership until all
DMA, RDMA, and worker accesses finish.

Validated on Linux (rebased onto post-NVIDIA#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene`, `selene-manager`, and `helios offload::`.

Design-Signed-Off-By: yatesdr; design-review=2e5b
yatesdr added a commit to yatesdr/flare-local-inference that referenced this pull request Nov 29, 2026
Several `selene-manager` paths accepted unvalidated peer metadata or
multi-process packed operations that could cause out-of-bounds arena
reads/writes, panics, or permanent slot and resource leaks.

- Reject multi-process (`world >= 2`) packed `PutBegin` and `PinAck`
  grants cleanly instead of sizing an arena extent to compressed bytes
  and passing uncompressed window lengths to `pass::run` or concurrent
  rank writers (`selene-manager/src/pool/store_bridge.rs`,
  `selene-manager/src/pool/claims.rs`).
- Cap scopes at 64 ranks and 1 TiB record sizes in `validate_scope`,
  replace panicking `next_power_of_two` calls with
  `checked_next_power_of_two`, check `PinAck` page and reservation
  bounds before allocating `PlannedWindow` vectors, and use checked
  arithmetic in `windows::plan` (`selene-manager/src/pool/mod.rs`,
  `selene-manager/src/store.rs`, `selene-manager/src/pool/claims.rs`,
  `selene-manager/src/pool/windows.rs`).
- Reparent replaced nodes to root in `Index::reparent_to_root` when
  rootless fallback converts a linked replacement to a root record, and
  refuse evicting page-only ancestors with active readers in
  `evict_accounted` (`selene/src/shared/index.rs`,
  `selene-manager/src/store.rs`).
- Reclaim terminal remote-channel `Pinned` exports on source disconnect,
  resolve rank-agent fences by `aid`, verify scope and rank secrets
  before keeping peer agents across rank-0 reconnect, bound and prune
  idle scopes, fall back to `kill(pid, 0)` when `pidfd_open` is
  unavailable, cap and time out TLS handshakes on `--listen`, and call
  `hub.shutdown()` before aborting `pool_task`
  (`selene-manager/src/pool/claims.rs`,
  `selene-manager/src/pool/ranks.rs`,
  `selene-manager/src/pool/core.rs`, `selene-manager/src/local.rs`,
  `selene-manager/src/control.rs`).

The manager now rejects malformed or unsupported multi-process packed
requests safely, resists oversize-geometry DoS inputs, keeps `Tree`
topology consistent across rootless replacements, and reclaims remote
export slots and shutdown resources cleanly.

Validated on Linux (rebased onto post-NVIDIA#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene` and `selene-manager`.

Design-Signed-Off-By: yatesdr; design-review=2e5b
yatesdr added a commit to yatesdr/flare-local-inference that referenced this pull request Nov 29, 2026
Several `selene-manager` paths accepted unvalidated peer metadata or
multi-process packed operations that could cause out-of-bounds arena
reads/writes, panics, or permanent slot and resource leaks.

- Reject multi-process (`world >= 2`) packed `PutBegin` and `PinAck`
  grants cleanly instead of sizing an arena extent to compressed bytes
  and passing uncompressed window lengths to `pass::run` or concurrent
  rank writers (`selene-manager/src/pool/store_bridge.rs`,
  `selene-manager/src/pool/claims.rs`).
- Cap scopes at 64 ranks and 1 TiB record sizes in `validate_scope`,
  replace panicking `next_power_of_two` calls with
  `checked_next_power_of_two`, check `PinAck` page and reservation
  bounds before allocating `PlannedWindow` vectors, and use checked
  arithmetic in `windows::plan` (`selene-manager/src/pool/mod.rs`,
  `selene-manager/src/store.rs`, `selene-manager/src/pool/claims.rs`,
  `selene-manager/src/pool/windows.rs`).
- Reparent replaced nodes to root in `Index::reparent_to_root` when
  rootless fallback converts a linked replacement to a root record, and
  refuse evicting page-only ancestors with active readers in
  `evict_accounted` (`selene/src/shared/index.rs`,
  `selene-manager/src/store.rs`).
- Reclaim terminal remote-channel `Pinned` exports on source disconnect,
  resolve rank-agent fences by `aid`, verify scope and rank secrets
  before keeping peer agents across rank-0 reconnect, bound and prune
  idle scopes, fall back to `kill(pid, 0)` when `pidfd_open` is
  unavailable, cap and time out TLS handshakes on `--listen`, and call
  `hub.shutdown()` before aborting `pool_task`
  (`selene-manager/src/pool/claims.rs`,
  `selene-manager/src/pool/ranks.rs`,
  `selene-manager/src/pool/core.rs`, `selene-manager/src/local.rs`,
  `selene-manager/src/control.rs`).

The manager now rejects malformed or unsupported multi-process packed
requests safely, resists oversize-geometry DoS inputs, keeps `Tree`
topology consistent across rootless replacements, and reclaims remote
export slots and shutdown resources cleanly.

Validated on Linux (rebased onto post-NVIDIA#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene` and `selene-manager`.

Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
Design-Signed-Off-By: yatesdr; design-review=2e5b
yatesdr added a commit to yatesdr/flare-local-inference that referenced this pull request Nov 29, 2026
Local storage tiers, prepared-input caching, sharded disk ranks, direct
I/O loops, and KV-codec helpers had several correctness, durability, and
accounting bugs:

- Track `HashingState { in_flight, notice, rehash }` in `Announce::hashing`
  so interleaved `Ready`/`Gone`/`Ready` transitions neither leak DRAM
  pins nor announce stale hashes, and fast-path `allocate_slots(0, false)`
  (`selene/src/memory.rs`).
- Refuse direct-to-disk writes under unwritten DRAM-parked ancestors in
  `CompositeStore::store`, fix `Inbound::used_disk` NVMe attribution,
  and remove the `waiting_spills` head-of-line cap
  (`selene/src/composite.rs`).
- Require `!receive_profiles.is_empty()` for v4 packed files in
  `DiskStore::new`, prevent self-eviction loops in `make_room_inner`,
  fix `Reclaim::unlinked` `used` accounting after `Truncate`-then-`Unlink`,
  and reject v4 empty `ranks` and replication flags in `Header::decode`
  (`selene/src/disk_store.rs`, `selene/src/shared/record.rs`).
- Use an unbounded invalidation queue, generation epochs, `WaiterGuard`,
  pre-eviction `retain()` checks, and accurate `len()` vs `capacity()`
  in `InputStore` (`selene/src/input.rs`).
- Return `(drained, result)` from `Peer::shutdown`, return
  `with_record_read()` on v4 mismatch and refuse rank-0 truncate fallback
  on corrupt v4 files, prune page-only leaves in `shard::agree`, close
  peers concurrently in `Sharded::close`, filter unreadable v4 files when
  `KvCompression::Off`, propagate the global minimum disk limit across
  3+ ranks, and canonicalize peer IPs (`selene/src/shard.rs`,
  `selene/src/shard/tests.rs`, `selene/src/offload/sharded.rs`).
- Retry `EINTR` in `fallocate` and `io_uring`, retry block-aligned short
  transfers, and make `Worker::publish` directory sync Windows-safe
  (`selene/src/disk.rs`).
- Reject duplicate in-flight keys in `PooledStore::fetch`, start rate
  tracking only after accepted paged fetches, prefer faster equal-length
  local hits when a remote tier is degraded, guard `worth_transfer`
  against NaN, use `RefCell::take` across Rayon in `GpuPlan::decode_checked_cpu`,
  use checked arithmetic in `geometry.rs`, and reject unknown buffer
  names in `codec_layout.rs` (`selene/src/pool/store.rs`,
  `selene/src/levels.rs`, `selene/src/store.rs`,
  `selene/src/shared/gpu_codec.rs`, `selene/src/geometry.rs`,
  `selene/src/shared/codec_layout.rs`).

Local tiers, sharded disk ranks, prepared-input caches, and codec paths
no longer leak pins or disk accounting, desync disk limits across 3+
ranks, or panic on corrupt v4 headers.

Validated on Linux (rebased onto post-NVIDIA#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene`, `selene-manager`, and `helios offload::`.

Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
Design-Signed-Off-By: yatesdr; design-review=2e5b
yatesdr added a commit to yatesdr/flare-local-inference that referenced this pull request Nov 29, 2026
Active GPU DMA, host compression, NIC RDMA, and concurrent data-channel
workers can access mapped host or shared-memory ranges across close,
panic unwind, quarantine, and multi-rank scatter paths. Unmapping a
region before every local copier, RDMA queue pair, and compression
worker has drained causes use-after-unmap, and constructing overlapping
`&mut [u8]` slices in `LocalRegions` is undefined behavior under
concurrent readers or multi-rank writes.

- Declare `transfers` before `core`/`pool` in `MemoryStore` and
  `disk_store::Resources`, close both tiers in `CompositeStore::close`,
  guard `AsyncCompressor`'s active count with an RAII drop guard, and
  leak the slab pool and report an error if compression does not finish
  before `MemoryStore::close` (`selene/src/memory.rs`,
  `selene/src/disk_store.rs`, `selene/src/composite.rs`).
- Retain `sess.regions` and `Attachment::Shm` in `Engine::quarantine`,
  retain `self.shared` in `Agent::quarantine`, and invoke
  `engine.quarantine()` when `conn::shutdown` fails to drain
  (`selene/src/pool/engine/mod.rs`, `selene/src/pool/conn.rs`,
  `selene/src/pool/agent.rs`).
- Wrap `Staging.region` in `Arc<Region>` and retain it inside
  `rdma::Device` so quarantined RDMA queue pairs keep their registered
  staging mapped (`selene/src/pool/rdma.rs`, `selene/src/pool/net.rs`).
- Add `LocalRegions::bytes_read`, `LocalRegions::ptr_mut`, and
  `SliceLayout::scatter_disjoint` so concurrent read paths borrow
  `&[u8]` and multi-rank data-channel scatter writes only each rank's
  disjoint byte ranges without aliasing `&mut [u8]`
  (`selene/src/shared/slice.rs`, `selene-manager/src/regions.rs`,
  `selene-manager/src/pool/pass.rs`,
  `selene-manager/src/data/channel.rs`).
- Attach `ReadAhead`'s overlapped file handle to its IOCP queue on
  Windows (`selene/src/disk.rs`).

Every affected teardown, quarantine, RDMA, and concurrent region access
path now preserves backing mappings and disjoint ownership until all
DMA, RDMA, and worker accesses finish.

Validated on Linux (rebased onto post-NVIDIA#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene`, `selene-manager`, and `helios offload::`.

Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
Design-Signed-Off-By: yatesdr; design-review=2e5b
yatesdr added a commit that referenced this pull request Nov 29, 2026
…609)

Active GPU DMA, host compression, NIC RDMA, and concurrent data-channel
workers can access mapped host or shared-memory ranges across close,
panic unwind, quarantine, and multi-rank scatter paths. Unmapping a
region before every local copier, RDMA queue pair, and compression
worker has drained causes use-after-unmap, and constructing overlapping
`&mut [u8]` slices in `LocalRegions` is undefined behavior under
concurrent readers or multi-rank writes.

- Declare `transfers` before `core`/`pool` in `MemoryStore` and
  `disk_store::Resources`, close both tiers in `CompositeStore::close`,
  guard `AsyncCompressor`'s active count with an RAII drop guard, and
  leak the slab pool and report an error if compression does not finish
  before `MemoryStore::close` (`selene/src/memory.rs`,
  `selene/src/disk_store.rs`, `selene/src/composite.rs`).
- Retain `sess.regions` and `Attachment::Shm` in `Engine::quarantine`,
  retain `self.shared` in `Agent::quarantine`, and invoke
  `engine.quarantine()` when `conn::shutdown` fails to drain
  (`selene/src/pool/engine/mod.rs`, `selene/src/pool/conn.rs`,
  `selene/src/pool/agent.rs`).
- Wrap `Staging.region` in `Arc<Region>` and retain it inside
  `rdma::Device` so quarantined RDMA queue pairs keep their registered
  staging mapped (`selene/src/pool/rdma.rs`, `selene/src/pool/net.rs`).
- Add `LocalRegions::bytes_read`, `LocalRegions::ptr_mut`, and
  `SliceLayout::scatter_disjoint` so concurrent read paths borrow
  `&[u8]` and multi-rank data-channel scatter writes only each rank's
  disjoint byte ranges without aliasing `&mut [u8]`
  (`selene/src/shared/slice.rs`, `selene-manager/src/regions.rs`,
  `selene-manager/src/pool/pass.rs`,
  `selene-manager/src/data/channel.rs`).
- Attach `ReadAhead`'s overlapped file handle to its IOCP queue on
  Windows (`selene/src/disk.rs`).

Every affected teardown, quarantine, RDMA, and concurrent region access
path now preserves backing mappings and disjoint ownership until all
DMA, RDMA, and worker accesses finish.

Validated on Linux (rebased onto post-#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene`, `selene-manager`, and `helios offload::`.


Design-Signed-Off-By: yatesdr; design-review=2e5b

Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
Co-authored-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
yatesdr added a commit that referenced this pull request Nov 29, 2026
…610)

Local storage tiers, prepared-input caching, sharded disk ranks, direct
I/O loops, and KV-codec helpers had several correctness, durability, and
accounting bugs:

- Track `HashingState { in_flight, notice, rehash }` in `Announce::hashing`
  so interleaved `Ready`/`Gone`/`Ready` transitions neither leak DRAM
  pins nor announce stale hashes, and fast-path `allocate_slots(0, false)`
  (`selene/src/memory.rs`).
- Refuse direct-to-disk writes under unwritten DRAM-parked ancestors in
  `CompositeStore::store`, fix `Inbound::used_disk` NVMe attribution,
  and remove the `waiting_spills` head-of-line cap
  (`selene/src/composite.rs`).
- Require `!receive_profiles.is_empty()` for v4 packed files in
  `DiskStore::new`, prevent self-eviction loops in `make_room_inner`,
  fix `Reclaim::unlinked` `used` accounting after `Truncate`-then-`Unlink`,
  and reject v4 empty `ranks` and replication flags in `Header::decode`
  (`selene/src/disk_store.rs`, `selene/src/shared/record.rs`).
- Use an unbounded invalidation queue, generation epochs, `WaiterGuard`,
  pre-eviction `retain()` checks, and accurate `len()` vs `capacity()`
  in `InputStore` (`selene/src/input.rs`).
- Return `(drained, result)` from `Peer::shutdown`, return
  `with_record_read()` on v4 mismatch and refuse rank-0 truncate fallback
  on corrupt v4 files, prune page-only leaves in `shard::agree`, close
  peers concurrently in `Sharded::close`, filter unreadable v4 files when
  `KvCompression::Off`, propagate the global minimum disk limit across
  3+ ranks, and canonicalize peer IPs (`selene/src/shard.rs`,
  `selene/src/shard/tests.rs`, `selene/src/offload/sharded.rs`).
- Retry `EINTR` in `fallocate` and `io_uring`, retry block-aligned short
  transfers, and make `Worker::publish` directory sync Windows-safe
  (`selene/src/disk.rs`).
- Reject duplicate in-flight keys in `PooledStore::fetch`, start rate
  tracking only after accepted paged fetches, prefer faster equal-length
  local hits when a remote tier is degraded, guard `worth_transfer`
  against NaN, use `RefCell::take` across Rayon in `GpuPlan::decode_checked_cpu`,
  use checked arithmetic in `geometry.rs`, and reject unknown buffer
  names in `codec_layout.rs` (`selene/src/pool/store.rs`,
  `selene/src/levels.rs`, `selene/src/store.rs`,
  `selene/src/shared/gpu_codec.rs`, `selene/src/geometry.rs`,
  `selene/src/shared/codec_layout.rs`).

Local tiers, sharded disk ranks, prepared-input caches, and codec paths
no longer leak pins or disk accounting, desync disk limits across 3+
ranks, or panic on corrupt v4 headers.

Validated on Linux (rebased onto post-#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene`, `selene-manager`, and `helios offload::`.


Design-Signed-Off-By: yatesdr; design-review=2e5b

Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
Co-authored-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
yatesdr added a commit to yatesdr/flare-local-inference that referenced this pull request Nov 29, 2026
Several `selene-manager` paths accepted unvalidated peer metadata or
multi-process packed operations that could cause out-of-bounds arena
reads/writes, panics, or permanent slot and resource leaks.

- Reject multi-process (`world >= 2`) packed `PutBegin` and `PinAck`
  grants cleanly instead of sizing an arena extent to compressed bytes
  and passing uncompressed window lengths to `pass::run` or concurrent
  rank writers (`selene-manager/src/pool/store_bridge.rs`,
  `selene-manager/src/pool/claims.rs`).
- Cap scopes at 64 ranks and 1 TiB record sizes in `validate_scope`,
  replace panicking `next_power_of_two` calls with
  `checked_next_power_of_two`, check `PinAck` page and reservation
  bounds before allocating `PlannedWindow` vectors, and use checked
  arithmetic in `windows::plan` (`selene-manager/src/pool/mod.rs`,
  `selene-manager/src/store.rs`, `selene-manager/src/pool/claims.rs`,
  `selene-manager/src/pool/windows.rs`).
- Reparent replaced nodes to root in `Index::reparent_to_root` when
  rootless fallback converts a linked replacement to a root record, and
  refuse evicting page-only ancestors with active readers in
  `evict_accounted` (`selene/src/shared/index.rs`,
  `selene-manager/src/store.rs`).
- Reclaim terminal remote-channel `Pinned` exports on source disconnect,
  resolve rank-agent fences by `aid`, verify scope and rank secrets
  before keeping peer agents across rank-0 reconnect, bound and prune
  idle scopes, fall back to `kill(pid, 0)` when `pidfd_open` is
  unavailable, cap and time out TLS handshakes on `--listen`, and call
  `hub.shutdown()` before aborting `pool_task`
  (`selene-manager/src/pool/claims.rs`,
  `selene-manager/src/pool/ranks.rs`,
  `selene-manager/src/pool/core.rs`, `selene-manager/src/local.rs`,
  `selene-manager/src/control.rs`).

The manager now rejects malformed or unsupported multi-process packed
requests safely, resists oversize-geometry DoS inputs, keeps `Tree`
topology consistent across rootless replacements, and reclaims remote
export slots and shutdown resources cleanly.

Validated on Linux (rebased onto post-NVIDIA#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene` and `selene-manager`.

Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
Design-Signed-Off-By: yatesdr; design-review=2e5b
yatesdr added a commit that referenced this pull request Nov 29, 2026
…612)

Several `selene-manager` paths accepted unvalidated peer metadata or
multi-process packed operations that could cause out-of-bounds arena
reads/writes, panics, or permanent slot and resource leaks.

- Reject multi-process (`world >= 2`) packed `PutBegin` and `PinAck`
  grants cleanly instead of sizing an arena extent to compressed bytes
  and passing uncompressed window lengths to `pass::run` or concurrent
  rank writers (`selene-manager/src/pool/store_bridge.rs`,
  `selene-manager/src/pool/claims.rs`).
- Cap scopes at 64 ranks and 1 TiB record sizes in `validate_scope`,
  replace panicking `next_power_of_two` calls with
  `checked_next_power_of_two`, check `PinAck` page and reservation
  bounds before allocating `PlannedWindow` vectors, and use checked
  arithmetic in `windows::plan` (`selene-manager/src/pool/mod.rs`,
  `selene-manager/src/store.rs`, `selene-manager/src/pool/claims.rs`,
  `selene-manager/src/pool/windows.rs`).
- Reparent replaced nodes to root in `Index::reparent_to_root` when
  rootless fallback converts a linked replacement to a root record, and
  refuse evicting page-only ancestors with active readers in
  `evict_accounted` (`selene/src/shared/index.rs`,
  `selene-manager/src/store.rs`).
- Reclaim terminal remote-channel `Pinned` exports on source disconnect,
  resolve rank-agent fences by `aid`, verify scope and rank secrets
  before keeping peer agents across rank-0 reconnect, bound and prune
  idle scopes, fall back to `kill(pid, 0)` when `pidfd_open` is
  unavailable, cap and time out TLS handshakes on `--listen`, and call
  `hub.shutdown()` before aborting `pool_task`
  (`selene-manager/src/pool/claims.rs`,
  `selene-manager/src/pool/ranks.rs`,
  `selene-manager/src/pool/core.rs`, `selene-manager/src/local.rs`,
  `selene-manager/src/control.rs`).

The manager now rejects malformed or unsupported multi-process packed
requests safely, resists oversize-geometry DoS inputs, keeps `Tree`
topology consistent across rootless replacements, and reclaims remote
export slots and shutdown resources cleanly.

Validated on Linux (rebased onto post-#607 main `5df8edd3c`), GB10, and
SM120 hardware across `selene` and `selene-manager`.


Design-Signed-Off-By: yatesdr; design-review=2e5b

Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
Co-authored-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Ready To Merge

PR #607 fixes six verified memory-safety, DoS, state-corruption, and offload lifecycle defects across selene-manager, selene, and helios in ~60 non-test production lines, each with targeted regression tests. No correctness regressions, wire/on-disk format breaks, or blockers were found at 4f12cae; two defence-in-depth polish items and two small simplifications are optional follow-ups.

  • Blockers: 0 · Should fix: 2 · Subtract/Simplify: 2 · Nits: 3
Walkthrough
  • Remote data-channel staging UAF (selene-manager/src/pool/claims.rs:1513-1516): Core::window_released now returns early when claim.channel().is_some(), so a remote gRPC WindowReleased cannot clear reader bit 0 and drop window.extent while the data-channel handler holds references; release stays driven by channel::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): entry_from and walk_chain reject zero or non-decreasing parent.consumed_tokens, reject max_nodes == 0, and bound total visited entries (including zero-page checkpoints) by max_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_drained calls forget_window after release_slot on a failed channel.send, preventing Agent::drive (agent.rs:1638-1642) from double-releasing the slot; Staging::release adds a duplicate-slot debug_assert!; Engine::withdraw_queued now requires w.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): Monotonic manager-side transfer IDs via StoreHandle::next_transfer (store_bridge.rs:122-126) for every StoreCommand prevent concurrent put_id == claim_id collisions in the store's per-connection ops map; the record-relative first_page calculation in Core::put_answer (store_bridge.rs:643-647) is hoisted so PutWin.first_page matches WindowSpec.first_page and put_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): Worker::park clears stale pre-park admission/pool fields before re-planning the extended prompt; the if !refill guard in MemoryStore::drain_compressed is removed so deferred children wake after async CPU-codec row refills; CompositeStore::disk_read releases incomplete copies and quarantines unreadable v1/v2/v3 records; Index::expired uses filter instead of take_while (fixing #439) with matching docs.
Merge Risk: Low · up to 4f12cae
  • Small, localized production surface: Every fix is 1–10 lines inside existing state machines; no wire protocol (selene.proto untouched), 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 covered by unit tests and Helios formal checks; live GPU/RDMA/multi-process runs were not executed on this PR alone (disclosed in Limitations), though downstream PRs #609/#610/#612 rebased onto #607 include SM120/GB10 hardware qualification.
  • Blast radius of edge cases: The two caveats (stray gRPC WindowReleased on channel claims treated as a no-op; quarantining an unpacked disk ancestor on transient OS open/read error) cannot corrupt data or cause UB — at worst a transient disk error triggers a cache miss/recompute until recapture.
Pre-merge checks: ✅ 3 passed · ⚠️ 1 warnings
  • ✅ Security / malicious screen: Fixes two remote security/DoS vectors (data-channel staging UAF; cyclic/zero-page walk_chain CPU hang) with no unsafe additions or credential/protocol exposure; minor gRPC validation tightening noted in Should Fix.
  • ✅ Charter & value fit: Directly advances the Selene prefix-cache sharing goal from priority contributor @lukealonso, includes all four required PR description sections, and adds no model-specific branches, config knobs, or non-goal scope.
  • ✅ Related / duplicate / conflict check: Companion PRs #609, #610, #611, #612 by yatesdr are already rebased onto #607 (overlapping hunks removed, #607 referenced explicitly); #439 is linked and closed.
  • ⚠️ Tests & verification evidence: All 11 regression tests exist, compile under the reported commands (selene/Cargo.toml:20 includes codec in test-support), and CI is green on 4f12cae; live GPU/RDMA/multi-process tests (FLARE_RUN_CUDA_TESTS=1) were not run on this branch (disclosed in Limitations), and two store_bridge.rs tests seed internal Claim/PutRec fixtures rather than driving claim_begin/put_begin end-to-end.

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:caching Prefix/KV reuse, cache retention, and model or payload cache behavior. area:selene Selene shared prefix-cache pool, protocol, manager, and transfers. bug Something isn't working duplicate This issue or pull request already exists triage:review Proposed change needs code review; this does not imply merge readiness.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Prefix-index sweep stops at a refreshed leaf whose access tick never advanced

3 participants