Skip to content

selene: parallelize startup disk scan and coalesce small header reads - #69

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

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

Conversation

@FujitsuPolycom

@FujitsuPolycom FujitsuPolycom commented Dec 4, 2026 •

Copy link
Copy Markdown
Owner

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), issuing two blocking read() calls per v4 packed record header. On local NVMe caches with hundreds to tens of thousands of records, serial metadata inspection leaves storage queue depth unutilized and stalls startup.

What changed

Coalesced small header reads and parallelized startup file inspection across bounded threads (+105 net non-test production LOC [+135/-30], 0 production unsafe, 0 new dependencies; on-disk v3/v4 .ckpt and .input formats, Protobuf wire schemas, and model core loading are unchanged):

  • Header::read_metadata (selene/src/shared/record.rs): Coalesces reads into one stack buffer (HEADER_BYTES + 4096) in a single read() loop for v3 headers and v4 directories up to 4 KiB, falling back to one read_exact tail read for larger v4 directories (bounded by packed::MAX_DIRECTORY). Documents read-ahead cursor semantics; all five callers in selene and selene-manager either drop the file handle or use positional read_exact_at.
  • record::scan and par_map (selene/src/shared/record.rs): Collects candidate entries and, at 64 or more items, runs fs::symlink_metadata (never following symlinks) and inspect across bounded worker threads (available_parallelism().clamp(1, 16), std::thread::scope, chunk size 8, fallible std::thread::Builder::new().name("flare-scan").spawn_scoped(...) with calling-thread participation, all file handles dropped before scope exit for Windows handle-close-before-unlink safety), then runs the sequential reduction and cleanup pass fail-closed: returns any 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): Collects .input.pending files without deleting them inside fs::read_dir, sorts .input paths lexicographically, inspects headers in parallel via record::par_map, rejects non-InvalidData I/O errors before unlinking .input.pending files or mutating self.disk/self.budget, and admits records deterministically under MAX_DISK_RECORDS and DiskBudget.

Result

Interleaved A-B-B-A bare-metal local NVMe ext4 microbenchmarks comparing exact git archive 22d2ac97dd46e6eee5a45bb479d370a9278469f8 (control) vs git archive 015076ec4aa746deaa7ddcefc4d015416c4b82c8 (candidate) using an uncommitted Rust example binary (selene/examples/scan_bench.rs) built --locked --release against flare-selene's public APIs (asserting exact recovered counts on every invocation):

  • Timing boundaries: Times record::scan in-process after DirectoryLock::acquire, and times InputStore::start_bounded including worker-thread startup. These are isolated component microbenchmarks, not end-to-end flare run startup timings.
  • Methodology & geometries: 10 Cold rounds (n=20/arm with sync && echo 3 > /proc/sys/vm/drop_caches before every invocation) and 20 Warm rounds (n=40/arm) after 1 warm-up pass per arm. .ckpt directories hold 50% v3 ∥ 50% v4 10-step chains (1 rank, 4 KiB plane and 4 KiB row, TAIL_PAGES = 4, PAGE_TOKENS = 64), where each v4 header carries 5 PackedUnit entries (4 pages + 1 row) with a <= 4 KiB protobuf directory; .input directories hold 4,440-byte files (88-byte header + 256-byte metadata + 4 KiB payload).

Values below are medians with p10–p90 spreads in parentheses (x86_64: 48-core, WD_BLACK SN850X 2 TB NVMe ext4; aarch64 GB10: 20-core Grace, Samsung MZALC4T0HBL1 3.7 TB NVMe ext4):

