//! 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::collections::HashMap; use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::{Path, PathBuf}; use lucisv_core::cache::content_hash; use vlog_semantic::{record_path, FileFacts, FACTS_FORMAT}; 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 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, } 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. 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(); if header_ok { for line in lines { let Ok(line) = std::str::from_utf8(line) else { continue }; if let Some((path, entry)) = parse_entry(line) { // 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. entries.insert(path, entry); } } } IndexCache { dir: Some(dir), entries, log: None, header_ok } } /// 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 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 entry = self.entries.get(path)?; if entry.content != content_hash(text.as_bytes()) { return None; } FileFacts::decode(&entry.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. pub fn record(&mut self, facts: &FileFacts, text: &str) { if self.dir.is_none() { return; } let Some(encoded) = facts.encode() else { return }; let content = content_hash(text.as_bytes()); self.append(&line(content, &encoded)); 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. pub fn compact(&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. 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()); } #[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:?}" ); } } #[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 ); } }