//! The persistent index cache: what a previous session's parse of a file //! found, kept on disk so reopening a workspace does not start from zero. //! //! One entry is one file's [`FileFacts`] — everything that file contributes to //! the workspace index — under the FNV-1a hash of the exact bytes those facts //! were read from. A hit therefore *is* the parse: the index built from a //! record and the index built from the file are the same index, which the //! `vlog_semantic` tests pin directly. A miss, a corrupt record, a record from //! another version: all of them mean "parse the file", which is what the //! server did before this existed. //! //! **The cache is a performance artifact and never a correctness input.** It //! is keyed on content and only on content — never on a timestamp — so a //! record can only ever be used for the bytes it was written from, and every //! record carries a checksum of its own fields, so a record damaged after it //! was written is dropped rather than served. Every failure mode is silent //! and costs work, never answers, exactly as `lucisv_core::cache` (the //! formatter's store, whose shape this follows) decided for the same reasons. //! //! The one thing neither check is: a defence against a store somebody edited //! *on purpose*. The checksum is a plain FNV-1a, not a keyed MAC, so a forger //! recomputes it — and anything that can write here can write the source files //! this index describes. That threat model (same user, same disk) is stated in //! `docs/features/index-persistence/README.md` and is the same one //! `lucisv_core::cache` accepts. use std::cell::Cell; use std::collections::HashMap; use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::{Path, PathBuf}; use std::time::Instant; use lucisv_core::cache::content_hash; use vlog_semantic::{record_path, FileFacts, FACTS_FORMAT}; use crate::scan_trace::CacheWork; use crate::settings::ClientSettings; /// The store inside the cache directory. const FILE: &str = "index-cache"; /// The version of *this* file's framing — the header line, the per-record /// line, the hash field, the per-record checksum. Bumped alongside /// `vlog_semantic::FACTS_FORMAT`, which versions what a record holds; a store /// stamped with either number the current build does not write is discarded /// whole. **2**: every record gained a checksum of its own facts field. const CACHE_FORMAT: u32 = 2; /// lucisv's version, part of the header: a new release can parse the same /// bytes into different facts, so another version's store is not read. const VERSION: &str = env!("CARGO_PKG_VERSION"); /// The subdirectory of the OS cache directory this server's stores live in. const OS_DIR: [&str; 2] = ["lucisv", "index"]; /// What one load of the store found — the numbers that decide whether the file /// on disk is *already* the file a compaction would write. /// /// [`IndexCache::render`] writes this build's header and then one line per /// path in path order, so a store this build compacted and nothing has /// appended to since comes back with every line kept, no line dropped, no path /// named twice and the paths ascending. Anything else — another version's /// header, a torn line, a record the checksum rejects, two lines for one path, /// a session's appends still unvacuumed — means the file and the render differ, /// and compaction is what makes them the same. #[derive(Clone, Copy, Default)] struct Load { /// Whether the first line was this build's own header. header: bool, /// Record lines the store held below the header. read: usize, /// Of those, the ones that became an entry of their own. kept: usize, /// Lines that were not a record this build can use. dropped: usize, /// Lines naming a path an earlier line had already named. duplicates: usize, /// Whether the paths arrived strictly ascending, the order `render` writes /// them in. ordered: bool, } impl Load { /// Whether these lines are exactly the lines [`IndexCache::render`] would /// write from the entries they produced. fn canonical(&self) -> bool { self.header && self.ordered && self.dropped == 0 && self.duplicates == 0 && self.kept == self.read } } /// What one entry asserts: a file with exactly this content contributed /// exactly these facts. struct Entry { /// FNV-1a hash of the bytes the facts were read from. content: u64, /// The facts, still encoded — decoded only for the files actually asked /// for, and written back out verbatim when the store is compacted. facts: String, } /// The index cache for one workspace: loaded when a rescan starts, appended to /// as the rescan parses files, rewritten when it ends. #[derive(Default)] pub struct IndexCache { /// Where the store lives; `None` when persistence is off, which makes /// every operation below a no-op. dir: Option, entries: HashMap, /// The append handle, opened on the first write of a session. log: Option, /// Whether the file on disk already carried *our* header when it was read. /// False for a missing store — which the first write claims — and for one /// from another version, which the first write replaces wholesale. header_ok: bool, /// What [`IndexCache::open`] read out of the store, which is what /// [`IndexCache::already_compact`] asks whether a rewrite would reproduce. load: Load, /// What this cache's own work has cost since it was opened, for the /// startup breakdown (`docs/features/perf5-p4/README.md`). /// /// A `Cell` because [`IndexCache::facts_for`] is a `&self` read and the /// hash/decode split is exactly the number §P4a needed. Counted whether /// anything is going to read it or not: four clock reads per file are /// noise beside the decode they bracket, and a flag threaded down here to /// save them would cost more code than time. work: Cell, } impl IndexCache { /// A cache that reads nothing and writes nothing — `lucisv.index.persist` /// off, or no directory to write in. pub fn disabled() -> IndexCache { IndexCache::default() } /// The cache stored in `dir`. Never fails: a missing, unreadable or /// corrupt store simply yields an empty cache that the rescan refills. /// /// A store whose header is not this version's is dropped **whole** — not /// entry by entry. The header names the two format numbers and the /// release, and any of them differing means the records below were written /// by code that is not this code. /// /// The store is read as *bytes* and decoded a line at a time, so a file /// whose tail was cut inside a multi-byte character costs the record that /// was torn and no other. Reading the whole buffer as text would have /// rejected all of it for one bad byte at the end. /// /// The load is *counted* as well as performed — lines read, kept, dropped /// and duplicated, and whether the paths arrived in order — because those /// five numbers are what say whether the file already is what /// [`IndexCache::compact`] would write over it. pub fn open(dir: Option) -> IndexCache { let Some(dir) = dir else { return IndexCache::disabled() }; let bytes = std::fs::read(dir.join(FILE)).unwrap_or_default(); let mut lines = store_lines(&bytes).into_iter(); let header_ok = lines.next() == Some(header().as_bytes()); let mut entries = HashMap::new(); let mut load = Load { header: header_ok, ordered: true, ..Load::default() }; if header_ok { let mut previous: Option = None; for line in lines { load.read += 1; let Ok(line) = std::str::from_utf8(line) else { load.dropped += 1; continue; }; let Some((path, entry)) = parse_entry(line) else { load.dropped += 1; continue; }; if let Some(previous) = &previous { load.ordered &= *previous < path; } previous = Some(path.clone()); // A later record for a path wins: the log is appended to // as a rescan goes, so the last one written is the one // that describes the file as the server last saw it. match entries.insert(path, entry) { Some(_) => load.duplicates += 1, None => load.kept += 1, } } } let work = Cell::new(CacheWork { opens: 1, ..CacheWork::default() }); IndexCache { dir: Some(dir), entries, log: None, header_ok, load, work } } /// What this cache has spent and moved since it was opened. pub fn work(&self) -> CacheWork { self.work.get() } /// How many records this cache is holding. pub fn entry_count(&self) -> usize { self.entries.len() } /// The encoded bytes those records weigh — the retention §P4's memory /// hypothesis is about, since every one of them sits beside a decoded /// copy in the workspace index. pub fn encoded_bytes(&self) -> usize { self.entries.values().map(|entry| entry.facts.len()).sum() } /// Where this cache writes. Test-only: production opens a cache from a /// directory it just worked out and never asks it back. #[cfg(test)] pub fn dir(&self) -> Option<&Path> { self.dir.as_deref() } /// The entry that asserts *exactly these bytes*, if there is one. /// /// The one place the record and the key it is filed under are read /// together: an entry holds the FNV-1a of the bytes its facts were read /// off, and this is the only comparison anything in the server makes /// against it. Both readers below go through here, so "the store answers /// for this text" means one thing in a scan and in a refactoring alike. fn entry_for(&self, path: &Path, text: &str) -> Option<&Entry> { self.entries.get(path).filter(|entry| entry.content == content_hash(text.as_bytes())) } /// [`IndexCache::facts_for`] asked by something that is **not** a scan. /// /// The same question, the same entry, the same answer — but the work is /// not counted into [`IndexCache::work`], because that counter is what a /// scan's own trace subtracts to say what *it* did. A refactoring reading /// records between two scans would otherwise show up as decodes the next /// scan never made (review round §R3b, `crate::state::Workspace::known_facts`). pub fn facts_now(&self, path: &Path, text: &str) -> Option { FileFacts::decode(&self.entry_for(path, text)?.facts) } /// The facts a previous session read off this exact text, if it did. /// /// The hash is of the text the server is about to index — an open buffer's /// when there is one, the file's bytes otherwise — so a hit means the /// record was written from these very bytes. A record that no longer /// decodes is a miss, silently: the file is parsed, and the fresh record /// replaces it. So is a record whose fields no longer match the checksum /// they were written with, which [`IndexCache::open`] drops before it ever /// gets here. pub fn facts_for(&self, path: &Path, text: &str) -> Option { let looking = Instant::now(); let found = self.entry_for(path, text); let mut work = self.work.get(); work.lookup_ns += elapsed_ns(looking); let Some(entry) = found else { work.misses += 1; self.work.set(work); return None; }; let decoding = Instant::now(); let facts = FileFacts::decode(&entry.facts); work.decode_ns += elapsed_ns(decoding); work.decoded_bytes += entry.facts.len(); // A record that no longer decodes costs a parse, so it is a miss — // the counters say what the scan actually did, not what it looked up. match facts.is_some() { true => work.hits += 1, false => work.misses += 1, } self.work.set(work); facts } /// Record what parsing `text` found, and write it through immediately. /// /// One `write` per file, appended: a session that is killed mid-scan /// leaves every file it had already parsed in the store, and at worst a /// final line without its newline — which [`IndexCache::open`] does not /// read, because `parse_entry` rejects it (a truncated record cannot carry /// the checksum of the facts it was written with) for the same reasons it /// rejects any other malformed record. That is the whole crash-safety /// argument, and it is why records are one line each. /// /// **A record the store already holds is not written again.** An open /// buffer is indexed from its own analysis on every scan and its record is /// written through with it, so a warm session appends a line for every /// open buffer that is byte-identical to the line already in the store — /// a duplicate the next load collapses, at the price of making the store /// non-canonical and so owing [`IndexCache::compact`] a full rewrite. The /// test is the exact one: same path, same content hash, same encoded /// facts. Anything that differs by a byte is a new record and is appended /// as it always was. pub fn record(&mut self, facts: &FileFacts, text: &str) { if self.dir.is_none() { return; } let encoding = Instant::now(); let Some(encoded) = facts.encode() else { return }; let content = content_hash(text.as_bytes()); let mut work = self.work.get(); work.encode_ns += elapsed_ns(encoding); if self.holds(facts.path(), content, &encoded) { work.repeats += 1; self.work.set(work); return; } let writing = Instant::now(); self.append(&line(content, &encoded)); work.write_ns += elapsed_ns(writing); work.records += 1; work.written_bytes += encoded.len(); self.work.set(work); self.entries.insert(facts.path().to_path_buf(), Entry { content, facts: encoded }); } /// Rewrite the store from what is held now: the header, then one line per /// entry, sorted by path. /// /// Called when a whole rescan ends, which is the one moment the live set /// of entries is known. It is what stops the append log growing forever — /// a path edited a thousand times has a thousand lines and one entry — /// and it drops entries whose file is gone, the way /// `lucisv_core::cache::store` does. /// /// Atomic and silent: written to a temporary file and renamed, and a /// failure anywhere leaves the previous store standing. A cache that could /// fail a rescan would be worse than no cache. /// /// **Skipped when the rewrite would reproduce the file byte for byte** /// ([`IndexCache::already_compact`]). A warm session whose every file hit /// the store appends nothing, so the store it loaded is the store it would /// write, and rewriting 44 MiB to produce the same 44 MiB was 182 ms of a /// 1.33 s start (`docs/features/perf5-p4/README.md`, §P4b (a)). pub fn compact(&mut self) { let before = self.store_bytes(); let compacting = Instant::now(); let rewriting = !self.already_compact(); if rewriting { self.compact_now(); } let mut work = self.work.get(); work.compact_ns += elapsed_ns(compacting); work.compactions += usize::from(rewriting); work.store_before = before; work.store_after = self.store_bytes(); self.work.set(work); } /// Whether the store on disk is already exactly what [`IndexCache::render`] /// would write over it. /// /// Four things have to hold, and any one of them failing compacts as /// before: /// /// * the store was **loaded canonical** — this build's header, every line /// a record this build can read, no path named twice, the paths /// ascending ([`Load::canonical`]); /// * **nothing has been appended since**, so no line is out of order and /// no path has a second one; /// * **no entry's file is gone**, because `render` drops those; /// * there is a directory to write in at all. /// /// **Crash safety is untouched.** A session that appended nothing left the /// store exactly as it found it, so what is on disk is already the /// compacted file and there is no half-written state a rewrite would /// resolve; skipping it only means the append log — which has no appends — /// stays as it is. The existence sweep is the one part that costs /// anything, one `stat` per entry, against the whole-store render and /// write it stands in for. fn already_compact(&self) -> bool { self.dir.is_some() && self.load.canonical() && self.work.get().records == 0 && self.entries.keys().all(|path| path.exists()) } /// Whether the store already holds exactly this record — the same path, /// the same content hash and the same encoded facts, byte for byte. /// /// Only exactly that counts. A record whose facts differ by a byte under /// the same hash is still written, because the line on disk and the facts /// in hand would then disagree and the store must say what this session /// last saw. fn holds(&self, path: &Path, content: u64, encoded: &str) -> bool { self.entries .get(path) .is_some_and(|entry| entry.content == content && entry.facts == encoded) } /// The store file's size on disk, or 0 when there is no store. fn store_bytes(&self) -> u64 { let Some(dir) = self.dir.as_ref() else { return 0 }; std::fs::metadata(dir.join(FILE)).map(|meta| meta.len()).unwrap_or_default() } /// [`IndexCache::compact`] without the accounting around it. fn compact_now(&mut self) { let Some(dir) = self.dir.clone() else { return }; // The append handle must go before the rename, or a later append would // write into the file the rename replaced. self.log = None; if std::fs::create_dir_all(&dir).is_err() { return; } // Self-ignoring, the way `lucisv_core::cache` marks its own directory: // a cache path inside the project is a plausible thing for a user to // ask for. let ignore = dir.join(".gitignore"); if !ignore.exists() { let _ = std::fs::write(&ignore, "*\n"); } let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id())); let store = dir.join(FILE); if std::fs::write(&tmp, self.render()).is_ok() { if std::fs::rename(&tmp, &store).is_err() { let _ = std::fs::remove_file(&tmp); return; } self.header_ok = true; } } /// The store's text: the header, then the live entries in path order, so /// two sessions over the same workspace write byte-identical stores. fn render(&self) -> String { let mut paths: Vec<&PathBuf> = self.entries.keys().collect(); paths.sort(); let mut text = header(); text.push('\n'); for path in paths { if !path.exists() { continue; } let entry = &self.entries[path]; text.push_str(&line(entry.content, &entry.facts)); text.push('\n'); } text } /// Append one record, opening the store on the first write of a session. fn append(&mut self, record: &str) { if self.log.is_none() { self.log = self.open_log(); } if let Some(file) = &mut self.log { // One `write_all` per record — not `writeln!`, whose formatting // machinery is free to split one line across two writes — so a // record a second server appends can never land inside ours, and // a torn record can only ever be the last. let _ = file.write_all(format!("{record}\n").as_bytes()); } } /// The append handle for this session, opened on its first write. /// /// A store this session already read a header out of is appended to. A /// store that is not there yet is *claimed* with `File::create_new`, which /// fails rather than truncating when another session made it first — so /// two servers cold-starting on one directory can no longer both decide /// they are the first and erase each other's records. Whoever loses finds /// the winner's header and appends under it. fn open_log(&mut self) -> Option { let dir = self.dir.clone()?; if std::fs::create_dir_all(&dir).is_err() { return None; } let path = dir.join(FILE); if !self.header_ok { claim(&path)?; self.header_ok = true; } OpenOptions::new().create(true).append(true).open(&path).ok() } } /// What is at the top of the store on disk right now. enum Header { /// This build's header, whoever wrote it. Ours, /// Nothing at all — a store claimed a moment ago, before its header. Empty, /// A whole first line that is not ours: another build's store, or junk. Foreign, } /// Put this build's header at the top of the store, whoever gets there first. /// /// `create_new` is the race fix, and the three shapes below are everything a /// session that lost the claim can find. fn claim(path: &Path) -> Option<()> { // Ignored on purpose: whether this session made the file or another one // did, what happens next is decided by what is in it. let _ = File::create_new(path); match settled_header(path) { // Ours, or the winner's — the same bytes either way. Header::Ours => Some(()), // Empty is the file one of us just made, caught before its header. // Both sessions want the identical line and each writes it with one // append, so the worst case is a duplicate header line — a record the // reader drops, not a store anybody loses. Header::Empty => append_line(path, &header()), // Truncation is left for the one case it is still right for: a header // this build cannot read, whose records were already dropped at load. // Appending under it would throw ours away at the next load too. Header::Foreign => replace_with_header(path), } } /// The store's first line, as one of the three answers [`claim`] acts on. fn settled_header(path: &Path) -> Header { let Ok(bytes) = std::fs::read(path) else { return Header::Foreign }; if bytes.is_empty() { return Header::Empty; } match store_lines(&bytes).first() { Some(first) if *first == header().as_bytes() => Header::Ours, _ => Header::Foreign, } } /// Append one whole line, creating the store if it is not there. fn append_line(path: &Path, line: &str) -> Option<()> { let mut file = OpenOptions::new().create(true).append(true).open(path).ok()?; file.write_all(format!("{line}\n").as_bytes()).ok() } /// Replace the store with nothing but this build's header. fn replace_with_header(path: &Path) -> Option<()> { let mut file = OpenOptions::new().create(true).write(true).truncate(true).open(path).ok()?; file.write_all(format!("{}\n", header()).as_bytes()).ok() } /// The store's lines, as bytes — exactly what `str::lines` yields, without /// asking the whole file to be valid UTF-8 first. fn store_lines(bytes: &[u8]) -> Vec<&[u8]> { let body = bytes.strip_suffix(b"\n").unwrap_or(bytes); if body.is_empty() { return Vec::new(); } body.split(|byte| *byte == b'\n').map(|line| line.strip_suffix(b"\r").unwrap_or(line)).collect() } /// The first line of the store: what wrote it, in what format, in what /// version. Anything else and the file is not read at all. fn header() -> String { format!("lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t{VERSION}") } /// One record: the content hash, the encoded facts (whose own first field is /// the path), and a checksum of exactly those encoded facts. /// /// The checksum is what makes a record damaged *after* it was written — bit /// rot, a torn interleaved append, an editor that rewrote the file's line /// endings — a dropped record rather than a served one, which is the whole /// difference between "never a correctness input" as a hope and as a /// property. It is a plain FNV-1a and not a keyed MAC, so it is no defence /// against a store edited on purpose; that is the threat model, not an /// oversight (see the feature README). fn line(content: u64, facts: &str) -> String { format!("{content:016x}\t{facts}\t{:016x}", content_hash(facts.as_bytes())) } /// One record read back — the hash and the path, with the facts left encoded. /// `None` for anything that is not a whole record whose facts still match /// their checksum, which includes the torn last line of a store whose writer /// was killed. /// Nanoseconds since `from`, saturated into the counters' `u64`. fn elapsed_ns(from: Instant) -> u64 { from.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64 } fn parse_entry(line: &str) -> Option<(PathBuf, Entry)> { let (hash, rest) = line.split_once('\t')?; // Exactly as wide as `line` writes it: a hash that reads as a number but // was written by something else is not this format's hash. if hash.len() != 16 { return None; } let content = u64::from_str_radix(hash, 16).ok()?; // The facts run to the last tab and the field after it is their checksum: // no encoded field can hold a raw tab, so the split is unambiguous. let (facts, checksum) = rest.rsplit_once('\t')?; if checksum.len() != 16 || u64::from_str_radix(checksum, 16).ok()? != content_hash(facts.as_bytes()) { return None; } let path = record_path(facts)?; Some((path, Entry { content, facts: facts.to_string() })) } /// Where this workspace's store lives, highest rung first: /// /// 1. **`lucisv.index.cachePath`** — the user said where, absolute or relative /// to the first workspace root, exactly as `lucisv.filelist` is read. /// 2. **`initializationOptions.storagePath`** — the editor said where. The /// VS Code extension passes its own workspace storage folder, which is /// per-workspace, is cleaned up when the workspace is forgotten, and is /// the answer for the overwhelmingly common case. /// 3. **The OS cache directory**, under `lucisv/index/` — for /// every other client, keyed by a hash of what this session is a session /// *of*: its workspace roots, or its filelist when it has no roots. /// 4. **Nowhere**, and then the index lives only in memory, exactly as it did /// before this feature: `lucisv.index.persist` off, no writable cache /// directory, or a rootless session with no filelist and no editor storage, /// which has no stable identity to key a store on. pub fn cache_dir( settings: &ClientSettings, storage: Option<&Path>, roots: &[PathBuf], filelist: Option<&Path>, ) -> Option { if !settings.index_persist { return None; } if let Some(configured) = settings.index_cache_path.as_deref() { let path = Path::new(configured); return Some(match roots.first() { Some(root) if path.is_relative() => root.join(path), _ => path.to_path_buf(), }); } if let Some(storage) = storage { return Some(storage.to_path_buf()); } let mut dir = os_cache_dir()?; for part in OS_DIR { dir.push(part); } Some(dir.join(workspace_key(roots, filelist)?)) } /// What this session is a session of, as one filename-safe word. /// /// The roots decide it — sorted, so the same workspace opened with its folders /// in another order is the same workspace — and a rootless session with a /// filelist is identified by the filelist, which is the project file. A /// session with neither has nothing stable to be keyed by: its scope is /// whatever single file the user opened, and it gets no store. fn workspace_key(roots: &[PathBuf], filelist: Option<&Path>) -> Option { let identity = if roots.is_empty() { filelist?.to_string_lossy().into_owned() } else { let mut sorted: Vec = roots.iter().map(|root| root.to_string_lossy().into_owned()).collect(); sorted.sort(); sorted.join("\n") }; Some(format!("{:016x}", content_hash(identity.as_bytes()))) } /// This platform's cache directory, hand-rolled from the two environment /// variables that define it. No dependency for three lines of `var_os`, and /// nothing is created here — the caller creates what it writes in. fn os_cache_dir() -> Option { #[cfg(target_os = "macos")] { std::env::var_os("HOME").map(|home| PathBuf::from(home).join("Library/Caches")) } #[cfg(windows)] { std::env::var_os("LOCALAPPDATA").map(PathBuf::from) } #[cfg(all(not(target_os = "macos"), not(windows)))] { std::env::var_os("XDG_CACHE_HOME") .map(PathBuf::from) .filter(|dir| dir.is_absolute()) .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache"))) } } #[cfg(test)] mod tests { use super::*; /// A throwaway directory, removed on drop — the same shape /// `lucisv_core::cache`'s tests use. struct TempDir { path: PathBuf, } impl TempDir { fn new(tag: &str) -> TempDir { use std::sync::atomic::{AtomicUsize, Ordering}; static COUNTER: AtomicUsize = AtomicUsize::new(0); let n = COUNTER.fetch_add(1, Ordering::Relaxed); let path = std::env::temp_dir() .join(format!("lucisv-index-cache-{}-{tag}-{n}", std::process::id())); let _ = std::fs::remove_dir_all(&path); std::fs::create_dir_all(&path).expect("create temp dir"); TempDir { path } } /// A source file on disk, so `render`'s existence check keeps its /// entry. fn file(&self, name: &str, text: &str) -> PathBuf { let path = self.path.join(name); std::fs::write(&path, text).expect("write file"); path } fn store_text(&self) -> String { std::fs::read_to_string(self.path.join(FILE)).expect("read store") } } impl Drop for TempDir { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.path); } } const M: &str = "module m;\n sub u ();\nendmodule\n"; fn facts(path: &Path, text: &str) -> FileFacts { FileFacts::of(path.to_path_buf(), text) } #[test] fn a_record_written_in_one_session_is_read_in_the_next() { let dir = TempDir::new("roundtrip"); let file = dir.file("m.sv", M); let mut cache = IndexCache::open(Some(dir.path.clone())); assert!(cache.facts_for(&file, M).is_none(), "an empty store answers nothing"); cache.record(&facts(&file, M), M); cache.compact(); let reopened = IndexCache::open(Some(dir.path.clone())); assert_eq!(reopened.facts_for(&file, M), Some(facts(&file, M))); // The content is the whole key: the same path with other bytes is a // miss, and so is another path. assert!(reopened.facts_for(&file, "module m; endmodule\n").is_none()); assert!(reopened.facts_for(Path::new("/nowhere.sv"), M).is_none()); } /// **The R3b tie, both ways.** `facts_now` is the same content key /// `facts_for` is — a record answers for the bytes it was read off and for /// no others — and it leaves the scan's own work counters alone. /// /// The stale case is the one that matters: a record written from one text /// must never be handed to a refactoring reading a different text, because /// the refactoring would index it as that file's facts and edit against an /// index describing bytes nobody has. #[test] fn a_request_local_read_answers_for_these_bytes_and_counts_as_no_scan_work() { let dir = TempDir::new("factsnow"); let file = dir.file("m.sv", M); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.record(&facts(&file, M), M); cache.compact(); let reopened = IndexCache::open(Some(dir.path.clone())); let before = reopened.work(); assert_eq!(reopened.facts_now(&file, M), Some(facts(&file, M)), "these bytes"); // Every way the bytes can differ, and the wrong path too. const EDITED: &str = "module m;\n sub u ();\n wire added;\nendmodule\n"; assert!(reopened.facts_now(&file, EDITED).is_none(), "a stale record must not be served"); assert!(reopened.facts_now(&file, "").is_none(), "nor an empty buffer's"); assert!(reopened.facts_now(&file, &M[..M.len() - 1]).is_none(), "nor one byte short"); assert!(reopened.facts_now(Path::new("/nowhere.sv"), M).is_none(), "nor another path's"); let after = reopened.work(); assert_eq!( (after.hits, after.misses, after.decode_ns, after.lookup_ns), (before.hits, before.misses, before.decode_ns, before.lookup_ns), "a refactoring's reads are not a scan's work" ); // The counted reader, asked the same questions, answers the same way. assert_eq!(reopened.facts_for(&file, M), reopened.facts_now(&file, M)); assert_eq!(reopened.facts_for(&file, EDITED), reopened.facts_now(&file, EDITED)); } #[test] fn a_record_survives_a_session_that_never_compacted() { // The crash case: records are written through as they are made, so a // session that is killed before it can rewrite the store still leaves // every file it had already parsed in it. let dir = TempDir::new("crash"); let first = dir.file("a.sv", M); let second = dir.file("b.sv", M); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.record(&facts(&first, M), M); cache.record(&facts(&second, M), M); drop(cache); // killed here — no compaction let reopened = IndexCache::open(Some(dir.path.clone())); assert!(reopened.facts_for(&first, M).is_some()); assert!(reopened.facts_for(&second, M).is_some()); } #[test] fn a_torn_final_record_costs_one_file_and_nothing_else() { let dir = TempDir::new("torn"); let good = dir.file("a.sv", M); let bad = dir.file("b.sv", M); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.record(&facts(&good, M), M); cache.record(&facts(&bad, M), M); drop(cache); // Cut the store mid-way through its last line, the way a process // killed inside a write would. let text = dir.store_text(); let cut = text.len() - (text.lines().last().expect("a last line").len() / 2); std::fs::write(dir.path.join(FILE), &text[..cut]).expect("truncate"); let reopened = IndexCache::open(Some(dir.path.clone())); assert!(reopened.facts_for(&good, M).is_some(), "the whole records survive"); assert!(reopened.facts_for(&bad, M).is_none(), "the torn one is simply gone"); } #[test] fn a_store_from_another_version_is_dropped_whole_and_replaced() { let dir = TempDir::new("version"); let file = dir.file("m.sv", M); let encoded = facts(&file, M).encode().expect("encodes"); let foreign = format!( "lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t0.0.0-not-this-one\n{}\n", line(content_hash(M.as_bytes()), &encoded) ); std::fs::write(dir.path.join(FILE), foreign).expect("write"); let mut cache = IndexCache::open(Some(dir.path.clone())); assert!(cache.facts_for(&file, M).is_none(), "another version's records are not read"); // …and the first write of this session replaces the file rather than // appending under a header nobody can read. cache.record(&facts(&file, M), M); let text = dir.store_text(); assert!(text.starts_with(&header()), "{text}"); assert!(!text.contains("0.0.0-not-this-one"), "{text}"); assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some()); } #[test] fn a_store_from_any_previous_facts_format_is_dropped_not_misread() { // Every `FACTS_FORMAT` this build is not, with today's `CACHE_FORMAT` // and `VERSION` — so the header's format field is the only thing that // can catch them. Written as a loop rather than against one number so // it cannot go stale the next time a record grows a field: it was // pinned at 2 for the `detail_span` bump (QA finding, // `docs/features/port-detail-spans/README.md`) and would have gone on // testing 2 forever. let dir = TempDir::new("factsformats"); let file = dir.file("m.sv", M); let encoded = facts(&file, M).encode().expect("encodes"); for format in 1..FACTS_FORMAT { let old_format_store = format!( "lucisv-index-cache\t{CACHE_FORMAT}\t{format}\t{VERSION}\n{}\n", line(content_hash(M.as_bytes()), &encoded) ); std::fs::write(dir.path.join(FILE), old_format_store).expect("write"); let cache = IndexCache::open(Some(dir.path.clone())); assert!( cache.facts_for(&file, M).is_none(), "a format-{format} record must not be read as a format-{FACTS_FORMAT} one" ); } // And the belt to that brace: a record really written in an older // *layout* — this one is a format-4 record, which is today's minus // every field `vscode-hierarchy-sidebar` added and minus the declared // type name `class-member-access` round 2 added (format 5 → 6 changed // the census, not the layout; 6 → 7 changed both) — does not decode as // one of today's *even if* something served it past the header. // Field-shifting is what the length prefixes and the end-of-record // check exist to make impossible. let previous = as_a_format_4_record(&encoded); assert_ne!(previous, encoded, "premise: the fixture has fields to strip"); assert!( FileFacts::decode(&previous).is_none(), "a format-4 record decoded as a format-{FACTS_FORMAT} one: {previous}" ); // Finally, the store is replaced under this build's header rather than // appended to, and reopening reads the fresh record back. let mut cache = IndexCache::open(Some(dir.path.clone())); cache.record(&facts(&file, M), M); let text = dir.store_text(); assert!( text.starts_with(&header()), "the store was replaced under this build's header: {text}" ); assert!( IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some(), "reopening reads the freshly written record back" ); } /// Today's encoded record, minus everything `FACTS_FORMAT` 5 and 7 added /// — i.e. exactly what format 4 wrote for the same file. Four additions /// and all four come out: a declaration's `decl_span`, a file-scope /// declaration's client positions, an instantiation's per-instance /// occurrences (format 5), and a declaration's declared type name /// (format 7). /// /// `M` declares exactly one unit, no members, and one instantiation of one /// instance, so every group's field index can be computed rather than /// parsed. Highest index first, so removing one strip does not move the /// others. fn as_a_format_4_record(encoded: &str) -> String { let mut fields: Vec<&str> = encoded.split('\t').collect(); let Some(instantiations) = fields.iter().position(|f| *f == "I") else { return encoded.to_string(); }; // I, count, module, owner (name + two ranges), site range — ten // fields, then the occurrence count and its one thirteen-field // occurrence. fields.drain(instantiations + 10..instantiations + 10 + 1 + 13); let Some(units) = fields.iter().position(|f| *f == "U") else { return encoded.to_string(); }; // U, count, then name, kind, name_span×2, decl_span×2, detail×2, // lines×2, type_name, and the unit's two client ranges — four numbers // each. let decl_at = units + 2; fields.drain(decl_at + 11..decl_at + 19); fields.drain(decl_at + 10..decl_at + 11); fields.drain(decl_at + 4..decl_at + 6); fields.join("\t") } #[test] fn an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace() { // The one shape `create_new` introduces: a zero-byte store, left by a // session killed between claiming the file and writing its header (or // seen for an instant by a second session racing the first). Neither // "another build's store" nor "ours" — the right move is to write the // header that is missing and carry on, which is what makes a crashed // claim cost nothing and a lost race cost nothing. let dir = TempDir::new("emptyclaim"); let file = dir.file("m.sv", M); std::fs::write(dir.path.join(FILE), "").expect("write"); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.record(&facts(&file, M), M); let text = dir.store_text(); assert!(text.starts_with(&header()), "{text}"); assert_eq!(text.lines().count(), 2, "the header, then the record: {text}"); assert_eq!( IndexCache::open(Some(dir.path.clone())).facts_for(&file, M), Some(facts(&file, M)) ); } #[test] fn a_corrupt_record_is_dropped_and_the_rest_of_the_store_is_not() { let dir = TempDir::new("corrupt"); let good = dir.file("a.sv", M); let encoded = facts(&good, M).encode().expect("encodes"); let other = facts(Path::new("/w/x.sv"), M).encode().expect("encodes"); // A whole record whose facts have been altered under an unchanged // checksum, and one written without a checksum field at all — the two // shapes a record damaged after it was written takes. let unchecksummed = format!("{:016x}\t{other}", content_hash(M.as_bytes())); let mismatched = format!("{:016x}\t{other}\t0000000000000000", content_hash(M.as_bytes())); for corrupt in [ "garbage", "", "\0\0\0", "not-hex\t/w/x.sv\tD0\tU0\tM0\tI0\tS0", // A hash of the wrong width — 16 hex digits, exactly. "0001\t/w/x.sv\tD0\tU0\tM0\tI0\tS0", "0000000000000001\t/w/x.sv\tD0\tU0\tM0\tI0", "0000000000000001", unchecksummed.as_str(), mismatched.as_str(), ] { let text = format!( "{}\n{}\n{corrupt}\n", header(), line(content_hash(M.as_bytes()), &encoded) ); std::fs::write(dir.path.join(FILE), text).expect("write"); let cache = IndexCache::open(Some(dir.path.clone())); assert!( cache.facts_for(&good, M).is_some(), "one bad record must not cost the good ones: {corrupt:?}" ); assert!( cache.facts_for(Path::new("/w/x.sv"), M).is_none(), "and the bad record itself is never served: {corrupt:?}" ); } } /// A store two files were recorded into and then compacted — this build's /// header and one line per path in path order, which is what every /// session after a whole rescan finds on disk. fn compacted_store(dir: &TempDir) -> (PathBuf, PathBuf) { let one = dir.file("a.sv", M); let two = dir.file("b.sv", M); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.record(&facts(&one, M), M); cache.record(&facts(&two, M), M); cache.compact(); assert_eq!(cache.work().compactions, 1, "premise: the store was written"); (one, two) } /// The store's bytes and its modification time — "not rewritten" as /// something a test can see rather than infer. fn store_stamp(dir: &TempDir) -> (Vec, std::time::SystemTime) { let path = dir.path.join(FILE); let bytes = std::fs::read(&path).expect("read store"); let stamp = std::fs::metadata(&path).expect("meta").modified().expect("mtime"); (bytes, stamp) } /// Rewrite the store's record lines, keeping this build's header. fn rewrite_records(dir: &TempDir, records: &[String]) { let mut text = header(); for record in records { text.push('\n'); text.push_str(record); } text.push('\n'); std::fs::write(dir.path.join(FILE), text).expect("write store"); } /// The store's record lines, header excluded. fn records_of(dir: &TempDir) -> Vec { dir.store_text().lines().skip(1).map(str::to_string).collect() } #[test] fn a_canonical_store_nothing_appended_to_is_not_rewritten() { // §P4b (a): a warm session hits the store for every file, appends // nothing, and would rewrite 44 MiB to produce the same 44 MiB — // 182 ms of a 1.33 s start. What is on disk is already what `render` // writes, so the rewrite is skipped and the file is not touched at // all: not its bytes, not even its modification time. let dir = TempDir::new("alreadycompact"); let (one, _) = compacted_store(&dir); let before = store_stamp(&dir); let mut warm = IndexCache::open(Some(dir.path.clone())); assert!(warm.facts_for(&one, M).is_some(), "premise: a warm session that only reads"); warm.compact(); assert_eq!(warm.work().compactions, 0, "the rewrite would have been byte-identical"); assert_eq!(store_stamp(&dir), before, "so the store was not touched"); // And what is on disk is still a store: the next session reads it. assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); } #[test] fn a_record_the_store_already_holds_is_not_appended_again() { // An open buffer is indexed from its own analysis on *every* scan and // its record is written through with it, so a warm session would // append a byte-identical duplicate for each open buffer — which // costs the store its canonical shape and so owes the next scan a // whole 44 MiB rewrite. The same record is a no-op; a changed one is // not (`docs/features/perf5-p4/README.md`, §P4b (a)). let dir = TempDir::new("repeatrecord"); let (one, _) = compacted_store(&dir); let before = store_stamp(&dir); let mut warm = IndexCache::open(Some(dir.path.clone())); warm.record(&facts(&one, M), M); assert_eq!(warm.work().records, 0, "nothing was appended"); assert_eq!(warm.work().repeats, 1, "and the store was already holding it"); assert_eq!(store_stamp(&dir), before, "so the store on disk did not move"); warm.compact(); assert_eq!(warm.work().compactions, 0, "which leaves it canonical"); assert_eq!(store_stamp(&dir), before); // One byte of difference and the record is written exactly as before. let edited = "module m;\n sub u ();\n wire w;\nendmodule\n"; warm.record(&facts(&one, edited), edited); assert_eq!(warm.work().records, 1, "different bytes are a new record"); assert_eq!(warm.work().repeats, 1); warm.compact(); assert_eq!(warm.work().compactions, 1, "and the rewrite is owed again"); assert_eq!( IndexCache::open(Some(dir.path.clone())).facts_for(&one, edited), Some(facts(&one, edited)), "the newer record is what the next session reads" ); } #[test] fn a_store_with_two_lines_for_one_path_is_compacted() { // The growth bound the skip must not cost: a session that saved a // file appended a second line for its path, and only a rewrite folds // the two back into one. let dir = TempDir::new("dupline"); let (one, _) = compacted_store(&dir); let mut records = records_of(&dir); let repeat = records[0].clone(); records.push(repeat); rewrite_records(&dir, &records); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.compact(); assert_eq!(cache.work().compactions, 1, "a duplicated path is not canonical"); assert_eq!(records_of(&dir).len(), 2, "one line per path again"); assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); } #[test] fn a_store_with_a_line_this_build_cannot_read_is_compacted() { // A record dropped at load — a torn append, bit rot, a checksum that // no longer matches — means the file on disk holds a line `render` // would not write, so the store is not canonical and the rewrite is // what removes it. let dir = TempDir::new("droppedline"); let (one, _) = compacted_store(&dir); let mut records = records_of(&dir); records.push(format!("{}\tnot a record at all\t{:016x}", "0".repeat(16), 0)); rewrite_records(&dir, &records); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.compact(); assert_eq!(cache.work().compactions, 1, "a dropped line is not canonical"); assert_eq!(records_of(&dir).len(), 2, "the unreadable line is gone"); assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); } #[test] fn a_store_whose_records_are_out_of_path_order_is_compacted() { // `render` writes paths sorted, so a store that arrives unsorted was // not written by a compaction of this shape and rewriting it is not a // no-op — even though every line in it is a good record. let dir = TempDir::new("unsorted"); let (one, _) = compacted_store(&dir); let mut records = records_of(&dir); records.reverse(); rewrite_records(&dir, &records); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.compact(); assert_eq!(cache.work().compactions, 1, "an unsorted store is not canonical"); let sorted: Vec = records_of(&dir); assert_eq!(sorted.len(), 2); assert!(sorted[0] < sorted[1], "path order restored: {sorted:?}"); assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); } #[test] fn a_session_that_recorded_one_file_compacts() { // The moment an append happens the store on disk is no longer the // store `render` would write — the appended line is out of order at // best and a second line for its path at worst — so the rewrite is // owed exactly as it always was. let dir = TempDir::new("appended"); let (one, _) = compacted_store(&dir); let third = dir.file("c.sv", M); let mut cache = IndexCache::open(Some(dir.path.clone())); assert!(cache.facts_for(&one, M).is_some(), "the other two still hit"); cache.record(&facts(&third, M), M); cache.compact(); assert_eq!(cache.work().compactions, 1, "a session that appended must rewrite"); assert_eq!(records_of(&dir).len(), 3); assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&third, M).is_some()); } #[test] fn a_store_holding_a_file_that_is_gone_is_compacted() { // `render` drops an entry whose file no longer exists, so a store // holding one is not what a rewrite would produce — and the rewrite // is what prunes it, exactly as before. let dir = TempDir::new("goneentry"); let (one, two) = compacted_store(&dir); std::fs::remove_file(&two).expect("remove"); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.compact(); assert_eq!(cache.work().compactions, 1, "a gone file must still be pruned"); assert_eq!(records_of(&dir).len(), 1, "the vanished file's line is gone"); assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); } #[test] fn a_store_from_another_version_is_replaced_even_by_a_session_that_wrote_nothing() { // The header is the one line the skip may never leave standing: its // records were dropped at load, so a session that keeps it leaves a // store nobody can read on disk for ever. let dir = TempDir::new("foreignheader"); let file = dir.file("m.sv", M); let encoded = facts(&file, M).encode().expect("encodes"); let foreign = format!( "lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t0.0.0-not-this-build\n{}\n", line(content_hash(M.as_bytes()), &encoded) ); std::fs::write(dir.path.join(FILE), foreign).expect("write"); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.compact(); assert_eq!(cache.work().compactions, 1, "another version's header is not canonical"); let text = dir.store_text(); assert_eq!(text, format!("{}\n", header()), "replaced with this build's own: {text}"); } #[test] fn a_record_whose_facts_no_longer_decode_is_a_miss_not_a_failure() { // The line is well-formed as far as the store is concerned — hash, // then a path, then a checksum that matches the facts as written — // but the facts themselves are truncated. Nothing may come of it // except a parse. let dir = TempDir::new("halfrecord"); let file = dir.file("m.sv", M); let half = format!("{}\tD0\tU1", file.display()); let text = format!("{}\n{}\n", header(), line(content_hash(M.as_bytes()), &half)); std::fs::write(dir.path.join(FILE), text).expect("write"); assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_none()); } #[test] fn a_store_from_the_previous_store_format_is_dropped_whole_and_replaced() { // The checksum field bumped `CACHE_FORMAT` 1 → 2, and the rule at the // constant is that a store stamped with a number this build does not // write is not read at all — no error, no half-trust, just a cache // that starts empty and refills. Written the way format 1 wrote it: // no checksum field on the record either. let dir = TempDir::new("oldformat"); let file = dir.file("m.sv", M); let encoded = facts(&file, M).encode().expect("encodes"); let old = format!( "lucisv-index-cache\t1\t{FACTS_FORMAT}\t{VERSION}\n{:016x}\t{encoded}\n", content_hash(M.as_bytes()) ); std::fs::write(dir.path.join(FILE), old).expect("write"); let mut cache = IndexCache::open(Some(dir.path.clone())); assert!(cache.facts_for(&file, M).is_none(), "format 1's records are not read"); cache.record(&facts(&file, M), M); let text = dir.store_text(); assert!(text.starts_with(&header()), "{text}"); assert_eq!(text.lines().count(), 2, "replaced, not appended to: {text}"); assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_some()); } #[test] fn compaction_keeps_one_line_per_path_and_drops_the_files_that_are_gone() { let dir = TempDir::new("compact"); let kept = dir.file("kept.sv", M); let gone = dir.file("gone.sv", M); let mut cache = IndexCache::open(Some(dir.path.clone())); // The same path recorded three times, as a session's worth of saves // would. for text in ["module a; endmodule\n", "module b; endmodule\n", M] { cache.record(&facts(&kept, text), text); } cache.record(&facts(&gone, M), M); assert_eq!(dir.store_text().lines().count(), 5, "the log holds every write"); std::fs::remove_file(&gone).expect("remove"); cache.compact(); let text = dir.store_text(); assert_eq!(text.lines().count(), 2, "header plus one live entry: {text}"); assert!(text.contains("kept.sv"), "{text}"); assert!(!text.contains("gone.sv"), "an entry for a file that is gone: {text}"); // The surviving entry is the *last* one written for that path. assert_eq!( IndexCache::open(Some(dir.path.clone())).facts_for(&kept, M), Some(facts(&kept, M)) ); } /// QA (2026-08-27), attack surface 1, fixed 2026-08-27: a record whose /// facts do not match the checksum they were written with is dropped, not /// served. Before the checksum, `facts_for` verified a record against the /// *file's* content hash and nothing else, so any line whose hash matched /// real bytes served whatever facts sat beside it — which is what every /// accidental way a record can change after it was written looks like: a /// flipped bit, a torn append two servers interleaved, an editor that /// rewrote the file. All of those are now misses. /// /// The second half of this test is the part that is *not* fixed, on /// purpose: a forger recomputes the checksum, because it is an FNV-1a and /// not a keyed MAC. That is the accepted threat model — anything that can /// write this store can write the source files it describes, and a key /// stored beside the data it authenticates is theatre. Pinned so nobody /// mistakes the checksum for a security boundary. #[test] fn a_record_whose_facts_do_not_match_their_checksum_is_dropped() { let dir = TempDir::new("poison"); let file = dir.file("m.sv", M); let genuine = facts(&file, M); // Same path, same hash (of `M`'s real bytes) — but facts that belong // to text that was never in `M` at all, spliced into a genuine // record's line under the *genuine* checksum. let evil_text = "module evil_backdoor;\nendmodule\n"; let evil = facts(&file, evil_text); let honest_line = line(content_hash(M.as_bytes()), &genuine.encode().expect("encodes")); let checksum = honest_line.rsplit('\t').next().expect("a checksum field"); let tampered = format!( "{:016x}\t{}\t{checksum}", content_hash(M.as_bytes()), evil.encode().expect("encodes") ); std::fs::write(dir.path.join(FILE), format!("{}\n{tampered}\n", header())).expect("write"); assert!( IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_none(), "facts that are not the facts the checksum was taken over are not served" ); // …and the honest record beside it is read exactly as before: the // checksum drops damaged records, it does not make the store fussier // about whole ones. std::fs::write(dir.path.join(FILE), format!("{}\n{honest_line}\n", header())) .expect("write"); assert_eq!( IndexCache::open(Some(dir.path.clone())).facts_for(&file, M), Some(genuine.clone()) ); // The accepted residue: a forger recomputes the checksum, and this // store has no secret to stop them. Anyone who can write here can // write `m.sv` itself. let forged = line(content_hash(M.as_bytes()), &evil.encode().expect("encodes")); std::fs::write(dir.path.join(FILE), format!("{}\n{forged}\n", header())).expect("write"); let served = IndexCache::open(Some(dir.path.clone())) .facts_for(&file, M) .expect("a deliberately reforged record is still a hit — the threat model says so"); assert_eq!(served, evil, "the checksum is an accident detector, not a MAC"); assert_ne!(served, genuine); } /// QA (2026-08-27), crash shapes, fixed 2026-08-27: kill -9 at every byte /// offset of a real store. Three properties must hold at *every* cut: no /// panic, nothing served is ever wrong, and — the part that used to fail — /// a cut costs only the record it landed in. A store holding a multi-byte /// character (a macro body with non-ASCII text) is what pins the third: /// `open` used to load with `read_to_string`, which rejects the *whole* /// buffer when its tail is not valid UTF-8, so a cut inside a multi-byte /// sequence threw away every intact record before it as well. `open` now /// reads bytes and validates a line at a time, so the assertion below is /// exact: past both good lines, both good records survive every single /// cut. #[test] fn truncating_the_store_at_every_byte_offset_costs_only_the_torn_record() { let dir = TempDir::new("bytetear"); let a = dir.file("a.sv", M); let b = dir.file("b.sv", M); let unicode_text = "`define GREETING \"h\u{e9}llo w\u{f6}rld\"\nmodule m; endmodule\n"; let c = dir.file("c.sv", unicode_text); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.record(&facts(&a, M), M); cache.record(&facts(&b, M), M); cache.record(&facts(&c, unicode_text), unicode_text); cache.compact(); let bytes = std::fs::read(dir.path.join(FILE)).expect("read store bytes"); // Where a.sv's and b.sv's *own* lines end, so a cut past both of them // is a cut where both records are fully present in the truncated // bytes — collateral loss past this point is not "the tail was // torn", it is the whole file being thrown away for a reason that // has nothing to do with either record. let text = String::from_utf8(bytes.clone()).expect("the untruncated store is valid UTF-8"); let b_line_end = { let mut offset = 0; let mut end = None; for line in text.lines() { offset += line.len() + 1; if line.contains("b.sv") { end = Some(offset); break; } } end.expect("b.sv's line") }; let mut lost_everything = 0; let mut collateral_loss = 0; let mut mid_character_cuts = 0; for cut in 1..bytes.len() { std::fs::write(dir.path.join(FILE), &bytes[..cut]).expect("truncate"); // Must never panic — the whole point of the exercise. let reopened = IndexCache::open(Some(dir.path.clone())); let mut hits = 0; for (path, text, genuine) in [ (&a, M, facts(&a, M)), (&b, M, facts(&b, M)), (&c, unicode_text, facts(&c, unicode_text)), ] { if let Some(served) = reopened.facts_for(path, text) { hits += 1; assert_eq!( served, genuine, "cut at byte {cut}: served facts must never be wrong" ); } } if hits == 0 { lost_everything += 1; } if std::str::from_utf8(&bytes[..cut]).is_err() { mid_character_cuts += 1; } if cut >= b_line_end { // a.sv's and b.sv's lines are both whole inside // `bytes[..cut]`; the only thing torn is c.sv's. Nothing // about that tear — including a cut landing deep inside one // of its multi-byte characters — may cost a record that is // entirely present. if hits < 2 { collateral_loss += 1; } assert!( hits >= 2, "cut at byte {cut}: both whole records must survive a torn last line, \ {hits} did" ); } } eprintln!( "{lost_everything} of {} truncation points lost every record (all of them before the \ first whole record); {collateral_loss} lost an already-whole record; \ {mid_character_cuts} cuts landed inside a multi-byte character", bytes.len() - 1 ); assert!( mid_character_cuts > 0, "premise: some cut must land mid-character, or this test proves nothing" ); assert_eq!(collateral_loss, 0, "no cut may cost more than the record it landed in"); } /// QA (2026-08-27), "two servers, one store", fixed 2026-08-27: four /// sessions racing to append their very *first* record now keep all /// hundred of them. The old `append` truncated whenever its own /// `header_ok` was false — which is every session's state the moment its /// workspace is first scanned — so a second cold starter erased the /// first's already-appended lines, and QA measured 25 of 100 records /// standing. `claim` replaces that with `File::create_new`: exactly one /// session creates the store, the rest find its header and append under /// it, and truncation is left for a header this build cannot read. /// /// The count is deterministic, not merely likely. The three shapes a /// loser can find are the three `settled_header` returns, and none of /// them drops a byte: `Ours` appends; `Empty` (the winner caught between /// its `create_new` and its header) appends the identical header line /// first, which at worst leaves a duplicate header the reader treats as /// one more malformed record; `Foreign` cannot happen here, because /// nothing but this build ever writes this directory. Every record and /// every header goes out in one `write_all` on an `O_APPEND` handle, so /// no line can land inside another. #[test] fn concurrent_first_writers_all_survive_and_none_is_ever_wrong() { let dir = TempDir::new("concurrent"); let mut writers = Vec::new(); for w in 0..4 { let path = dir.path.clone(); writers.push(std::thread::spawn(move || { let mut cache = IndexCache::open(Some(path)); let mut written = Vec::new(); for n in 0..25 { // Long bodies, to widen whatever window a real interleave // would need. let body = format!("writer{w}-record{n}-{}", "x".repeat(2000)); let text = format!("`define BODY \"{body}\"\nmodule m{w}_{n}; endmodule\n"); let file = PathBuf::from(format!("/w/writer{w}_{n}.sv")); let f = facts(&file, &text); cache.record(&f, &text); written.push((file, text, f)); } written })); } let mut all_written = Vec::new(); for w in writers { all_written.extend(w.join().expect("writer thread")); } // No compaction: read exactly what four racing append logs left // behind. let reopened = IndexCache::open(Some(dir.path.clone())); let mut survived = 0; for (path, text, genuine) in &all_written { if let Some(served) = reopened.facts_for(path, text) { survived += 1; assert_eq!( served, *genuine, "a served record must never be a mix of two writers' bytes" ); } } eprintln!( "{survived} of {} records from 4 racing first-writers survived with no compaction", all_written.len() ); assert_eq!(survived, all_written.len(), "a racing cold start may not cost a record"); } /// QA (2026-08-27): the header comparison is exact-string equality, so /// pin both directions explicitly — a header this exact build wrote is /// accepted, and one with anything appended after the version field /// (a hypothetical future extra column) is rejected wholesale, the same /// as a wrong version number. There is no forward-compatible "unknown /// trailing field is ignored" path. #[test] fn a_header_with_an_extra_trailing_field_is_rejected_like_any_other_mismatch() { let dir = TempDir::new("headerextra"); let file = dir.file("m.sv", M); let encoded = facts(&file, M).encode().expect("encodes"); let text = format!("{}\textra-field\n{}\n", header(), line(content_hash(M.as_bytes()), &encoded)); std::fs::write(dir.path.join(FILE), text).expect("write"); assert!( IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_none(), "an extra header field must not be tolerated" ); } /// QA (2026-08-27): a store file holding two lines for the same path — /// not two `record()` calls in one session (already covered by /// `compaction_keeps_one_line_per_path_and_drops_the_files_that_are_gone`), /// but two lines actually sitting in the file, the shape a hand-edited /// or externally concatenated store would take. `open`'s loop inserts /// into the map in file order, so the *last* line for a path is what /// answers — pinned directly against the raw file rather than through /// `record`. #[test] fn two_raw_lines_for_the_same_path_in_the_store_file_last_one_wins() { let dir = TempDir::new("duplicate"); let file = dir.file("m.sv", "module first; endmodule\n"); let first = facts(&file, "module first; endmodule\n").encode().expect("encodes"); let second_text = "module second; endmodule\n"; let second = facts(&file, second_text).encode().expect("encodes"); let text = format!( "{}\n{}\n{}\n", header(), line(content_hash(b"module first; endmodule\n"), &first), line(content_hash(second_text.as_bytes()), &second) ); std::fs::write(dir.path.join(FILE), text).expect("write"); let cache = IndexCache::open(Some(dir.path.clone())); assert!( cache.facts_for(&file, "module first; endmodule\n").is_none(), "the first line lost" ); assert_eq!(cache.facts_for(&file, second_text), Some(facts(&file, second_text))); } /// QA (2026-08-27), crash shapes: a compaction killed between the /// temp-file write and the rename leaves `index-cache..tmp` /// sitting next to the real store. It is harmless to correctness — /// `open` only ever reads the exact name `index-cache`, so a stray /// `.tmp` file is invisible to it — but nothing anywhere sweeps one up: /// not `open`, not a later `compact` (which names its own tmp file /// after *this* process's pid, a name the dead process's leftover will /// only collide with by pid reuse). A machine whose editor is killed /// mid-compaction repeatedly accumulates one orphaned file per crash, /// each up to the size of the whole store. Filed as a minor, /// unbounded-but-slow disk leak — not a correctness issue. #[test] fn an_orphaned_compaction_tmp_file_is_never_swept_up() { let dir = TempDir::new("orphantmp"); let file = dir.file("m.sv", M); // Simulate a previous process's compaction, killed after the write // but before the rename — a stray tmp file under some pid that is // not this process's. let orphan = dir.path.join("index-cache.999999.tmp"); std::fs::write(&orphan, "leftover from a killed compaction\n").expect("write"); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.record(&facts(&file, M), M); cache.compact(); assert!(orphan.exists(), "nothing sweeps up a tmp file from another pid"); // And it did not interfere with the real store either. assert_eq!( IndexCache::open(Some(dir.path.clone())).facts_for(&file, M), Some(facts(&file, M)) ); } /// QA (2026-08-27), crash shapes: a write failure must never panic and /// must never corrupt a store that already exists. Simulated with a /// directory whose owner-write bit is cleared, which — like a full disk /// — fails any attempt to *create* a file in it. This does not stop an /// append to an already-open, already-existing file (a directory's /// write permission gates creating and unlinking entries, not writing /// through a handle opened before the permission changed, or reopening /// a file that already exists), so `record` keeps succeeding; `compact` /// does fail — its temp file is a new directory entry — and does so the /// documented way: silently, via the `.is_ok()` check, leaving whatever /// is already on disk in place rather than a half-written store. #[test] #[cfg(unix)] fn a_write_failure_is_silent_and_never_panics_or_leaves_a_half_written_store() { use std::os::unix::fs::PermissionsExt; let dir = TempDir::new("readonly"); let file = dir.file("m.sv", M); let mut cache = IndexCache::open(Some(dir.path.clone())); cache.record(&facts(&file, M), M); cache.compact(); let mut perms = std::fs::metadata(&dir.path).expect("meta").permissions(); perms.set_mode(0o500); // r-x: no new directory entries, no rename std::fs::set_permissions(&dir.path, perms).expect("chmod"); let second = dir.path.join("second.sv"); cache.record(&facts(&second, M), M); // must not panic cache.compact(); // must not panic — its rename cannot land, and must not half-write let mut restore = std::fs::metadata(&dir.path).expect("meta").permissions(); restore.set_mode(0o700); std::fs::set_permissions(&dir.path, restore).expect("chmod back"); // Whatever is left on disk must still be a whole, valid store: the // header intact and the original entry still readable. `compact`'s // failed rename must not have left a torn file in `index-cache`'s // place — only ever in its own tmp name, which `open` never reads. let reopened = IndexCache::open(Some(dir.path.clone())); assert_eq!( reopened.facts_for(&file, M), Some(facts(&file, M)), "the original entry must still be readable after the failed compaction" ); } /// QA fix-round re-verification (2026-08-27): the checksum field itself, /// corrupted three ways — odd length, wrong-but-right-length (non-hex), /// and simply absent. None of these may panic, and all three must drop /// the line rather than serve it. (`a_corrupt_record_is_dropped_and_the_ /// rest_of_the_store_is_not` already exercises two of these shapes /// incidentally; this test names them explicitly, one at a time, and /// checks the good record beside each survives.) #[test] fn a_corrupted_checksum_field_drops_the_line_and_never_panics() { let dir = TempDir::new("checksumshapes"); let good = dir.file("a.sv", M); let good_line = line(content_hash(M.as_bytes()), &facts(&good, M).encode().expect("x")); let victim = facts(Path::new("/w/x.sv"), M).encode().expect("encodes"); let hash = format!("{:016x}", content_hash(M.as_bytes())); // Odd length: the genuine checksum with its last hex digit dropped — // 15 characters, and (`format!("{:015x}", ...)` would not have // guaranteed this: it is a *minimum* width, not a truncation, so a // naturally-16-digit value survives it unchanged and the record // would have decoded as genuinely valid). let real_checksum = format!("{:016x}", content_hash(victim.as_bytes())); let odd = format!("{hash}\t{victim}\t{}", &real_checksum[..15]); // Right length, not hex. let non_hex = format!("{hash}\t{victim}\tzzzzzzzzzzzzzzzz"); // Missing entirely: the line ends at the facts with no third field — // constructed so the facts themselves hold no tab, so `rsplit_once` // has nothing to split off as a checksum at all. let missing = format!("{hash}\tjust-one-field-no-tabs-here"); for corrupt in [odd.as_str(), non_hex.as_str(), missing.as_str()] { let text = format!("{}\n{good_line}\n{corrupt}\n", header()); std::fs::write(dir.path.join(FILE), text).expect("write"); // Must not panic (the loop itself is the assertion) and must not // serve the malformed record under any path. let cache = IndexCache::open(Some(dir.path.clone())); assert!( cache.facts_for(&good, M).is_some(), "a corrupted checksum field must not cost an unrelated good record: {corrupt:?}" ); assert!( cache.facts_for(Path::new("/w/x.sv"), M).is_none(), "a corrupted checksum field must never itself be served: {corrupt:?}" ); } } /// QA fix-round re-verification (2026-08-27): the checksum is over the /// exact bytes `decode` receives, not over the decoded *value* the bytes /// happen to produce. Constructed by finding a shape where two distinct /// byte strings decode to the identical [`FileFacts`] — `u32::parse` /// accepts a leading zero (`"00"` parses to `0`) even though `encode` /// never writes one — and confirming that a record whose facts were /// silently re-spelled that way, but whose checksum is still the /// *original* bytes' checksum, is dropped rather than "close enough". /// This is the structural property that makes the checksum sound against /// any equivalent-but-different-bytes re-escaping, not only against /// arbitrary tampering: nothing about "decode would agree anyway" /// excuses a byte mismatch, because the checksum never looks at the /// decoded value at all. #[test] fn a_benign_reencoding_with_the_original_checksum_is_still_dropped() { let dir = TempDir::new("benignreencode"); let file = dir.file("m.sv", M); let encoded = facts(&file, M).encode().expect("encodes"); // `M` has no `` `define``s, so its D-count field is a lone "0". let reencoded = encoded.replacen("\tD\t0\t", "\tD\t00\t", 1); assert_ne!(encoded, reencoded, "premise: the reencoding actually changed a byte"); assert_eq!( FileFacts::decode(&reencoded), FileFacts::decode(&encoded), "premise: the two byte strings decode to the same facts" ); let original_checksum = format!("{:016x}", content_hash(encoded.as_bytes())); let stale = format!("{:016x}\t{reencoded}\t{original_checksum}", content_hash(M.as_bytes())); std::fs::write(dir.path.join(FILE), format!("{}\n{stale}\n", header())).expect("write"); assert!( IndexCache::open(Some(dir.path.clone())).facts_for(&file, M).is_none(), "the checksum must reject bytes it was not computed over, even when decode would \ have agreed with the original" ); } /// QA fix-round re-verification (2026-08-27): the crash shape the /// `Empty` arm exists for, raced for real rather than constructed as a /// single sequential write. A store already sitting at zero bytes (a /// writer that crashed between its `create_new` and its header, exactly /// as `an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace` /// sets up) is then found by *two* fresh sessions at once, both of which /// must decide `Empty` and both write the identical header line — the /// duplicate-header residue the work log describes, not a corrupted /// store. Every one of both writers' records must still be readable /// afterward. #[test] fn two_writers_racing_the_empty_arm_leave_a_valid_store() { let dir = TempDir::new("emptyrace"); // Simulate the crashed writer: the file exists, and is empty. std::fs::write(dir.path.join(FILE), "").expect("write"); let mut writers = Vec::new(); for w in 0..2 { let path = dir.path.clone(); writers.push(std::thread::spawn(move || { let mut cache = IndexCache::open(Some(path)); let file = PathBuf::from(format!("/w/racer{w}.sv")); let text = format!("module racer{w}; endmodule\n"); let f = facts(&file, &text); cache.record(&f, &text); (file, text, f) })); } let written: Vec<_> = writers.into_iter().map(|w| w.join().expect("thread")).collect(); let text = dir.store_text(); let header_lines = text.lines().filter(|l| *l == header()).count(); assert!(header_lines >= 1, "the header must be present at least once: {text}"); // Every non-header line must still be a well-formed, checksummed // record or the reader's own rejection of it — never a panic, and // never a line that swallows part of another. let reopened = IndexCache::open(Some(dir.path.clone())); for (path, content, genuine) in &written { assert_eq!( reopened.facts_for(path, content), Some(genuine.clone()), "both racers' records must survive a shared Empty-arm race: {text}" ); } } #[test] fn a_disabled_cache_reads_nothing_and_writes_nothing() { let dir = TempDir::new("disabled"); let file = dir.file("m.sv", M); let mut warm = IndexCache::open(Some(dir.path.clone())); warm.record(&facts(&file, M), M); warm.compact(); let before = dir.store_text(); let mut off = IndexCache::disabled(); assert!(off.facts_for(&file, M).is_none(), "persist: false must not read"); off.record(&facts(&file, M), M); off.compact(); assert_eq!(dir.store_text(), before, "persist: false must not write"); assert_eq!(off.dir(), None); } #[test] fn nothing_is_created_until_something_is_recorded() { let dir = TempDir::new("lazy"); let nested = dir.path.join("deep/inner"); let cache = IndexCache::open(Some(nested.clone())); assert!(!nested.exists(), "opening an empty store creates no directory"); assert_eq!(cache.dir(), Some(nested.as_path())); let file = dir.file("m.sv", M); let mut cache = IndexCache::open(Some(nested.clone())); cache.record(&facts(&file, M), M); assert!(nested.join(FILE).exists(), "the directory is made on demand"); cache.compact(); assert_eq!(std::fs::read_to_string(nested.join(".gitignore")).expect("ignore"), "*\n"); let leftovers: Vec = std::fs::read_dir(&nested) .expect("read dir") .filter_map(|entry| entry.ok()) .map(|entry| entry.file_name().to_string_lossy().into_owned()) .filter(|name| name.ends_with(".tmp")) .collect(); assert!(leftovers.is_empty(), "{leftovers:?}"); } #[test] fn the_cache_directory_is_the_highest_rung_that_answers() { let settings = |persist: bool, path: Option<&str>| ClientSettings { index_persist: persist, index_cache_path: path.map(str::to_string), ..ClientSettings::default() }; let roots = [PathBuf::from("/w/root"), PathBuf::from("/w/aaa")]; let storage = Path::new("/storage/ws"); let filelist = Path::new("/w/project.f"); // Rung 1 beats everything, and a relative path hangs off the first // root — the rule `lucisv.filelist` already uses. assert_eq!( cache_dir(&settings(true, Some("/abs/cache")), Some(storage), &roots, Some(filelist)), Some(PathBuf::from("/abs/cache")) ); assert_eq!( cache_dir(&settings(true, Some(".lucisv_index")), Some(storage), &roots, None), Some(PathBuf::from("/w/root/.lucisv_index")) ); // Rung 2: what the editor said. assert_eq!( cache_dir(&settings(true, None), Some(storage), &roots, None), Some(storage.to_path_buf()) ); // Rung 3: the OS directory, keyed by the roots in sorted order — so // the same two folders opened the other way round is one store. let os = cache_dir(&settings(true, None), None, &roots, None).expect("an OS cache dir"); let swapped = cache_dir(&settings(true, None), None, &[roots[1].clone(), roots[0].clone()], None); assert_eq!(Some(os.clone()), swapped, "the root order is not part of the identity"); assert!(os.starts_with(os_cache_dir().expect("an OS cache dir")), "{}", os.display()); assert!(os.ends_with(workspace_key(&roots, None).expect("a key")), "{}", os.display()); // A different workspace is a different store. assert_ne!(Some(os), cache_dir(&settings(true, None), None, &roots[..1], None)); // A rootless session is keyed by its filelist, and has no store // without one. assert!(cache_dir(&settings(true, None), None, &[], Some(filelist)).is_some()); assert_eq!(cache_dir(&settings(true, None), None, &[], None), None); // Rung 4: off is off, whatever every other rung says. assert_eq!( cache_dir(&settings(false, Some("/abs/cache")), Some(storage), &roots, None), None ); } }