crates/state/cache/src/index.rs 14.9 KiB 457 lines Raw
1 //! The snapshot and the CRC32C-framed WAL.2 //!3 //! The payload files are the cache; this index is how a restart finds them.4 //! A commit is visible only after its file has been renamed and the WAL record5 //! has reached the disk. A torn WAL tail is ignored and truncated, never6 //! guessed. An unindexed payload file is an orphan and is removed.7 8 use std::collections::BTreeMap;9 use std::fs::{self, File, OpenOptions};10 use std::io::{self, Read, Seek, SeekFrom, Write};11 use std::os::unix::fs::OpenOptionsExt;12 use std::path::Path;13 14 use rustix::fs::OFlags;15 16 use crate::{EntryId, EntryKind, EntryMeta};17 use inf3r_crc32c::crc32c;18 19 const SNAP_MAGIC: &[u8; 8] = b"I3SNAP01";20 const SNAP_VERSION: u32 = 1;21 const RECORD_LIMIT: usize = 64 * 1024 * 1024;22 /// A snapshot larger than this is not a cache index; ignore it instead of23 /// allocating the file. The WAL is bounded the same way.24 const SNAP_LIMIT: u64 = 256 * 1024 * 1024;25 const LOG_LIMIT: u64 = 256 * 1024 * 1024;26 27 /// One durable change.28 #[derive(Clone, Debug)]29 #[allow(clippy::large_enum_variant)]30 pub enum Record {31     Commit(EntryMeta),32     Touch {33         id: EntryId,34         touched: u64,35         hits: u32,36         anchor: bool,37     },38     Pin {39         id: EntryId,40         pinned: bool,41     },42     Evict(EntryId),43     Demote {44         id: EntryId,45         tier: u16,46     },47 }48 49 /// What a scan found, and how much of the log is trustworthy.50 pub struct Recovered {51     pub entries: BTreeMap<EntryId, EntryMeta>,52     pub valid_log: u64,53 }54 55 /// Loads the snapshot and replays the valid prefix of the WAL.56 pub fn recover(dir: &Path) -> Result<Recovered, String> {57     let mut entries = BTreeMap::new();58     let snap = dir.join("index.snap");59     if snap.exists() {60         match read_snapshot_file(&snap) {61             Ok(Some(found)) => entries = found,62             Ok(None) => {}63             Err(why) => eprintln!("cache snapshot ignored: {why}"),64         }65     }66     let log_path = dir.join("index.log");67     let mut log = match OpenOptions::new()68         .read(true)69         .custom_flags(OFlags::NOFOLLOW.bits() as i32)70         .open(&log_path)71     {72         Ok(file) => file,73         Err(why) if why.kind() == io::ErrorKind::NotFound => {74             return Ok(Recovered {75                 entries,76                 valid_log: 0,77             });78         }79         Err(why) => return Err(format!("{}: {why}", log_path.display())),80     };81     let len = log82         .metadata()83         .map_err(|why| format!("{}: {why}", log_path.display()))?84         .len();85     let mut bytes = Vec::new();86     if len > LOG_LIMIT {87         eprintln!(88             "cache WAL {} is {len} bytes; reading at most {LOG_LIMIT}",89             log_path.display()90         );91         log.take(LOG_LIMIT)92             .read_to_end(&mut bytes)93             .map_err(|why| format!("{}: {why}", log_path.display()))?;94     } else {95         log.read_to_end(&mut bytes)96             .map_err(|why| format!("{}: {why}", log_path.display()))?;97     }98     let mut at = 0usize;99     let mut valid = 0u64;100     while at + 8 <= bytes.len() {101         let len =102             u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) as usize;103         if len > RECORD_LIMIT || at + 8 + len > bytes.len() {104             break;105         }106         let expected =107             u32::from_le_bytes([bytes[at + 4], bytes[at + 5], bytes[at + 6], bytes[at + 7]]);108         let payload = &bytes[at + 8..at + 8 + len];109         if crc32c(payload) != expected {110             break;111         }112         let Ok(record) = decode_record(payload) else {113             break;114         };115         apply(&mut entries, record);116         at += 8 + len;117         valid = at as u64;118     }119     Ok(Recovered {120         entries,121         valid_log: valid,122     })123 }124 125 fn read_snapshot_file(path: &Path) -> Result<Option<BTreeMap<EntryId, EntryMeta>>, String> {126     let mut file = OpenOptions::new()127         .read(true)128         .custom_flags(OFlags::NOFOLLOW.bits() as i32)129         .open(path)130         .map_err(|why| format!("{}: {why}", path.display()))?;131     let len = file132         .metadata()133         .map_err(|why| format!("{}: {why}", path.display()))?134         .len();135     if len > SNAP_LIMIT {136         return Err(format!(137             "{} is {len} bytes, above the {SNAP_LIMIT}-byte snapshot limit",138             path.display()139         ));140     }141     let mut bytes = Vec::new();142     file.read_to_end(&mut bytes)143         .map_err(|why| format!("{}: {why}", path.display()))?;144     read_snapshot(&bytes).map(Some)145 }146 147 fn apply(entries: &mut BTreeMap<EntryId, EntryMeta>, record: Record) {148     match record {149         Record::Commit(meta) => {150             entries.insert(meta.id, meta);151         }152         Record::Touch {153             id,154             touched,155             hits,156             anchor,157         } => {158             if let Some(meta) = entries.get_mut(&id) {159                 meta.touched = touched;160                 meta.hits = hits;161                 meta.anchor = anchor || meta.anchor;162             }163         }164         Record::Pin { id, pinned } => {165             if let Some(meta) = entries.get_mut(&id) {166                 meta.pinned = pinned;167             }168         }169         Record::Evict(id) => {170             entries.remove(&id);171         }172         Record::Demote { id, tier } => {173             if let Some(meta) = entries.get_mut(&id) {174                 meta.tier = tier;175             }176         }177     }178 }179 180 /// Appends one record and makes it durable.181 pub fn append(log: &mut File, record: &Record) -> Result<(), String> {182     let payload = encode_record(record);183     let crc = crc32c(&payload);184     let len = u32::try_from(payload.len()).map_err(|_| "a WAL record is too large")?;185     log.seek(SeekFrom::End(0))186         .map_err(|why| format!("WAL seek: {why}"))?;187     log.write_all(&len.to_le_bytes())188         .and_then(|()| log.write_all(&crc.to_le_bytes()))189         .and_then(|()| log.write_all(&payload))190         .and_then(|()| log.sync_data())191         .map_err(|why| format!("WAL write: {why}"))192 }193 194 /// Writes a new snapshot and empties the WAL.195 ///196 /// The snapshot is written to a temp file, fsynced, and renamed. A crash at any197 /// point leaves either the old snapshot+WAL or the new snapshot and an empty198 /// WAL; it never leaves a half-readable snapshot with a truncated log.199 pub fn compact(200     dir: &Path,201     entries: &BTreeMap<EntryId, EntryMeta>,202     log: &mut File,203 ) -> Result<(), String> {204     let bytes = write_snapshot(entries);205     let tmp = dir.join("index.snap.tmp");206     let target = dir.join("index.snap");207     {208         let mut file = OpenOptions::new()209             .write(true)210             .create(true)211             .truncate(true)212             .mode(0o600)213             .custom_flags(OFlags::NOFOLLOW.bits() as i32)214             .open(&tmp)215             .map_err(|why| format!("{}: {why}", tmp.display()))?;216         file.write_all(&bytes)217             .and_then(|()| file.sync_all())218             .map_err(|why| format!("{}: {why}", tmp.display()))?;219     }220     fs::rename(&tmp, &target).map_err(|why| format!("{}: {why}", target.display()))?;221     if let Ok(dir_file) = File::open(dir) {222         let _ = dir_file.sync_all();223     }224     log.set_len(0)225         .map_err(|why| format!("WAL truncate: {why}"))?;226     log.seek(SeekFrom::Start(0))227         .map_err(|why| format!("WAL seek: {why}"))?;228     log.sync_all().map_err(|why| format!("WAL sync: {why}"))?;229     Ok(())230 }231 232 fn write_snapshot(entries: &BTreeMap<EntryId, EntryMeta>) -> Vec<u8> {233     let mut out = Vec::new();234     out.extend_from_slice(SNAP_MAGIC);235     out.extend_from_slice(&SNAP_VERSION.to_le_bytes());236     out.extend_from_slice(&(entries.len() as u64).to_le_bytes());237     for meta in entries.values() {238         let body = encode_meta(meta);239         out.extend_from_slice(&(body.len() as u32).to_le_bytes());240         out.extend_from_slice(&body);241     }242     let crc = crc32c(&out);243     out.extend_from_slice(&crc.to_le_bytes());244     out245 }246 247 fn read_snapshot(bytes: &[u8]) -> Result<BTreeMap<EntryId, EntryMeta>, String> {248     if bytes.len() < 8 + 4 + 8 + 4 || &bytes[..8] != SNAP_MAGIC {249         return Err("not an inf3r cache snapshot".into());250     }251     let version = u32::from_le_bytes(bytes[8..12].try_into().unwrap());252     if version != SNAP_VERSION {253         return Err(format!("snapshot version {version} is not {SNAP_VERSION}"));254     }255     let body_end = bytes.len() - 4;256     let expected = u32::from_le_bytes(bytes[body_end..].try_into().unwrap());257     if crc32c(&bytes[..body_end]) != expected {258         return Err("snapshot CRC32C mismatch".into());259     }260     let count = u64::from_le_bytes(bytes[12..20].try_into().unwrap());261     let mut at = 20usize;262     let mut entries = BTreeMap::new();263     for _ in 0..count {264         if at + 4 > body_end {265             return Err("snapshot ended inside a record header".into());266         }267         let len = u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) as usize;268         at += 4;269         if at + len > body_end {270             return Err("snapshot ended inside a record".into());271         }272         let meta = decode_meta(&bytes[at..at + len])?;273         at += len;274         entries.insert(meta.id, meta);275     }276     if at != body_end {277         return Err("snapshot has bytes after its last record".into());278     }279     Ok(entries)280 }281 282 fn encode_record(record: &Record) -> Vec<u8> {283     let mut out = Vec::new();284     match record {285         Record::Commit(meta) => {286             out.push(1);287             out.extend_from_slice(&encode_meta(meta));288         }289         Record::Touch {290             id,291             touched,292             hits,293             anchor,294         } => {295             out.push(2);296             out.extend_from_slice(id);297             out.extend_from_slice(&touched.to_le_bytes());298             out.extend_from_slice(&hits.to_le_bytes());299             out.push(u8::from(*anchor));300         }301         Record::Pin { id, pinned } => {302             out.push(3);303             out.extend_from_slice(id);304             out.push(u8::from(*pinned));305         }306         Record::Evict(id) => {307             out.push(4);308             out.extend_from_slice(id);309         }310         Record::Demote { id, tier } => {311             out.push(5);312             out.extend_from_slice(id);313             out.extend_from_slice(&tier.to_le_bytes());314         }315     }316     out317 }318 319 fn decode_record(bytes: &[u8]) -> Result<Record, String> {320     let (&tag, rest) = bytes.split_first().ok_or("empty WAL record")?;321     match tag {322         1 => Ok(Record::Commit(decode_meta(rest)?)),323         2 => {324             let id = array(rest, 0)?;325             let touched = u64::from_le_bytes(array(rest, 32)?);326             let hits = u32::from_le_bytes(array(rest, 40)?);327             let anchor = *rest.get(44).ok_or("short touch record")? != 0;328             Ok(Record::Touch {329                 id,330                 touched,331                 hits,332                 anchor,333             })334         }335         3 => {336             let id = array(rest, 0)?;337             Ok(Record::Pin {338                 id,339                 pinned: *rest.get(32).ok_or("short pin record")? != 0,340             })341         }342         4 => Ok(Record::Evict(array(rest, 0)?)),343         5 => Ok(Record::Demote {344             id: array(rest, 0)?,345             tier: u16::from_le_bytes(array(rest, 32)?),346         }),347         other => Err(format!("unknown WAL record {other}")),348     }349 }350 351 fn encode_meta(meta: &EntryMeta) -> Vec<u8> {352     let mut out = Vec::new();353     out.extend_from_slice(&meta.id);354     out.extend_from_slice(&meta.key);355     out.extend_from_slice(&meta.fingerprint);356     out.extend_from_slice(&meta.bytes.to_le_bytes());357     out.extend_from_slice(&meta.allocated.to_le_bytes());358     out.extend_from_slice(&meta.crc32c.to_le_bytes());359     out.extend_from_slice(&meta.created.to_le_bytes());360     out.extend_from_slice(&meta.touched.to_le_bytes());361     out.extend_from_slice(&meta.expires.to_le_bytes());362     out.extend_from_slice(&meta.token_count.to_le_bytes());363     out.extend_from_slice(&meta.prefill_ms.to_le_bytes());364     out.extend_from_slice(&meta.hits.to_le_bytes());365     out.extend_from_slice(&meta.tier.to_le_bytes());366     out.push(match meta.kind {367         EntryKind::Tip => 0,368         EntryKind::Anchor => 1,369     });370     out.extend_from_slice(&meta.lineage.unwrap_or([0; 32]));371     out.extend_from_slice(&meta.supersedes.unwrap_or([0; 32]));372     out.push(u8::from(meta.pinned));373     out.push(u8::from(meta.anchor));374     out.push(u8::from(meta.lineage.is_some()));375     out.push(u8::from(meta.supersedes.is_some()));376     let bundle = meta.bundle.as_bytes();377     out.extend_from_slice(&(bundle.len() as u16).to_le_bytes());378     out.extend_from_slice(bundle);379     out380 }381 382 fn decode_meta(bytes: &[u8]) -> Result<EntryMeta, String> {383     let id = array(bytes, 0)?;384     let key = array(bytes, 32)?;385     let fingerprint = array(bytes, 64)?;386     let bytes_used = u64::from_le_bytes(array(bytes, 96)?);387     let allocated = u64::from_le_bytes(array(bytes, 104)?);388     let crc32c = u32::from_le_bytes(array(bytes, 112)?);389     let created = u64::from_le_bytes(array(bytes, 116)?);390     let touched = u64::from_le_bytes(array(bytes, 124)?);391     let expires = u64::from_le_bytes(array(bytes, 132)?);392     let token_count = u64::from_le_bytes(array(bytes, 140)?);393     let prefill_ms = u64::from_le_bytes(array(bytes, 148)?);394     let hits = u32::from_le_bytes(array(bytes, 156)?);395     let tier = u16::from_le_bytes(array(bytes, 160)?);396     let kind = match *bytes.get(162).ok_or("short entry")? {397         0 => EntryKind::Tip,398         1 => EntryKind::Anchor,399         other => return Err(format!("unknown entry kind {other}")),400     };401     let lineage_raw = array::<32>(bytes, 163)?;402     let supersedes_raw = array::<32>(bytes, 195)?;403     let pinned = *bytes.get(227).ok_or("short entry")? != 0;404     let anchor = *bytes.get(228).ok_or("short entry")? != 0;405     let has_lineage = *bytes.get(229).ok_or("short entry")? != 0;406     let has_supersedes = *bytes.get(230).ok_or("short entry")? != 0;407     let bundle_len = u16::from_le_bytes(array::<2>(bytes, 231)?) as usize;408     let bundle_start = 233usize;409     let bundle_end = bundle_start410         .checked_add(bundle_len)411         .ok_or("entry bundle length overflow")?;412     let bundle = std::str::from_utf8(413         bytes414             .get(bundle_start..bundle_end)415             .ok_or("short entry bundle")?,416     )417     .map_err(|_| "entry bundle is not UTF-8")?418     .to_string();419     Ok(EntryMeta {420         id,421         key,422         fingerprint,423         bundle,424         kind,425         lineage: has_lineage.then_some(lineage_raw),426         supersedes: has_supersedes.then_some(supersedes_raw),427         bytes: bytes_used,428         allocated,429         crc32c,430         created,431         touched,432         expires,433         token_count,434         prefill_ms,435         pinned,436         hits,437         anchor,438         tier,439     })440 }441 442 fn array<const N: usize>(bytes: &[u8], at: usize) -> Result<[u8; N], String> {443     bytes444         .get(at..at + N)445         .ok_or_else(|| "short record".to_string())?446         .try_into()447         .map_err(|_| "short record".to_string())448 }449 450 /// Removes a payload file, ignoring an already-gone file.451 pub fn unlink(path: &Path) -> io::Result<()> {452     match fs::remove_file(path) {453         Ok(()) => Ok(()),454         Err(why) if why.kind() == io::ErrorKind::NotFound => Ok(()),455         Err(why) => Err(why),456     }457 }