Workload (16-worker cap) Cache (n=20 Cold ∥ n=40 Warm) x86_64 NVMe Ctrl → Cand (Med, p10–p90) x86_64 Speedup aarch64 GB10 NVMe Ctrl → Cand (Med, p10–p90) aarch64 Speedup
record::scan 500 .ckpt (50% v3 ∥ 50% v4) Cold (drop_caches) 27.56 (27.44–27.87) → 3.68 (3.58–3.80) ms 7.49x 111.50 (105.44–156.97) → 12.36 (11.61–13.18) ms 9.02x
record::scan 500 .ckpt (50% v3 ∥ 50% v4) Warm 1.61 (1.54–1.87) → 1.17 (1.10–1.24) ms 1.38x 3.89 (2.48–4.24) → 1.63 (1.40–1.93) ms 2.39x
record::scan 2,000 .ckpt (50% v3 ∥ 50% v4) Cold (drop_caches) 117.52 (117.15–118.93) → 12.88 (12.72–13.05) ms 9.12x 441.56 (418.44–605.27) → 43.68 (40.70–45.99) ms 10.11x
record::scan 2,000 .ckpt (50% v3 ∥ 50% v4) Warm 6.83 (6.50–7.15) → 3.69 (3.55–3.77) ms 1.85x 15.93 (10.09–16.98) → 5.07 (4.03–5.31) ms 3.14x
record::scan 10,000 .ckpt (50% v3 ∥ 50% v4) Cold (drop_caches) 604.56 (602.63–609.83) → 60.87 (60.20–64.13) ms 9.93x 2,276.23 (2,110.36–3,334.46) → 210.07 (200.29–234.72) ms 10.84x
record::scan 10,000 .ckpt (50% v3 ∥ 50% v4) Warm 36.81 (35.45–38.35) → 16.17 (15.83–16.64) ms 2.28x 62.72 (51.64–65.68) → 20.98 (18.43–23.11) ms 2.99x
InputStore::start_bounded (Worker::scan) 1,000 .input Cold (drop_caches) 76.42 (76.01–76.95) → 9.14 (8.96–9.29) ms 8.36x 235.69 (214.48–337.22) → 26.12 (23.53–29.33) ms 9.02x
InputStore::start_bounded (Worker::scan) 1,000 .input Warm 2.09 (1.94–2.22) → 2.53 (2.42–2.64) ms 0.83x 4.75 (3.09–5.36) → 3.75 (2.69–3.93) ms 1.27x
  • On x86_64, warm InputStore::start_bounded (1,000 RAM-cached 88-byte .input headers) is +0.44 ms slower (2.09 → 2.53 ms, 0.83x), expected from thread-scope setup and lexicographic path sorting (not separately isolated by ablation).
  • On aarch64 GB10, warm distributions are bimodal across both arms (notably InputStore::start_bounded warm p10–p90 3.09–5.36 ms control vs 2.69–3.93 ms candidate), while every cold cell on both architectures has non-overlapping control and candidate ranges (max(Cand) << min(Ctrl)).

Evidence & Limitations

Verified on clean git archive 015076ec4aa746deaa7ddcefc4d015416c4b82c8 atop NVIDIA/hyperflare-inference:main (22d2ac97dd46e6eee5a45bb479d370a9278469f8, git merge-tree --write-tree clean):

  • Bare-metal aarch64 GB10 non-root NVMe selene release tests (uid=1001, rustc 1.99.1):
    • cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support: 591 passed (590 lib + 1 integration), 0 failed, 0 ignored (both Unix 0o000 unreadable-entry tests and the live-target Unix symlink check executed without skipping).
    • cargo test --locked --release --manifest-path selene/Cargo.toml --no-default-features --lib: 566 passed, 0 failed, 0 ignored.
  • Containerized x86_64 non-root selene release tests on host NVMe (uid=1000, rustc 1.94.1):
    • cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support: 591 passed (590 lib + 1 integration), 0 failed, 0 ignored (both Unix 0o000 unreadable-entry tests and the live-target Unix symlink check executed without skipping).
    • cargo test --locked --release --manifest-path selene/Cargo.toml --no-default-features --lib: 566 passed, 0 failed, 0 ignored.
  • Full --release crate suites (x86_64 Linux non-root uid=1000, rustc 1.100.0, 3,907 Rust + 4 Python passed, 0 failed, 94 ignored):
    • cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support: 591 passed (590 lib + 1 integration), 0 failed, 0 ignored.
    • cargo test --locked --release --manifest-path selene/Cargo.toml --no-default-features --lib: 566 passed, 0 failed, 0 ignored.
    • FLARE_TEST_TEMPLATE_DIR=<dir> cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server (templates populated via tests/frontend/prepare_templates.py --output <dir>): 1,976 passed (1,914 lib + 62 integration), 0 failed, 86 ignored (49 lib + 37 integration).
    • 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: 224 passed, 0 failed, 3 ignored.
    • cargo test --locked --release --manifest-path selene-manager/Cargo.toml --lib: 205 passed, 0 failed, 1 ignored.
    • cargo test --locked --release --manifest-path selene-manager/Cargo.toml --test packed --test client: 98 passed (86 client + 12 packed), 0 failed, 0 ignored.
    • pytest tests/preparation/test_core_boundary.py: 4 passed, 0 failed.
  • Added unit tests (+419 test LOC): read_metadata_uses_single_read_for_v3_and_small_v4_and_handles_large_v4 (including 37-byte short-read coverage on both v3 and v4 plus one-shot EINTR retry), parallel_scan_handles_large_mixed_v3_v4_directory_deterministically (preserving foreign files, subdirectories, dangling symlinks, and live Unix symlinks pointing to existing regular files), parallel_scan_preserves_directory_on_unreadable_entry, parallel_scan_recovers_large_directory_deterministically_under_tight_budget, and parallel_scan_preserves_directory_and_budget_on_unreadable_entry (>= 64 valid files + corrupt .input + .input.pending + 0o000 unreadable .input under tight DiskBudget).
  • Microbenchmark reproduction: Place the Rust source below into selene/examples/scan_bench.rs inside clean archive checkouts of control (22d2ac97) and candidate (015076ec), build both 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 time interleaved A-B-B-A invocations of <bin> scan-ckpt <dir> <N> and <bin> scan-input <dir> 1000 (running sync && echo 3 > /proc/sys/vm/drop_caches before each cold run).
