From b7bd3fa9032f4ee306f0995495ed6dd463818ada Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:09:16 -0600 Subject: [PATCH] selene: parallelize startup disk scan 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`) 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)` 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> --- docs/prefix-cache-offload.md | 8 +- selene/src/input.rs | 147 ++++++++++- selene/src/shared/record.rs | 455 +++++++++++++++++++++++++++-------- 3 files changed, 498 insertions(+), 112 deletions(-) diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index 68136f371..cd0272fac 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -678,6 +678,7 @@ directory. The disk store's startup scan reads each file's header, validates the version, identity, fingerprint, and name, derives row presence from the size, seeds the access order from the modification time, deletes temporary files, and deletes any node whose parent is missing together with its descendants. +An unreadable `.ckpt` entry fails the scan before deleting temporary or invalid files. Leaf-first eviction never unlinks a parent before its children, so orphans arise only from interrupted operations or external changes. @@ -1195,8 +1196,11 @@ the required input. Concurrent lookups share disk work, and bounded source locks prevent repeated decoding of a retained source during concurrent frontend preparation. -Startup fails if scanning or cleanup cannot establish the owned files' disk -usage. If a failed write leaves a temporary file that cannot be removed, its +Startup fails before removing temporary, corrupt, or over-budget `.input` files +if scanning cannot establish the owned files' disk usage, and also fails if +removing any of those files fails. Otherwise, `.input` recovery admits valid +files in lexicographic path order up to the record count and disk budget +limits. If a failed write leaves a temporary file that cannot be removed, its reservation remains charged and input disk writes stop until restart. Both record kinds share disk reservations. Pressure can reclaim either diff --git a/selene/src/input.rs b/selene/src/input.rs index 2781542e0..7c6f971bc 100644 --- a/selene/src/input.rs +++ b/selene/src/input.rs @@ -518,6 +518,8 @@ impl Worker { let failure = |action: &str, path: &Path, error| { super::record::io_failure(format!("{action} {}", path.display()), error) }; + let mut entries = Vec::new(); + let mut temporaries = Vec::new(); for entry in fs::read_dir(directory) .map_err(|error| failure("scan prepared-input directory", directory, error))? { @@ -536,9 +538,7 @@ impl Worker { .and_then(|name| name.to_str()) .is_some_and(is_temporary_name) { - fs::remove_file(&path).map_err(|error| { - failure("remove incomplete prepared-input record", &path, error) - })?; + temporaries.push(path); continue; } if path @@ -547,7 +547,26 @@ impl Worker { { continue; } - match inspect(&path) { + entries.push(path); + } + entries.sort_unstable_by(|a, b| a.as_os_str().cmp(b.as_os_str())); + let mut inspected = super::record::par_map(&entries, |path| inspect(path)); + if let Some(pos) = inspected.iter().position(|result| { + matches!(result, Err(error) if error.kind() != std::io::ErrorKind::InvalidData) + }) { + return Err(failure( + "read prepared-input record", + &entries[pos], + inspected.swap_remove(pos).unwrap_err(), + )); + } + for path in temporaries { + fs::remove_file(&path).map_err(|error| { + failure("remove incomplete prepared-input record", &path, error) + })?; + } + for (path, result) in entries.into_iter().zip(inspected) { + match result { Ok((key, bytes, has_payload)) if self.disk.len() < MAX_DISK_RECORDS && self.budget.reserve_input(bytes) => { @@ -560,9 +579,6 @@ impl Worker { }, ); } - Err(error) if error.kind() != std::io::ErrorKind::InvalidData => { - return Err(failure("read prepared-input record", &path, error)); - } _ => fs::remove_file(&path) .map_err(|error| failure("remove prepared-input record", &path, error))?, } @@ -1624,4 +1640,121 @@ mod tests { std::thread::sleep(Duration::from_millis(5)); } } + + fn indexed_key(fill: u8, index: u64) -> [u8; 32] { + let mut key = [fill; 32]; + key[..8].copy_from_slice(&index.to_be_bytes()); + key + } + + fn seed_valid_inputs( + dir: &Path, + indices: impl IntoIterator, + sample: &PreparedInputRecord, + ) -> Vec<[u8; 32]> { + indices + .into_iter() + .map(|index| { + let key = indexed_key(0, index); + write(&dir.join(file_name(&key)), key, sample).unwrap(); + key + }) + .collect() + } + + #[test] + fn parallel_scan_recovers_large_directory_deterministically_under_tight_budget() { + let dir = Directory::new(); + let sample = record(true); + let record_bytes = HEADER as u64 + + sample.metadata.len() as u64 + + sample.payload.as_ref().unwrap().len() as u64; + // Seed in non-monotonic (odd-then-even) order so admission fails without sorting on FIFO, LIFO (tmpfs), and hash-indexed (ext4) filesystems. + let mut keys = seed_valid_inputs(&dir.0, (1u64..140).step_by(2).chain((0u64..140).step_by(2)), &sample); + keys.sort_unstable(); + let mut deleted = Vec::new(); + for index in 0u64..10 { + let pending = dir.0.join(format!("{}.pending", file_name(&indexed_key(0xee, index)))); + fs::write(&pending, b"partial").unwrap(); + deleted.push(pending); + let corrupt = dir.0.join(file_name(&indexed_key(0xdd, index))); + fs::write(&corrupt, b"corrupt").unwrap(); + deleted.push(corrupt); + } + let unrelated = dir.0.join("notes.txt"); + fs::write(&unrelated, b"keep").unwrap(); + + let keep_count = 80usize; + let budget = DiskBudget::new(record_bytes * keep_count as u64, 0); + let store = InputStore::start(0, Some(dir.0.clone()), budget).unwrap(); + assert_eq!(store.stats().disk_records, keep_count); + for key in &keys[..keep_count] { + assert!(store.get_blocking(*key, true).is_some()); + } + for key in &keys[keep_count..] { + assert!(!dir.0.join(file_name(key)).exists()); + assert!(store.get_blocking(*key, true).is_none()); + } + for path in &deleted { + assert!(!path.exists(), "{} survived parallel input scan", path.display()); + } + assert!(unrelated.exists()); + } + + #[test] + #[cfg(unix)] + fn parallel_scan_preserves_directory_and_budget_on_unreadable_entry() { + if !modes_restrict_user() { + return; + } + let dir = Directory::new(); + let sample = record(true); + let record_bytes = HEADER as u64 + + sample.metadata.len() as u64 + + sample.payload.as_ref().unwrap().len() as u64; + let mut preserved = Vec::new(); + let seed_invalid_siblings = |range: std::ops::Range, out: &mut Vec| { + for index in range { + let corrupt = dir.0.join(file_name(&indexed_key(0xdd, index))); + fs::write(&corrupt, b"corrupt").unwrap(); + out.push(corrupt); + let pending = + dir.0.join(format!("{}.pending", file_name(&indexed_key(0xee, index)))); + fs::write(&pending, b"partial").unwrap(); + out.push(pending); + } + }; + for key in seed_valid_inputs(&dir.0, (1u64..80).step_by(2), &sample) { + preserved.push(dir.0.join(file_name(&key))); + } + seed_invalid_siblings(0..8, &mut preserved); + let blocked_key = [0xff; 32]; + let blocked = dir.0.join(file_name(&blocked_key)); + write(&blocked, blocked_key, &sample).unwrap(); + let _mode = ModeGuard::set(&blocked, 0o000); + preserved.push(blocked.clone()); + seed_invalid_siblings(8..16, &mut preserved); + for key in seed_valid_inputs(&dir.0, (0u64..80).step_by(2), &sample) { + preserved.push(dir.0.join(file_name(&key))); + } + + let limit = record_bytes * 40; + let budget = DiskBudget::new(limit, 0); + let error = InputStore::start(0, Some(dir.0.clone()), budget.clone()) + .err() + .unwrap() + .to_string(); + assert!(error.contains("read prepared-input record"), "{error}"); + assert!(error.contains(&file_name(&blocked_key)), "{error}"); + for path in &preserved { + assert!( + path.exists(), + "{} must not be deleted on unreadable scan failure", + path.display() + ); + } + assert_eq!(budget.checkpoint_limit(), limit); + assert_eq!(budget.checkpoint_pressure(), 0); + assert!(budget.reserve_input(limit)); + } } diff --git a/selene/src/shared/record.rs b/selene/src/shared/record.rs index 7f6a9289c..cb7093d22 100644 --- a/selene/src/shared/record.rs +++ b/selene/src/shared/record.rs @@ -77,7 +77,10 @@ use super::{ wire::{PackedOffer, RankPlanes}, }; use prost::Message; -use std::sync::Arc; +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; pub const MAGIC: [u8; 8] = *b"FLARECKP"; /// Header version byte for raw records (packed codec records use `packed::REVISION = 4`). @@ -1112,6 +1115,61 @@ impl DirectoryLock { } } +const PARALLEL_SCAN_THRESHOLD: usize = 64; +const PARALLEL_SCAN_CHUNK: usize = 8; +const MAX_SCAN_WORKERS: usize = 16; + +/// Map `f` over `items` in bounded parallel chunks when large enough to amortize +/// thread spawn overhead, preserving the input order with zero `unsafe`. +pub(crate) fn par_map R + Sync>(items: &[T], f: F) -> Vec { + let chunk_count = items.len().div_ceil(PARALLEL_SCAN_CHUNK); + let workers = std::thread::available_parallelism() + .map_or(4, |n| n.get()) + .min(MAX_SCAN_WORKERS) + .min(chunk_count); + if items.len() < PARALLEL_SCAN_THRESHOLD || workers <= 1 { + return items.iter().map(f).collect(); + } + let next = AtomicUsize::new(0); + let worker = || { + let mut chunks = Vec::new(); + loop { + let start = next.fetch_add(PARALLEL_SCAN_CHUNK, Ordering::Relaxed); + if start >= items.len() { + break; + } + let end = (start + PARALLEL_SCAN_CHUNK).min(items.len()); + chunks.push((start, items[start..end].iter().map(&f).collect::>())); + } + chunks + }; + let mut chunks = Vec::with_capacity(chunk_count); + std::thread::scope(|scope| { + let handles: Vec<_> = (1..workers) + .filter_map(|_| { + std::thread::Builder::new() + .name("flare-scan".into()) + .spawn_scoped(scope, worker) + .ok() + }) + .collect(); + chunks.extend(worker()); + for handle in handles { + chunks.extend( + handle + .join() + .unwrap_or_else(|payload| std::panic::resume_unwind(payload)), + ); + } + }); + chunks.sort_unstable_by_key(|(start, _)| *start); + let mut ordered = Vec::with_capacity(items.len()); + for (_, chunk) in chunks { + ordered.extend(chunk); + } + ordered +} + /// Read every record header in `directory`, delete temporary files, files /// whose header or name is invalid or belongs to another identity, fingerprint, /// or layout, and records whose parent is missing together with their @@ -1126,7 +1184,8 @@ impl DirectoryLock { /// record. A file that vanishes while the scan runs is treated as absent. /// Only a file whose contents fail a check is deleted: a `.ckpt` file the /// scan cannot open or read for another reason, such as a permission or -/// device error, fails the scan with an error naming it and stays in place. +/// device error, fails the scan with an error naming it before deleting +/// temporary or invalid files. pub fn scan( directory: &DirectoryLock, identity: &[u8; 32], @@ -1141,7 +1200,7 @@ pub fn scan( error, ) })?; - let mut records = Vec::new(); + let mut candidates = Vec::new(); for entry in entries { let entry = match entry { Ok(entry) => entry, @@ -1157,34 +1216,46 @@ pub fn scan( let Some(name) = name.to_str() else { continue; }; - let path = entry.path(); - let metadata = match fs::symlink_metadata(&path) { + if !name.ends_with(SUFFIX) && !(name.starts_with('.') && name.ends_with(".tmp")) { + continue; + } + candidates.push(entry.path()); + } + let outcomes = par_map(&candidates, |path| { + let metadata = match fs::symlink_metadata(path) { Ok(metadata) => metadata, - Err(error) if error.kind() == io::ErrorKind::NotFound => continue, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Inspection::Absent, Err(error) => { - return Err(io_failure( + return Inspection::Unreadable(io_failure( format!("inspect record file {}", path.display()), error, )); } }; if !metadata.is_file() { - continue; - } - if name.starts_with('.') && name.ends_with(".tmp") { - remove(&path)?; - continue; + return Inspection::Absent; } + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { + return Inspection::Absent; + }; if !name.ends_with(SUFFIX) { - continue; + return Inspection::Invalid; } - match inspect(&path, name, &metadata, identity, fingerprint, page_tokens, ranks) { + inspect(path, name, &metadata, identity, fingerprint, page_tokens, ranks) + }); + let mut records = Vec::new(); + let mut removals = Vec::new(); + for (path, outcome) in candidates.into_iter().zip(outcomes) { + match outcome { Inspection::Record(scanned) => records.push(scanned), - Inspection::Absent => {} - Inspection::Invalid => remove(&path)?, + Inspection::Invalid => removals.push(path), Inspection::Unreadable(error) => return Err(error), + Inspection::Absent => {} } } + for path in removals { + remove(&path)?; + } remove_orphans(records) } @@ -1212,14 +1283,14 @@ pub(crate) fn remove_orphans(mut records: Vec) -> Result> Ok(records) } -/// What the scan found a `.ckpt` file to be. +/// Outcome of inspecting a candidate directory entry (`.ckpt` or `.*.tmp`). enum Inspection { Record(Scanned), - /// The file vanished while the scan ran. + /// The entry vanished while the scan ran or is not a regular file. Absent, - /// The file's name or contents fail a record check; the scan deletes it. + /// A temporary `.*.tmp` file or a `.ckpt` whose name or contents fail a record check; the scan deletes it. Invalid, - /// The file could not be opened or read; the scan fails and keeps it. + /// Entry metadata or file contents could not be read; the scan fails and keeps it. Unreadable(Error), } @@ -1892,14 +1963,34 @@ mod tests { .collect() } + struct Directory(PathBuf); + impl Directory { + fn new(label: &str) -> Self { + static SERIAL: AtomicUsize = AtomicUsize::new(0); + let path = std::env::temp_dir().join(format!( + "flare-record-{label}-{}-{}", + std::process::id(), + SERIAL.fetch_add(1, Ordering::Relaxed) + )); + let _ = fs::remove_dir_all(&path); + Self(path) + } + } + impl std::ops::Deref for Directory { + type Target = Path; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + impl Drop for Directory { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + #[test] fn scan_keeps_the_valid_tree_and_deletes_everything_else() { - let directory = std::env::temp_dir().join(format!( - "flare-record-scan-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - let _ = fs::remove_dir_all(&directory); + let directory = Directory::new("scan"); let geometry = geometries().remove(0); let root = header(&geometry, 200, None); let child = header(&geometry, 400, Some(200)); @@ -2058,17 +2149,11 @@ mod tests { let file = directory.join("file"); fs::write(&file, b"").unwrap(); assert!(crate::testing::directory_lock(&file).is_err()); - drop(lock); - fs::remove_dir_all(&directory).unwrap(); } #[test] fn scan_prunes_page_only_leaves_left_by_an_incomplete_spill_chain() { - let directory = std::env::temp_dir().join(format!( - "flare-record-page-only-leaves-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); + let directory = Directory::new("page-only-leaves"); let lock = crate::testing::directory_lock(&directory).unwrap(); let geometry = geometries().remove(0); let root = header(&geometry, 64, None); @@ -2091,18 +2176,9 @@ mod tests { header.row_segment, ) }); - let records = scan( - &lock, - &IDENTITY, - &FINGERPRINT, - geometry[0].page_tokens, - &rank_sizes(&geometry), - ) - .unwrap(); + let records = scan_default(&lock, &geometry).unwrap(); assert_eq!(names(&records), [file_name(&root.key)]); assert!(dead.iter().all(|path| !path.exists())); - drop(lock); - fs::remove_dir_all(directory).unwrap(); } #[test] @@ -2113,13 +2189,7 @@ mod tests { eprintln!("skipping: file modes do not restrict the superuser"); return; } - let directory = std::env::temp_dir().join(format!( - "flare-record-unreadable-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - let _ = fs::remove_dir_all(&directory); - fs::create_dir_all(&directory).unwrap(); + let directory = Directory::new("unreadable"); let lock = crate::testing::directory_lock(&directory).unwrap(); let geometry = geometries().remove(0); let root = header(&geometry, 200, None); @@ -2138,18 +2208,11 @@ mod tests { fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); let records = scan(&lock, &IDENTITY, &FINGERPRINT, geometry[0].page_tokens, &rank_sizes(&geometry)).unwrap(); assert_eq!(names(&records), [file_name(&root.key)]); - drop(lock); - fs::remove_dir_all(&directory).unwrap(); } #[test] fn directory_lock_prevents_another_scan_from_deleting_an_active_write() { - let directory = std::env::temp_dir().join(format!( - "flare-record-lock-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - let _ = fs::remove_dir_all(&directory); + let directory = Directory::new("lock"); let geometry = geometries().remove(0); let owner = crate::testing::directory_lock(&directory).unwrap(); assert!( @@ -2177,8 +2240,6 @@ mod tests { .is_empty() ); assert!(!temporary.exists()); - drop(next); - fs::remove_dir_all(&directory).unwrap(); } #[test] fn replication_header_preserves_geometry_and_old_records() { @@ -2233,10 +2294,6 @@ mod tests { #[test] fn header_eq_implies_same_hash() { - use crate::shared::wire::{ - PackedOffer, PackedUnit, - packed_unit::{Kind, Representation}, - }; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; @@ -2262,50 +2319,14 @@ mod tests { assert_ne!(a, c); assert_ne!(digest(&a), digest(&c)); - let first_page = a.parent.unwrap().consumed_tokens / a.page_tokens; - let mut units = Vec::new(); - for p in 0..a.tail_pages { - for (rank_idx, rank_sizes) in a.ranks.iter().enumerate() { - units.push(PackedUnit { - kind: Kind::Page as i32, - logical_index: first_page + u64::from(p), - stored_rank: rank_idx as u32, - representation: Representation::Packet as i32, - profile: vec![0x42; 32], - original_length: rank_sizes.page_record_bytes(), - stored_length: 128, - replicas: Vec::new(), - stored_crc: 11 + p, - original_crc: 22 + p, - raw_xxh3: 0, - }); - } - } - for (rank_idx, rank_sizes) in a.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, - }); - } - let packed_layout = - packed::Layout::new(PackedOffer { first_page, units }, &a.ranks, first_page, a.tail_pages) - .unwrap(); + let packed = packed_header(&geometry, 512, Some(256)).packed; let mut d = a.clone(); - d.packed = Some(Arc::new(packed_layout.clone())); + d.packed = packed.clone(); assert_ne!(a, d); assert_ne!(digest(&a), digest(&d)); let mut e = a.clone(); - e.packed = Some(Arc::new(packed_layout)); + e.packed = packed; assert_eq!(d, e); assert_eq!(digest(&d), digest(&e)); } @@ -2337,4 +2358,232 @@ mod tests { raw[HEADER_BYTES..].copy_from_slice(&dir); assert!(Header::decode(&raw).is_err()); } + + fn packed_header(geometry: &[CacheGeometry], consumed_tokens: u64, parent: Option) -> Header { + use crate::shared::wire::{ + PackedUnit, + packed_unit::{Kind, Representation}, + }; + let base = header(geometry, consumed_tokens, parent); + let first_page = parent.map_or(0, |p| p / base.page_tokens); + let unit = |kind: Kind, logical_index, stored_rank, original_length, stored_crc, original_crc| { + PackedUnit { + kind: kind as i32, + logical_index, + stored_rank: stored_rank as u32, + representation: Representation::Packet as i32, + profile: vec![0x42; 32], + original_length, + stored_length: 256, + stored_crc, + original_crc, + ..Default::default() + } + }; + let mut units = Vec::new(); + for offset in 0..u64::from(base.tail_pages) { + for (rank_idx, rank_sizes) in base.ranks.iter().enumerate() { + units.push(unit( + Kind::Page, + first_page + offset, + rank_idx, + rank_sizes.page_record_bytes(), + 11, + 22, + )); + } + } + for (rank_idx, rank_sizes) in base.ranks.iter().enumerate() { + units.push(unit( + Kind::Row, + 0, + rank_idx, + rank_sizes.row_record_bytes(), + 33, + 44, + )); + } + base.with_packed(PackedOffer { first_page, units }).unwrap() + } + + fn scan_default(lock: &DirectoryLock, geometry: &[CacheGeometry]) -> Result> { + scan(lock, &IDENTITY, &FINGERPRINT, geometry[0].page_tokens, &rank_sizes(geometry)) + } + + #[test] + fn parallel_scan_handles_large_mixed_v3_v4_directory_deterministically() { + let directory = Directory::new("parallel-scan"); + let lock = crate::testing::directory_lock(&directory).unwrap(); + let geometry = geometries().remove(0); + + let mut expected = Vec::new(); + // 100 valid v3 records in 20 chains of length 5 + for chain in 0u64..20 { + let mut prev = None; + for step in 1u64..=5 { + let tokens = (chain * 10 + step) * 64; + let h = header(&geometry, tokens, prev); + write_record(&directory, &h, &file_name(&h.key), h.length_with_row()); + expected.push(h); + prev = Some(tokens); + } + } + // 40 valid v4 packed records in 10 chains of length 4 + for chain in 0u64..10 { + let mut prev = None; + for step in 1u64..=4 { + let tokens = (300 + chain * 10 + step) * 64; + let h = packed_header(&geometry, tokens, prev); + let path = directory.join(file_name(&h.key)); + let mut file = File::create(&path).unwrap(); + file.write_all(&h.packed_metadata().unwrap()).unwrap(); + file.set_len(h.length_with_row()).unwrap(); + expected.push(h); + prev = Some(tokens); + } + } + assert!(expected.len() >= PARALLEL_SCAN_THRESHOLD * 2); + + let mut deleted = Vec::new(); + // 12 .tmp files + for i in 0u64..12 { + let path = directory.join(temporary_name(&key(50_000 + i * 64, i as u8))); + fs::write(&path, b"pending").unwrap(); + deleted.push(path); + } + // 10 truncated .ckpt files + for i in 0u64..10 { + let h = header(&geometry, (600 + i) * 64, None); + let path = write_record(&directory, &h, &file_name(&h.key), h.row_segment - 1); + deleted.push(path); + } + // 10 bogus-header .ckpt files + for i in 0u64..10 { + let path = directory.join(format!("bogus-{i}.ckpt")); + fs::write(&path, b"not a valid header").unwrap(); + deleted.push(path); + } + // 6 wrong-identity .ckpt files + for i in 0u64..6 { + let mut h = header(&geometry, (700 + i) * 64, None); + h.identity = [9; 32]; + deleted.push(write_record(&directory, &h, &file_name(&h.key), h.length_with_row())); + } + // 10 cascading orphans (missing root at 800 * 64) + for i in 1u64..=10 { + let h = header(&geometry, (800 + i) * 64, Some((800 + i - 1) * 64)); + deleted.push(write_record(&directory, &h, &file_name(&h.key), h.length_with_row())); + } + // Foreign file, subdirectories, and symlinks (dangling and live) must survive untouched. + let foreign = directory.join("README"); + fs::write(&foreign, b"keep").unwrap(); + let subdir = directory.join("nested.ckpt"); + fs::create_dir(&subdir).unwrap(); + let tmp_subdir = directory.join(".dir.tmp"); + fs::create_dir(&tmp_subdir).unwrap(); + #[cfg(unix)] + let link = directory.join(file_name(&key(999 * 64, 9))); + #[cfg(unix)] + symlink("/nonexistent/target.ckpt", &link).unwrap(); + #[cfg(unix)] + let live_link = directory.join(file_name(&key(998 * 64, 8))); + #[cfg(unix)] + symlink(&foreign, &live_link).unwrap(); + #[cfg(unix)] + let tmp_link = directory.join(".link.tmp"); + #[cfg(unix)] + symlink(&foreign, &tmp_link).unwrap(); + + expected.sort_by_key(|h| (h.key.consumed_tokens, h.key.digest)); + let expected_names: Vec<_> = expected.iter().map(|h| file_name(&h.key)).collect(); + + let records = scan_default(&lock, &geometry).unwrap(); + assert_eq!(names(&records), expected_names); + assert_eq!(records.iter().filter(|r| r.header.packed.is_some()).count(), 40); + assert_eq!(records.iter().filter(|r| r.header.packed.is_none()).count(), 100); + for path in &deleted { + assert!(!path.exists(), "{} survived parallel scan", path.display()); + } + assert!(foreign.exists()); + assert!(subdir.is_dir()); + assert!(tmp_subdir.is_dir()); + #[cfg(unix)] + { + assert!(fs::symlink_metadata(&link).unwrap().is_symlink()); + assert!(fs::symlink_metadata(&live_link).unwrap().is_symlink()); + assert!(fs::symlink_metadata(&tmp_link).unwrap().is_symlink()); + } + + let again = scan_default(&lock, &geometry).unwrap(); + assert_eq!(again, records); + } + + #[test] + #[cfg(unix)] + fn parallel_scan_preserves_directory_on_unreadable_entry() { + // SAFETY: `geteuid` has no preconditions. + if unsafe { libc::geteuid() } == 0 { + eprintln!("skipping: file modes do not restrict the superuser"); + return; + } + let directory = Directory::new("parallel-unreadable"); + let lock = crate::testing::directory_lock(&directory).unwrap(); + let geometry = geometries().remove(0); + + let mut preserved = Vec::new(); + let seed_invalid_siblings = |batch: u64, out: &mut Vec| { + for i in 0u64..8 { + let temp = directory.join(temporary_name(&key( + 90_000 + batch * 1_000 + i * 64, + i as u8, + ))); + fs::write(&temp, b"pending").unwrap(); + out.push(temp); + let bogus = directory.join(format!("bogus-unreadable-{batch}-{i}.ckpt")); + fs::write(&bogus, b"not a valid header").unwrap(); + out.push(bogus); + } + }; + for i in 1u64..=35 { + let h = header(&geometry, i * 64, None); + preserved.push(write_record( + &directory, + &h, + &file_name(&h.key), + h.length_with_row(), + )); + } + seed_invalid_siblings(0, &mut preserved); + let blocked = header(&geometry, 100 * 64, None); + let blocked_path = write_record( + &directory, + &blocked, + &file_name(&blocked.key), + blocked.length_with_row(), + ); + fs::set_permissions(&blocked_path, fs::Permissions::from_mode(0o000)).unwrap(); + preserved.push(blocked_path.clone()); + seed_invalid_siblings(1, &mut preserved); + for i in 36u64..=70 { + let h = header(&geometry, i * 64, None); + preserved.push(write_record( + &directory, + &h, + &file_name(&h.key), + h.length_with_row(), + )); + } + + let error = scan_default(&lock, &geometry).unwrap_err().to_string(); + assert!(error.contains(&file_name(&blocked.key)), "{error}"); + for path in &preserved { + assert!( + path.exists(), + "{} must not be deleted on unreadable scan failure", + path.display() + ); + } + + fs::set_permissions(&blocked_path, fs::Permissions::from_mode(0o600)).unwrap(); + } }