Skip to content

selene: parallelize startup disk scan - #734

Open
FujitsuPolycom wants to merge 1 commit into
NVIDIA:mainfrom
FujitsuPolycom:perf/selene-parallel-startup-scan
Open

FujitsuPolycom wants to merge 1 commit into
NVIDIA:mainfrom
FujitsuPolycom:perf/selene-parallel-startup-scan

Conversation

@FujitsuPolycom

@FujitsuPolycom FujitsuPolycom commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Why

Startup recovery in Selene (selene/src/shared/record.rs::scan and selene/src/input.rs Worker::scan) inspects every cached .ckpt and .input file sequentially (QD=1). On local NVMe caches holding hundreds to tens of thousands of records, serial metadata inspection leaves storage queue depth unused and stalls Prepare host prefix cache during server startup.

What changed

Parallelized startup file inspection across bounded threads with 0 production unsafe and 0 new dependencies. On-disk v3/v4 .ckpt and .input formats, Protobuf wire schemas, and model core loading are unchanged.

  • par_map and record::scan (selene/src/shared/record.rs):
    • Before: Inspected .ckpt and .tmp entries sequentially in fs::read_dir order and unlinked invalid entries inline.
    • After: Pre-filters candidate .ckpt and .*.tmp paths (Vec<PathBuf>) and, at 64 or more items, runs fs::symlink_metadata (never following symlinks) and inspect across bounded threads (available_parallelism().min(16), std::thread::scope, chunk size 8). Workers use fallible Builder::spawn_scoped named flare-scan with calling-thread participation, return per-chunk (start, Vec<R>) blocks for order restoration, and close all file handles before scope exit for Windows handle-close-before-unlink safety. The sequential reduction pass fails closed: it returns the first Unreadable error before deleting .tmp or invalid entries and preserves deterministic remove_orphans ordering ((consumed_tokens, digest)). selene-manager/src/disk.rs::recover delegates full directory scans to record::scan.
  • Worker::scan (selene/src/input.rs):
    • Before: Unlinked .input.pending files inline during fs::read_dir and inspected .input files sequentially.
    • After: Defers .input.pending removal, sorts .input paths in lexicographic OsStr order (sort_unstable_by(|a, b| a.as_os_str().cmp(b.as_os_str())), avoiding Path::cmp component parsing), inspects headers in parallel via record::par_map, rejects non-InvalidData I/O errors before unlinking .input.pending or mutating self.disk/self.budget, and admits records deterministically under MAX_DISK_RECORDS and DiskBudget.
  • Documentation (docs/prefix-cache-offload.md): Documents that unreadable .ckpt and .input entries fail startup scans before deleting temporary, invalid, or over-budget files, that .input startup also fails if removing those files fails, and that .input recovery admits files in lexicographic path order.

Result

All measurements below compare clean git archive be4092d7e1f0efe8a16049568c12ec7b841a2e8e (NVIDIA/hyperflare-inference:main commit parent and benchmark control) vs clean git archive b7bd3fa9032f4ee306f0995495ed6dd463818ada (candidate), built --locked --release on plain local NVMe ext4.

1. End-to-end flare run startup A/B (Prepare host prefix cache & timings.disk_scan)

Measured on bare-metal aarch64 GB10 (20-core Grace, local Samsung MZALC4T0HBL1 NVMe ext4) booting a signed TP1 Qwen4-35B-A3B-NVFP4 core with --prefix-cache-disk, --prefix-cache-disk-limit 2000G, and --lossless-kv-compression cpu.

  • Cache population: Booted flare run once with --prefix-cache-drain-on-shutdown=30s and one 443-token chat request to drain a genuine Qwen4-35B-A3B-NVFP4 .ckpt file and observe its exact namespace, identity, fingerprint, page_tokens = 64, ranks, and bucket. Seeded that namespace directory with 10,000 sparse .ckpt files (5,000 v3 + 5,000 v4 Representation::Literal, 1,000 10-step chains, tail_pages = 1, 697,774,713,000 logical bytes / 649.85 GiB; per-format byte counts in <details> below), plus 1,000 .input files (4,440 bytes each). Every single boot verified 10,000 scanned records in Prepare host prefix cache, flare_host_cache_disk_records == 10000 and flare_input_cache_disk_records == 1000 on /metrics, HTTP /health ready, and 10,000 .ckpt + 1,000 .input files untouched after clean SIGTERM shutdown (0 deletions, 0 rejections across all 22 boots: 20 measured + 2 warm-up).
  • Methodology: n=5 interleaved Cold boots per arm (sync && echo 3 > /proc/sys/vm/drop_caches before every boot) and n=5 interleaved Warm boots per arm after 1 warm-up boot per arm. Prepare host prefix cache wall time is measured directly from flushed redirected stderr [ PENDING ] -> [ OK ] timestamps; scan (timings.disk_scan) and phase totals are flare run's printed {:.1}s values; values are medians with min–max ranges.
flare run Startup Metric (10,000 .ckpt + 1,000 .input, n=5/arm) Cache Control (be4092d7) Candidate (b7bd3fa9) Speedup / Delta
Prepare host prefix cache wall time (stderr pipe) Cold (drop_caches) 2,542.00 (2,373.92–3,630.11) ms 295.44 (283.98–346.06) ms 8.60x (-2.25 s)
timings.disk_scan (scan, printed 0.1s res) Cold (drop_caches) 2.2 (2.1–3.4) s 0.2 (0.2–0.3) s -2.0 s
Prepare host prefix cache printed total (0.1s res) Cold (drop_caches) 2.5 (2.4–3.6) s 0.3 (0.3–0.3) s -2.2 s
Process spawn -> HTTP /health ready Cold (drop_caches) 17.57 (17.08–18.94) s 15.36 (14.96–15.74) s -2.21 s (-12.6%)
Prepare host prefix cache wall time (stderr pipe) Warm 95.58 (90.82–97.36) ms 53.20 (52.30–54.06) ms 1.80x (-42.38 ms)
timings.disk_scan (scan, printed 0.1s res) Warm 0.1 (0.1–0.1) s 0.0 (0.0–0.0) s -0.1 s
Process spawn -> HTTP /health ready Warm 14.71 (14.53–14.75) s 14.64 (14.29–15.10) s -0.06 s (within boot noise)