Microbenchmark reproduction harness (against public flare_selene APIs)
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;
    let mut v3_count = 0usize;
    let mut v4_count = 0usize;
    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 {
                let meta = h.packed_metadata().expect("packed_metadata");
                file.write_all(&meta).expect("write v4 meta");
                v4_count += 1;
            } else {
                let meta = h.encode().expect("encode v3");
                file.write_all(&meta).expect("write v3 meta");
                v3_count += 1;
            }
            file.set_len(h.length_with_row()).expect("set_len");
        }
    }
    assert_eq!(v3_count + v4_count, count);
    assert_eq!(v3_count, v4_count);
    // Sanity-verify once
    let lock = DirectoryLock::acquire(dir).expect("lock");
    let scanned = record::scan(&lock, &IDENTITY, &FINGERPRINT, PAGE_TOKENS, &ranks).expect("scan");
    assert_eq!(scanned.len(), count, "prep-ckpt scan mismatch");
    let packed_n = scanned.iter().filter(|r| r.header.packed.is_some()).count();
    assert_eq!(packed_n, v4_count, "packed count mismatch");
    println!("PREPPED_CKPT count={count} v3={v3_count} v4={v4_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,
        "scan_ckpt expected {expected}, got {}",
        scanned.len()
    );
    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 input store");
    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());
        // Keep queue below QUEUE=8 so no writes are skipped
        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,
                    "timed out waiting for stored={target}, got {}",
                    store.stats().stored
                );
                std::thread::sleep(Duration::from_millis(1));
            }
        }
    }
    let stats = store.stats();
    assert_eq!(stats.stored, count as u64, "stored mismatch");
    assert_eq!(stats.skipped, 0, "skipped writes");
    assert_eq!(stats.disk_records, count, "disk_records mismatch");
    drop(store);
    println!("PREPPED_INPUT count={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 input store");
    let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0;
    let recovered = store.stats().disk_records;
    assert_eq!(
        recovered, expected,
        "scan_input expected {expected}, got {recovered}"
    );
    drop(store);
    println!("{elapsed_ms:.4}");
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() != 4 {
        eprintln!(
            "usage: {} <prep-ckpt|scan-ckpt|prep-input|scan-input> <dir> <count>",
            args[0]
        );
        std::process::exit(2);
    }
    let cmd = args[1].as_str();
    let dir = PathBuf::from(&args[2]);
    let count: usize = args[3].parse().expect("count");
    match cmd {
        "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 => {
            eprintln!("unknown subcommand: {other}");
            std::process::exit(2);
        }
    }
}
  • Limitations: Native Windows execution (including handle-close-before-unlink under concurrency) was audited statically and remains unexecuted on a Windows host. Microbenchmark timings measure isolated record::scan and InputStore::start_bounded calls rather than end-to-end flare run startup.

Discord: Dooner

@FujitsuPolycom
FujitsuPolycom force-pushed the perf/selene-parallel-startup-scan branch 2 times, most recently from 5a3e9b1 to 015076e Compare December 4, 2026 20:08
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant