Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/prefix-cache-offload.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down
147 changes: 140 additions & 7 deletions selene/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))?
{
Expand All @@ -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
Expand All @@ -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) =>
{
Expand All @@ -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))?,
}
Expand Down Expand Up @@ -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<Item = u64>,
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<u64>, out: &mut Vec<PathBuf>| {
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));
}
}
Loading
Loading