2. Component scan benchmarks & .input sort ablation

Interleaved mirrored rounds on plain local NVMe ext4 using an uncommitted flare-selene public-API harness (scan_bench.rs), reporting medians (p10–p90 in parentheses; 10 Cold rounds n=20/arm with drop_caches before every invocation, 20 Warm rounds n=40/arm after 1 warm-up pass per arm). .ckpt datasets hold 50% v3 ∥ 50% v4 10-step chains (1 rank, 4 KiB plane/row, TAIL_PAGES = 4, PAGE_TOKENS = 64); .input datasets hold 1,000 4,440-byte files.

Bare-metal aarch64 GB10 NVMe (record::scan, n=20 Cold ∥ n=40 Warm):

Workload Cache Control (be4092d7) Candidate (b7bd3fa9) Speedup
record::scan 500 .ckpt Cold 119.44 (103.62–153.22) ms 11.19 (10.08–11.97) ms 10.68x
record::scan 500 .ckpt Warm 3.31 (2.28–4.13) ms 1.70 (1.34–1.88) ms 1.94x
record::scan 2,000 .ckpt Cold 466.08 (422.01–636.24) ms 43.80 (41.94–45.61) ms 10.64x
record::scan 2,000 .ckpt Warm 15.53 (9.86–16.44) ms 4.81 (3.80–5.04) ms 3.23x
record::scan 10,000 .ckpt Cold 2,122.11 (2,083.26–3,033.40) ms 211.29 (199.84–267.23) ms 10.04x
record::scan 10,000 .ckpt Warm 61.43 (51.77–64.07) ms 16.54 (16.08–20.98) ms 3.71x

InputStore::start_bounded (1,000 .input files) sort and concurrency ablation:

Platform & Cache Control (be4092d7, unsorted seq) OsStr::cmp seq (no par_map) Path::cmp + par_map (ablation) Candidate (b7bd3fa9, OsStr::cmp + par_map) Candidate Speedup
aarch64 GB10 NVMe, Cold (n=20) 214.43 (209.18–304.87) ms 218.11 (209.74–323.54, 0.98x) ms 23.96 (22.10–27.13, 8.95x) ms 23.16 (21.25–24.32) ms 9.26x
aarch64 GB10 NVMe, Warm (n=40) 4.73 (3.24–5.24) ms 5.28 (3.32–5.51, 0.90x) ms 3.55 (2.57–3.68, 1.33x) ms 2.50 (1.94–2.62) ms 1.89x
x86_64 Linux NVMe, Warm (n=40, WSL2 ext4) 4.40 (4.29–4.66) ms 4.55 (4.38–6.74, 0.97x) ms 3.05 (2.78–3.34, 1.44x) ms 2.60 (2.28–2.86) ms 1.69x

Sorting .input paths by raw OsStr (sort_unstable_by(|a, b| a.as_os_str().cmp(b.as_os_str()))) avoids Path::cmp component parsing on 1,000 warm files (3.05 -> 2.60 ms on x86_64, raising warm speedup from 1.44x to 1.69x; 3.55 -> 2.50 ms on aarch64 GB10, raising warm speedup from 1.33x to 1.89x) while keeping recovery order deterministic.

Evidence & Limitations

Verified on clean git archive b7bd3fa9032f4ee306f0995495ed6dd463818ada atop NVIDIA/hyperflare-inference:main be4092d7e1f0efe8a16049568c12ec7b841a2e8e (git merge-tree --write-tree clean: bf2ee0ef12c283b709a409486d77751b92e6e66e):

  • Bare-metal aarch64 GB10 non-root NVMe --release tests (uid=1000, rustc 1.99.1, 1,945 passed, 0 failed, 8 ignored):
    • cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support: 645 passed (644 lib + 1 integration), 0 failed, 0 ignored (Unix 0o000 unreadable-entry tests and live-target symlink checks ran without skipping).
    • cargo test --locked --release --manifest-path selene/Cargo.toml --no-default-features --lib: 620 passed, 0 failed, 0 ignored.
    • cargo test --locked --release --manifest-path selene-manager/Cargo.toml --lib: 205 passed, 0 failed, 1 ignored.
    • cargo test --locked --release --manifest-path flare/Cargo.toml --lib: 247 passed, 0 failed, 4 ignored.
    • cargo test --locked --release --manifest-path flare-cli/Cargo.toml --bins: 228 passed, 0 failed, 3 ignored.
  • x86_64 Linux non-root --release tests (uid=1000, rustc 1.100.0, 3,287 Rust + 4 Python passed, 0 failed, 86 ignored):
    • cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support: 645 passed (644 lib + 1 integration), 0 failed, 0 ignored.
    • cargo test --locked --release --manifest-path selene/Cargo.toml --no-default-features --lib: 620 passed, 0 failed, 0 ignored.
    • FLARE_TEST_TEMPLATE_DIR=<dir> cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server (11 templates prepared via tests/frontend/prepare_templates.py): 2,022 passed (1,960 lib + 62 integration), 0 failed, 86 ignored (49 lib + 37 integration).
    • pytest tests/preparation/test_core_boundary.py: 4 passed, 0 failed.
  • Unit test coverage: parallel_scan_handles_large_mixed_v3_v4_directory_deterministically (preserving foreign files, subdirectories including .dir.tmp, dangling symlinks, and live Unix symlinks including .link.tmp), parallel_scan_preserves_directory_on_unreadable_entry (seeding valid, .tmp, and invalid .ckpt siblings both before and after the 0o000 entry so pre-PR inline deletion fails on both ext4 and LIFO tmpfs), parallel_scan_recovers_large_directory_deterministically_under_tight_budget (seeded in non-monotonic odd-then-even order (1..140).step_by(2).chain((0..140).step_by(2)) so removing entries.sort_unstable_by fails on FIFO, LIFO tmpfs, and hash-indexed ext4 filesystems), and parallel_scan_preserves_directory_and_budget_on_unreadable_entry (seeding 80 valid/over-budget .input, 16 corrupt .input, and 16 .input.pending files split before and after the 0o000 entry under tight DiskBudget).
