use super::*;
#[derive(Clone, Copy, Debug)]
struct DiskEntry {
bytes: u64,
lru_seq: u64,
}
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub struct SpillStoreStats {
pub writes_committed: u64,
pub bytes_written: u64,
pub reads_hit: u64,
pub reads_miss: u64,
pub corrupt_files_removed: u64,
pub disk_gc_evictions: u64,
pub over_budget_drops: u64,
pub orphans_swept: u64,
}
struct LockedDirGuard(File);
impl Drop for LockedDirGuard {
fn drop(&mut self) {
let _ = self.0.unlock();
}
}
enum OpenLockedOutcome {
Opened(SpillStore),
ModeMismatch {
locked_dir: LockedDirGuard,
expected: u32,
found: u32,
},
}
pub struct SpillStore {
directory_lock: LockedDirGuard,
last_allocated_id: u64,
dir: PathBuf,
max_bytes: u64,
used_bytes: u64,
lru_clock: u64,
kvb: u32,
entries: HashMap<SpillKey, DiskEntry>,
stats: SpillStoreStats,
}
fn enable_nocache(file: &File) {
#[cfg(target_os = "macos")]
{
use std::os::fd::AsRawFd;
unsafe {
libc::fcntl(file.as_raw_fd(), libc::F_NOCACHE, 1);
}
}
#[cfg(not(target_os = "macos"))]
{
let _ = file;
}
}
fn fsync_dir(dir: &Path) -> io::Result<()> {
let f = File::open(dir)?;
f.sync_all()
}
fn unlink_if_present(path: &Path) -> io::Result<bool> {
match fs::remove_file(path) {
Ok(()) => Ok(true),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e),
}
}
fn pread_exact(file: &File, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
#[cfg(unix)]
{
while !buf.is_empty() {
let n = file.read_at(buf, offset)?;
if n == 0 {
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "unexpected EOF in pread"));
}
buf = &mut buf[n..];
offset = offset.checked_add(n as u64).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "pread offset overflow")
})?;
}
Ok(())
}
#[cfg(not(unix))]
{
use std::io::{Read, Seek, SeekFrom};
let mut f = file;
f.seek(SeekFrom::Start(offset))?;
f.read_exact(buf)
}
}
fn encode_header(
key: SpillKey,
kvb: u32,
generation: u64,
kv_bytes: &[u8],
recurrent_state: Option<&[u8]>,
) -> [u8; SPILL_HEADER_LEN] {
let state_slice = recurrent_state.unwrap_or(&[]);
let mut header = [0u8; SPILL_HEADER_LEN];
header[0..8].copy_from_slice(&SPILL_MAGIC);
header[8..12].copy_from_slice(&SPILL_FORMAT_VERSION.to_le_bytes());
header[12..14].copy_from_slice(&(key.kind as u16).to_le_bytes());
header[14..16].copy_from_slice(&(kvb as u16).to_le_bytes());
header[16..24].copy_from_slice(&key.id.to_le_bytes());
header[24..32].copy_from_slice(&generation.to_le_bytes());
header[32..40].copy_from_slice(&(kv_bytes.len() as u64).to_le_bytes());
header[40..48].copy_from_slice(&(state_slice.len() as u64).to_le_bytes());
let mut hasher = Sha256::new();
hasher.update(&header[0..HEADER_PREFIX_LEN]);
hasher.update(kv_bytes);
if !state_slice.is_empty() {
hasher.update(state_slice);
}
let digest = hasher.finalize();
header[48..80].copy_from_slice(&digest);
header
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StaleSpillRotation {
pub moved_to: PathBuf,
pub old_mode_desc: String,
pub new_mode_desc: String,
}
impl StaleSpillRotation {
pub fn format_warning(&self, spill_dir: &Path) -> String {
format!(
"[serve] WARNING: --spill-dir {} stale cache mismatch (found {}, expected {}); moved existing spill directory aside intact to {} and initialized a fresh empty spill cache",
spill_dir.display(),
self.old_mode_desc,
self.new_mode_desc,
self.moved_to.display(),
)
}
}
impl SpillStore {
pub fn open(dir: impl AsRef<Path>, max_bytes: u64) -> Result<Self, SpillError> {
Self::open_with_kvb(dir, max_bytes, 2)
}
pub fn open_with_kvb(dir: impl AsRef<Path>, max_bytes: u64, kvb: u32) -> Result<Self, SpillError> {
if kvb != 1 && kvb != 2 {
return Err(SpillError::InvalidKvb(kvb));
}
Self::open_inner(dir, max_bytes, kvb)
}
pub fn open_with_mode(
dir: impl AsRef<Path>,
max_bytes: u64,
mode: crate::blocks::KvMode,
) -> Result<Self, SpillError> {
Self::open_inner(dir, max_bytes, mode.kvb_tag())
}
pub fn open_with_kv4_digest(
dir: impl AsRef<Path>,
max_bytes: u64,
kv4_digest: [u8; 32],
) -> Result<Self, SpillError> {
let mut store = Self::open_with_mode(dir, max_bytes, crate::blocks::KvMode::Kv4)?;
store.verify_or_stamp_kv4_digest(kv4_digest)?;
Ok(store)
}
pub fn open_or_rotate_stale(
dir: impl AsRef<Path>,
max_bytes: u64,
mode: crate::blocks::KvMode,
kv4_digest: Option<[u8; 32]>,
) -> Result<(Self, Option<StaleSpillRotation>), SpillError> {
let unix_ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
Self::open_or_rotate_stale_at(dir, max_bytes, mode, kv4_digest, unix_ts)
}
pub fn open_or_rotate_stale_at(
dir: impl AsRef<Path>,
max_bytes: u64,
mode: crate::blocks::KvMode,
kv4_digest: Option<[u8; 32]>,
unix_ts: u64,
) -> Result<(Self, Option<StaleSpillRotation>), SpillError> {
let dir_path = dir.as_ref();
match Self::open_locked(dir_path, max_bytes, mode.kvb_tag())? {
OpenLockedOutcome::Opened(mut store) => {
if let Some(d) = kv4_digest {
match store.verify_or_stamp_kv4_digest(d) {
Ok(()) => Ok((store, None)),
Err(SpillError::ModeMismatch { found, .. }) => {
let Self { directory_lock, .. } = store;
Self::rotate_locked_and_reopen(
dir_path,
directory_lock,
max_bytes,
mode,
kv4_digest,
found,
unix_ts,
)
}
Err(e) => Err(e),
}
} else {
Ok((store, None))
}
}
OpenLockedOutcome::ModeMismatch { locked_dir, found, .. } => {
Self::rotate_locked_and_reopen(
dir_path,
locked_dir,
max_bytes,
mode,
kv4_digest,
found,
unix_ts,
)
}
}
}
pub fn verify_or_rotate_kv4_digest(
mut self,
kv4_digest: [u8; 32],
) -> Result<(Self, Option<StaleSpillRotation>), SpillError> {
match self.verify_or_stamp_kv4_digest(kv4_digest) {
Ok(()) => Ok((self, None)),
Err(SpillError::ModeMismatch { found, .. }) => {
let unix_ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let Self { directory_lock, dir, max_bytes, .. } = self;
Self::rotate_locked_and_reopen(
&dir,
directory_lock,
max_bytes,
crate::blocks::KvMode::Kv4,
Some(kv4_digest),
found,
unix_ts,
)
}
Err(e) => Err(e),
}
}
fn rotate_locked_and_reopen(
dir_path: &Path,
locked_dir: LockedDirGuard,
max_bytes: u64,
mode: crate::blocks::KvMode,
kv4_digest: Option<[u8; 32]>,
found_kvb: u32,
unix_ts: u64,
) -> Result<(Self, Option<StaleSpillRotation>), SpillError> {
let new_mode_desc = Self::describe_requested_mode(mode, kv4_digest);
let old_mode_desc = Self::describe_existing_spill_dir(dir_path, found_kvb);
let moved_to = Self::rotate_stale_spill_dir_locked(dir_path, locked_dir, unix_ts)?;
let fresh = match kv4_digest {
Some(d) => Self::open_with_kv4_digest(dir_path, max_bytes, d)?,
None => Self::open_with_mode(dir_path, max_bytes, mode)?,
};
Ok((
fresh,
Some(StaleSpillRotation { moved_to, old_mode_desc, new_mode_desc }),
))
}
fn describe_kvb_tag(kvb: u32) -> String {
match kvb {
2 => "kvb=2 (fp16)".into(),
1 => "kvb=1 (kv8)".into(),
k if k == crate::blocks::KVB_KV4 => format!("kvb={k} (kv4)"),
other => format!("kvb={other}"),
}
}
fn describe_requested_mode(mode: crate::blocks::KvMode, kv4_digest: Option<[u8; 32]>) -> String {
match (mode, kv4_digest) {
(crate::blocks::KvMode::Kv4, Some(d)) => {
format!("kvb={} (kv4-wht-v1 sha256={})", crate::blocks::KVB_KV4, Self::format_hex32(&d))
}
(m, _) => Self::describe_kvb_tag(m.kvb_tag()),
}
}
fn describe_existing_spill_dir(dir: &Path, fallback_found_kvb: u32) -> String {
let marker = dir.join(SPILL_KV4_MARKER_FILENAME);
if let Ok(meta) = fs::symlink_metadata(&marker) {
if meta.file_type().is_file() && meta.len() <= 256 {
if let Ok(raw) = fs::read(&marker) {
if let Ok(s) = std::str::from_utf8(&raw) {
let t = s.trim();
if !t.is_empty() {
return format!("kvb={} ({t})", crate::blocks::KVB_KV4);
}
}
}
}
}
if let Some(idx_kvb) = Self::peek_index_kvb(&dir.join(SPILL_INDEX_FILENAME)) {
return Self::describe_kvb_tag(idx_kvb);
}
if let Ok(rd) = fs::read_dir(dir) {
for entry in rd.flatten() {
let path = entry.path();
if let Some(name) = entry.file_name().to_str() {
if SpillKey::parse_blk_filename(name).is_some() {
if let Some(blk_kvb) = Self::peek_blk_kvb(&path) {
return Self::describe_kvb_tag(blk_kvb);
}
}
}
}
}
Self::describe_kvb_tag(fallback_found_kvb)
}
fn rotate_stale_spill_dir_locked(
dir: &Path,
locked_dir: LockedDirGuard,
unix_ts: u64,
) -> Result<PathBuf, SpillError> {
let clean: PathBuf = dir.components().collect();
let Some(parent) = clean.parent() else {
return Err(SpillError::InvalidDir(format!("cannot rotate root path {}", dir.display())));
};
let parent_dir = if parent.as_os_str().is_empty() { Path::new(".") } else { parent };
let Some(base_os) = clean.file_name() else {
return Err(SpillError::InvalidDir(format!("cannot rotate {}", dir.display())));
};
let base = base_os.to_string_lossy();
#[cfg(test)]
run_test_spill_rotate_hook(&clean);
let path_meta = fs::symlink_metadata(&clean)?;
if !path_meta.file_type().is_dir() {
return Err(SpillError::InvalidDir(format!(
"--spill-dir {} is not a regular directory",
dir.display()
)));
}
#[cfg(unix)]
{
let fd_meta = locked_dir.0.metadata()?;
if (fd_meta.dev(), fd_meta.ino()) != (path_meta.dev(), path_meta.ino()) {
return Err(SpillError::InvalidDir(format!(
"--spill-dir {} inode changed while locked (locked {}:{}, path {}:{})",
dir.display(),
fd_meta.dev(),
fd_meta.ino(),
path_meta.dev(),
path_meta.ino(),
)));
}
}
for attempt in 0u64..10_000 {
let cand_name = if attempt == 0 {
format!("{base}.stale-{unix_ts}")
} else {
format!("{base}.stale-{unix_ts}-{attempt}")
};
let cand_path = parent_dir.join(cand_name);
if fs::symlink_metadata(&cand_path).is_ok() {
continue;
}
match fs::rename(&clean, &cand_path) {
Ok(()) => {
fsync_dir(parent_dir)?;
drop(locked_dir);
return Ok(cand_path);
}
Err(e)
if e.kind() == io::ErrorKind::AlreadyExists
|| e.kind() == io::ErrorKind::DirectoryNotEmpty =>
{
continue;
}
Err(e) => return Err(SpillError::Io(e)),
}
}
Err(SpillError::InvalidDir(format!(
"exhausted stale rotation names for {}",
dir.display()
)))
}
fn acquire_spill_dir_lock(dir: &Path) -> Result<LockedDirGuard, SpillError> {
for _attempt in 0..4 {
prepare_spill_dir(dir)?;
let mut options = OpenOptions::new();
options.read(true);
#[cfg(unix)]
options.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW);
let file = match options.open(dir) {
Ok(f) => f,
Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
Err(e) => return Err(e.into()),
};
match file.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => {
return Err(SpillError::DirectoryLocked(dir.to_path_buf()));
}
Err(std::fs::TryLockError::Error(err)) => return Err(err.into()),
}
let guard = LockedDirGuard(file);
#[cfg(unix)]
{
let fd_meta = guard.0.metadata()?;
match fs::symlink_metadata(dir) {
Ok(path_meta)
if path_meta.file_type().is_dir()
&& (fd_meta.dev(), fd_meta.ino()) == (path_meta.dev(), path_meta.ino()) =>
{
return Ok(guard);
}
Ok(_) | Err(_) => {
drop(guard);
continue;
}
}
}
#[cfg(not(unix))]
{
return Ok(guard);
}
}
Err(SpillError::InvalidDir(format!(
"concurrent directory replacement contended on {}",
dir.display()
)))
}
fn open_locked(dir: &Path, max_bytes: u64, kvb: u32) -> Result<OpenLockedOutcome, SpillError> {
let directory_lock = Self::acquire_spill_dir_lock(dir)?;
let mut store = Self {
directory_lock,
last_allocated_id: 1,
dir: dir.to_path_buf(),
max_bytes,
used_bytes: 0,
lru_clock: 0,
kvb,
entries: HashMap::new(),
stats: SpillStoreStats::default(),
};
match store.scan_and_sweep() {
Ok(()) => Ok(OpenLockedOutcome::Opened(store)),
Err(SpillError::ModeMismatch { expected, found }) => {
let Self { directory_lock, .. } = store;
Ok(OpenLockedOutcome::ModeMismatch {
locked_dir: directory_lock,
expected,
found,
})
}
Err(e) => Err(e),
}
}
fn open_inner(dir: impl AsRef<Path>, max_bytes: u64, kvb: u32) -> Result<Self, SpillError> {
match Self::open_locked(dir.as_ref(), max_bytes, kvb)? {
OpenLockedOutcome::Opened(store) => Ok(store),
OpenLockedOutcome::ModeMismatch { expected, found, .. } => {
Err(SpillError::ModeMismatch { expected, found })
}
}
}
pub fn kvb(&self) -> u32 {
self.kvb
}
#[cfg(test)]
pub(super) fn clone_directory_lock(&self) -> io::Result<File> {
self.directory_lock.0.try_clone()
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn used_bytes(&self) -> u64 {
self.used_bytes
}
pub fn max_bytes(&self) -> u64 {
self.max_bytes
}
pub fn stats(&self) -> SpillStoreStats {
self.stats
}
pub fn contains(&self, key: SpillKey) -> bool {
self.entries.contains_key(&key)
}
pub fn fresh_key(&mut self, kind: SpillBlockKind) -> SpillKey {
loop {
self.last_allocated_id = self.last_allocated_id.wrapping_add(1).max(1);
let key = SpillKey::new(kind, self.last_allocated_id);
if !self.contains(key) {
return key;
}
}
}
pub(super) fn keys(&self) -> impl Iterator<Item = SpillKey> + '_ {
self.entries.keys().copied()
}
pub fn entry_count(&self) -> usize {
self.entries.len()
}
pub fn block_path(&self, key: SpillKey) -> PathBuf {
self.dir.join(key.blk_filename())
}
fn next_lru(&mut self) -> u64 {
self.lru_clock = self.lru_clock.wrapping_add(1);
self.lru_clock
}
fn peek_blk_kvb(path: &Path) -> Option<u32> {
let mut opts = OpenOptions::new();
opts.read(true);
#[cfg(unix)]
{
opts.custom_flags(libc::O_NOFOLLOW);
}
let file = opts.open(path).ok()?;
let mut hdr = [0u8; 16];
pread_exact(&file, &mut hdr, 0).ok()?;
if hdr[0..8] != SPILL_MAGIC {
return None;
}
let ver = u32::from_le_bytes(hdr[8..12].try_into().ok()?);
if ver != SPILL_FORMAT_VERSION {
return None;
}
Some(u32::from(u16::from_le_bytes(hdr[14..16].try_into().ok()?)))
}
fn peek_index_kvb(path: &Path) -> Option<u32> {
let mut opts = OpenOptions::new();
opts.read(true);
#[cfg(unix)]
{
opts.custom_flags(libc::O_NOFOLLOW);
}
let file = opts.open(path).ok()?;
let mut hdr = [0u8; 16];
pread_exact(&file, &mut hdr, 0).ok()?;
if hdr[0..8] != SPILL_INDEX_MAGIC {
return None;
}
Some(u32::from_le_bytes(hdr[12..16].try_into().ok()?))
}
fn format_hex32(bytes: &[u8; 32]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(64);
for &b in bytes {
out.push(HEX[(b >> 4) as usize] as char);
out.push(HEX[(b & 0x0f) as usize] as char);
}
out
}
fn parse_hex32(s: &str) -> Option<[u8; 32]> {
if s.len() != 64 {
return None;
}
let hex_nibble = |c: u8| -> Option<u8> {
match c {
b'0'..=b'9' => Some(c - b'0'),
b'a'..=b'f' => Some(c - b'a' + 10),
b'A'..=b'F' => Some(c - b'A' + 10),
_ => None,
}
};
let raw = s.as_bytes();
let mut out = [0u8; 32];
for (i, slot) in out.iter_mut().enumerate() {
let hi = hex_nibble(raw[2 * i])?;
let lo = hex_nibble(raw[2 * i + 1])?;
*slot = (hi << 4) | lo;
}
Some(out)
}
fn write_kv4_marker_atomic(&self, content: &[u8]) -> Result<(), SpillError> {
let final_path = self.dir.join(SPILL_KV4_MARKER_FILENAME);
let nonce = TEMP_NONCE.fetch_add(1, Ordering::Relaxed);
let tmp_path = self.dir.join(format!("{SPILL_KV4_MARKER_TMP_PREFIX}{}.{nonce}", std::process::id()));
let res = (|| -> io::Result<()> {
let mut opts = OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
opts.mode(0o600).custom_flags(libc::O_NOFOLLOW);
}
let mut file = opts.open(&tmp_path)?;
#[cfg(unix)]
{
file.set_permissions(fs::Permissions::from_mode(0o600))?;
}
file.write_all(content)?;
file.sync_all()?;
drop(file);
fs::rename(&tmp_path, &final_path)?;
fsync_dir(&self.dir)?;
Ok(())
})();
if let Err(e) = res {
let _ = fs::remove_file(&tmp_path);
return Err(SpillError::Io(e));
}
Ok(())
}
pub fn verify_or_stamp_kv4_digest(&mut self, kv4_digest: [u8; 32]) -> Result<(), SpillError> {
let kv4_tag = crate::blocks::KVB_KV4;
if self.kvb != kv4_tag {
return Err(SpillError::ModeMismatch { expected: kv4_tag, found: self.kvb });
}
let kv4_marker = self.dir.join(SPILL_KV4_MARKER_FILENAME);
let pending_line = "kv4-wht-v1 pending";
if let Ok(meta) = fs::symlink_metadata(&kv4_marker) {
if !meta.file_type().is_file() || meta.len() > 256 {
return Err(SpillError::ModeMismatch { expected: kv4_tag, found: kv4_tag });
}
let mut opts = OpenOptions::new();
opts.read(true);
#[cfg(unix)]
{
opts.custom_flags(libc::O_NOFOLLOW);
}
let mut file = opts.open(&kv4_marker)?;
let mut buf = Vec::with_capacity(meta.len() as usize);
io::Read::read_to_end(&mut file, &mut buf)?;
let Ok(text) = std::str::from_utf8(&buf) else {
return Err(SpillError::ModeMismatch { expected: kv4_tag, found: kv4_tag });
};
let trimmed = text.trim();
if let Some(hex) = trimmed.strip_prefix("kv4-wht-v1 sha256=") {
let Some(found_digest) = Self::parse_hex32(hex) else {
return Err(SpillError::ModeMismatch { expected: kv4_tag, found: kv4_tag });
};
if found_digest != kv4_digest {
return Err(SpillError::ModeMismatch { expected: kv4_tag, found: kv4_tag });
}
return Ok(());
}
if trimmed != pending_line {
return Err(SpillError::ModeMismatch { expected: kv4_tag, found: kv4_tag });
}
}
if !self.entries.is_empty() || fs::symlink_metadata(self.dir.join(SPILL_INDEX_FILENAME)).is_ok() {
return Err(SpillError::ModeMismatch { expected: kv4_tag, found: kv4_tag });
}
let stamped = format!("kv4-wht-v1 sha256={}\n", Self::format_hex32(&kv4_digest));
self.write_kv4_marker_atomic(stamped.as_bytes())
}
fn write_arith_marker_atomic(&self, content: &[u8]) -> Result<(), SpillError> {
let final_path = self.dir.join(SPILL_ARITH_MARKER_FILENAME);
let nonce = TEMP_NONCE.fetch_add(1, Ordering::Relaxed);
let tmp_path = self.dir.join(format!("{SPILL_ARITH_MARKER_TMP_PREFIX}{}.{nonce}", std::process::id()));
let res = (|| -> io::Result<()> {
let mut opts = OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
opts.mode(0o600).custom_flags(libc::O_NOFOLLOW);
}
let mut file = opts.open(&tmp_path)?;
#[cfg(unix)]
{
file.set_permissions(fs::Permissions::from_mode(0o600))?;
}
file.write_all(content)?;
file.sync_all()?;
drop(file);
fs::rename(&tmp_path, &final_path)?;
fsync_dir(&self.dir)?;
Ok(())
})();
if let Err(e) = res {
let _ = fs::remove_file(&tmp_path);
return Err(SpillError::Io(e));
}
Ok(())
}
pub fn verify_or_stamp_prefill_arith(&mut self, arith: crate::blocks::PrefillArithMode) -> Result<(), SpillError> {
match self.prefill_arith_mismatch(arith)? {
None => Ok(()),
Some(_) => Err(SpillError::ModeMismatch { expected: self.kvb, found: self.kvb }),
}
}
fn prefill_arith_mismatch(&self, arith: crate::blocks::PrefillArithMode) -> Result<Option<&'static str>, SpillError> {
use std::io::Read;
const LIMIT: u64 = 256;
const INVALID: &str = "invalid-prefill-arith";
let marker = self.dir.join(SPILL_ARITH_MARKER_FILENAME);
match fs::symlink_metadata(&marker) {
Ok(meta) if !meta.is_file() || meta.len() > LIMIT => return Ok(Some(INVALID)),
Ok(_) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
if !self.entries.is_empty() || fs::symlink_metadata(self.dir.join(SPILL_INDEX_FILENAME)).is_ok() {
return Ok(Some("untagged-legacy-prefill"));
}
let stamped = format!("{}\n", arith.spill_marker_line());
self.write_arith_marker_atomic(stamped.as_bytes())?;
return Ok(None);
}
Err(e) => return Err(e.into()),
}
let mut opts = OpenOptions::new();
opts.read(true);
#[cfg(unix)]
opts.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
let file = opts.open(marker)?;
let meta = file.metadata()?;
if !meta.is_file() || meta.len() > LIMIT {
return Ok(Some(INVALID));
}
let mut buf = Vec::with_capacity(meta.len() as usize);
file.take(LIMIT + 1).read_to_end(&mut buf)?;
if buf.len() as u64 > LIMIT {
return Ok(Some(INVALID));
}
let found = std::str::from_utf8(&buf).ok()
.and_then(crate::blocks::PrefillArithMode::from_spill_marker_line);
Ok(match found {
Some(mode) if mode == arith => None,
Some(mode) => Some(mode.spill_marker_line()),
None => Some(INVALID),
})
}
pub fn verify_or_rotate_prefill_arith(
self,
mode: crate::blocks::KvMode,
kv4_digest: Option<[u8; 32]>,
arith: crate::blocks::PrefillArithMode,
) -> Result<(Self, Option<StaleSpillRotation>), SpillError> {
let unix_ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
self.verify_or_rotate_prefill_arith_at(mode, kv4_digest, arith, unix_ts)
}
pub fn verify_or_rotate_prefill_arith_at(
self,
mode: crate::blocks::KvMode,
kv4_digest: Option<[u8; 32]>,
arith: crate::blocks::PrefillArithMode,
unix_ts: u64,
) -> Result<(Self, Option<StaleSpillRotation>), SpillError> {
match self.prefill_arith_mismatch(arith)? {
None => Ok((self, None)),
Some(old_arith_desc) => {
let old_mode_desc = format!(
"{}, {}",
Self::describe_existing_spill_dir(&self.dir, self.kvb),
old_arith_desc
);
let new_mode_desc = format!(
"{}, {}",
Self::describe_requested_mode(mode, kv4_digest),
arith.spill_marker_line()
);
let Self { directory_lock, dir, max_bytes, .. } = self;
let moved_to = Self::rotate_stale_spill_dir_locked(&dir, directory_lock, unix_ts)?;
let mut fresh = match kv4_digest {
Some(d) => Self::open_with_kv4_digest(&dir, max_bytes, d)?,
None => Self::open_with_mode(&dir, max_bytes, mode)?,
};
fresh.verify_or_stamp_prefill_arith(arith)?;
Ok((fresh, Some(StaleSpillRotation { moved_to, old_mode_desc, new_mode_desc })))
}
}
}
fn scan_and_sweep(&mut self) -> Result<(), SpillError> {
let kv4_tag = crate::blocks::KVB_KV4;
let kv4_marker = self.dir.join(SPILL_KV4_MARKER_FILENAME);
if fs::symlink_metadata(&kv4_marker).is_ok() && self.kvb != kv4_tag {
return Err(SpillError::ModeMismatch { expected: self.kvb, found: kv4_tag });
}
if let Some(idx_kvb) = Self::peek_index_kvb(&self.dir.join(SPILL_INDEX_FILENAME)) {
if (self.kvb == kv4_tag || idx_kvb == kv4_tag) && idx_kvb != self.kvb {
return Err(SpillError::ModeMismatch { expected: self.kvb, found: idx_kvb });
}
}
let mut discovered: Vec<(SpillKey, u64, u64)> = Vec::new();
let mut pending_orphan_tmps: Vec<PathBuf> = Vec::new();
let mut pending_non_regular_blks: Vec<PathBuf> = Vec::new();
for entry in fs::read_dir(&self.dir)? {
let entry = entry?;
let path = entry.path();
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
let meta = match fs::symlink_metadata(&path) {
Ok(m) => m,
Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
Err(e) => return Err(e.into()),
};
if SpillKey::parse_tmp_filename(&name).is_some()
|| name.starts_with(SPILL_INDEX_TMP_PREFIX)
|| name.starts_with(SPILL_KV4_MARKER_TMP_PREFIX)
|| name.starts_with(SPILL_ARITH_MARKER_TMP_PREFIX)
{
if meta.is_file() {
pending_orphan_tmps.push(path);
}
continue;
}
if let Some(key) = SpillKey::parse_blk_filename(&name) {
if !meta.file_type().is_file() {
pending_non_regular_blks.push(path);
continue;
}
if let Some(blk_kvb) = Self::peek_blk_kvb(&path) {
if (self.kvb == kv4_tag || blk_kvb == kv4_tag) && blk_kvb != self.kvb {
return Err(SpillError::ModeMismatch { expected: self.kvb, found: blk_kvb });
}
}
let mtime_key = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
discovered.push((key, meta.len(), mtime_key));
}
}
for path in pending_orphan_tmps {
if unlink_if_present(&path)? {
self.stats.orphans_swept += 1;
}
}
for path in pending_non_regular_blks {
if unlink_if_present(&path)? {
self.stats.corrupt_files_removed += 1;
}
}
if self.kvb == kv4_tag && fs::symlink_metadata(&kv4_marker).is_err() {
self.write_kv4_marker_atomic(b"kv4-wht-v1 pending\n")?;
}
discovered.sort_by_key(|&(key, _, mtime)| (mtime, key));
for (key, len, _) in discovered {
self.last_allocated_id = self.last_allocated_id.max(key.id);
let seq = self.next_lru();
self.entries.insert(key, DiskEntry { bytes: len, lru_seq: seq });
self.used_bytes = self.used_bytes.saturating_add(len);
}
if self.stats.orphans_swept > 0 {
fsync_dir(&self.dir)?;
}
let empty = HashSet::new();
self.evict_lru_to_fit(0, &empty);
if self.used_bytes > self.max_bytes {
return Err(SpillError::InvalidDir(format!(
"could not reduce spill usage of {} bytes to the {} byte budget",
self.used_bytes, self.max_bytes
)));
}
Ok(())
}
pub fn evict_lru_to_fit(
&mut self,
additional: u64,
protected: &HashSet<SpillKey>,
) -> Vec<SpillKey> {
let mut evicted = Vec::new();
let mut failed = HashSet::new();
while self.used_bytes.saturating_add(additional) > self.max_bytes {
let victim = self
.entries
.iter()
.filter(|(k, _)| !protected.contains(k) && !failed.contains(*k))
.min_by_key(|(k, e)| (e.lru_seq, **k))
.map(|(k, _)| *k);
let Some(victim_key) = victim else {
break;
};
if self.remove_block(victim_key) {
self.stats.disk_gc_evictions += 1;
evicted.push(victim_key);
} else {
failed.insert(victim_key);
}
}
evicted
}
pub fn remove_block(&mut self, key: SpillKey) -> bool {
let indexed = self.entries.contains_key(&key);
self.unlink_block(key).is_ok_and(|removed| removed || indexed)
}
fn forget_block(&mut self, key: SpillKey) {
if let Some(entry) = self.entries.remove(&key) {
self.used_bytes = self.used_bytes.saturating_sub(entry.bytes);
}
}
fn unlink_block(&mut self, key: SpillKey) -> io::Result<bool> {
let removed = unlink_if_present(&self.block_path(key))?;
self.forget_block(key);
Ok(removed)
}
pub fn write_block(
&mut self,
key: SpillKey,
generation: u64,
kv_bytes: &[u8],
recurrent_state: Option<&[u8]>,
protected: &HashSet<SpillKey>,
) -> Result<(WriteOutcome, Vec<SpillKey>), SpillError> {
if kv_bytes.len() > MAX_KV_PAYLOAD_BYTES {
return Err(SpillError::PayloadTooLarge(kv_bytes.len()));
}
let state_slice = recurrent_state.unwrap_or(&[]);
if state_slice.len() > MAX_RECURRENT_STATE_BYTES {
return Err(SpillError::PayloadTooLarge(state_slice.len()));
}
let total_bytes = (SPILL_HEADER_LEN as u64)
.checked_add(kv_bytes.len() as u64)
.and_then(|v| v.checked_add(state_slice.len() as u64))
.ok_or(SpillError::PayloadTooLarge(usize::MAX))?;
if total_bytes > self.max_bytes {
self.stats.over_budget_drops += 1;
return Ok((WriteOutcome::OverBudget, Vec::new()));
}
let final_path = self.block_path(key);
let existing_bytes = match self.entries.get(&key) {
Some(entry) => entry.bytes,
None => match fs::symlink_metadata(&final_path) {
Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
Err(e) => return Err(e.into()),
Ok(_) => {
return Err(io::Error::new(io::ErrorKind::AlreadyExists,
format!("unindexed file at {}", final_path.display())).into());
}
},
};
let net_additional = total_bytes.saturating_sub(existing_bytes);
let mut protected_with_self = protected.clone();
protected_with_self.insert(key);
let evicted = self.evict_lru_to_fit(net_additional, &protected_with_self);
if self.used_bytes.saturating_sub(existing_bytes).saturating_add(total_bytes) > self.max_bytes {
self.stats.over_budget_drops += 1;
return Ok((WriteOutcome::OverBudget, evicted));
}
let header = encode_header(key, self.kvb, generation, kv_bytes, recurrent_state);
let pid = std::process::id();
let nonce = TEMP_NONCE.fetch_add(1, Ordering::Relaxed);
let tmp_path = self.dir.join(key.tmp_filename(pid, nonce));
let write_result = (|| -> io::Result<()> {
let mut opts = OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
opts.mode(0o600).custom_flags(libc::O_NOFOLLOW);
}
let mut file = opts.open(&tmp_path)?;
#[cfg(unix)]
{
file.set_permissions(fs::Permissions::from_mode(0o600))?;
}
enable_nocache(&file);
file.write_all(&header)?;
if std::env::var("INKY_SERVE_ALLOW_FAULT_INJECTION").as_deref() == Ok("1") {
if let Some(marker) = std::env::var_os("INKY_TEST_SPILL_PAUSE_MID_WRITE") {
let marker_path = Path::new(&marker);
if !marker_path.exists() {
let _ = file.flush();
let _ = fs::write(marker_path, tmp_path.to_string_lossy().as_bytes());
std::thread::sleep(std::time::Duration::from_millis(800));
}
}
}
file.write_all(kv_bytes)?;
if !state_slice.is_empty() {
file.write_all(state_slice)?;
}
file.sync_all()?;
drop(file);
fs::rename(&tmp_path, &final_path)?;
fsync_dir(&self.dir)?;
Ok(())
})();
if let Err(e) = write_result {
let _ = fs::remove_file(&tmp_path);
return Err(SpillError::Io(e));
}
if let Some(old) = self.entries.remove(&key) {
self.used_bytes = self.used_bytes.saturating_sub(old.bytes);
}
let seq = self.next_lru();
self.entries.insert(key, DiskEntry { bytes: total_bytes, lru_seq: seq });
self.used_bytes = self.used_bytes.saturating_add(total_bytes);
self.stats.writes_committed += 1;
self.stats.bytes_written = self.stats.bytes_written.saturating_add(total_bytes);
Ok((WriteOutcome::Written { on_disk_bytes: total_bytes }, evicted))
}
pub fn read_block(&mut self, key: SpillKey, expected_kv_len: Option<usize>) -> ReadOutcome {
let raw = read_block_from_dir(&self.dir, self.kvb, key, expected_kv_len);
self.apply_raw_read(key, raw)
}
pub fn apply_raw_read(&mut self, key: SpillKey, raw: RawDiskRead) -> ReadOutcome {
if let Some(file_len) = raw.observed_file_len {
let entry = self.entries.entry(key).or_insert(DiskEntry { bytes: 0, lru_seq: 0 });
self.used_bytes = self.used_bytes.saturating_sub(entry.bytes).saturating_add(file_len);
entry.bytes = file_len;
}
match &raw.outcome {
ReadOutcome::Hit(_) => {
let seq = self.next_lru();
let entry = self.entries.entry(key).or_insert(DiskEntry { bytes: 0, lru_seq: 0 });
entry.lru_seq = seq;
self.stats.reads_hit += 1;
}
ReadOutcome::Miss(reason) => {
if raw.is_corrupt {
self.drop_corrupt(key);
} else {
if *reason == MissReason::NotFound {
self.forget_block(key);
}
self.stats.reads_miss += 1;
}
}
}
raw.outcome
}
pub fn retain_keys(&mut self, keep: &HashSet<SpillKey>) -> usize {
let stale: Vec<SpillKey> = self
.entries
.keys()
.copied()
.filter(|k| !keep.contains(k))
.collect();
let mut removed = 0usize;
for k in stale {
if self.remove_block(k) {
removed += 1;
}
}
removed
}
pub fn write_index_bytes(&self, bytes: &[u8]) -> Result<(), SpillError> {
let final_path = self.dir.join(SPILL_INDEX_FILENAME);
let pid = std::process::id();
let nonce = TEMP_NONCE.fetch_add(1, Ordering::Relaxed);
let tmp_path = self.dir.join(format!("{SPILL_INDEX_TMP_PREFIX}{pid:08x}.{nonce:016x}"));
let res = (|| -> io::Result<()> {
let mut opts = OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
opts.mode(0o600).custom_flags(libc::O_NOFOLLOW);
}
let mut file = opts.open(&tmp_path)?;
#[cfg(unix)]
{
file.set_permissions(fs::Permissions::from_mode(0o600))?;
}
file.write_all(bytes)?;
file.sync_all()?;
drop(file);
fs::rename(&tmp_path, &final_path)?;
fsync_dir(&self.dir)?;
Ok(())
})();
if let Err(e) = res {
let _ = fs::remove_file(&tmp_path);
return Err(SpillError::Io(e));
}
Ok(())
}
pub fn read_index_bytes(&mut self, max_len: usize) -> Option<Vec<u8>> {
let path = self.dir.join(SPILL_INDEX_FILENAME);
let mut opts = OpenOptions::new();
opts.read(true);
#[cfg(unix)]
{
opts.custom_flags(libc::O_NOFOLLOW);
}
let file = match opts.open(&path) {
Ok(f) => f,
Err(e) if e.kind() == io::ErrorKind::NotFound => return None,
Err(_) => {
if matches!(unlink_if_present(&path), Ok(true)) {
self.stats.corrupt_files_removed += 1;
}
return None;
}
};
let meta = match file.metadata() {
Ok(m) if m.is_file() && m.len() <= max_len as u64 => m,
_ => {
drop(file);
if matches!(unlink_if_present(&path), Ok(true)) {
self.stats.corrupt_files_removed += 1;
}
return None;
}
};
let len = meta.len() as usize;
let mut buf = vec![0u8; len];
if pread_exact(&file, &mut buf, 0).is_err() {
drop(file);
if matches!(unlink_if_present(&path), Ok(true)) {
self.stats.corrupt_files_removed += 1;
}
return None;
}
Some(buf)
}
pub fn remove_index(&mut self, count_corrupt: bool) {
let path = self.dir.join(SPILL_INDEX_FILENAME);
if matches!(unlink_if_present(&path), Ok(true)) && count_corrupt {
self.stats.corrupt_files_removed += 1;
}
}
fn drop_corrupt(&mut self, key: SpillKey) {
if matches!(self.unlink_block(key), Ok(true)) {
self.stats.corrupt_files_removed += 1;
}
self.stats.reads_miss += 1;
}
}
#[derive(Debug)]
pub struct RawDiskRead {
pub outcome: ReadOutcome,
pub observed_file_len: Option<u64>,
pub is_corrupt: bool,
}
pub fn read_block_from_dir(
dir: &Path,
kvb: u32,
key: SpillKey,
expected_kv_len: Option<usize>,
) -> RawDiskRead {
#[cfg(test)]
super::run_test_spill_read_hook(dir, key);
let path = dir.join(key.blk_filename());
let mut opts = OpenOptions::new();
opts.read(true);
#[cfg(unix)]
{
opts.custom_flags(libc::O_NOFOLLOW);
}
let file = match opts.open(&path) {
Ok(f) => f,
Err(e) => {
#[cfg(unix)]
if e.raw_os_error() == Some(libc::ELOOP) {
return RawDiskRead {
outcome: ReadOutcome::Miss(MissReason::NotRegularFile),
observed_file_len: None,
is_corrupt: true,
};
}
let reason = if e.kind() == io::ErrorKind::NotFound {
MissReason::NotFound
} else {
MissReason::IoReadError
};
return RawDiskRead {
outcome: ReadOutcome::Miss(reason),
observed_file_len: None,
is_corrupt: false,
};
}
};
enable_nocache(&file);
let meta = match file.metadata() {
Ok(m) => m,
Err(_) => {
return RawDiskRead {
outcome: ReadOutcome::Miss(MissReason::IoReadError),
observed_file_len: None,
is_corrupt: true,
};
}
};
if !meta.is_file() {
return RawDiskRead {
outcome: ReadOutcome::Miss(MissReason::NotRegularFile),
observed_file_len: None,
is_corrupt: true,
};
}
let file_len = meta.len();
let miss_corrupt = |reason: MissReason| RawDiskRead {
outcome: ReadOutcome::Miss(reason),
observed_file_len: Some(file_len),
is_corrupt: true,
};
if file_len < SPILL_HEADER_LEN as u64 {
return miss_corrupt(MissReason::TruncatedHeader);
}
let mut header = [0u8; SPILL_HEADER_LEN];
if pread_exact(&file, &mut header, 0).is_err() {
return miss_corrupt(MissReason::TruncatedHeader);
}
if header[0..8] != SPILL_MAGIC {
return miss_corrupt(MissReason::BadMagic);
}
let version = u32::from_le_bytes(header[8..12].try_into().unwrap());
if version != SPILL_FORMAT_VERSION {
return miss_corrupt(MissReason::UnsupportedVersion);
}
let raw_kind = u32::from(u16::from_le_bytes(header[12..14].try_into().unwrap()));
let Some(kind) = SpillBlockKind::from_u32(raw_kind) else {
return miss_corrupt(MissReason::BadBlockKind);
};
let file_kvb = u32::from(u16::from_le_bytes(header[14..16].try_into().unwrap()));
if file_kvb != kvb {
return miss_corrupt(MissReason::KvbMismatch);
}
let block_id = u64::from_le_bytes(header[16..24].try_into().unwrap());
if kind != key.kind || block_id != key.id {
return miss_corrupt(MissReason::MetadataMismatch);
}
let generation = u64::from_le_bytes(header[24..32].try_into().unwrap());
let kv_len_u64 = u64::from_le_bytes(header[32..40].try_into().unwrap());
let state_len_u64 = u64::from_le_bytes(header[40..48].try_into().unwrap());
let stored_digest: [u8; 32] = header[48..80].try_into().unwrap();
let (Ok(kv_len), Ok(state_len)) = (usize::try_from(kv_len_u64), usize::try_from(state_len_u64)) else {
return miss_corrupt(MissReason::PayloadTooLarge);
};
if kv_len > MAX_KV_PAYLOAD_BYTES || state_len > MAX_RECURRENT_STATE_BYTES {
return miss_corrupt(MissReason::PayloadTooLarge);
}
if let Some(exp) = expected_kv_len {
if kv_len != exp {
return miss_corrupt(MissReason::LengthMismatch);
}
}
let expected_file_len = (SPILL_HEADER_LEN as u64)
.checked_add(kv_len_u64)
.and_then(|v| v.checked_add(state_len_u64));
if expected_file_len != Some(file_len) {
return miss_corrupt(MissReason::SizeMismatch);
}
let mut kv_bytes = vec![0u8; kv_len];
if kv_len > 0 && pread_exact(&file, &mut kv_bytes, SPILL_HEADER_LEN as u64).is_err() {
return miss_corrupt(MissReason::IoReadError);
}
let recurrent_state = if state_len > 0 {
let mut st = vec![0u8; state_len];
let st_off = (SPILL_HEADER_LEN as u64).saturating_add(kv_len_u64);
if pread_exact(&file, &mut st, st_off).is_err() {
return miss_corrupt(MissReason::IoReadError);
}
Some(st)
} else {
None
};
let mut hasher = Sha256::new();
hasher.update(&header[0..HEADER_PREFIX_LEN]);
hasher.update(&kv_bytes);
if let Some(st) = &recurrent_state {
hasher.update(st);
}
let computed = hasher.finalize();
if !ct_eq_32(&computed, &stored_digest) {
return miss_corrupt(MissReason::ChecksumMismatch);
}
RawDiskRead {
outcome: ReadOutcome::Hit(RestoredBlock {
key,
generation,
kv_bytes,
recurrent_state,
}),
observed_file_len: Some(file_len),
is_corrupt: false,
}
}
pub(super) fn prepare_spill_dir(dir: &Path) -> Result<(), SpillError> {
match fs::symlink_metadata(dir) {
Ok(meta) => {
if meta.file_type().is_symlink() {
return Err(SpillError::InvalidDir(format!(
"{} must not be a symlink",
dir.display()
)));
}
if !meta.is_dir() {
return Err(SpillError::InvalidDir(format!(
"{} exists and is not a directory",
dir.display()
)));
}
#[cfg(unix)]
{
let mode = meta.mode() & 0o777;
if mode != 0o700 {
fs::set_permissions(dir, fs::Permissions::from_mode(0o700))?;
}
}
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
let mut builder = fs::DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
{
builder.mode(0o700);
}
builder.create(dir)?;
#[cfg(unix)]
{
fs::set_permissions(dir, fs::Permissions::from_mode(0o700))?;
}
}
Err(e) => return Err(SpillError::Io(e)),
}
Ok(())
}