Reproduction harness (`scan_bench.rs`) and `flare run` startup A/B commands
  1. Component & .input sort ablation harness (scan_bench.rs): Place the source below into selene/examples/scan_bench.rs inside clean git archive checkouts of be4092d7 and b7bd3fa9 (and, for the two intermediate .input ablation columns, patch selene/src/input.rs Worker::scan with entries.iter().map(...) for OsStr::cmp sequential or entries.sort_unstable() for Path::cmp + par_map), build with cargo build --locked --release --manifest-path selene/Cargo.toml --example scan_bench, remove the example file, prepare datasets with <bin> prep-ckpt <dir> <500|2000|10000> and <bin> prep-input <dir> 1000, and run interleaved mirrored rounds of <bin> scan-ckpt <dir> <N> and <bin> scan-input <dir> 1000 (with sync && echo 3 > /proc/sys/vm/drop_caches before each cold run).
use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};

use flare_selene::input::{DiskBudget, InputStore, PreparedInputRecord};
use flare_selene::record::{self, DirectoryLock, Header, RankSizes, file_name};
use flare_selene::shared::wire::{
    PackedOffer, PackedUnit,
    packed_unit::{Kind, Representation},
};
use flare_selene::PrefixKey;

const IDENTITY: [u8; 32] = [0x11; 32];
const FINGERPRINT: [u8; 16] = [0x22; 16];
const BUCKET: [u8; 16] = [0x33; 16];
const PAGE_TOKENS: u64 = 64;
const TAIL_PAGES: u32 = 4;

fn default_ranks() -> Vec<RankSizes> {
    vec![RankSizes {
        planes: vec![4096],
        row_bytes: 4096,
    }]
}

fn make_key(chain: u64, step: u64) -> PrefixKey {
    let consumed_tokens = (step + 1) * (TAIL_PAGES as u64) * PAGE_TOKENS;
    let mut digest = [0u8; 16];
    digest[..8].copy_from_slice(&chain.to_be_bytes());
    digest[8..16].copy_from_slice(&step.to_be_bytes());
    PrefixKey {
        consumed_tokens,
        digest,
    }
}

fn make_header(ranks: &[RankSizes], chain: u64, step: u64, packed: bool) -> Header {
    let key = make_key(chain, step);
    let parent = if step == 0 {
        None
    } else {
        Some(make_key(chain, step - 1))
    };
    let base = Header::from_sizes(
        PAGE_TOKENS,
        ranks.to_vec(),
        IDENTITY,
        FINGERPRINT,
        key,
        parent,
        BUCKET,
        TAIL_PAGES,
        1_700_000_000 + chain * 10 + step,
    )
    .expect("from_sizes");
    if !packed {
        return base;
    }
    let first_page = parent.map_or(0, |p| p.consumed_tokens / PAGE_TOKENS);
    let mut units = Vec::new();
    for offset in 0..u64::from(TAIL_PAGES) {
        for (rank_idx, rank_sizes) in ranks.iter().enumerate() {
            units.push(PackedUnit {
                kind: Kind::Page as i32,
                logical_index: first_page + offset,
                stored_rank: rank_idx as u32,
                representation: Representation::Packet as i32,
                profile: vec![0x42; 32],
                original_length: rank_sizes.page_record_bytes(),
                stored_length: 256,
                replicas: Vec::new(),
                stored_crc: 11,
                original_crc: 22,
                raw_xxh3: 0,
            });
        }
    }
    for (rank_idx, rank_sizes) in ranks.iter().enumerate() {
        units.push(PackedUnit {
            kind: Kind::Row as i32,
            logical_index: 0,
            stored_rank: rank_idx as u32,
            representation: Representation::Packet as i32,
            profile: vec![0x42; 32],
            original_length: rank_sizes.row_record_bytes(),
            stored_length: 256,
            replicas: Vec::new(),
            stored_crc: 33,
            original_crc: 44,
            raw_xxh3: 0,
        });
    }
    base.with_packed(PackedOffer { first_page, units })
        .expect("with_packed")
}

fn prep_ckpt(dir: &Path, count: usize) {
    assert_eq!(count % 10, 0, "count must be a multiple of 10");
    let _ = fs::remove_dir_all(dir);
    fs::create_dir_all(dir).expect("create_dir_all");
    let ranks = default_ranks();
    let chains = (count / 10) as u64;
    for chain in 0..chains {
        let is_v4 = chain % 2 == 1;
        for step in 0..10u64 {
            let h = make_header(&ranks, chain, step, is_v4);
            let path = dir.join(file_name(&h.key));
            let mut file = File::create(&path).expect("create ckpt");
            if is_v4 {
                file.write_all(&h.packed_metadata().expect("packed_metadata")).expect("write v4");
            } else {
                file.write_all(&h.encode().expect("encode v3")).expect("write v3");
            }
            file.set_len(h.length_with_row()).expect("set_len");
        }
    }
    let lock = DirectoryLock::acquire(dir).expect("lock");
    let scanned = record::scan(&lock, &IDENTITY, &FINGERPRINT, PAGE_TOKENS, &ranks).expect("scan");
    assert_eq!(scanned.len(), count);
}

fn scan_ckpt(dir: &Path, expected: usize) {
    let ranks = default_ranks();
    let lock = DirectoryLock::acquire(dir).expect("lock");
    let t0 = Instant::now();
    let scanned = record::scan(&lock, &IDENTITY, &FINGERPRINT, PAGE_TOKENS, &ranks).expect("scan");
    let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0;
    assert_eq!(scanned.len(), expected);
    println!("{elapsed_ms:.4}");
}

fn prep_input(dir: &Path, count: usize) {
    let _ = fs::remove_dir_all(dir);
    fs::create_dir_all(dir).expect("create_dir_all");
    let budget = DiskBudget::new(1 << 30, 0);
    let store = InputStore::start_bounded(0, Some(dir.to_path_buf()), budget, 64 << 20).expect("start");
    let sample = Arc::new(PreparedInputRecord {
        metadata: Arc::from(vec![0x5a_u8; 256]),
        payload: Some(Arc::new(vec![0xa5_u8; 4096])),
    });
    for i in 0..count {
        let mut key = [0u8; 32];
        key[..8].copy_from_slice(&(i as u64).to_be_bytes());
        store.insert(key, sample.clone());
        if (i + 1) % 4 == 0 || i + 1 == count {
            let target = (i + 1) as u64;
            let deadline = Instant::now() + Duration::from_secs(60);
            while store.stats().stored < target {
                assert!(Instant::now() < deadline);
                std::thread::sleep(Duration::from_millis(1));
            }
        }
    }
    assert_eq!(store.stats().disk_records, count);
}

fn scan_input(dir: &Path, expected: usize) {
    let budget = DiskBudget::new(1 << 30, 0);
    let t0 = Instant::now();
    let store = InputStore::start_bounded(0, Some(dir.to_path_buf()), budget, 64 << 20).expect("start");
    let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0;
    assert_eq!(store.stats().disk_records, expected);
    drop(store);
    println!("{elapsed_ms:.4}");
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    let dir = PathBuf::from(&args[2]);
    let count: usize = args[3].parse().expect("count");
    match args[1].as_str() {
        "prep-ckpt" => prep_ckpt(&dir, count),
        "scan-ckpt" => scan_ckpt(&dir, count),
        "prep-input" => prep_input(&dir, count),
        "scan-input" => scan_input(&dir, count),
        other => panic!("unknown subcommand: {other}"),
    }
}
  1. End-to-end flare run startup A/B: Build --release flare from clean git archive be4092d7 and git archive b7bd3fa9 (cargo build --locked --release --manifest-path flare-cli/Cargo.toml --bin flare), boot once with --prefix-cache-disk <disk_cache> --prefix-cache-memory 1G --prefix-cache-drain-on-shutdown=30s and one 443-token chat request to drain a template .ckpt for the target core's namespace, then seed that namespace directory with 10,000 sparse .ckpt files (1,000 10-step chains, tail_pages = 1, file.set_len(h.length_with_row()): 5,000 v3 files of 69,779,456 bytes each and 5,000 v4 Representation::Literal files — 500 step-0 files of 69,775,483 bytes and 4,500 step 1–9 files of 69,775,487 bytes — totaling 697,774,713,000 logical bytes / 649.85 GiB) plus 1,000 .input files (256-byte metadata + 4,096-byte payload = 4,440 bytes each). Alternate boots (n=5 Cold with sync && echo 3 > /proc/sys/vm/drop_caches before every boot, then 1 warm-up per arm + n=5 Warm) with:
flare run <core>/model.safetensors \
  --host 127.0.0.1 --port 8096 --no-advertise --gpus 0 \
  --max-concurrency 8 --kv-cache-limit memory --memory-limit=-12G \
  --embedding-table-storage ram \
  --publisher-keys <keys>/development-publisher.json \
  --trust-store <keys>/trust.toml \
  --dangerously-approve-key <pub-key-sha256> \
  --dangerously-accept-publisher local-development \
  --core-cache <serve_cache> \
  --prefix-cache-disk <disk_cache> \
  --prefix-cache-disk-limit 2000G \
  --lossless-kv-compression cpu

Timestamp redirected stderr [ PENDING ] -> [ OK ] Prepare host prefix cache. on every boot, verify HTTP /health (200), scrape /metrics asserting flare_host_cache_disk_records == 10000 and flare_input_cache_disk_records == 1000, send SIGTERM, and verify all 10,000 .ckpt and 1,000 .input files remain on disk.

  • Limitations: Native Windows execution (including handle-close-before-unlink under concurrency) was audited statically and remains unexecuted on a Windows host. The flare run startup A/B exercised a single-GPU TP1 GB10 core (Qwen4-35B-A3B-NVFP4) with sparse seeded .ckpt payload bodies; multi-host TP startup scans and bare-metal x86_64 flare run startup timings were not run on this revision (warm .input isolation on x86_64 ran on local NVMe ext4 inside WSL2).

Discord: Dooner

@flare-autobot flare-autobot added area:selene Selene shared prefix-cache pool, protocol, manager, and transfers. performance Performance, latency, throughput, or memory-efficiency investigation or improvement. labels Dec 4, 2026
@FujitsuPolycom
FujitsuPolycom marked this pull request as ready for review December 4, 2026 21:39
@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 734.
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 triage:review Proposed change needs code review; this does not imply merge readiness. triage:validation Proposed implementation needs acceptance evidence; no claim that a reported defect is fixed. and removed triage:review Proposed change needs code review; this does not imply merge readiness. labels Dec 4, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The implementation is clean, well-scoped, and passes an independent correctness, boundary, and cursor-safety audit with zero code defects — but as a pure performance PR it lacks the Charter-required served-workload (flare run) evidence and a coalescing-vs-par_map ablation that also explains the disclosed warm .input regression.

  • Blockers: 0 · Should fix: 1 · Subtract/Simplify: 3 · Nits: 3
Walkthrough
  • selene/src/shared/record.rs:357-397 (Header::read_metadata): Replaces two read_exact calls with a single [0u8; HEADER_BYTES + 4096] stack buffer read loop (handling short reads and EINTR), returning immediately for v3 headers and v4 directories <= 4096 bytes and falling back to one read_exact tail read for larger v4 directories (bounded by packed::MAX_DIRECTORY = 2 MiB). Documents non-guaranteed reader cursor position.
  • selene/src/shared/record.rs:1142-1192 (par_map): Adds a pub(crate) bounded parallel mapper (threshold = 64, chunk = 8, workers = available_parallelism().clamp(1, 16)) using std::thread::scope, dynamic AtomicUsize chunking, fallible thread spawning (spawn_scoped(...).ok() with calling-thread participation), and index-order restoration.
  • selene/src/shared/record.rs:1209-1278 (record::scan): Pre-filters .*.tmp / *.ckpt candidates during fs::read_dir, runs fs::symlink_metadata (never following symlinks) and inspect via par_map, and reduces sequentially fail-closed (returning the first Inspection::Unreadable before deleting .tmp/invalid entries) before unchanged remove_orphans.
  • selene/src/input.rs:514-587 (Worker::scan): Defers .input.pending removal out of fs::read_dir, sorts .input paths lexicographically for deterministic admission under MAX_DISK_RECORDS (4,096) and DiskBudget, inspects headers via record::par_map, and aborts on the first non-InvalidData error before unlinking temporaries or mutating self.disk/self.budget.
  • Unit tests (selene/src/shared/record.rs:2430-2741, selene/src/input.rs:1644-1750): Adds single-read/large-v4/short-read/EINTR/truncation/invalid-length tests for read_metadata, mixed v3/v4 parallel scan determinism and symlink/foreign-file preservation tests, tight-budget deterministic .input recovery, and Unix 0o000 unreadable-entry fail-closed tests.
Merge Risk: Low · up to 015076e
  • Implementation safety: Header::read_metadata read-ahead (HEADER_BYTES + 4096) is verified cursor-safe across all five production callers (selene/src/shared/record.rs:1334, selene/src/disk.rs:1478, selene/src/shard.rs:1202,1251, selene-manager/src/disk.rs:77), none of which uses O_DIRECT or relies on post-call file cursor position; par_map drops all file handles inside inspect before std::thread::scope exits (keeping concurrent FDs <= 16 and preserving Windows close-before-unlink safety) and preserves symlink/directory safety.
  • Compatibility & blast radius: Strictly confined to pre-serving startup directory scans (record::scan and Worker::scan). On-disk v3/v4 .ckpt and .input layouts, protobuf schemas, remove_orphans ordering, and --no-default-features builds (rayon-free) are preserved.
  • Remaining risk: Minor warm-path latency regression (2.09 → 2.53 ms, 0.83x on x86_64 1,000 warm .input files) and unverified end-to-end flare run startup impact; native Windows execution was audited statically only.
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings
  • ✅ Security / malicious screen: Zero production unsafe (only libc::geteuid() in a #[cfg(unix)] test with // SAFETY:), zero new dependencies, symlinks never followed or unlinked, packed::MAX_DIRECTORY validated before allocation, no prompt-injection or suspicious code.
  • ⚠️ Charter & value fit: Squarely within Selene's disk prefix-cache charter goal with no model branches, flags, or format changes, but lacks the served-workload (flare run) benchmark and regression ablation required for performance PRs (#210, docs/design-review.md:106-115, docs/core-design.md:1834-1836).
  • ✅ Related / duplicate / conflict check: Cleanly extends #496/#497 (same author, fetch/restore paths) to startup scan with zero overlapping hunks and zero conflicts against main (22d2ac9).
  • ⚠️ Tests & verification evidence: Thorough unit-test coverage added and dual-architecture A-B-B-A component microbenchmarks reported (7.5x–10.8x cold NVMe .ckpt, 8.4x–9.0x cold .input), but no end-to-end flare run measurement, no coalescing-vs-par_map ablation, and native Windows remains statically audited only (disclosed).

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.

Startup recovery in Selene (`selene/src/shared/record.rs::scan` and
`selene/src/input.rs` `Worker::scan`) inspects every cached `.ckpt` and
`.input` file sequentially (`QD=1`). On local NVMe caches holding
hundreds to tens of thousands of records, serial metadata inspection
leaves storage queue depth unused and stalls `Prepare host prefix cache`
during server startup.

Changes:
- `selene/src/shared/record.rs` (`par_map`, `record::scan`):
  - Before: inspected `.ckpt` and `.tmp` entries sequentially in
    `fs::read_dir` order and unlinked invalid entries inline.
  - After: pre-filters candidate `.ckpt` and `.*.tmp` paths
    (`Vec<PathBuf>`) and, at 64 or more items, runs `fs::symlink_metadata`
    (never following symlinks) and `inspect` across bounded threads
    (`available_parallelism().min(16)` via `std::thread::scope` and
    chunk size 8). Workers use fallible `Builder::spawn_scoped` named
    `flare-scan` with calling-thread participation, return per-chunk
    `(start, Vec<R>)` blocks for order restoration, and close all file
    handles before scope exit for Windows handle-close-before-unlink
    safety. The sequential reduction pass fails closed, returning the
    first `Unreadable` error before deleting `.tmp` or invalid entries
    and preserving deterministic `remove_orphans` ordering
    (`(consumed_tokens, digest)`). `selene-manager/src/disk.rs::recover`
    delegates full directory scans to `record::scan`.
- `selene/src/input.rs` (`Worker::scan`):
  - Before: unlinked `.input.pending` files inline during `fs::read_dir`
    and inspected `.input` files sequentially.
  - After: defers `.input.pending` removal, sorts `.input` paths in
    lexicographic `OsStr` order
    (`sort_unstable_by(|a, b| a.as_os_str().cmp(b.as_os_str()))`, avoiding
    `Path::cmp` component parsing), inspects headers in parallel via
    `record::par_map`, rejects non-`InvalidData` I/O errors before
    unlinking `.input.pending` or mutating `self.disk`/`self.budget`,
    and admits records deterministically under `MAX_DISK_RECORDS` and
    `DiskBudget`.
- `docs/prefix-cache-offload.md`: documents that unreadable `.ckpt` and
  `.input` entries fail startup scans before deleting temporary, invalid,
  or over-budget files, that `.input` startup also fails if removing
  those files fails, and that `.input` recovery admits files in
  lexicographic path order.
- Compatibility: on-disk v3/v4 `.ckpt` and `.input` record formats,
  Protobuf wire schemas, and model core loading are unchanged. Zero
  production `unsafe` and zero new dependencies.

Expected and measured scope:
- Parallelizing metadata inspection up to 16 workers reduces cold and warm
  local NVMe scan time on directories at or above the 64-entry threshold
  while preserving deterministic order and fail-closed cleanup. Sorting
  `.input` paths by raw `OsStr` keeps recovery deterministic without
  `Path::cmp` component-parsing overhead on warm scans.
- End-to-end `flare run` `Prepare host prefix cache` startup A/B and
  local NVMe component measurements comparing this commit against its
  `main` base are recorded in the pull request description.

Evidence and limitations:
- Unit tests in `selene/src/shared/record.rs` and `selene/src/input.rs`
  cover single-field `Header.packed` equality/hash isolation, large
  mixed v3/v4 deterministic parallel `.ckpt` scans (preserving foreign
  files, subdirectories including `.dir.tmp`, and dangling and
  live-target Unix symlinks including `.link.tmp`), deterministic
  parallel `.input` recovery under tight `DiskBudget` (seeded in
  non-monotonic odd-then-even order so admission fails without sorting
  on FIFO, LIFO `tmpfs`, and hash-indexed `ext4` filesystems), and
  fail-closed preservation on unreadable `.ckpt` and `.input` entries
  (seeding temporary, invalid/corrupt, and valid/over-budget siblings
  both before and after the `0o000` entry).
- Release crate suites (`selene` with `--features test-support` and
  `--no-default-features --lib`, `helios --features runtime-core,server`,
  `flare --lib`, `flare-cli --bins`, `selene-manager --lib`, and
  `pytest tests/preparation/test_core_boundary.py`) execute on clean
  non-root archives of this commit on Linux (`x86_64` and `aarch64`).
- Limitation: native Windows execution (including handle-close-before-
  unlink under concurrency) is audited statically and not executed on a
  Windows host.

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b
Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com>
@FujitsuPolycom
FujitsuPolycom force-pushed the perf/selene-parallel-startup-scan branch from 015076e to b7bd3fa Compare December 5, 2026 01:10
@FujitsuPolycom FujitsuPolycom changed the title selene: parallelize startup disk scan and coalesce small header reads selene: parallelize startup disk scan Dec 5, 2026
@FujitsuPolycom

Copy link
Copy Markdown
Contributor Author

@flare-autobot Addressed at b7bd3fa9032f4ee306f0995495ed6dd463818ada atop NVIDIA/hyperflare-inference:main (be4092d7e1f0efe8a16049568c12ec7b841a2e8e, incremental diff 015076ec..b7bd3fa9). The PR title (selene: parallelize startup disk scan) and description have also been updated so the rationale, ablations, end-to-end flare run startup A/B, and limits stand on their own.

Should Fix

  1. End-to-end flare run startup A/B, mechanism simplification, and .input sort ablation (selene/src/offload.rs, selene/src/shared/record.rs, selene/src/input.rs):
    • Dropped Header::read_metadata 4 KiB read-ahead coalescing (-26 net prod / -94 test LOC): Component ablation showed sequential read-ahead slowed warm scans (4.7%–9.2%) without improving parallel cold scans (Linux page-cache readahead already prefetches the adjacent 4 KiB page) and weakened pub fn Header::read_metadata's io::Read cursor contract. Restored exact main read_exact semantics; par_map alone delivers the full 10.04x–10.68x cold and 1.94x–3.71x warm .ckpt speedup.
    • End-to-end flare run startup A/B (b7bd3fa9 vs be4092d7): Built --release flare binaries from clean git archive checkouts on bare-metal aarch64 GB10 local NVMe ext4 and booted a signed TP1 Qwen4-35B-A3B-NVFP4 core against a populated --prefix-cache-disk namespace (10,000 .ckpt [5,000 v3 of 69,779,456 B ∥ 5,000 v4 Representation::Literal of 69,775,483/69,775,487 B, tail_pages = 1, 697,774,713,000 logical B / 649.85 GiB] + 1,000 .input [4,440 B each], --prefix-cache-disk-limit 2000G --lossless-kv-compression cpu; every single boot across all 22 boots verified 10000 records in Prepare host prefix cache, flare_host_cache_disk_records == 10000 and flare_input_cache_disk_records == 1000 on /metrics, HTTP /health ready, and 0 deletions / 0 rejections after SIGTERM):
      • Cold (n=5/arm, drop_caches before every boot): Prepare host prefix cache stderr-pipe wall time dropped 2,542.00 -> 295.44 ms (8.60x, -2.25 s); printed scan (timings.disk_scan) 2.2 -> 0.2 s; printed phase total 2.5 -> 0.3 s; process spawn -> /health ready 17.57 -> 15.36 s (-2.21 s, -12.6%).
      • Warm (n=5/arm after 1 warm-up per arm): Prepare host prefix cache wall time dropped 95.58 -> 53.20 ms (1.80x, -42.38 ms); printed scan 0.1 -> 0.0 s (ready: 14.71 -> 14.64 s, within normal warm boot noise).
    • .ckpt component scan (aarch64 GB10 NVMe, n=20 Cold ∥ n=40 Warm): 500 .ckpt 119.44 -> 11.19 ms (10.68x) cold / 3.31 -> 1.70 ms (1.94x) warm; 2,000 .ckpt 466.08 -> 43.80 ms (10.64x) cold / 15.53 -> 4.81 ms (3.23x) warm; 10,000 .ckpt 2,122.11 -> 211.29 ms (10.04x) cold / 61.43 -> 16.54 ms (3.71x) warm.
    • .input sort ablation (selene/src/input.rs): Sorting .input paths by raw OsStr (entries.sort_unstable_by(|a, b| a.as_os_str().cmp(b.as_os_str()))) avoids Path::cmp component parsing while preserving identical lexicographic recovery order:
      • x86_64 Linux NVMe Warm (1,000 files, n=40/arm, WSL2 ext4): main 4.40 ms (1.00x) -> OsStr::cmp seq 4.55 ms (0.97x) -> Path::cmp + par_map 3.05 ms (1.44x) -> b7bd3fa9 2.60 ms (1.69x).
      • aarch64 GB10 NVMe (1,000 files, n=20 Cold ∥ n=40 Warm): Warm main 4.73 ms -> OsStr::cmp seq 5.28 ms (0.90x) -> Path::cmp + par_map 3.55 ms (1.33x) -> b7bd3fa9 2.50 ms (1.89x); Cold main 214.43 ms -> OsStr::cmp seq 218.11 ms (0.98x) -> Path::cmp + par_map 23.96 ms (8.95x) -> b7bd3fa9 23.16 ms (9.26x).
    • Test fault sensitivity (selene/src/shared/record.rs, selene/src/input.rs): header_eq_implies_same_hash isolates Header.packed without mutating page_segment/row_segment; parallel_scan_recovers_large_directory_deterministically_under_tight_budget seeds in non-monotonic odd-then-even order (1u64..140).step_by(2).chain((0u64..140).step_by(2)); and both parallel_scan_preserves_directory_on_unreadable_entry and parallel_scan_preserves_directory_and_budget_on_unreadable_entry seed temporary, invalid/corrupt, and valid/over-budget siblings both before and after the 0o000 entry. Verified locally that omitting Header.packed or restoring inline deletion fails each corresponding test on both ext4 and LIFO tmpfs.
    • Remaining limit: Native Windows execution remains statically audited only; flare run A/B covered TP1 GB10 with sparse seeded .ckpt bodies (warm .input x86_64 isolation ran on local NVMe ext4 inside WSL2).

Subtract / Simplify

  1. Deduplicated PackedUnit fixture & test helpers (selene/src/shared/record.rs, selene/src/input.rs): Reused packed_header(...).packed in header_eq_implies_same_hash while isolating Header.packed, used a local unit closure with ..Default::default(), added file-local scan_default in record.rs tests and indexed_key/seed_valid_inputs in input.rs tests, and unified existence/deletion loops.
  2. Per-chunk tagging & simplified arithmetic in par_map (selene/src/shared/record.rs): Workers return Vec<(usize, Vec<R>)> sorted by chunk start and flattened into Vec::with_capacity(items.len()) (8x lower sort cardinality); hoisted chunk_count and simplified .clamp(1, MAX_SCAN_WORKERS) to .min(MAX_SCAN_WORKERS).
  3. Zero per-entry String allocations in record::scan (selene/src/shared/record.rs): candidates stores Vec<PathBuf>, checks !name.ends_with(SUFFIX) before .*.tmp, and borrows path.file_name().and_then(|n| n.to_str()) directly inside par_map (with .dir.tmp and .link.tmp non-regular survival tests).
  4. File-local RAII Directory fixture (selene/src/shared/record.rs): Added a Drop-based Directory helper across all six record::scan tests (declaring directory before lock so lock drops first before remove_dir_all).

Nits

  1. Present-state docs (docs/prefix-cache-offload.md, selene/src/shared/record.rs): Documented fail-closed preservation before deleting .tmp/invalid/over-budget files on unreadable entries, failure if removing those .input files fails, lexicographic path order during .input recovery, and updated enum Inspection doc comments.

Exact-SHA Verification (b7bd3fa9032f4ee306f0995495ed6dd463818ada)

  • aarch64 GB10 non-root --release (1,945 passed, 0 failed, 8 ignored): selene --features test-support (645), selene --no-default-features --lib (620), selene-manager --lib (205, 1 ignored), flare --lib (247, 4 ignored), flare-cli --bins (228, 3 ignored).
  • x86_64 Linux non-root --release (3,287 Rust + 4 Python passed, 0 failed, 86 ignored): selene --features test-support (645), selene --no-default-features --lib (620), helios --features runtime-core,server (2,022, 86 ignored, 11 templates prepared), pytest tests/preparation/test_core_boundary.py (4).

Could you take another look at b7bd3fa9?

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Ready To Merge

All Round 1 requirements and simplification items are resolved cleanly at b7bd3fa: the Header::read_metadata read-ahead was reverted, an attributable end-to-end flare run startup A/B was supplied on GB10 NVMe, and the sorting, par_map, fixture, and documentation items were all addressed. Direct verification of the changed code, callees, state transitions, and boundary cases confirms zero correctness defects and zero hot-path regressions.

  • Blockers: 0 · Should fix: 0 · Subtract/Simplify: 0 · Nits: 2
Walkthrough
  • selene/src/shared/record.rs:358-373 (Header::read_metadata): Reverted to main's exact two-read_exact implementation, removing the Round 1 read-ahead and restoring the original io::Read cursor contract.
  • selene/src/shared/record.rs:1118-1171 (par_map): pub(crate) bounded parallel mapper (threshold = 64, chunk = 8, workers = available_parallelism().map_or(4, ..).min(16).min(chunk_count)) using std::thread::scope, fallible spawn_scoped(...).ok() with calling-thread participation, panic propagation via resume_unwind, and per-chunk (start, Vec<R>) sorting for exact input-order restoration.
  • selene/src/shared/record.rs:1189-1260 (record::scan): Pre-filters *.ckpt and .*.tmp candidate paths (Vec<PathBuf>, zero per-entry String allocations), inspects fs::symlink_metadata (never following symlinks) and headers in parallel via par_map, and reduces sequentially fail-closed (returning the first Inspection::Unreadable before deleting .tmp/invalid entries) prior to unchanged remove_orphans.
  • selene/src/input.rs:514-587 (Worker::scan): Defers .input.pending removal out of fs::read_dir, sorts .input paths in lexicographic raw OsStr order (sort_unstable_by(|a, b| a.as_os_str().cmp(b.as_os_str()))), inspects headers via record::par_map, and aborts on the first non-InvalidData error before unlinking temporaries or mutating self.disk/self.budget.
  • docs/prefix-cache-offload.md:681,1199-1204: Documents fail-closed startup preservation on unreadable .ckpt/.input entries, failure on .input cleanup errors, and lexicographic path-order .input admission.
  • Unit tests (selene/src/shared/record.rs:1966-1989,2322-2588, selene/src/input.rs:1644-1759): Extracts RAII Directory (declared before lock across all six record::scan tests) and deduplicated packed_header/scan_default helpers; adds large mixed v3/v4 parallel scan determinism (including .dir.tmp, .link.tmp, live/dangling symlink survival), non-monotonic odd-then-even tight-budget .input recovery, and Unix 0o000 fail-closed tests with siblings seeded on both sides of the unreadable entry.
Merge Risk: Low · up to b7bd3fa
  • Implementation safety: Strictly confined to pre-serving startup directory scans (selene/src/shared/record.rs::scan, selene/src/input.rs Worker::scan) with zero production unsafe, zero new dependencies, and bounded concurrency (<= 16 "flare-scan" scoped threads and <= 16 open FDs per scan). Every File handle opened inside inspect drops before std::thread::scope exits and before sequential remove/remove_file calls, preserving Windows close-before-unlink safety and symlink/subdirectory exclusion.
  • Compatibility & blast radius: Header::read_metadata, on-disk v3/v4 .ckpt and .input layouts, protobuf wire schemas, remove_orphans (consumed_tokens, digest) ordering, DiskBudget unwind invariants (selene/src/input.rs:506-510), and --no-default-features (rayon-free) builds are preserved. Both behavioral refinements (fail-closed error-before-deletion and lexicographic .input admission) are documented and pinned by fault-sensitive tests.
  • Disclosed residual limits: Native Windows execution was audited statically only, and the x86_64 warm .input ablation ran on WSL2 ext4 (control 4.40 ms vs Round 1's 2.09 ms host baseline) rather than rerunning on the original x86_64 host; the governing served-workload GB10 flare run Cold + Warm A/B and GB10 warm .input (1.89x) both improve cleanly.
Pre-merge checks: ✅ 4 passed
  • ✅ Security / malicious screen: Zero production unsafe (only test-only libc::geteuid() under #[cfg(unix)] with // SAFETY: at selene/src/shared/record.rs:2525), zero new dependencies, symlinks/subdirectories never followed or unlinked, no prompt-injection or suspicious code.
  • ✅ Charter & value fit: Squarely within Selene's disk prefix-cache goal with no model branches, flags, or format changes, and now backed by served-workload flare run A/B evidence (#210, docs/design-review.md:106-115).
  • ✅ Related / duplicate / conflict check: Cleanly extends #496/#497 to startup recovery atop main (be4092d7) with zero conflicts; selene-manager/src/disk.rs:101 delegates full scans to record::scan unchanged.
  • ✅ Tests & verification evidence: End-to-end flare run Cold/Warm A/B reconciles with component benchmarks and .input sort ablation; extensive non-root --release test runs reported passing on aarch64 GB10 and x86_64 Linux (native Windows static-audit limitation and WSL2 x86_64 warm ablation environment honestly disclosed).

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:selene Selene shared prefix-cache pool, protocol, manager, and transfers. performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:validation Proposed implementation needs acceptance evidence; no claim that a reported defect is fixed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants