From e4b1f55c12abf6abbcb0c4626be969b828bb4ee8 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Thu, 27 Aug 2026 16:33:52 -0700 Subject: [PATCH] Persistent index cache: a half-indexed workarea resumes where it stopped MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Owner-requested round. Every parsed file's FileFacts record is written through to an index-cache store (append per file, atomic compaction at scan end — a crash loses at most the file in flight), keyed by a content hash that is the whole key: no mtime fast path, by measured argument (6 ms of a 181 ms warm scan, and unsound against save-time write-through). On reopen, hits skip parsing and the resume is visible — cached: vs indexing: log lines, the bar counting through hits, and an end message saying how many came from cache. Warm rescan 322 to 179 ms release, 1.5 s to 0.76 s debug; 910 KB store for the 860-file corpus. Location: lucisv.index.cachePath > the extension's context.storageUri via initializationOptions (the one extension.js change) > the OS cache dir keyed by workspace identity > nowhere; lucisv.index.persist (default on) gates both directions immediately. The cache is a performance artifact, never a correctness input, and after the fix round that promise is total against everything but intentional forgery — which the threat model now formally excludes (same-user disk; a keyed MAC would be theater): a per-record checksum drops every corrupt-but-parseable line (poisoned and reforged shapes both pinned so the checksum is never mistaken for a MAC), first-writer initialization is a create_new claim with structural 100/100 survival, and a torn multi-byte tail costs exactly the torn record (0 of 583 offsets lose more). Old-format stores discard wholesale. Load==fresh fingerprint equality swept over the corpus. 45 tests added across the main and fix rounds (dev 33+2, QA 9+3, one QA test-construction bug self-caught), 2 ignored probes. docs/features/index-persistence/README.md Co-Authored-By: Claude Fable 5 --- TODO.md | 16 +- crates/lucisv_server/src/index_cache.rs | 1273 ++++++++++++++++++++ crates/lucisv_server/src/main.rs | 23 +- crates/lucisv_server/src/server.rs | 186 ++- crates/lucisv_server/src/settings.rs | 63 +- crates/lucisv_server/src/state.rs | 578 ++++++++- crates/lucisv_server/tests/e2e.rs | 112 +- crates/vlog_semantic/src/facts.rs | 432 +++++++ crates/vlog_semantic/src/lib.rs | 6 +- crates/vlog_semantic/src/workspace.rs | 80 +- crates/vlog_semantic/tests/workspace.rs | 151 ++- docs/features/incremental-index/README.md | 11 +- docs/features/index-persistence/README.md | 1339 +++++++++++++++++++++ docs/features/indexing-ux/README.md | 13 + docs/features/lucisv-server/README.md | 23 +- editors/vscode/extension.js | 12 + editors/vscode/package.json | 12 +- 17 files changed, 4280 insertions(+), 50 deletions(-) create mode 100644 crates/lucisv_server/src/index_cache.rs create mode 100644 crates/vlog_semantic/src/facts.rs create mode 100644 docs/features/index-persistence/README.md diff --git a/TODO.md b/TODO.md index 9b83afd..ccef98e 100644 --- a/TODO.md +++ b/TODO.md @@ -493,7 +493,10 @@ later: in other files. Start as a full-scan-on-startup index (Verilog codebases are small); ~~incrementality comes with salsa later~~ — one file at a time since 2026-08-27, without salsa - (`docs/features/incremental-index/README.md`). + (`docs/features/incremental-index/README.md`); and ~~re-scanned from zero on + every startup~~ — what a scan learns persists since 2026-08-27, so a reopened + workspace indexes from records rather than parses and an interrupted scan + resumes (`docs/features/index-persistence/README.md`). → `vlog_semantic::WorkspaceIndex::build(files) `+ `resolve_external(&Semantics, &WorkspaceIndex) -> ExternalResolutions`, a two-layer design: the index is a full scan (860 corpus files in 0.7 s), @@ -565,7 +568,11 @@ later: replaces one file's contribution and provably gives the index a whole build would have, so a save costs 33 ms instead of 1.5 s over the corpus. No query graph and no dependency tracking — the salsa question is still open, and is - still deferred. + still deferred. **A second piece answered without salsa, 2026-08-27** + (`docs/features/index-persistence/README.md`): every file's `FileFacts` are + written to a content-keyed store as a scan parses them, so the recompute a + *new session* would otherwise repeat is skipped instead — 1.8x on a whole + corpus rescan, and a scan interrupted halfway resumes where it stopped. - [x] **Release prep.** `LICENSE` (MIT), `CHANGELOG.md` (v0.2.0), version bumped to 0.2.0 across the workspace and the extension, `tools/release.sh` (release binaries + `.vsix` + `SHA256SUMS` into a gitignored `dist/`) and @@ -768,6 +775,11 @@ and are not gaps. 1000 reports per rescan), a per-file `window/logMessage` under `lucisv.index.logFiles`, and a 1 MiB default walk-file size cap under `lucisv.index.maxFileSize` whose skips the `end` message counts. + → **Extended again, 2026-08-27** + (`docs/features/index-persistence/README.md`): a file restored from the + persistent index cache logs `cached:` rather than `indexing:` and is counted + in the `end` message — `860 files indexed, 860 from cache` — so a rescan that + flew past says why. Everything else above — the capability gate, the token scheme, the create's ignored answer, the ordering against the republish — is unchanged. diff --git a/crates/lucisv_server/src/index_cache.rs b/crates/lucisv_server/src/index_cache.rs new file mode 100644 index 0000000..879c349 --- /dev/null +++ b/crates/lucisv_server/src/index_cache.rs @@ -0,0 +1,1273 @@ +//! 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 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 + ); + } +} diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 7556830..643960c 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -18,6 +18,7 @@ mod format; mod hierarchy; mod hover; mod includes; +mod index_cache; mod inlay; mod inline; mod lens; @@ -71,6 +72,10 @@ fn main() -> Result<(), Box> { // capabilities have no field for it and drop it on the floor — see // `ranges_formatting_support`. let ranges_formatting = ranges_formatting_support(¶ms); + // Read from the raw params for the same reason, and because it is not a + // capability at all: `initializationOptions` is whatever the client's + // extension put there. + let storage = storage_path(¶ms); // A client that sends params we cannot read still gets a server; every // field we want is optional anyway. let params: InitializeParams = serde_json::from_value(params).unwrap_or_default(); @@ -87,7 +92,7 @@ fn main() -> Result<(), Box> { }; connection.initialize_finish(id, initialize_value(ranges_formatting)?)?; - Server::new(connection, roots, abilities).run()?; + Server::new(connection, roots, abilities, storage).run()?; io_threads.join()?; Ok(()) } @@ -373,6 +378,22 @@ fn ranges_formatting_support(params: &serde_json::Value) -> bool { params["capabilities"]["textDocument"]["rangeFormatting"]["rangesSupport"] == true } +/// The folder the client set aside for this workspace's server state — +/// `initializationOptions.storagePath`, which the VS Code extension fills in +/// with `context.storageUri`. +/// +/// The persistent index cache goes here when there is one: it is +/// per-workspace, the editor cleans it up when the workspace is forgotten, +/// and it needs no guess about where this platform keeps caches. A client +/// that sends nothing — every client but ours, and ours before this — leaves +/// the OS cache directory to decide +/// (`docs/features/index-persistence/README.md`). A blank value counts as +/// unset, the same reading `lucisv.serverPath` gives a blank setting. +fn storage_path(params: &serde_json::Value) -> Option { + let path = params["initializationOptions"]["storagePath"].as_str()?; + (!path.trim().is_empty()).then(|| PathBuf::from(path)) +} + /// Whether the client can expand `${1:x}` tabstops in a completion item. /// /// A client that did not say so gets the skeleton as plain text: a literal diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index d870a7e..e50ddd6 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -189,8 +189,9 @@ impl Server { connection: Connection, roots: Vec, abilities: ClientAbilities, + storage: Option, ) -> Server { - Server::started(connection, roots, abilities, ClientSettings::default()) + Server::started(connection, roots, abilities, ClientSettings::default(), storage) } /// [`Server::new`] with a client's settings already in hand — the seam the @@ -203,6 +204,7 @@ impl Server { roots: Vec, abilities: ClientAbilities, client: ClientSettings, + storage: Option, ) -> Server { let mut server = Server { connection, @@ -222,6 +224,10 @@ impl Server { // `true` this returns for a non-default `client` is the rebuild that // is about to happen anyway. let _ = server.workspace.set_client_settings(client); + // Before the first build, because it is one rung of the ladder that + // decides where that build reads its cache from + // (`docs/features/index-persistence/README.md`). + server.workspace.set_storage_path(storage); // The earliest legal moment for anything server-initiated: `main` // builds this only after `initialize_finish`, which returns once the // client's `initialized` notification has arrived — and consumes it, @@ -236,8 +242,8 @@ impl Server { let Server { connection, workspace, .. } = &mut server; let mut watch = IndexWatch::new(connection, bar.as_ref(), workspace.client_settings()); let warnings = workspace.open_roots_with(roots, &mut |event| watch.see(event)); - let skipped = watch.skipped; - server.end_indexing(bar, skipped); + let (skipped, cached) = (watch.skipped, watch.cached); + server.end_indexing(bar, skipped, cached); server.report_scope(warnings); server.register_watchers(); // The pull half of the settings model. Asked here because this is the @@ -1398,8 +1404,8 @@ impl Server { let Server { connection, workspace, .. } = self; let mut watch = IndexWatch::new(connection, bar.as_ref(), workspace.client_settings()); let warnings = workspace.rebuild_index_with(&mut |event| watch.see(event)); - let skipped = watch.skipped; - self.end_indexing(bar, skipped); + let (skipped, cached) = (watch.skipped, watch.cached); + self.end_indexing(bar, skipped, cached); // A rescan can change any module's instantiation count, so every lens // a client is holding may now read wrong. Sent after the bar comes // down, for the same reason the bar comes down before the republishes: @@ -1462,16 +1468,22 @@ impl Server { /// `skipped` is how many files the size cap kept out, and it is named here /// whether or not the per-file log is on: the log is the *detail*, and a /// user who turned it off should still learn that part of their workspace - /// is not in the index. - fn end_indexing(&self, token: Option, skipped: usize) { + /// is not in the index. `cached` is how many were restored from the + /// persistent index cache rather than parsed, and is named for the + /// opposite reason — a scan that finished suspiciously fast should say + /// why (`docs/features/index-persistence/README.md`). + fn end_indexing(&self, token: Option, skipped: usize, cached: usize) { let Some(token) = token else { return }; let files = self.workspace.index().files().len(); let plural = if files == 1 { "" } else { "s" }; - let message = Some(match skipped { - 0 => format!("{files} file{plural} indexed"), - _ => format!("{files} file{plural} indexed, {skipped} skipped"), - }); - self.progress(token, WorkDoneProgress::End(WorkDoneProgressEnd { message })); + let mut message = format!("{files} file{plural} indexed"); + if cached > 0 { + message.push_str(&format!(", {cached} from cache")); + } + if skipped > 0 { + message.push_str(&format!(", {skipped} skipped")); + } + self.progress(token, WorkDoneProgress::End(WorkDoneProgressEnd { message: Some(message) })); } /// Ask the client to re-request its code lenses, because the rescan just @@ -1619,6 +1631,11 @@ struct IndexWatch<'a> { /// How many files the size cap kept out of this rebuild. Counted whether /// or not the log is on, because the end message names it either way. skipped: usize, + /// How many files came out of the persistent cache instead of being + /// parsed. Counted for the same reason and named in the same message: it + /// is the difference between "this scan was fast" and "this scan was fast + /// **because** it did not have to redo last session's work". + cached: usize, } impl<'a> IndexWatch<'a> { @@ -1627,7 +1644,7 @@ impl<'a> IndexWatch<'a> { bar: Option<&'a ProgressToken>, settings: &ClientSettings, ) -> IndexWatch<'a> { - IndexWatch { connection, bar, log_files: settings.log_files, skipped: 0 } + IndexWatch { connection, bar, log_files: settings.log_files, skipped: 0, cached: 0 } } /// Report one thing the rebuild just did. @@ -1637,6 +1654,14 @@ impl<'a> IndexWatch<'a> { self.say(format!("indexing: {}", path.display())); self.tick(done, total, path); } + // A different word for a file that cost nothing, and the same + // tick: a cached file is a file of the work list, and the bar + // flying through them is exactly what the cache bought. + IndexEvent::Cached { done, total, path } => { + self.cached += 1; + self.say(format!("cached: {}", path.display())); + self.tick(done, total, path); + } IndexEvent::Skipped { path, size, cap } => { self.skipped += 1; self.say(format!( @@ -1962,9 +1987,21 @@ mod tests { roots: Vec, abilities: ClientAbilities, settings: ClientSettings, + ) -> Session { + Session::started_in(roots, abilities, settings, None) + } + + /// [`Session::started`] against a client that offered a storage + /// folder — `initializationOptions.storagePath`, which is where the + /// persistent index cache goes. + fn started_in( + roots: Vec, + abilities: ClientAbilities, + settings: ClientSettings, + storage: Option, ) -> Session { let (server_end, client) = Connection::memory(); - let server = Server::started(server_end, roots, abilities, settings); + let server = Server::started(server_end, roots, abilities, settings, storage); Session { server, client } } @@ -2569,6 +2606,127 @@ mod tests { }) } + /// The `message` of every `$/progress` end in one drained batch, and every + /// `window/logMessage` line in it. Read off one drain rather than through + /// `Session::ended`/`logged`, because a test that wants both cannot drain + /// twice. + fn ends(messages: &[Message]) -> Vec> { + messages + .iter() + .filter_map(|message| match message { + Message::Notification(n) if n.method == Progress::METHOD => { + let params: ProgressParams = + serde_json::from_value(n.params.clone()).expect("progress params"); + let ProgressParamsValue::WorkDone(work) = params.value; + match work { + WorkDoneProgress::End(end) => Some(end.message), + _ => None, + } + } + _ => None, + }) + .collect() + } + + fn log_lines(messages: &[Message]) -> Vec { + messages + .iter() + .filter_map(|message| match message { + Message::Notification(n) if n.method == LogMessage::METHOD => { + let params: LogMessageParams = + serde_json::from_value(n.params.clone()).expect("log params"); + Some(params.message) + } + _ => None, + }) + .collect() + } + + #[test] + fn a_second_session_over_the_same_storage_folder_resumes_from_the_cache() { + // The owner's case, end to end through the real dispatch: a session + // indexes a tree, the editor goes away, and the next session over the + // same storage folder gets the same index without parsing anything. + let tree = Tree::new("resume"); + tree.package("rtl/a.sv", "a_pkg"); + tree.package("rtl/b.sv", "b_pkg"); + let storage = Tree::new("resume_storage"); + let wide = ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + ..Default::default() + }; + + let mut first = Session::started_in( + vec![tree.path.clone()], + watching_progress(), + wide.clone(), + Some(storage.path.clone()), + ); + let cold = first.drain(); + assert_eq!(ends(&cold), vec![Some("2 files indexed".to_string())], "a cold session"); + assert_eq!( + log_lines(&cold).iter().filter(|line| line.starts_with("indexing: ")).count(), + 2, + "both files were parsed: {:?}", + log_lines(&cold) + ); + let before = first.server.workspace.index().fingerprint(); + let answer = + first.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query": "pkg"})); + drop(first); + + let mut second = Session::started_in( + vec![tree.path.clone()], + watching_progress(), + wide, + Some(storage.path.clone()), + ); + let warm = second.drain(); + assert_eq!( + ends(&warm), + vec![Some("2 files indexed, 2 from cache".to_string())], + "the bar says where the files came from" + ); + let lines = log_lines(&warm); + assert_eq!( + lines.iter().filter(|line| line.starts_with("cached: ")).count(), + 2, + "and so does the log, file by file: {lines:?}" + ); + assert!( + !lines.iter().any(|line| line.starts_with("indexing: ")), + "nothing was parsed: {lines:?}" + ); + assert_eq!( + second.server.workspace.index().fingerprint(), + before, + "the same index, byte for byte" + ); + assert_eq!( + second.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query": "pkg"})), + answer, + "and the same answers over the wire" + ); + } + + #[test] + fn a_session_that_was_offered_no_storage_folder_keeps_its_index_in_memory() { + // What every client but ours does, and what `smoke.js` does: no + // `storagePath`, no workspace root to key an OS-directory store on, + // so nothing is persisted and nothing is read — today's behaviour, + // unchanged. + let tree = Tree::new("nostorage"); + tree.package("rtl/a.sv", "a_pkg"); + let session = Session::wide_with(vec![tree.path.clone()], watching_progress()); + let first = session.drain(); + assert_eq!(ends(&first), vec![Some("1 file indexed".to_string())]); + assert!( + log_lines(&first).iter().all(|line| !line.starts_with("cached: ")), + "nothing can come from a cache that was never written: {:?}", + log_lines(&first) + ); + } + #[test] fn the_end_message_names_what_the_cap_skipped() { // The count survives even when the per-file log is off, because it is diff --git a/crates/lucisv_server/src/settings.rs b/crates/lucisv_server/src/settings.rs index 0b85b3c..274f01e 100644 --- a/crates/lucisv_server/src/settings.rs +++ b/crates/lucisv_server/src/settings.rs @@ -112,6 +112,18 @@ pub struct ClientSettings { /// file's own folder. Ignored when `index_scope` is /// [`IndexScope::Workspace`] or when a filelist defines the scope. pub index_scope_depth: u64, + /// `lucisv.index.persist`: whether what a scan parsed is written to disk + /// so the next session can skip parsing the files that have not changed. + /// On unless a client says otherwise — a half-finished scan that has to + /// start again from zero is the thing this exists to prevent. Off means + /// off in both directions: nothing is read and nothing is written + /// (`docs/features/index-persistence/README.md`). + pub index_persist: bool, + /// `lucisv.index.cachePath`: where that store lives, absolute or relative + /// to the first workspace root. Empty means "unset", and then the + /// editor's own storage folder — or this platform's cache directory — + /// decides; see `index_cache::cache_dir` for the ladder. + pub index_cache_path: Option, } /// The settings a client that said nothing is treated as having asked for. @@ -132,6 +144,8 @@ impl Default for ClientSettings { log_files: true, index_scope: IndexScope::Folder, index_scope_depth: 0, + index_persist: true, + index_cache_path: None, } } } @@ -180,6 +194,13 @@ pub fn from_payload(settings: &Value) -> ClientSettings { // guess in. index_scope: scope(index.and_then(|i| i.get("scope"))).unwrap_or_default(), index_scope_depth: count(index.and_then(|i| i.get("scopeDepth"))).unwrap_or(0), + // A wrong-typed `persist` leaves the cache on. The direction that + // costs something is turning it *off* by accident — a user who never + // touched the setting would silently pay for every parse again — and + // a cache that is on can only ever cost a file's parse, because every + // hit is verified against the file's own bytes. + index_persist: flag(index.and_then(|i| i.get("persist"))).unwrap_or(true), + index_cache_path: path(index.and_then(|i| i.get("cachePath"))), } } @@ -362,7 +383,8 @@ mod tests { let section = json!({ "index": { "maxFileSize": 4096, "logFiles": false, - "scope": "workspace", "scopeDepth": 2 + "scope": "workspace", "scopeDepth": 2, + "persist": false, "cachePath": "/tmp/store" } }); let pulled = from_section(§ion); @@ -370,9 +392,48 @@ mod tests { assert!(!pulled.log_files); assert_eq!(pulled.index_scope, IndexScope::Workspace); assert_eq!(pulled.index_scope_depth, 2); + assert!(!pulled.index_persist); + assert_eq!(pulled.index_cache_path.as_deref(), Some("/tmp/store")); assert_eq!(pulled, settings(json!({ "lucisv": section })), "one set of rules"); } + #[test] + fn the_index_cache_is_on_until_a_client_turns_it_off() { + // Same shape as the file log, and the same direction for junk: the + // setting that costs a user work if it is guessed wrong is "off", so + // anything unreadable leaves it on. + assert!(settings(json!({ "lucisv": {} })).index_persist, "absence is on"); + assert!(settings(json!({ "lucisv": { "index": {} } })).index_persist, "so is an empty one"); + assert!(settings(json!({ "lucisv": { "index": { "persist": true } } })).index_persist); + assert!(!settings(json!({ "lucisv": { "index": { "persist": false } } })).index_persist); + for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] { + let found = settings(json!({ "lucisv": { "index": { "persist": bad } } })); + assert!(found.index_persist, "persist {bad} must be ignored"); + } + } + + #[test] + fn the_cache_path_is_unset_until_a_client_names_one() { + // The empty string is `lucisv.index.cachePath`'s own default and means + // "you decide", exactly as it does for `lucisv.filelist` — not "the + // directory named by the empty path". + assert_eq!(settings(json!({ "lucisv": {} })).index_cache_path, None); + assert_eq!( + settings(json!({ "lucisv": { "index": { "cachePath": "" } } })).index_cache_path, + None + ); + assert_eq!( + settings(json!({ "lucisv": { "index": { "cachePath": ".cache/lucisv" } } })) + .index_cache_path + .as_deref(), + Some(".cache/lucisv") + ); + for bad in [json!(1), json!(true), json!(null), json!(["/a"]), json!({ "path": "/a" })] { + let found = settings(json!({ "lucisv": { "index": { "cachePath": bad } } })); + assert_eq!(found.index_cache_path, None, "cachePath {bad} must be ignored"); + } + } + #[test] fn the_index_scope_is_the_open_folder_until_a_client_asks_for_the_workspace() { // The default is the narrow one, and it is what silence, an empty diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index 96605b8..c5de810 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -13,8 +13,8 @@ use vlog_parser::defines::{collect_defines, DefineTable}; use vlog_parser::token::Token; use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic}; use vlog_semantic::{ - analyze, index_order, resolve_external, ExternalResolutions, IndexBuilder, Semantics, - WorkspaceIndex, + analyze, index_order, resolve_external, ExternalResolutions, FileFacts, IndexBuilder, + Semantics, WorkspaceIndex, }; use lucisv_core::config::Discovery; @@ -23,6 +23,7 @@ use lucisv_core::walk::{collect_files, EXTENSIONS}; use crate::candidates::Candidates; use crate::convert::Positions; use crate::includes::IncludeGraph; +use crate::index_cache::IndexCache; use crate::settings::{ClientSettings, IndexScope}; use crate::uri::uri_to_path; @@ -114,6 +115,12 @@ pub enum IndexEvent<'a> { /// counts from 0, so the file being reported is number `done + 1` of /// `total`. Parsing { done: usize, total: usize, path: &'a Path }, + /// One file went into the index from the persistent cache instead of + /// being parsed. The same three numbers [`IndexEvent::Parsing`] carries, + /// because it is the same file of the same work list — it is *how* it got + /// there that differs, and a user watching a rescan fly through a + /// thousand files deserves to be told why. + Cached { done: usize, total: usize, path: &'a Path }, /// A walked file was skipped without being read, because it is bigger /// than the size cap in force. Skipped { path: &'a Path, size: u64, cap: u64 }, @@ -150,6 +157,15 @@ pub struct Workspace { includes: IncludeGraph, /// The last `lucisv.*` settings a client pushed. Default until it does. client: ClientSettings, + /// What previous sessions' scans parsed, keyed by content: a file whose + /// bytes are in here is indexed without being parsed again. Re-opened at + /// the start of every whole rescan, because that is when the directory it + /// should live in can have moved (`docs/features/index-persistence`). + cache: IndexCache, + /// `initializationOptions.storagePath`: the per-workspace folder the + /// editor offered for exactly this. One rung of the cache-directory + /// ladder, and the only one the server cannot work out for itself. + storage: Option, /// Every directory a buffer has been opened from this session, unraised /// and deduped. The folder scope is derived from these rather than from /// the currently-open buffers, so **closing a file never narrows the @@ -336,10 +352,53 @@ impl Workspace { || self.client.max_file_size != settings.max_file_size || self.client.index_scope != settings.index_scope || self.client.index_scope_depth != settings.index_scope_depth; + // Neither cache setting changes *which files exist*, so neither asks + // for a rescan — but both change where, or whether, the cache writes, + // and the cache in hand was opened under the old ones. Dropping it + // here is what makes `persist: false` take effect at once in both + // directions: nothing more is written, and nothing held is read. The + // next whole rescan opens the store the new settings name. + if self.client.index_persist != settings.index_persist + || self.client.index_cache_path != settings.index_cache_path + { + self.cache = IndexCache::disabled(); + } self.client = settings; rescan } + /// Where the persistent index cache should live, by + /// [`crate::index_cache::cache_dir`]'s ladder — the client's setting, the + /// editor's storage folder, this platform's cache directory, or nowhere. + fn cache_dir(&self) -> Option { + // In this crate's own tests nothing falls through to the OS cache + // directory: a unit test must not write into the developer's own + // `~/Library/Caches`, and every test that is *about* the cache names + // a directory of its own — a `cachePath` or a `storagePath` — which + // the ladder below still answers with. The OS rung itself is tested + // where it is written, against `index_cache::cache_dir` directly. + #[cfg(test)] + if self.client.index_cache_path.is_none() && self.storage.is_none() { + return None; + } + crate::index_cache::cache_dir( + &self.client, + self.storage.as_deref(), + &self.roots, + self.filelist_path().as_deref(), + ) + } + + /// Adopt `initializationOptions.storagePath` — the folder the editor set + /// aside for this workspace's server state. + /// + /// Called once, before the first index build, because it is one rung of + /// the ladder that decides where the cache is read from. A client that + /// sends nothing leaves the OS cache directory to decide. + pub fn set_storage_path(&mut self, storage: Option) { + self.storage = storage; + } + pub fn document(&self, uri: &Uri) -> Option<&Document> { self.docs.get(uri) } @@ -404,12 +463,35 @@ impl Workspace { let ordered = self.open_first(index_order(sources.iter().map(|(p, t)| (p.clone(), t.as_str())))); let total = ordered.len(); + // Re-opened here rather than held across rescans: the directory it + // belongs in depends on settings that arrive after startup, and a + // second session over the same workspace may have written records + // this one has not seen. + self.cache = IndexCache::open(self.cache_dir()); let mut builder = IndexBuilder::new(); for (done, (path, text)) in ordered.into_iter().enumerate() { - watch(IndexEvent::Parsing { done, total, path: &path }); - builder.add_file(path, text); + // The cache answers for the exact bytes about to be indexed, so a + // hit is the parse and not a guess at it. A miss — a new file, a + // changed one, a record this version cannot read — parses, and + // the result is written through immediately, which is what makes + // an interrupted scan resumable. + match self.cache.facts_for(&path, text) { + Some(facts) => { + watch(IndexEvent::Cached { done, total, path: &path }); + builder.add_facts(facts); + } + None => { + watch(IndexEvent::Parsing { done, total, path: &path }); + let facts = FileFacts::of(path, text); + self.cache.record(&facts, text); + builder.add_facts(facts); + } + } } self.index = builder.finish(); + // The one moment the live set of entries is known, so the one moment + // the append log is worth rewriting. + self.cache.compact(); // Built here, from the same list, so a file the scope ladder excluded // contributes no completion candidates either. self.candidates = Candidates::build(&self.index, &sources); @@ -457,6 +539,15 @@ impl Workspace { self.index.update_file(path.to_path_buf(), &text); self.candidates.update_file(&self.index, path, &text); self.includes.update_file(path, &text, self.index.files()); + // Written through here too, so an hour of saves is an hour of + // work the next session does not repeat. The record is the + // one the update just made — no second parse — and it is + // keyed by the text it was made from, which is the buffer's + // when a buffer beat disk. That record is simply never hit + // again if the file on disk says something else. + if let Some(facts) = self.index.facts_for(path) { + self.cache.record(facts, &text); + } } None => { self.index.remove_file(path); @@ -2206,4 +2297,483 @@ mod tests { "and with nothing to clamp against the climb stops at the filesystem root" ); } + + // ------------------------------------------------------------------ + // the persistent index cache (docs/features/index-persistence) + // ------------------------------------------------------------------ + + /// A client that keeps its index cache in `dir`. + fn caching(dir: &Path) -> ClientSettings { + ClientSettings { + index_cache_path: Some(dir.to_string_lossy().into_owned()), + ..Default::default() + } + } + + /// What one whole scan did, file by file: what it parsed, and what it + /// took from the cache instead. The two together are the work list. + #[derive(Debug, Default, PartialEq, Eq)] + struct Scan { + parsed: Vec, + cached: Vec, + } + + /// Scan `roots` (or rescan what is already open, with `None`) and record + /// which files were parsed and which came out of the cache. + fn scan(ws: &mut Workspace, roots: Option>) -> Scan { + let mut out = Scan::default(); + { + let mut see = |event: IndexEvent| match event { + IndexEvent::Parsing { path, .. } => out.parsed.push(file_name(path)), + IndexEvent::Cached { path, .. } => out.cached.push(file_name(path)), + IndexEvent::Skipped { .. } => {} + }; + match roots { + Some(roots) => ws.open_whole_workspace_with(roots, &mut see), + None => ws.rebuild_index_with(&mut see), + }; + } + out + } + + fn file_name(path: &Path) -> String { + path.file_name().expect("a file").to_string_lossy().into_owned() + } + + /// A workspace that keeps its cache in `store` and indexes every root. + fn cached_workspace(store: &Path) -> Workspace { + let mut ws = Workspace::default(); + ws.set_client_settings(wide(caching(store))); + ws + } + + #[test] + fn a_second_session_over_the_same_store_parses_nothing_it_parsed_before() { + let tree = Tree::new("cachewarm"); + tree.package("a.sv", "a_pkg"); + tree.package("b.sv", "b_pkg"); + let store = Tree::new("cachewarm_store"); + + let mut cold = cached_workspace(&store.path); + let first = scan(&mut cold, Some(vec![tree.path.clone()])); + assert_eq!(first.parsed, ["a.sv", "b.sv"], "a cold scan parses everything"); + assert!(first.cached.is_empty(), "{first:?}"); + let fingerprint = cold.index().fingerprint(); + + // A whole new server over the same tree and the same store — which is + // what reopening the editor is. + let mut warm = cached_workspace(&store.path); + let second = scan(&mut warm, Some(vec![tree.path.clone()])); + assert!(second.parsed.is_empty(), "a warm scan parses nothing: {second:?}"); + assert_eq!(second.cached, ["a.sv", "b.sv"]); + assert_eq!( + warm.index().fingerprint(), + fingerprint, + "and the index it built is the index the parses built" + ); + } + + #[test] + fn a_half_warm_scan_parses_exactly_what_the_store_cannot_answer_for() { + // The resume case, which is the whole feature: a store holding some + // of the workspace — because the last session was killed halfway, or + // because files have changed since — costs exactly the files it does + // not answer for, and nothing else. + let tree = Tree::new("cachehalf"); + tree.package("a.sv", "a_pkg"); + tree.package("b.sv", "b_pkg"); + let store = Tree::new("cachehalf_store"); + + let mut first = cached_workspace(&store.path); + scan(&mut first, Some(vec![tree.path.clone()])); + + tree.package("b.sv", "b_renamed_pkg"); // changed since + tree.package("c.sv", "c_pkg"); // never seen + let mut second = cached_workspace(&store.path); + let half = scan(&mut second, Some(vec![tree.path.clone()])); + assert_eq!(half.cached, ["a.sv"], "only the untouched file: {half:?}"); + assert_eq!(half.parsed, ["b.sv", "c.sv"]); + + let mut fresh = Workspace::default(); + fresh.set_client_settings(wide(ClientSettings::default())); + fresh.open_whole_workspace(vec![tree.path.clone()]); + assert_eq!( + second.index().fingerprint(), + fresh.index().fingerprint(), + "a half-cached index is the index a cacheless scan would have built" + ); + } + + #[test] + fn the_key_is_the_content_and_only_the_content() { + // Both directions of "no timestamp is trusted": a file rewritten with + // the same bytes still hits (its modification time moved and nothing + // else did), and a file rewritten with *different* bytes of the same + // length misses. A cache keyed on size and mtime would get both of + // these exactly the wrong way round. + let tree = Tree::new("cachekey"); + tree.write("a.sv", "package a_pkg;\n localparam K = 1;\nendpackage\n"); + let store = Tree::new("cachekey_store"); + + let mut ws = cached_workspace(&store.path); + scan(&mut ws, Some(vec![tree.path.clone()])); + + tree.write("a.sv", "package a_pkg;\n localparam K = 1;\nendpackage\n"); + let touched = scan(&mut ws, None); + assert_eq!(touched.cached, ["a.sv"], "the same bytes are the same file: {touched:?}"); + + tree.write("a.sv", "package a_pkg;\n localparam K = 2;\nendpackage\n"); + let changed = scan(&mut ws, None); + assert_eq!(changed.parsed, ["a.sv"], "one byte of difference is a miss: {changed:?}"); + } + + #[test] + fn the_cache_never_puts_back_a_file_the_scan_no_longer_visits() { + // A record is not a file. The scope ladder decides what is walked; + // the cache only ever answers *for* something already on the work + // list, so a session whose scope has narrowed has an index that + // narrowed with it, records or no records. + let tree = Tree::new("cachescope"); + tree.package("rtl/a.sv", "a_pkg"); + tree.package("tb/b.sv", "b_pkg"); + let store = Tree::new("cachescope_store"); + + let mut wide_session = cached_workspace(&store.path); + scan(&mut wide_session, Some(vec![tree.path.clone()])); + assert_eq!(indexed(&wide_session, &["a_pkg", "b_pkg"]), ["a_pkg", "b_pkg"]); + + // The next session is folder-scoped and only ever opens a file in + // `rtl/`, so `tb/` is not walked at all. + let mut narrow = Workspace::default(); + narrow.set_client_settings(caching(&store.path)); + narrow.open_roots_with(vec![tree.path.clone()], &mut |_| {}); + open(&mut narrow, &tree, "rtl/a.sv"); + let narrowed = scan(&mut narrow, None); + assert_eq!(narrowed.cached, ["a.sv"], "{narrowed:?}"); + assert_eq!( + indexed(&narrow, &["a_pkg", "b_pkg"]), + ["a_pkg"], + "the record for tb/b.sv exists and is still not an indexed file" + ); + } + + #[test] + fn persistence_off_reads_nothing_and_writes_nothing() { + let tree = Tree::new("cacheoff"); + tree.package("a.sv", "a_pkg"); + let store = Tree::new("cacheoff_store"); + + // Nothing is written while it is off… + let mut off = Workspace::default(); + off.set_client_settings(wide(ClientSettings { + index_persist: false, + ..caching(&store.path) + })); + scan(&mut off, Some(vec![tree.path.clone()])); + assert!(!store.path.join("index-cache").exists(), "persist: false must not write"); + + // …and a store that already exists is not read when it goes off. + let mut on = cached_workspace(&store.path); + scan(&mut on, Some(vec![tree.path.clone()])); + assert!(store.path.join("index-cache").exists(), "premise: a store to ignore"); + let mut ignoring = Workspace::default(); + ignoring.set_client_settings(wide(ClientSettings { + index_persist: false, + ..caching(&store.path) + })); + let scanned = scan(&mut ignoring, Some(vec![tree.path.clone()])); + assert_eq!(scanned.parsed, ["a.sv"], "persist: false must not read: {scanned:?}"); + } + + #[test] + fn turning_persistence_off_mid_session_stops_the_write_through_at_once() { + // A save takes the incremental path, which writes its record through + // without any rescan — so `persist: false` has to reach it the moment + // it lands, not at the next scan. + let tree = Tree::new("cachemidsession"); + tree.package("a.sv", "a_pkg"); + let store = Tree::new("cachemidsession_store"); + + let mut ws = cached_workspace(&store.path); + scan(&mut ws, Some(vec![tree.path.clone()])); + tree.package("a.sv", "a_pkg_v2"); + assert!(ws.update_one(&tree.path.join("a.sv")), "premise: the fast path took it"); + let after_save = fs::read_to_string(store.path.join("index-cache")).expect("a store"); + assert!(after_save.contains("a_pkg_v2"), "a save writes its record through"); + + ws.set_client_settings(wide(ClientSettings { + index_persist: false, + ..caching(&store.path) + })); + tree.package("a.sv", "a_pkg_v3"); + assert!(ws.update_one(&tree.path.join("a.sv"))); + let after_off = fs::read_to_string(store.path.join("index-cache")).expect("a store"); + assert_eq!(after_off, after_save, "nothing more is written once it is off"); + } + + /// QA (2026-08-27), the no-mtime deviation's save-path half: the + /// write-through on `update_one` must key its record on the *buffer's* + /// bytes, never on what happens to be on disk — that is the argument the + /// README gives for why a stored `(size, mtime)` would have been unsound + /// (a save's text can come from an unsaved buffer). Constructed + /// directly: open a buffer whose text disagrees with the file on disk, + /// let the incremental path write its record through, and check the + /// store's record is keyed by the *buffer's* hash and holds the + /// *buffer's* facts — and that disk's actual bytes, hashed, do not + /// match what got written. + #[test] + fn a_saved_buffers_record_is_keyed_and_filled_from_the_buffer_not_stale_disk() { + let tree = Tree::new("cachebuffer"); + tree.package("a.sv", "a_pkg_on_disk"); + let store = Tree::new("cachebuffer_store"); + + let mut ws = cached_workspace(&store.path); + scan(&mut ws, Some(vec![tree.path.clone()])); + + // The buffer disagrees with disk — as it does the moment a user + // types, before the editor's next `didSave` reaches disk at all. + let path = tree.path.join("a.sv"); + let buffer_text = "package a_pkg_in_buffer;\n localparam K = 1;\nendpackage\n"; + let uri = crate::uri::path_to_uri(&path).expect("uri"); + ws.set_document(uri, buffer_text.to_string()); + assert!(ws.update_one(&path), "premise: the fast path took it"); + + // The append log still holds the earlier, disk-keyed line too — it is + // not rewritten until the next whole-scan compaction — so the write + // itself is checked by what it added, and the *effective* record + // (what `open` resolves a repeated path to: the last line wins) is + // checked separately below, which is the property that actually + // matters for correctness. + let store_text = fs::read_to_string(store.path.join("index-cache")).expect("a store"); + assert!( + store_text.contains("a_pkg_in_buffer"), + "the write-through must have appended the buffer's facts: {store_text}" + ); + let buffer_hash = lucisv_core::cache::content_hash(buffer_text.as_bytes()); + assert!( + store_text.contains(&format!("{buffer_hash:016x}")), + "the appended record's key is the buffer's content hash: {store_text}" + ); + + let disk_text = fs::read_to_string(&path).expect("disk"); + let disk_hash = lucisv_core::cache::content_hash(disk_text.as_bytes()); + assert_ne!(disk_hash, buffer_hash, "premise: disk and buffer really do disagree"); + + let reopened = IndexCache::open(Some(store.path.clone())); + assert_eq!( + reopened.facts_for(&path, buffer_text), + Some(FileFacts::of(path.clone(), buffer_text)), + "the record a fresh session resolves to is the buffer's, not disk's stale one" + ); + assert!( + reopened.facts_for(&path, &disk_text).is_none(), + "disk's own current bytes must not hit — no record was ever keyed on them" + ); + } + + #[test] + fn a_configured_cache_path_beats_the_editors_storage_folder() { + // Rung 1 over rung 2 of `index_cache::cache_dir`'s ladder, through + // the workspace rather than against the function: the store lands + // where the *setting* says, and the editor's folder is left alone. + let tree = Tree::new("cacheladder"); + tree.package("a.sv", "a_pkg"); + let storage = Tree::new("cacheladder_storage"); + let configured = Tree::new("cacheladder_configured"); + + let mut ws = Workspace::default(); + ws.set_storage_path(Some(storage.path.clone())); + ws.set_client_settings(wide(caching(&configured.path))); + scan(&mut ws, Some(vec![tree.path.clone()])); + assert!(configured.path.join("index-cache").exists(), "the setting won"); + assert!(!storage.path.join("index-cache").exists(), "the editor's folder is untouched"); + + // Unset it and the editor's folder is what is left standing — on the + // next scan, which is when the store is re-opened. + ws.set_client_settings(wide(ClientSettings::default())); + ws.set_storage_path(Some(storage.path.clone())); + scan(&mut ws, None); + assert!(storage.path.join("index-cache").exists(), "and now the editor's folder"); + } + + #[test] + fn a_storage_folder_that_does_not_exist_yet_is_made_on_demand() { + // What VS Code hands over: `context.storageUri` names a folder the + // editor has not necessarily created. + let tree = Tree::new("cachemkdir"); + tree.package("a.sv", "a_pkg"); + let storage = Tree::new("cachemkdir_storage"); + let nested = storage.path.join("deep/inner"); + + let mut ws = Workspace::default(); + ws.set_storage_path(Some(nested.clone())); + ws.set_client_settings(wide(ClientSettings::default())); + scan(&mut ws, Some(vec![tree.path.clone()])); + assert!(nested.join("index-cache").exists(), "made on demand"); + + let mut warm = Workspace::default(); + warm.set_storage_path(Some(nested)); + warm.set_client_settings(wide(ClientSettings::default())); + let second = scan(&mut warm, Some(vec![tree.path.clone()])); + assert_eq!(second.cached, ["a.sv"], "{second:?}"); + } + + #[test] + fn the_cached_index_is_the_index_a_fresh_scan_would_have_built_over_the_corpus() { + // The paranoid sweep, against the real corpus: every file in, every + // file out of the cache, and the two indexes compared observable by + // observable through the fingerprint. + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let store = Tree::new("cachecorpus_store"); + + let mut cold = cached_workspace(&store.path); + let first = scan(&mut cold, Some(vec![corpus.clone()])); + assert!(first.parsed.len() > 500, "premise: the corpus was really scanned"); + assert!(first.cached.is_empty()); + + let mut warm = cached_workspace(&store.path); + let second = scan(&mut warm, Some(vec![corpus])); + assert_eq!(second.cached.len(), first.parsed.len(), "every file came back"); + assert!(second.parsed.is_empty(), "and none was parsed again"); + assert_eq!( + warm.index().fingerprint(), + cold.index().fingerprint(), + "the cached index is the parsed index, file ids and all" + ); + assert_eq!(warm.index().counts(), cold.index().counts()); + // The completion tables and the include graph are built from the + // files' text either way, so they cannot drift — pinned rather than + // assumed, since the cache is the one thing that skips a file's parse. + assert_eq!(warm.candidates().words(""), cold.candidates().words("")); + } + + /// QA (2026-08-27), attack surface 1/4, fixed 2026-08-27: the negative + /// control the equivalence sweep above cannot run on its own, through the + /// whole workspace rather than the store. A record used to be verified + /// only against the *file's* content hash, so a line whose hash matched + /// `a.sv`'s real bytes but whose facts were altered was a hit and the + /// index it produced silently diverged from what a fresh parse gives. + /// Every record now carries a checksum of its own facts, so the damaged + /// line is dropped: the file is parsed, the scan reports it as parsed + /// rather than cached, and the fingerprint is exactly a fresh scan's. + /// That is `docs/features/index-persistence`'s "a performance artifact + /// and never a correctness input" holding against *accidental* damage of + /// any shape; a store deliberately reforged is out of the threat model + /// and pinned as such in `index_cache.rs`. + #[test] + fn a_poisoned_cache_record_is_dropped_and_the_index_is_a_fresh_scans() { + let tree = Tree::new("poisonfingerprint"); + tree.package("a.sv", "a_pkg"); + let store = Tree::new("poisonfingerprint_store"); + + let mut cold = cached_workspace(&store.path); + scan(&mut cold, Some(vec![tree.path.clone()])); + let honest = cold.index().fingerprint(); + + // Hand-tamper the store on disk: keep the header, the hash of `a.sv`'s + // *real* bytes and the checksum the genuine record was written with, + // but swap in facts a parse of those bytes never produced (a different + // package name entirely) — which is what every accidental way a + // written record can change looks like from the reader's side. + let store_file = store.path.join("index-cache"); + let text = fs::read_to_string(&store_file).expect("a store"); + let header_line = text.lines().next().expect("header").to_string(); + let record = text.lines().nth(1).expect("a record").to_string(); + let checksum = record.rsplit('\t').next().expect("a checksum field"); + let real_text = "package a_pkg;\n localparam K = 1;\nendpackage\n"; + let hash = lucisv_core::cache::content_hash(real_text.as_bytes()); + let evil = FileFacts::of( + tree.path.join("a.sv"), + "package poisoned_pkg;\n localparam K = 999;\nendpackage\n", + ); + let poisoned = format!( + "{header_line}\n{hash:016x}\t{}\t{checksum}\n", + evil.encode().expect("encodes") + ); + fs::write(&store_file, poisoned).expect("write"); + + let mut warm = cached_workspace(&store.path); + let scanned = scan(&mut warm, Some(vec![tree.path.clone()])); + assert_eq!(scanned.parsed, ["a.sv"], "the tampered record is dropped: {scanned:?}"); + assert!(scanned.cached.is_empty(), "and it is not served: {scanned:?}"); + assert_eq!( + warm.index().fingerprint(), + honest, + "a record whose facts no longer match their checksum cannot reach the index, so \ + the equivalence sweep's own claim holds against damage as well as staleness" + ); + } + + /// The measurement behind the README's numbers: a scan with no cache at + /// all, a cold one that fills the store, a warm one that reads it, and a + /// half-warm one with a single file changed. + #[test] + #[ignore = "measurement, not a test"] + fn qa_perf_cold_warm_and_half_warm_scans() { + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let store = Tree::new("cacheperf_store"); + let timed = |ws: &mut Workspace| { + let started = std::time::Instant::now(); + let scanned = scan(ws, None); + (started.elapsed(), scanned) + }; + + // The baseline: what a rescan cost before this feature existed. + let mut off = Workspace::default(); + off.set_client_settings(wide(ClientSettings { + index_persist: false, + ..caching(&store.path) + })); + scan(&mut off, Some(vec![corpus.clone()])); + let (cacheless, _) = timed(&mut off); + + let mut ws = cached_workspace(&store.path); + let started = std::time::Instant::now(); + let cold_scan = scan(&mut ws, Some(vec![corpus.clone()])); + let cold = started.elapsed(); + let (warm, warm_scan) = timed(&mut ws); + + // Half-warm: the store answers for every file but the one edited. + let one = ws.index().files()[0].clone(); + let text = fs::read_to_string(&one).expect("read"); + fs::write(&one, format!("{text}\n// edited\n")).expect("write"); + let (half, half_scan) = timed(&mut ws); + fs::write(&one, &text).expect("restore"); + + let files = ws.index().files().len(); + eprintln!( + "{files} files: no cache {cacheless:?}; cold {cold:?} ({} parsed); \ + warm {warm:?} ({} cached); half-warm {half:?} ({} parsed, {} cached) — \ + warm is {:.2}x the cacheless scan", + cold_scan.parsed.len(), + warm_scan.cached.len(), + half_scan.parsed.len(), + half_scan.cached.len(), + cacheless.as_secs_f64() / warm.as_secs_f64().max(f64::MIN_POSITIVE) + ); + let store_size = fs::metadata(store.path.join("index-cache")).expect("a store").len(); + eprintln!("store: {store_size} bytes for {files} files"); + + // What the key costs, which is the whole argument for keying on + // content rather than on a timestamp: the text is read on every scan + // anyway (the completion tables and the include graph are built from + // it), so the alternative would only ever have saved this. + let texts: Vec = + ws.index().files().iter().filter_map(|path| fs::read_to_string(path).ok()).collect(); + let bytes: usize = texts.iter().map(String::len).sum(); + let started = std::time::Instant::now(); + let mut sink = 0u64; + for text in &texts { + sink ^= lucisv_core::cache::content_hash(text.as_bytes()); + } + eprintln!("hashing {bytes} bytes of {files} files: {:?} ({sink:016x})", started.elapsed()); + } } diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 10ac854..e0f1804 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -61,6 +61,27 @@ fn read_message(input: &mut impl BufRead) -> Option { serde_json::from_slice(&body).ok() } +/// The server binary, with its OS cache directory pointed somewhere a test +/// may write. +/// +/// Without a client-supplied `storagePath` the persistent index cache falls +/// back to this platform's cache directory +/// (`docs/features/index-persistence/README.md`), and the developer's own +/// `~/Library/Caches` is not somewhere a test run may leave anything. The +/// three variables below are the ones that decide it on the three platforms. +/// A test whose subject *is* the cache passes a `storagePath` of its own, +/// which outranks all of them. +fn server_command() -> Command { + let sandbox = + std::env::temp_dir().join(format!("lucisv_server_e2e_home_{}", std::process::id())); + let mut command = Command::new(env!("CARGO_BIN_EXE_lucisv-server")); + command + .env("HOME", &sandbox) + .env("XDG_CACHE_HOME", sandbox.join("cache")) + .env("LOCALAPPDATA", sandbox.join("cache")); + command +} + fn temp_dir(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("lucisv_server_e2e_{}_{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); @@ -74,7 +95,7 @@ fn temp_dir(name: &str) -> PathBuf { /// processes the messages in order and exits on `exit`, so stdout closes and /// the read terminates on its own. fn talk(session: &str) -> Vec { - let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server")) + let mut child = server_command() .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) @@ -2167,7 +2188,7 @@ struct Live { impl Live { fn start() -> Live { - let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server")) + let mut child = server_command() .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) @@ -4374,3 +4395,90 @@ fn a_save_of_one_file_updates_the_index_over_the_wire() { let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn a_second_session_over_the_same_storage_path_indexes_from_the_cache() { + // The owner's case on the wire, with the real binary: one session indexes + // a workspace and writes what it learned into the folder the client named + // in `initializationOptions.storagePath`; a second session over the same + // folder gets the same index without parsing a file + // (docs/features/index-persistence/README.md). + let dir = temp_dir("persist"); + let storage = temp_dir("persist_storage"); + std::fs::write(dir.join("a.sv"), "module a;\nendmodule\n").expect("write"); + std::fs::write(dir.join("b.sv"), "module b;\nendmodule\n").expect("write"); + let root = format!("file://{}", dir.display()); + + let session = || { + [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","initializationOptions":{{"storagePath":{}}},"capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"#, + serde_json::to_string(&storage.display().to_string()).expect("json") + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + // The scope push is what makes the workspace really get walked; + // it also rescans, which is the scan these assertions are about. + frame(WIDE_SCOPE), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat() + }; + + /// Every `window/logMessage` line of a transcript. + fn log_lines(messages: &[serde_json::Value]) -> Vec { + messages + .iter() + .filter(|m| m["method"] == "window/logMessage") + .filter_map(|m| m["params"]["message"].as_str().map(str::to_string)) + .collect() + } + + /// Every progress `end` message of a transcript. + fn ends(messages: &[serde_json::Value]) -> Vec { + messages + .iter() + .filter(|m| m["params"]["value"]["kind"] == "end") + .filter_map(|m| m["params"]["value"]["message"].as_str().map(str::to_string)) + .collect() + } + + let cold = talk(&session()); + assert_eq!(ends(&cold), ["0 files indexed", "2 files indexed"], "{cold:#?}"); + let parsed: Vec = + log_lines(&cold).into_iter().filter(|l| l.starts_with("indexing: ")).collect(); + assert_eq!(parsed.len(), 2, "the first session parses both files: {parsed:?}"); + assert!( + storage.join("index-cache").exists(), + "and writes what it found where the client said: {}", + storage.display() + ); + + let warm = talk(&session()); + assert_eq!( + ends(&warm), + ["0 files indexed", "2 files indexed, 2 from cache"], + "the second session's bar says where its files came from: {warm:#?}" + ); + let lines = log_lines(&warm); + assert_eq!( + lines.iter().filter(|l| l.starts_with("cached: ")).count(), + 2, + "and its log names them one by one: {lines:?}" + ); + assert!( + !lines.iter().any(|l| l.starts_with("indexing: ")), + "with nothing parsed at all: {lines:?}" + ); + + // A file changed between sessions is the only thing the third one parses. + std::fs::write(dir.join("b.sv"), "module b_renamed;\nendmodule\n").expect("write"); + let half = talk(&session()); + let lines = log_lines(&half); + assert_eq!(lines.iter().filter(|l| l.starts_with("cached: ")).count(), 1, "{lines:?}"); + assert_eq!(lines.iter().filter(|l| l.starts_with("indexing: ")).count(), 1, "{lines:?}"); + assert_eq!(ends(&half), ["0 files indexed", "2 files indexed, 1 from cache"], "{half:#?}"); + + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&storage); +} diff --git a/crates/vlog_semantic/src/facts.rs b/crates/vlog_semantic/src/facts.rs new file mode 100644 index 0000000..31b1512 --- /dev/null +++ b/crates/vlog_semantic/src/facts.rs @@ -0,0 +1,432 @@ +//! [`FileFacts`] as one line of text: the format the index cache stores a +//! parse's result in, and reads it back from. +//! +//! Hand-rolled, because the alternative is a serialization dependency in a +//! crate that has one dependency and it is the parser. The shape is the one +//! `lucisv_core::cache` established for the formatter's store — tab-separated +//! fields on one line, so a torn write is a line without a newline and a +//! record that does not parse is a record that is dropped — with lists +//! length-prefixed rather than nested, so reading a record is one pass over a +//! flat token stream and nothing is ambiguous. +//! +//! **Anything that changes what a record holds, or how it is written, bumps +//! [`FACTS_FORMAT`].** A record written by another format is not read at all; +//! see `docs/features/index-persistence/README.md` for why the cache would +//! rather redo the work than guess. + +use std::path::PathBuf; + +use vlog_parser::defines::{Define, DefineKind, DefineTable}; +use vlog_parser::span::TextRange; + +use crate::model::SymbolKind; +use crate::workspace::{Decl, DeclSite, FileFacts, SiteFact}; + +/// The version of the encoding below. Bump it on **any** change to what a +/// record holds or to how it is written: a store stamped with another number +/// is discarded whole, which is the only way a reader can be sure it is not +/// reading last month's field order as this month's. +pub const FACTS_FORMAT: u32 = 1; + +impl FileFacts { + /// These facts as one line's worth of fields, tab-separated. + /// + /// `None` for a path that cannot be written on a line of text — not UTF-8, + /// or holding a tab or a newline. Such a file is simply never cached, the + /// same answer `lucisv_core::cache` gives for the same shape of path. + /// Every *other* string a record holds is escaped instead, because a macro + /// body really can contain a tab. + pub fn encode(&self) -> Option { + let path = self.path.to_str()?; + let mut out = Writer::default(); + out.text(path); + out.tag("D", self.defines.entries().len()); + for define in self.defines.entries() { + out.define(define); + } + out.tag("U", self.units.len()); + for decl in &self.units { + out.decl(decl); + } + out.tag("M", self.members.len()); + for (unit, decl) in &self.members { + out.text(unit); + out.decl(decl); + } + out.tag("I", self.instantiations.len()); + for (module, site) in &self.instantiations { + out.text(module); + out.site(&site.owner); + out.range(site.site_span); + } + out.tag("S", self.subclasses.len()); + for (base, subclass) in &self.subclasses { + out.text(base); + out.site(subclass); + } + Some(out.out) + } + + /// The facts a record describes, or `None` for anything that is not + /// exactly one whole record of this format. + /// + /// Strict on purpose, in both directions: a field missing, a number that + /// does not parse, a kind this version has no name for, a count that + /// outruns the line, **or a field left over at the end** all mean the same + /// thing — this is not a record this version wrote, so nothing is taken + /// from it. A dropped record costs one file's parse; a half-read one would + /// cost correctness. + pub fn decode(line: &str) -> Option { + let mut input = Reader::new(line); + let path = PathBuf::from(input.text()?); + let mut defines = Vec::new(); + for _ in 0..input.tag("D")? { + defines.push(input.define()?); + } + let mut units = Vec::new(); + for _ in 0..input.tag("U")? { + units.push(input.decl()?); + } + let mut members = Vec::new(); + for _ in 0..input.tag("M")? { + members.push((input.text()?, input.decl()?)); + } + let mut instantiations = Vec::new(); + for _ in 0..input.tag("I")? { + let module = input.text()?; + let owner = input.site()?; + instantiations.push((module, SiteFact { owner, site_span: input.range()? })); + } + let mut subclasses = Vec::new(); + for _ in 0..input.tag("S")? { + subclasses.push((input.text()?, input.site()?)); + } + if !input.done() { + return None; + } + Some(FileFacts { + path, + defines: DefineTable::from_entries(defines), + units, + members, + instantiations, + subclasses, + }) + } +} + +/// The path a record is for, without decoding the rest of it. +/// +/// A store keyed by path has to read this out of every record it holds, and +/// only ever decodes the handful it is asked for — so the cheap half of the +/// format is public separately from [`FileFacts::decode`]. `None` for a record +/// whose first field is not a readable path, which is a record that would not +/// decode either. +pub fn record_path(record: &str) -> Option { + let field = record.split('\t').next()?; + Some(PathBuf::from(unescape(field)?)) +} + +/// A record under construction: fields pushed in order, separated by tabs. +#[derive(Default)] +struct Writer { + out: String, + /// Whether a field has been written yet, so the separator goes *between* + /// fields — asked of a flag rather than of `out.is_empty()`, which would + /// be wrong for a first field that is itself empty. + written: bool, +} + +impl Writer { + /// One string field, escaped. + fn text(&mut self, text: &str) { + self.field(); + for ch in text.chars() { + match ch { + '\\' => self.out.push_str("\\\\"), + '\t' => self.out.push_str("\\t"), + '\n' => self.out.push_str("\\n"), + '\r' => self.out.push_str("\\r"), + _ => self.out.push(ch), + } + } + } + + /// One number field. + fn num(&mut self, n: u32) { + self.field(); + self.out.push_str(&n.to_string()); + } + + /// A list's marker and its length — the length prefix that makes the + /// stream flat and still unambiguous. + fn tag(&mut self, tag: &str, len: usize) { + self.field(); + self.out.push_str(tag); + self.num(len as u32); + } + + fn range(&mut self, range: TextRange) { + self.num(range.start); + self.num(range.end); + } + + fn decl(&mut self, decl: &Decl) { + self.text(&decl.name); + self.field(); + self.out.push_str(kind_name(decl.kind)); + self.range(decl.name_span); + } + + fn site(&mut self, site: &DeclSite) { + self.text(&site.name); + self.range(site.name_span); + self.range(site.span); + } + + fn define(&mut self, define: &Define) { + self.field(); + self.out.push(match define.kind { + DefineKind::Define => 'd', + DefineKind::Undef => 'u', + }); + self.text(&define.name); + match &define.params { + // A macro with no parameter list at all is not a macro with an + // empty one — `` `define A x`` against `` `define A() x`` — so the + // two cannot share a spelling. + None => { + self.field(); + self.out.push('-'); + } + Some(params) => { + self.num(params.len() as u32); + for param in params { + self.text(param); + } + } + } + self.text(&define.body); + self.range(define.span); + self.range(define.name_span); + } + + /// The separator before every field but the first. + fn field(&mut self) { + if self.written { + self.out.push('\t'); + } + self.written = true; + } +} + +/// A record being read, one field at a time. +struct Reader<'a> { + fields: Vec<&'a str>, + at: usize, +} + +impl<'a> Reader<'a> { + fn new(line: &'a str) -> Reader<'a> { + Reader { fields: line.split('\t').collect(), at: 0 } + } + + fn next(&mut self) -> Option<&'a str> { + let field = self.fields.get(self.at)?; + self.at += 1; + Some(field) + } + + /// Whether every field has been read — the check that makes a record with + /// something extra on the end invalid rather than merely surprising. + fn done(&self) -> bool { + self.at == self.fields.len() + } + + fn text(&mut self) -> Option { + unescape(self.next()?) + } + + fn num(&mut self) -> Option { + self.next()?.parse().ok() + } + + fn range(&mut self) -> Option { + Some(TextRange::new(self.num()?, self.num()?)) + } + + /// A list's length, once its marker has been confirmed. The marker is what + /// turns a misaligned read into a dropped record instead of a plausible + /// one. + fn tag(&mut self, tag: &str) -> Option { + if self.next()? != tag { + return None; + } + Some(self.num()? as usize) + } + + fn decl(&mut self) -> Option { + let name = self.text()?; + let kind = kind_of(self.next()?)?; + Some(Decl { name, name_span: self.range()?, kind }) + } + + fn site(&mut self) -> Option { + Some(DeclSite { name: self.text()?, name_span: self.range()?, span: self.range()? }) + } + + fn define(&mut self) -> Option { + let kind = match self.next()? { + "d" => DefineKind::Define, + "u" => DefineKind::Undef, + _ => return None, + }; + let name = self.text()?; + let params = match self.next()? { + "-" => None, + count => { + let count: u32 = count.parse().ok()?; + let mut params = Vec::new(); + for _ in 0..count { + params.push(self.text()?); + } + Some(params) + } + }; + Some(Define { + kind, + name, + params, + body: self.text()?, + span: self.range()?, + name_span: self.range()?, + }) + } +} + +/// One escaped string field, back as it was written. `None` for an escape +/// this format does not write, which is a record it did not write either. +fn unescape(field: &str) -> Option { + let mut out = String::with_capacity(field.len()); + let mut chars = field.chars(); + while let Some(ch) = chars.next() { + if ch != '\\' { + out.push(ch); + continue; + } + out.push(match chars.next()? { + '\\' => '\\', + 't' => '\t', + 'n' => '\n', + 'r' => '\r', + _ => return None, + }); + } + Some(out) +} + +/// A [`SymbolKind`]'s name in a record. Written out rather than numbered, so +/// a variant inserted in the middle of the enum cannot silently turn one kind +/// into another — and a name this version does not know drops the record. +fn kind_name(kind: SymbolKind) -> &'static str { + match kind { + SymbolKind::Module => "module", + SymbolKind::Package => "package", + SymbolKind::Port => "port", + SymbolKind::Net => "net", + SymbolKind::Var => "var", + SymbolKind::Param => "param", + SymbolKind::Genvar => "genvar", + SymbolKind::Typedef => "typedef", + SymbolKind::EnumVariant => "enumvariant", + SymbolKind::Function => "function", + SymbolKind::Task => "task", + SymbolKind::TfArg => "tfarg", + SymbolKind::Instance => "instance", + SymbolKind::Block => "block", + SymbolKind::StructMember => "structmember", + SymbolKind::Class => "class", + } +} + +/// The inverse of [`kind_name`], total in the other direction: anything else +/// is not a kind this version writes. +fn kind_of(name: &str) -> Option { + Some(match name { + "module" => SymbolKind::Module, + "package" => SymbolKind::Package, + "port" => SymbolKind::Port, + "net" => SymbolKind::Net, + "var" => SymbolKind::Var, + "param" => SymbolKind::Param, + "genvar" => SymbolKind::Genvar, + "typedef" => SymbolKind::Typedef, + "enumvariant" => SymbolKind::EnumVariant, + "function" => SymbolKind::Function, + "task" => SymbolKind::Task, + "tfarg" => SymbolKind::TfArg, + "instance" => SymbolKind::Instance, + "block" => SymbolKind::Block, + "structmember" => SymbolKind::StructMember, + "class" => SymbolKind::Class, + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every kind round-trips, and the two directions are inverses. If a + /// variant is added to `SymbolKind` this fails to compile in `kind_name` + /// first, which is the point of writing both matches out. + #[test] + fn every_symbol_kind_has_a_name_and_only_its_own() { + let kinds = [ + SymbolKind::Module, + SymbolKind::Package, + SymbolKind::Port, + SymbolKind::Net, + SymbolKind::Var, + SymbolKind::Param, + SymbolKind::Genvar, + SymbolKind::Typedef, + SymbolKind::EnumVariant, + SymbolKind::Function, + SymbolKind::Task, + SymbolKind::TfArg, + SymbolKind::Instance, + SymbolKind::Block, + SymbolKind::StructMember, + SymbolKind::Class, + ]; + let mut names: Vec<&str> = kinds.iter().map(|k| kind_name(*k)).collect(); + for kind in kinds { + assert_eq!(kind_of(kind_name(kind)), Some(kind)); + } + names.sort_unstable(); + let before = names.len(); + names.dedup(); + assert_eq!(names.len(), before, "two kinds share a name: {names:?}"); + assert_eq!(kind_of("Module"), None, "the names are exact"); + assert_eq!(kind_of(""), None); + } + + #[test] + fn every_escape_survives_a_round_trip() { + for text in ["", "plain", "a\tb", "a\nb", "a\\b", "a\\\\tb", "\r\n", "\\", "üñî"] { + let mut out = Writer::default(); + out.text(text); + let field = out.out; + assert_eq!(unescape(&field).as_deref(), Some(text), "{text:?}"); + assert!(!field.contains('\t'), "a field never holds a raw tab: {field:?}"); + assert!(!field.contains('\n'), "nor a newline: {field:?}"); + } + } + + #[test] + fn an_escape_this_format_does_not_write_is_not_read() { + assert_eq!(unescape("a\\qb"), None); + assert_eq!(unescape("trailing\\"), None); + } +} diff --git a/crates/vlog_semantic/src/lib.rs b/crates/vlog_semantic/src/lib.rs index 29d252d..ccfa1d4 100644 --- a/crates/vlog_semantic/src/lib.rs +++ b/crates/vlog_semantic/src/lib.rs @@ -18,20 +18,22 @@ mod bind; pub mod classes; +mod facts; pub mod instantiations; mod model; mod resolve; mod scan; mod workspace; +pub use facts::{record_path, FACTS_FORMAT}; pub use model::{ DocumentSymbol, Import, Reference, ReferenceId, Resolution, Scope, ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind, }; pub use workspace::{ index_order, resolve_external, DeclSite, Def, Definition, ExternalResolutions, ExternalTarget, - FileId, IndexBuilder, IndexCounts, InheritanceEdge, InstantiationEdge, WorkspaceIndex, - WorkspaceSymbol, + FileFacts, FileId, IndexBuilder, IndexCounts, InheritanceEdge, InstantiationEdge, + WorkspaceIndex, WorkspaceSymbol, }; use std::collections::HashMap; diff --git a/crates/vlog_semantic/src/workspace.rs b/crates/vlog_semantic/src/workspace.rs index f316b43..3063c59 100644 --- a/crates/vlog_semantic/src/workspace.rs +++ b/crates/vlog_semantic/src/workspace.rs @@ -200,6 +200,17 @@ impl WorkspaceIndex { self.subclasses.iter().map(|(name, edges)| (name.as_str(), edges.as_slice())) } + /// What one file contributes to this index, by path. + /// + /// The unmerged record — everything the file's parse found. Public so a + /// caller that persists those records can store the one an incremental + /// update just produced without parsing the file a second time + /// (`docs/features/index-persistence/README.md`). + pub fn facts_for(&self, path: &Path) -> Option<&FileFacts> { + let at = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)).ok()?; + self.facts.get(at) + } + /// The `` `define`` table of one file. pub fn defines(&self, file: FileId) -> Option<&DefineTable> { self.facts.get(file.0 as usize).map(|facts| &facts.defines) @@ -493,11 +504,11 @@ impl Affected { /// One declaration as a single file contributes it, before that file has a /// [`FileId`]. The id depends on where the file's path sorts among all of /// them, which is not known until [`IndexBuilder::finish`]. -#[derive(Debug, Clone)] -struct Decl { - name: String, - name_span: TextRange, - kind: SymbolKind, +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Decl { + pub(crate) name: String, + pub(crate) name_span: TextRange, + pub(crate) kind: SymbolKind, } impl Decl { @@ -512,10 +523,10 @@ impl Decl { /// One instantiation site as a single file contributes it — an /// [`InstantiationEdge`] without its [`FileId`]. -#[derive(Debug, Clone)] -struct SiteFact { - owner: DeclSite, - site_span: TextRange, +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct SiteFact { + pub(crate) owner: DeclSite, + pub(crate) site_span: TextRange, } /// Everything one file contributes to an index: read while the file is parsed, @@ -523,22 +534,40 @@ struct SiteFact { /// /// This is the same data the finished index holds, kept per file rather than /// merged, which is what lets the merge happen in an order the caller does not -/// choose. -#[derive(Debug, Clone)] -struct FileFacts { - path: PathBuf, - defines: DefineTable, +/// choose — and, since it is *everything* one file contributes, the one thing +/// worth storing between two sessions. [`FileFacts::encode`] and +/// [`FileFacts::decode`] are that store's format; a decoded record put back +/// through [`IndexBuilder::add_facts`] gives the index the file's parse would +/// have, without the parse (`docs/features/index-persistence/README.md`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FileFacts { + pub(crate) path: PathBuf, + pub(crate) defines: DefineTable, /// File-scope declarations, in declaration order. - units: Vec, + pub(crate) units: Vec, /// Members, each under the name of the unit that exports it, in the order /// the scope tree yields them. - members: Vec<(String, Decl)>, + pub(crate) members: Vec<(String, Decl)>, /// Instantiation sites, each under the name of the module instantiated, in /// walk order. - instantiations: Vec<(String, SiteFact)>, + pub(crate) instantiations: Vec<(String, SiteFact)>, /// Class declarations with a base, each under the base's name, in walk /// order. - subclasses: Vec<(String, DeclSite)>, + pub(crate) subclasses: Vec<(String, DeclSite)>, +} + +impl FileFacts { + /// Read off what one file contributes to an index — the parse + /// [`IndexBuilder::add_file`] does, exposed so a caller that stores the + /// result can do the parse itself exactly once. + pub fn of(path: PathBuf, src: &str) -> FileFacts { + facts_of(path, src) + } + + /// The file these facts were read from. + pub fn path(&self) -> &Path { + &self.path + } } /// Parse one file and read off what it declares and what it points at. @@ -690,7 +719,20 @@ impl IndexBuilder { /// The parse happens here, not in `finish`, so a caller reporting progress /// between calls is reporting work that has really been done. pub fn add_file(&mut self, path: PathBuf, src: &str) { - self.files.push(facts_of(path, src)); + self.add_facts(FileFacts::of(path, src)); + } + + /// Add one file whose facts are already known — restored from a cache + /// rather than read from the file's text. + /// + /// Exactly [`IndexBuilder::add_file`] with the parse already done: the + /// record is what that parse produces, so an index built from records and + /// an index built from text are the same index. Whether the record really + /// describes the file is the caller's business, and the caller answers it + /// by keying its store on the file's content + /// (`docs/features/index-persistence/README.md`). + pub fn add_facts(&mut self, facts: FileFacts) { + self.files.push(facts); } /// The finished index: the files sorted by path, then merged. diff --git a/crates/vlog_semantic/tests/workspace.rs b/crates/vlog_semantic/tests/workspace.rs index e26f380..8f7975c 100644 --- a/crates/vlog_semantic/tests/workspace.rs +++ b/crates/vlog_semantic/tests/workspace.rs @@ -4,8 +4,8 @@ use std::path::{Path, PathBuf}; use vlog_parser::parse_source_tolerant; use vlog_semantic::{ - analyze, resolve_external, Def, Definition, ExternalTarget, FileId, Resolution, Semantics, - SymbolKind, WorkspaceIndex, + analyze, resolve_external, Def, Definition, ExternalTarget, FileFacts, FileId, Resolution, + Semantics, SymbolKind, WorkspaceIndex, }; /// Build an index from `(path, source)` literals, as a server would from disk. @@ -1455,3 +1455,150 @@ fn same_named_files_in_different_directories_updated_alternately_stay_correct() "alternating back to the first file" ); } + +// ---------------------------------------------------------------------- +// FileFacts as a record: the persistent index cache's format +// ---------------------------------------------------------------------- + +/// A fixture that exercises every field of a record at once: file-scope +/// units of three kinds, members (including a class nested in a package, +/// which is registered twice), instantiation edges, an inheritance edge, +/// and a `` `define`` table with both an object-like and a function-like +/// macro, an `` `undef``, and a body carrying the characters the format has +/// to escape. +const EVERY_FIELD: &str = concat!( + "`define PLAIN 8\n", + "`define ARGS(a, b = 8) {a, b}\t// a tab and a \\ backslash\n", + "`undef PLAIN\n", + "package p;\n", + " typedef logic [7:0] byte_t;\n", + " class base; endclass\n", + " class derived extends base;\n", + " function void f(); endfunction\n", + " endclass\n", + "endpackage\n", + "typedef int top_t;\n", + "module top;\n", + " sub u_sub ();\n", + " other u_other ();\n", + "endmodule\n", +); + +#[test] +fn a_records_every_field_survives_the_round_trip() { + let facts = FileFacts::of(PathBuf::from("/w/every.sv"), EVERY_FIELD); + let line = facts.encode().expect("an ordinary path encodes"); + assert!(!line.contains('\n'), "a record is one line: {line}"); + let back = FileFacts::decode(&line).expect("what was written reads back"); + // `FileFacts` compares every field it holds — path, defines (kind, name, + // params, body, both spans), units, members, instantiation edges, + // inheritance edges — so this is the whole record, not a summary of it. + assert_eq!(back, facts); + assert_eq!(back.encode(), Some(line), "and re-encodes byte for byte"); +} + +#[test] +fn an_index_built_from_records_is_the_index_the_parse_would_have_given() { + // The claim the cache rests on: facts through the record format and back + // give the same index as the files themselves. Checked over a workspace + // with duplicate names and cross-file edges, by fingerprint — ids, + // disambiguation order, member tables, both edge tables, define counts. + let sources = [ + ("/w/a.sv", EVERY_FIELD), + ("/w/b.sv", "module sub; endmodule\nmodule dup; endmodule\n"), + ("/w/c.sv", "`define X 1\nmodule dup;\n sub u ();\nendmodule\n"), + ("/w/d.sv", "class late extends base; endclass\n"), + ]; + let fresh = index(&sources); + + let mut builder = vlog_semantic::IndexBuilder::new(); + for (path, src) in sources { + let line = FileFacts::of(PathBuf::from(path), src).encode().expect("encodes"); + builder.add_facts(FileFacts::decode(&line).expect("decodes")); + } + let restored = builder.finish(); + + assert_eq!(restored.fingerprint(), fresh.fingerprint()); + assert_eq!(restored.counts(), fresh.counts()); +} + +#[test] +fn a_record_that_is_not_exactly_a_record_decodes_to_nothing() { + let facts = FileFacts::of(PathBuf::from("/w/every.sv"), EVERY_FIELD); + let line = facts.encode().expect("encodes"); + let fields: Vec<&str> = line.split('\t').collect(); + + // Truncation at *every* length, not just at one: a torn write can stop + // anywhere, and every stopping point must be a dropped record rather + // than a plausible one. + for cut in 0..fields.len() { + let truncated = fields[..cut].join("\t"); + assert_eq!( + FileFacts::decode(&truncated), + None, + "a record cut to {cut} of {} fields is not a record", + fields.len() + ); + } + // And anything left over on the end is not a record either. + assert_eq!(FileFacts::decode(&format!("{line}\textra")), None, "trailing field"); + + for garbage in [ + "", + "garbage", + "\0\0\0", + "/w/a.sv\tD0\tU0\tM0\tI0", // a list marker missing + "/w/a.sv\tD0\tU1\tm\tmodule\t0\t1\tM0\tI0\tS0", // a count that outruns the line + "/w/a.sv\tD0\tU1\tm\tnosuchkind\t0\t1\tM0\tI0\tS0", // a kind no version writes + "/w/a.sv\tD0\tU1\tm\tmodule\tzero\t1\tM0\tI0\tS0", // a number that is not one + "/w/a.sv\tX0\tU0\tM0\tI0\tS0", // the wrong marker + "/w/a\\qb.sv\tD0\tU0\tM0\tI0\tS0", // an escape this format never writes + "/w/a.sv\tD1\td\tM\t-\tbody\t0\t1\t2\tM0\tI0\tS0", // a define's fields cut short + ] { + assert_eq!(FileFacts::decode(garbage), None, "{garbage:?} is not a record"); + } +} + +#[test] +fn a_path_with_a_separator_in_it_is_escaped_like_any_other_string() { + // The path is a string field like the rest, so a tab or a newline in it + // is escaped rather than fatal — the same treatment a macro body gets, + // and it needs it (`EVERY_FIELD` has both). + for path in ["/w/a\tb.sv", "/w/a\nb.sv", "/w/a\\b.sv"] { + let facts = FileFacts::of(PathBuf::from(path), "module m; endmodule\n"); + let line = facts.encode().expect("encodes"); + assert!(!line.contains('\n'), "still one line: {line}"); + assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "{path:?}"); + } +} + +#[cfg(unix)] +#[test] +fn a_path_that_is_not_utf_8_is_simply_never_cached() { + // The one path shape that has no record: it cannot be written as text at + // all. `None` rather than a lossy spelling — a record whose path is not + // the file's path would be a record that answers for the wrong file. + // Same answer `lucisv_core::cache` gives the same shape of path. + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt; + let path = PathBuf::from(OsStr::from_bytes(b"/w/\xff\xfe.sv")); + assert_eq!(FileFacts::of(path, "module m; endmodule\n").encode(), None); +} + +#[test] +fn a_degenerate_file_still_makes_a_record() { + // The shapes `an_update_survives_every_degenerate_file_there_is` covers, + // through the record format: an empty file, one that does not lex, one + // that is not Verilog at all. Each has a record, and each round-trips. + for src in [ + "", + " \n\t\n", + "this is not verilog\n", + "module m;\n \"unterminated\n", + "// just a comment\n", + ] { + let facts = FileFacts::of(PathBuf::from("/w/x.sv"), src); + let line = facts.encode().expect("encodes"); + assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "{src:?}"); + } +} diff --git a/docs/features/incremental-index/README.md b/docs/features/incremental-index/README.md index eee5a08..d6a6ca3 100644 --- a/docs/features/incremental-index/README.md +++ b/docs/features/incremental-index/README.md @@ -52,7 +52,10 @@ lookups — 92 ms → 0.26 ms for a whole file's code lenses, 82 ms → 0.71 ms - **The index keeps every file's contribution unmerged.** `FileFacts` — the path, the define table, the file-scope declarations, the members, the instantiation edges and the inheritance edges — used to live only until - `IndexBuilder::finish` and now lives in the index. That is what makes the + `IndexBuilder::finish` and now lives in the index. (**Since + index-persistence, 2026-08-27** it also lives on *disk*: `FileFacts` is + public, encodable and decodable, and a record put back through + `IndexBuilder::add_facts` gives the index the file's parse would have.) That is what makes the restricted re-merge possible, and it is the round's honest memory cost: the same names and spans the merged tables hold, held once more, per file. No `Semantics` and no source text is retained, exactly as before. @@ -169,6 +172,11 @@ pub struct InheritanceEdge { pub file: FileId, pub subclass: DeclSite } It patches all four pieces of state a rebuild produces (index, completion tables, include graph, every open buffer's overlay) and is documented piece by piece at the function. + **Amended (index-persistence, 2026-08-27):** it also writes the file's new + record through to the on-disk index cache, using + `WorkspaceIndex::facts_for` to take back the record the update just made + rather than parsing anything twice. An hour of saves is an hour of work the + next session does not repeat. - `Workspace::update_one_checked` is the `#[cfg(test)]` paranoid form: it runs the update, then rebuilds the whole workspace and asserts the two agree on the index's fingerprint *and* on the completion word table. @@ -223,6 +231,7 @@ the remaining rows. | `IncludeGraph::edges` | this file's `` `include``s | re-scanned for this file; other files' left standing (see Assumptions) | | `IncludeGraph::known` / `folded` | the file set | re-learned from `index.files()` | | every open buffer's `ExternalResolutions` | the index | refreshed, as after a rebuild | +| the persistent index cache | this file's new record | written through, from the record `update_file` just made — no second parse (`docs/features/index-persistence/README.md`, 2026-08-27) | | the diagnostics generation | — | bumped | | the client's code lenses | the index | refresh requested | diff --git a/docs/features/index-persistence/README.md b/docs/features/index-persistence/README.md new file mode 100644 index 0000000..7031c44 --- /dev/null +++ b/docs/features/index-persistence/README.md @@ -0,0 +1,1339 @@ +# index-persistence + +## Goal + +Indexing a large workarea takes perceptible seconds, and until this round +**every one of those seconds was paid again from zero on every reopen**: the +workspace index lived in memory and nowhere else, so an editor that crashed — +or was simply closed — halfway through its first scan started the same scan +over. This round writes what a scan *learned* to disk as it learns it: one +record per file, holding exactly the `FileFacts` that file contributes to the +index, keyed by the FNV-1a hash of the bytes those facts were read from. A +reopened workspace then indexes from records instead of from parses, and a +scan that was interrupted resumes rather than restarts, because a record is +written through the moment its file is parsed. The store lives in the folder +the editor set aside for exactly this (`context.storageUri`, passed as +`initializationOptions.storagePath` — the round's one `extension.js` change), +falls back to this platform's cache directory for every other client, and is +off entirely under `lucisv.index.persist: false`. + +The measured shape, release build, the checked-in 860-file corpus: a whole +rescan goes **322 ms → 179 ms** — the parse was a little more than half of it — +and the bar says `860 files indexed, 860 from cache` so the user can see it. + +## Assumptions + +- **What persists is the per-file record, never the merged index.** `FileFacts` + is what `IndexBuilder::add_file` produces before any `FileId` exists — the + path, the `` `define`` table, the file-scope declarations, the members, the + instantiation edges, the inheritance edges. The merged tables and the ids + are re-derived by the same `finish`/`merge` every build has always ended in, + which is what makes the round's central claim structural rather than + hopeful: `add_facts(decode(encode(facts)))` and `add_file(path, src)` put the + *same value* in the builder, so a cached index and a parsed index are the + same index, byte for byte, ids and disambiguation order included. Pinned + directly (`an_index_built_from_records_is_the_index_the_parse_would_have_given`) + and over the whole corpus through + `WorkspaceIndex::fingerprint` + (`the_cached_index_is_the_index_a_fresh_scan_would_have_built_over_the_corpus`). +- **Content is the whole key, and no timestamp is trusted — a deviation from + the brief, argued below in the work log.** An entry is used for the bytes it + was made from and for nothing else. There is no (size, mtime) fast path: the + brief asked for one, and the honest reason not to have it is that it would + buy nothing here, because the file's text is read on every scan anyway (see + the next point), so the mtime check could only ever save one FNV pass over + bytes already in memory — **6.4 ms of a 179 ms warm scan, measured** — in + exchange for making a filesystem timestamp part of the correctness argument. + Both directions are pinned in `the_key_is_the_content_and_only_the_content`: + a file rewritten with the same bytes (new mtime) still hits, and a file + rewritten with different bytes of the same length misses. +- **The cache skips the parse. It does not skip the read**, and that is the + honest ceiling on what it can buy. `Workspace::collect_sources` reads every + in-scope file because two things besides the index are built from that text — + `Candidates` (the completion word table, re-lexed per file) and + `IncludeGraph` (each file's `` `include`` edges) — and neither is cached this + round. So a warm scan still costs the read, the lex for words, and the + include scan; what it stops costing is `parse` + `analyze`, which the + measurements below put at a little over half of a rescan. Caching the other + two is filed, not done: they are a second and third record format with their + own invalidation, and one is worth shipping before three are guessed at. +- **A hit is verified before it is used, and every failure is silent and + costs work rather than answers.** A record whose hash does not match is a + miss; a record whose fields do not match the checksum they were written with + is dropped; a record whose fields do not decode is a miss; a store whose + header is not this exact build's is dropped whole; a directory that cannot + be written in is a cache that writes nothing. Nothing in this round can make + the server answer differently — only faster or slower. That is the same + posture `lucisv_core::cache` (the formatter's content-hash store) took, and + the same reasoning: a cache that could change an answer is a bug waiting for + a user. +- **The threat model is the same-user disk, and a deliberately forged store is + outside it** — the same posture `lucisv_core::cache` takes, with one + difference worth stating rather than hiding. QA's finding (2026-08-27) is + exactly right about the consequence: that cache's entry is a skip-or-not + bit, so poisoning one only wrongly skips a reformat, while this one's fields + are served straight into the workspace index, so a poisoned one would serve + fabricated definitions, hovers and rename targets for a real file. The + ruling is still that this is accepted: anything that can write the cache + directory can write the source files the index describes (and the binary + that reads them), so the forgery buys an attacker nothing they did not + already have, and the only thing that would actually detect it — a keyed MAC + — would have to keep its key on the same disk as the data it authenticates, + which is theatre rather than defence. So: **no defence against a hand-edited + store is claimed, and none is implemented.** What *is* implemented, because + it is cheap and because the promise should be true against everything that + is not a person with a hex editor, is the per-record checksum: every + accidental way a written record can change — bit rot, a torn interleaved + append, an editor rewriting line endings, a partial write — now drops that + record instead of serving it + (`a_record_whose_facts_do_not_match_their_checksum_is_dropped`, and through + the whole workspace by fingerprint in + `a_poisoned_cache_record_is_dropped_and_the_index_is_a_fresh_scans`). The + accepted residue — a forger who recomputes the checksum is still served — is + pinned in the same test, so nobody later mistakes the checksum for a + security boundary. +- **The store is written through per file, and compacted once per whole + scan.** One `write` per parsed file, appended, so a process killed mid-scan + loses at most the file in flight; then one atomic rewrite (tempfile + + rename) when the scan ends, which is the only moment the live set of entries + is known. Growth is therefore bounded by the workspace and not by the + session: a path saved a thousand times is a thousand appended lines during + the session and one line after the next whole rescan, and a record whose + file no longer exists is dropped at that rewrite, exactly as + `lucisv_core::cache::store` drops its own. +- **A save writes its record through too**, on the incremental path, without a + second parse — `WorkspaceIndex::facts_for` hands back the record + `update_file` just made. An hour of saves is an hour of work the next + session does not repeat. When the text came from an unsaved *buffer* the + record is written under the buffer's content hash, which the file on disk + will simply never match; that is a wasted line, never a wrong answer, and it + is the reason the key may not include the file's metadata. +- **Records for files that leave the scope stay, and `remove_file` deletes + nothing.** A record is not a file: it can only ever answer *for* something + already on the work list that the scope ladder built, so a session whose + scope narrowed has an index that narrowed with it, records or no records + (`the_cache_never_puts_back_a_file_the_scan_no_longer_visits`). Keeping them + is what makes reopening a folder that was in scope last week free again, and + they are dropped when the file itself is gone. +- **The cache never widens the scope, never changes which files are walked, + and is not consulted for anything but a file the scan already decided to + index.** The scope ladder (`index-scope`) and the size cap (`indexing-ux`) + are untouched by this round: `collect_sources` runs first, exactly as + before, and the cache is asked only about the list it produced. +- **One store may hold more than one workspace's files, and that is + harmless.** Records are keyed by absolute path, so a store shared between + two workspaces — a rootless VS Code window falling back to the *global* + storage folder, or a `cachePath` deliberately pointed at one place — simply + answers for the union. Nothing collides; the only cost is a store that holds + entries a given session never asks about, and compaction drops the ones + whose files are gone. +- **Two servers over one store cannot corrupt each other's answers, and since + 2026-08-27 they do not lose each other's records at a cold start either.** + Both may append, and the last compaction wins; every record is + independently keyed, independently checksummed and independently verified, + so the worst case is a session whose records another session's rewrite + dropped, which costs re-parsing those files. A store that does not exist yet + is *claimed* with `File::create_new`, so exactly one session creates it and + the rest append under the header it wrote — where before, every session that + had not read a header truncated the file on its first write, and QA measured + four racing cold starters keeping 25 of 100 records. Each record and each + header goes out in a single `write_all` on an append handle, so no line can + land inside another. Still no locking, and none is worth taking a dependency + for. +- **Truncating the store is left for exactly one case: a first line this build + cannot read.** Those records were already dropped at load, and appending + under a header nobody can read would throw the new ones away at the next + load too. The residue, argued rather than hidden: two sessions cold-starting + on the *same* store from another version can still both truncate it, and the + first one's early records go with it. That window is one write wide, it + needs two servers first-scanning one workspace in the same instant after an + upgrade, what is lost is a cache nobody could read anyway, and the end of + either scan rewrites the store whole from memory. A zero-length store — a + session killed between its claim and its header — is neither ours nor + foreign, and is finished rather than replaced + (`an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace`), so a + crash in that window costs nothing at all. +- **`lucisv.index.persist: false` is off in both directions and takes effect + at once.** Nothing is read and nothing is written; the setting landing + mid-session drops the cache in hand rather than waiting for a rescan, so + even a save's write-through stops immediately + (`turning_persistence_off_mid_session_stops_the_write_through_at_once`). + Neither cache setting asks for a rescan, because neither changes which files + exist — a new `cachePath` takes effect at the next one. +- **A store is per build, not per machine.** The header carries the store + format, the record format (`vlog_semantic::FACTS_FORMAT`) and lucisv's own + version; a new release parses the same bytes into possibly different facts, + so its first scan discards the old store and writes a fresh one. This is the + same rule the formatter's cache applies for the same reason, one level up: + there, another version's *entry* is dropped; here, the whole file is, + because the framing itself may have moved. +- **Nothing is persisted for a session that has no stable identity.** With no + `cachePath`, no `storagePath` and no workspace root or filelist to key an OS + cache directory entry on — a single file opened on its own — there is + nothing to name a store after, and the index lives in memory exactly as it + did before this round. + +## Handshakes + +### `vlog_parser` — one additive constructor, two derives + +```rust +impl DefineTable { + /// A table from entries that are already known, in source order. + pub fn from_entries(entries: Vec) -> DefineTable; +} +``` + +- `Define` and `DefineTable` gain `PartialEq`/`Eq`. `collect_defines` is still + the only thing that *reads* a table out of a file; `from_entries` exists + because a record restores one that was read a session ago, and the derives + exist so the round-trip test can say "every field", rather than comparing + renderings of the fields. + +### `vlog_semantic` — `FileFacts` becomes a value you can keep + +```rust +pub struct FileFacts { /* fields private */ } +impl FileFacts { + pub fn of(path: PathBuf, src: &str) -> FileFacts; // the parse `add_file` does + pub fn encode(&self) -> Option; // one line of fields + pub fn decode(line: &str) -> Option; // strictly, or nothing + pub fn path(&self) -> &Path; +} +pub fn record_path(record: &str) -> Option; // the cheap half of decode +pub const FACTS_FORMAT: u32; // bump on any change + +impl IndexBuilder { + pub fn add_facts(&mut self, facts: FileFacts); // `add_file` without the parse +} +impl WorkspaceIndex { + pub fn facts_for(&self, path: &Path) -> Option<&FileFacts>; +} +``` + +- `add_file` is now `add_facts(FileFacts::of(path, src))` — one implementation, + so the cached path cannot drift from the parsed one. +- `record_path` is public separately because a store keyed by path reads that + field out of every record it holds and decodes only the ones it is asked + for. +- `facts_for` is what lets a save write its record through without parsing the + file a second time. +- The codec lives in `crates/vlog_semantic/src/facts.rs`; `FileFacts` itself + stays declared beside the index it belongs to, with `pub(crate)` fields. + +### `lucisv_server::index_cache` — the store + +```rust +pub struct IndexCache; +impl IndexCache { + pub fn disabled() -> IndexCache; + pub fn open(dir: Option) -> IndexCache; + pub fn facts_for(&self, path: &Path, text: &str) -> Option; + pub fn record(&mut self, facts: &FileFacts, text: &str); + pub fn compact(&mut self); +} +pub fn cache_dir(settings: &ClientSettings, storage: Option<&Path>, + roots: &[PathBuf], filelist: Option<&Path>) -> Option; +``` + +- The content hash is `lucisv_core::cache::content_hash` — **reused, not + copied**. `lucisv_server` already depends on `lucisv_core` (for the walk and + for config discovery), so this adds no dependency edge at all, and the + alternative — a second FNV-1a in another crate — would be a second thing to + keep byte-identical with a store on disk. + +### `lucisv_server::state` + +- `Workspace` gains the cache and the storage path: + `Workspace::set_storage_path(Option)`, called once before the first + build. The cache is re-opened at the top of every whole rescan, because the + settings that decide where it lives arrive after startup. +- `IndexEvent::Cached { done, total, path }` — the same three numbers + `Parsing` carries, for a file that cost nothing. Every existing consumer of + the enum had to grow one arm, which is the compiler making the distinction + impossible to forget. +- `rebuild_index_with` asks the cache before parsing and writes every miss + through; `update_one` writes its own record through. Nothing else in the + rebuild moved. + +### `lucisv_server::settings` + +- `index_persist: bool` (default **true**) from `lucisv.index.persist`, and + `index_cache_path: Option` from `lucisv.index.cachePath` — nested + under `index` like the other four, so both settings doors carry them with no + new code. A wrong-typed `persist` leaves the cache **on**: the direction + that silently costs a user work is "off". + +### `lucisv_server::server` / `main.rs` + +- `Server::new`/`started` take the storage path; `main` reads it out of the + raw `initialize` params (`initializationOptions.storagePath`), the same way + `rangesSupport` is read and for a related reason — it is not a capability, + it is whatever the client's extension put there. A blank value is unset. +- `IndexWatch` counts cached files and logs `cached: ` where it logs + `indexing: `; `end_indexing` names the count: + `860 files indexed, 860 from cache`, and with a size cap in play + `860 files indexed, 858 from cache, 2 skipped`. + +### `editors/vscode` + +- `extension.js` gains **one** thing — + `initializationOptions: { storagePath: (context.storageUri || context.globalStorageUri).fsPath }`. + `storageUri` is VS Code's own per-workspace folder for server state and is + cleaned up when the workspace is forgotten; it is `undefined` when no + workspace is open, and the global one stands in there. +- `package.json` declares `lucisv.index.persist` and `lucisv.index.cachePath`, + both with the honest notes: what the key is, that a stale entry costs a + re-parse and can never affect an answer, and that turning it off is exactly + the pre-round behaviour. + +## The store format + +One directory, one file, `index-cache`. A header line, then one line per +record; a `.gitignore` beside it saying `*`, the way +`lucisv_core::cache` marks its own directory. + +``` +lucisv-index-cache 2 1 0.10.2 +<16 hex content hash> D … U … M … I … S … <16 hex facts checksum> +``` + +The header is `magic`, **store format**, `vlog_semantic::FACTS_FORMAT`, +lucisv's version. Any difference and the file is not read at all — and the +first write of the session replaces it rather than appending under a header +nobody can read. (Store format **2**, since 2026-08-27: the per-record +checksum below. Format 1's stores are discarded wholesale on the first scan +after an upgrade, which costs one re-parse of the workspace and is what the +version field is for.) + +A record is tab-separated fields on one line, in this order: the path, then +five length-prefixed lists — `D`efines, `U`nits, `M`embers, `I`nstantiations, +`S`ubclasses — and last the checksum. The letter is a marker and the number +after it is the count, so the stream is flat and a misaligned read is a +*rejected* record rather than a plausible one. Every string field is escaped +(`\\`, `\t`, `\n`, `\r`), which is what keeps a record on one line when a +macro body holds a tab; every number is decimal; every `SymbolKind` is its own +word, so a variant inserted into the enum cannot silently become another kind. +`TextRange`s are written as their two offsets. + +The last field is the FNV-1a of everything between the content hash and it — +the encoded facts, exactly as written. It is checked before a record is +believed, so a record that changed *after* it was written is dropped rather +than served: bit rot, a torn append two servers interleaved, an editor that +"helpfully" rewrote the file. It is what makes "never a correctness input" +true against every accident rather than only against staleness. It is a plain +FNV-1a and not a keyed MAC, which is a threat-model decision and not an +oversight — see Assumptions. The facts run to the *last* tab and no encoded +field can contain a raw one, so the split is unambiguous; a record whose +checksum field is missing, is not sixteen hex digits, or does not match is not +a record. + +An example, the whole record for a two-line file (tabs shown as `→`): + +``` +verilog +`define W 8 +module m; sub u (); endmodule +``` + +``` +2f0a8bd7c1d1f5a1→/w/m.sv→D→1→d→W→-→8→0→11→8→9→U→1→m→module→19→20→M→0→I→1→sub→m→19→20→12→41→22→25→S→0→9b1c04e2a7f3d081 +``` + +— one define (`d` for `` `define``, name `W`, `-` for "no parameter list", +body `8`, span `0..11`, name span `8..9`), one file-scope unit (`m`, a module, +name span `19..20`), no members, one instantiation edge (of `sub`, owned by +`m` whose name is at `19..20` and whose declaration runs `12..41`, with the +site's own name span `22..25`), no subclasses, and the checksum of all of +that. The record is what lies between the hash field and the checksum; both +hashes above are illustrative. + +**Any change to what a record holds or how it is written bumps +`FACTS_FORMAT`** — that is the rule, written at the constant, and it is what +lets the reader be as strict as it is. + +### Why one line per record + +Because it is what makes the append log crash-safe with no framing of its own. +A record is written with one `write_all` (not `writeln!`, whose formatting +machinery may split a line across two writes — the one thing QA's O_APPEND +reasoning was right to doubt), and a record contains no raw newline, so a +process killed mid-write leaves a final line without its terminator — which +the reader yields and the parser rejects for the same reasons it rejects any +other malformed record, and which cannot carry the checksum of the facts it +was written with in any case. There is nothing to detect and nothing to +repair: the torn record costs one file's parse +(`a_torn_final_record_costs_one_file_and_nothing_else`). + +The store is read as **bytes**, and each line is decoded as UTF-8 on its own. +That is not fussiness: a cut landing inside a multi-byte character used to +make `read_to_string` reject the whole buffer, which was indistinguishable +from "no header" and threw away every intact record in the file — QA measured +it at 2 of 534 cut points on a store with one non-ASCII macro body, and any +workspace with non-ASCII comments or string literals has them. Per line, a +torn multi-byte tail costs the torn record and nothing else, which is what +`truncating_the_store_at_every_byte_offset_costs_only_the_torn_record` now +asserts at every one of 583 cut points: past the last whole record, every +whole record survives. + +This is the one place the round deliberately differs from +`lucisv_core::cache`'s posture, which discards a whole store on one malformed +line ("partial trust in a file already caught lying"). Here a malformed *last* +line is the expected shape of a crash, not evidence of lying, and every record +is independently keyed and independently verified before use — so a bad line +drops that record and no other +(`a_corrupt_record_is_dropped_and_the_rest_of_the_store_is_not`). A bad +*header* still discards everything, because the header is the claim that the +rest of the file is ours at all. + +## The precedence ladder + +| rung | where | when | +|---|---|---| +| 1 | `lucisv.index.cachePath` | the user said where — absolute, or relative to the first workspace root (the rule `lucisv.filelist` already uses) | +| 2 | `initializationOptions.storagePath` | the editor said where. VS Code's per-workspace storage folder | +| 3 | the OS cache directory, `lucisv/index/` | every other client. `$XDG_CACHE_HOME` or `~/.cache` (Unix), `~/Library/Caches` (macOS), `%LOCALAPPDATA%` (Windows), keyed by a hash of the sorted workspace roots — or of the filelist, with no roots | +| 4 | nowhere | `lucisv.index.persist: false`, or nothing above answered. The index is in memory only, exactly as before this round | + +Pinned rung by rung in `the_cache_directory_is_the_highest_rung_that_answers`, +and through the workspace in +`a_configured_cache_path_beats_the_editors_storage_folder`. + +## Measured + +`corpus/`: 860 files, 4.94 MB of Verilog. Both builds, this Mac, min of the +runs the `#[ignore]`d probe does +(`cargo test -p lucisv_server --bin lucisv-server qa_perf_cold_warm -- --ignored --nocapture`). + +Re-measured after the 2026-08-27 fix round, which added the per-record +checksum (one more FNV-1a pass over each record, written and read). + +| whole rescan of 860 files | debug | release | +|---|---:|---:| +| no cache (the pre-round cost) | 1.498 s | 322 ms | +| cold, filling the store | 1.587 s | 340 ms | +| **warm, every file from the store** | **0.756 s** | **179 ms** | +| half-warm, one file edited | 0.760 s | 180 ms | + +So the parse is a little over half of a rescan, and the cache takes all of it: +**2.0× in debug and 1.8× in release**. Filling the store costs **6%** on the +one scan that fills it. The remaining 179 ms is the read, the completion word +table's lex and the include scan — none of which this round caches, and all of +which are named in Assumptions. The checksum is inside the noise of these +numbers: it hashes the record, which is a fifth the size of the source line +the record describes, and the store is only touched once per file per scan. + +**The store is 910 KB for 860 files** (895 KB before the checksum: the field +costs exactly 17 bytes per record, 15 KB over the corpus) — about 1 KB per +file, 18% of the 4.94 MB of source it describes. Growth is one line per file +per *content*, compacted to one line per file at the end of every whole scan, +so a session's saves do not accumulate across sessions; a workspace of 10,000 +files should expect a store around 11 MB, which is the number to revisit if +anyone ever wants compaction to be cleverer than "rewrite it". + +**Hashing all 4.94 MB is 6.4 ms of that 179 ms** (24.4 ms of 756 ms in debug), +which is the measurement behind dropping the brief's mtime fast path: the text +is read either way, so an mtime match could only ever have saved this. + +## Status / TODO + +- [x] `FileFacts` persisted per file, keyed by content hash + record format + + store format + lucisv version +- [x] Hand-rolled, versioned, escaped, length-prefixed one-line record format; + no new dependency +- [x] Write-through per file as a scan parses it; atomic compaction at the end + of a whole scan; a torn final record ignored, never fatal +- [x] A save's record written through on the incremental path, with no second + parse +- [x] `lucisv.index.persist` (default on) and `lucisv.index.cachePath`, both + settings doors, both in `package.json` +- [x] `initializationOptions.storagePath`, passed by the extension from + `context.storageUri` — the round's one `extension.js` change +- [x] The four-rung directory ladder, including the hand-rolled OS cache + directory keyed by workspace identity +- [x] `cached:` log lines beside `indexing:`, cached files counted in the bar, + `N from cache` in the end message +- [x] Load-from-cache index == fresh index over the corpus, by fingerprint, + plus counts and the completion word table +- [x] 33 new tests (9 `vlog_semantic`, 10 `index_cache`, 9 `state`, + 2 `server`, 2 `settings`, 1 e2e), 1 new `#[ignore]`d probe +- [x] **Fix round (2026-08-27), QA finding 1**: a per-record checksum of the + encoded facts, checked at load, so a record damaged after it was written + is dropped rather than served; store format 1 → 2. A deliberately + reforged store stays out of the threat model, ruled and written down in + Assumptions +- [x] **Fix round, QA finding 2**: a brand-new store is claimed with + `File::create_new`, and truncation is left for a header this build + cannot read, so four racing cold starters keep 100 of 100 records where + they kept 25 +- [x] **Fix round, QA finding 3**: the store is read as bytes and decoded a + line at a time, so a cut inside a multi-byte character costs the torn + record and no other — zero of 583 cut points now lose a whole record +- [ ] **Not done, deliberately: no (size, mtime) fast path.** It would save + 6.4 ms of a 179 ms warm scan, because the file is read anyway, and would + put a filesystem timestamp inside the correctness argument. See the work + log. +- [ ] **Not done, deliberately: the completion word table and the include + graph are not cached.** They are what the remaining 179 ms is, and each + is its own record format with its own invalidation. One store shipped + and measured beats three guessed at. +- [ ] **Not done, deliberately: no background compaction, and no size bound.** + The store is rewritten at the end of every whole scan, which is where + the growth math above lands; a scheme that also pruned by age or by size + would be guessing at a workspace nobody has reported. +- [ ] **Not done, deliberately: no locking between two servers over one + store.** Records are content-keyed, checksummed and independently + verified, and a new store is claimed rather than truncated, so a race + costs re-parsing at worst, never an answer. +- [ ] **Not done, filed by QA (Low), still open:** an `index-cache..tmp` + left by a compaction killed between its write and its rename is never + swept up (`an_orphaned_compaction_tmp_file_is_never_swept_up`). Harmless + to correctness, one orphan per crash in that window. +- [ ] **Not done, filed by QA (Low), still open:** `os_cache_dir`'s Windows + and XDG branches are compiled out of this repo's macOS CI, and the macOS + branch is only exercised against the ambient `HOME`. Making the + environment lookups injectable is a testability refactor, not a fix, and + belongs with whoever adds a second CI runner. +- [ ] **Filed, not done:** the store is not read at all until the first whole + rescan of a session, so a session that only ever takes the incremental + path (open one file, save it) writes records it never reads. It reads + them on the next session's scan, which is the case this round is about. + +## Work log + +### 2026-08-27 — dev agent (a persistent index cache with crash/reopen resume) + +- **The key is the content and only the content, and that is the round's one + deviation from the brief.** The brief asked for `(size, mtime)` to skip even + the hash, with a hash check on mtime mismatch. I implemented the store + first, measured, and dropped the fast path, because the premise it rests on + is not true here: a cache hit does **not** skip reading the file. It cannot + — `Candidates` (the completion word table) and `IncludeGraph` are built from + the same text in the same rescan, and neither is cached this round — so by + the time the cache is asked about a file, that file's bytes are already in + memory, and an mtime match would save exactly one FNV pass over them: **6.2 + ms of a 181 ms warm scan** over the corpus, measured by the probe. The price + would have been real: a stored `(size, mtime)` is a claim about a file that + the file itself does not carry, and it takes two ways to go wrong that + content hashing has none of. It also would have made the save-time + write-through unsound as written — a save's text can come from an unsaved + buffer, and a record whose hash is the buffer's but whose metadata is the + disk file's would be a fast-path hit with the *wrong* facts. Keyed on + content, that same record is simply a line the disk file never matches. The + deviation is pinned from both sides in + `the_key_is_the_content_and_only_the_content`, and the assumption that + justifies it (the read is not skipped) is stated in Assumptions rather than + buried here. If the word table and the include graph are ever cached too, + the read *does* become skippable and this decision is worth reopening — with + the mtime question then paying for something real. +- **One line per record, because that is the crash-safety mechanism.** The + brief allowed either tempfile+rename per batch or an append log with a + load-time validity check, and asked for the crash-safest shape that stays + boring. It is both, and they compose: append one line per parsed file + (killing the process loses at most the file in flight), then rewrite + atomically at the end of the scan (which bounds growth and drops dead + entries). What makes the append half safe with no framing of its own is that + a record holds no raw newline — every string field is escaped — so a torn + write is a line the reader rejects anyway. No length prefix on the line, no + per-line checksum, no repair path. +- **A malformed line drops that record, not the store.** This is a considered + departure from `lucisv_core::cache`, which discards wholesale on one bad + line. There, a malformed line is evidence the file is not what it claims; + here it is the *expected* shape of a crash, and the store's own value is + that most of it survived. The safety argument is that it costs nothing to be + lenient: every record is separately keyed by content and separately + verified, so a corrupt record cannot be *used*, only ignored. The header is + the one thing still trusted wholesale, and it is checked exactly. +- **Strictness is where the safety is, so `decode` refuses everything it does + not recognise**: a missing field, a number that will not parse, a list + marker in the wrong place, a `SymbolKind` name this version does not write, + a count that outruns the line — and a field left over at the end. + `a_record_that_is_not_exactly_a_record_decodes_to_nothing` truncates a real + record at *every* one of its field boundaries and asserts every prefix is + rejected, which is the shape a torn write actually takes. +- **`FileFacts` became public rather than a parallel "cache record" type.** + The brief warned against storing parse inputs instead; the opposite trap was + a second struct mirroring the first, which would need a conversion nobody + could prove was total. Making the existing value encodable, with + `add_file` redefined as `add_facts(FileFacts::of(...))`, means the cached + and parsed paths are the same code from the builder's point of view — there + is nowhere for them to disagree, and the equivalence test is checking the + codec rather than the index. +- **`DefineTable::from_entries` is the one thing this round needed from + `vlog_parser`.** A `DefineTable`'s entries are readable and were not + writable, and a record has to restore one. It is additive, it is documented + as the inverse of `entries()`, and `collect_defines` remains the only thing + that reads a table out of a file. `Define`/`DefineTable` also gained + `PartialEq`/`Eq` so the round-trip test can assert *every field* rather than + compare two renderings. +- **The content hash is reused, not copied.** `lucisv_server` already depends + on `lucisv_core`, so `lucisv_core::cache::content_hash` is one `use` away — + no new edge, and no second FNV-1a to keep byte-identical with a file on + disk. (The brief allowed a justified copy; there was nothing to justify.) +- **`IndexEvent::Cached` rather than a `cached: bool` on `Parsing`.** A + `Parsing` event that did not parse is a lie in the one place a reader looks + to find out what a rescan did, and the new variant makes every consumer grow + an arm — the compiler asking each of them what it wants to say. The bar + ticks identically for both; only the log line and the count differ. +- **Tests may not write into the developer's cache directory, and two + mechanisms keep them out.** In-process tests: `Workspace::cache_dir` returns + `None` under `#[cfg(test)]` unless the test named a `cachePath` or a + `storagePath` of its own, so the OS rung is never reached by accident (it is + tested directly against `index_cache::cache_dir`). The e2e tests spawn the + real binary, where no `cfg(test)` applies, so `server_command()` points + `HOME`/`XDG_CACHE_HOME`/`LOCALAPPDATA` at a scratch directory for every + session. This was not theoretical: the first full run left **104** + directories in `~/Library/Caches/lucisv/index`. +- **The e2e test is three sessions, not two.** Cold, warm, and half-warm with + one file changed between them — the third is the one that proves the resume + is per file rather than all-or-nothing, over the wire, with the real binary + and a real `storagePath`. +- Files touched: `crates/vlog_parser/src/defines.rs`, + `crates/vlog_semantic/src/{facts.rs (new),workspace.rs,lib.rs}`, + `crates/vlog_semantic/tests/workspace.rs`, + `crates/lucisv_server/src/{index_cache.rs (new),state.rs,server.rs,settings.rs,main.rs}`, + `crates/lucisv_server/tests/e2e.rs`, `editors/vscode/extension.js`, + `editors/vscode/package.json`, `TODO.md`, + `docs/features/{lucisv-server,indexing-ux,incremental-index,index-scope}/README.md`, + this README. No new dependency, no version bump, no `docs/site/`, no + commits. + +**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy +--all-targets --workspace`: zero warnings. `cargo test --workspace`: **2286 +passed, 0 failed, 9 ignored** — measured against a stashed `HEAD` tree's +**2253 passed, 8 ignored** in the same session, so 33 new passing tests and +one new `#[ignore]`d probe, with nothing superseded and nothing renamed. `cargo test -p vlog_formatter`: 180 +passed across its seven binaries, untouched — `verify.rs` does not appear in +this round's diff. `cargo build && node editors/vscode/smoke.js +target/debug/lucisv-server`: `smoke: OK` (it passes no `storagePath` and has +no root, so it takes the no-persistence path unchanged). +`node -e JSON.parse(package.json)`: parses. + +The 33 new tests, and what each is for: + +| test | pins | +|---|---| +| `a_records_every_field_survives_the_round_trip` (vlog_semantic) | encode → decode → equal, over a fixture with every field populated, tabs and backslashes included; and re-encoding byte for byte | +| `an_index_built_from_records_is_the_index_the_parse_would_have_given` (vlog_semantic) | the round's central claim, by fingerprint, over duplicate names and cross-file edges | +| `a_record_that_is_not_exactly_a_record_decodes_to_nothing` (vlog_semantic) | every truncation point, a trailing field, and ten crafted malformations | +| `a_degenerate_file_still_makes_a_record` (vlog_semantic) | empty, whitespace, not-Verilog, does-not-lex, comment-only | +| `a_path_with_a_separator_in_it_is_escaped_like_any_other_string` (vlog_semantic) | a tab, a newline and a backslash in the path | +| `a_path_that_is_not_utf_8_is_simply_never_cached` (vlog_semantic, unix) | the one path shape with no record at all | +| `every_symbol_kind_has_a_name_and_only_its_own`, `every_escape_survives_a_round_trip`, `an_escape_this_format_does_not_write_is_not_read` (vlog_semantic `facts`) | the two total matches are inverses and share no name; the escape is a bijection | +| `a_record_written_in_one_session_is_read_in_the_next` (index_cache) | the store round-trip, and that content and path are both part of the key | +| `a_record_survives_a_session_that_never_compacted` (index_cache) | the crash case: write-through with no compaction | +| `a_torn_final_record_costs_one_file_and_nothing_else` (index_cache) | a store cut mid-line, the way a killed process leaves one | +| `a_store_from_another_version_is_dropped_whole_and_replaced` (index_cache) | the header, and that the first write replaces rather than appends | +| `a_corrupt_record_is_dropped_and_the_rest_of_the_store_is_not` (index_cache) | seven malformed lines beside a good one | +| `a_record_whose_facts_no_longer_decode_is_a_miss_not_a_failure` (index_cache) | a well-framed line whose facts are truncated | +| `compaction_keeps_one_line_per_path_and_drops_the_files_that_are_gone` (index_cache) | the growth bound, last-write-wins, and pruning | +| `a_disabled_cache_reads_nothing_and_writes_nothing` (index_cache) | `persist: false` at the store level | +| `nothing_is_created_until_something_is_recorded` (index_cache) | lazy `mkdir`, the `.gitignore`, no leftover temp file | +| `the_cache_directory_is_the_highest_rung_that_answers` (index_cache) | the four rungs, the relative-path rule, and that the root order is not part of the workspace identity | +| `a_second_session_over_the_same_store_parses_nothing_it_parsed_before` (state) | the headline: a whole new workspace over the same store parses nothing and builds the same index | +| `a_half_warm_scan_parses_exactly_what_the_store_cannot_answer_for` (state) | the resume: one changed file and one new file parsed, one cached, and the result equal to a cacheless scan | +| `the_key_is_the_content_and_only_the_content` (state) | both directions of "no timestamp is trusted" | +| `the_cache_never_puts_back_a_file_the_scan_no_longer_visits` (state) | the scope is decided before the cache is asked | +| `persistence_off_reads_nothing_and_writes_nothing` (state) | both directions of the setting, through the workspace | +| `turning_persistence_off_mid_session_stops_the_write_through_at_once` (state) | the save path stops writing the moment the setting lands | +| `a_configured_cache_path_beats_the_editors_storage_folder` (state) | rung 1 over rung 2, and the fall-back when it is unset | +| `a_storage_folder_that_does_not_exist_yet_is_made_on_demand` (state) | what `context.storageUri` really hands over | +| `the_cached_index_is_the_index_a_fresh_scan_would_have_built_over_the_corpus` (state) | the paranoid sweep: 860 real files in and out of the store, fingerprint, counts and the completion word table | +| `qa_perf_cold_warm_and_half_warm_scans` (state, `#[ignore]`) | the numbers above, the store size, and the cost of the hash | +| `a_second_session_over_the_same_storage_folder_resumes_from_the_cache` (server) | through the real dispatch: the end message, the `cached:` lines, the fingerprint, and the same `workspace/symbol` answer | +| `a_session_that_was_offered_no_storage_folder_keeps_its_index_in_memory` (server) | what every client but ours does, unchanged | +| `the_index_cache_is_on_until_a_client_turns_it_off`, `the_cache_path_is_unset_until_a_client_names_one` (settings) | the defaults, the empty string, five wrong types each; the pull-door test grew both keys | +| `a_second_session_over_the_same_storage_path_indexes_from_the_cache` (e2e) | the real binary, three sessions over one `storagePath`: cold, warm, and one file changed | + +### 2026-08-27 — dev agent (fix round: QA's three findings) + +Three fixes, all inside `index_cache.rs` and the tests that pin it. No +handshake moved: `FileFacts`, its codec and `FACTS_FORMAT` are untouched — what +changed is the *store's* framing, which is `CACHE_FORMAT`'s to version. + +- **Finding 1 (Medium, poisoned records) — the trust question is ruled, and + the accident half is closed anyway.** The ruling, written into Assumptions + in full: a store somebody edited on purpose is outside the threat model, + because anything that can write the cache directory can write the source + files (and the binary), and the only thing that would detect a forgery is a + keyed MAC whose key would have to live on the same disk as the data it + authenticates. QA's point that the *consequence* here is stronger than + `lucisv_core::cache`'s (fields served into the index versus a skip-or-not + bit) is recorded with the ruling rather than argued away. What the round + does add is a **16-hex FNV-1a of the encoded facts, appended to every + record and checked before the record is believed**. That is what makes the + module's "never a correctness input" promise true against every *accident* + a written record can suffer — bit rot, a torn append two servers + interleaved, an editor rewriting line endings, a partial write — rather than + only against staleness. It is deliberately not a security boundary, and the + test says so out loud: `a_record_whose_facts_do_not_match_their_checksum_is_dropped` + asserts the tampered record is dropped, the honest one beside it still + reads, and a *reforged* one (checksum recomputed) is still served, which is + the accepted residue. QA's two tests flipped accordingly — the store-level + one renamed from `..._is_served_verbatim`, and the workspace-level + `a_poisoned_cache_record_makes_the_fingerprint_diverge_from_a_fresh_scan` + renamed to `a_poisoned_cache_record_is_dropped_and_the_index_is_a_fresh_scans`, + where the fingerprint now *equals* the fresh scan's and the file is reported + parsed rather than cached. The checksum goes last on the line because the + facts hold no raw tab, so `rsplit_once` recovers it unambiguously and the + encoded facts are handed to `decode` byte-identical to how they were + written. `CACHE_FORMAT` 1 → 2 by the rule at the constant; format 1's + stores are discarded whole, which + `a_store_from_the_previous_store_format_is_dropped_whole_and_replaced` + pins with a real format-1 store, header and unchecksummed record and all. +- **Finding 2 (Medium, first-writer race) — `create_new`, and truncation kept + for the one case that still deserves it.** `append`'s old `else` branch + truncated whenever *this instance* had not read a header, which is every + session's state at its first cold scan, so a second server erased the + first's records; QA measured 25 of 100. The store is now *claimed* with + `File::create_new`, and the header is written into whatever settled. There + are exactly three shapes a session can find, and `settled_header` names + them: **Ours** (append — this is the loser of the race, and the winner's + header is as good as its own), **Empty** (the file one of us just made, + caught before its header: write the identical header line and append, so at + worst the store carries a duplicate header line, which the reader drops as + one more malformed record), **Foreign** (a whole first line this build + cannot read: replace it, because its records were dropped at load and + appending under it would lose ours at the next load too). `writeln!` was + also replaced with a single `write_all` per record and per header, since + `writeln!`'s formatting machinery is free to split a line across two writes + — the doubt QA raised about the O_APPEND argument, and the thing that makes + the "Empty" case's duplicate header a whole line rather than two spliced + ones. **The count is deterministic**, not merely likely: no branch above + drops a byte, no session truncates a store another session is appending to, + and each line is one write on an append handle. QA's test, renamed + `concurrent_first_writers_all_survive_and_none_is_ever_wrong`, now asserts + 100 of 100 and was run 10 times in a row for 100 every time. + **The residue, stated honestly**: two sessions cold-starting on the same + *foreign* (another version's) store can still both replace it and lose each + other's early records. A cousin of the same residue, from QA's fix-round + re-check: `settled_header`'s single read could in principle observe a torn + read of a concurrent header write and misclassify a store as Foreign, + truncating it unwarrantedly — the same one-write window, the same + self-healing loss of nothing a current-version reader could use, + portable-untestable, accepted alongside. Closing that needs either a lock or a + rename-to-claim dance whose failure mode (a writer appending to an unlinked + inode) is worse than what it fixes; the window is one write wide, needs an + upgrade plus two simultaneous first scans of one workspace, and what is lost + is a cache nobody could read. The end of either scan rewrites the store + whole from memory regardless. The other window `create_new` could have + introduced — a zero-byte store from a session killed between the claim and + the header — is what the **Empty** arm exists for, pinned by + `an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace`. +- **Finding 3 (Low, UTF-8 truncation) — bytes in, one line at a time.** + `open` read the store with `read_to_string`, so a cut landing inside any + multi-byte character rejected the *whole* buffer, which `unwrap_or_default` + then made indistinguishable from "no header": every intact record thrown + away because something later in the file tore mid-character. It now reads + bytes, splits them the way `str::lines` would (`store_lines`, which also + strips a `\r` so the header check is what it always was), and validates each + line's UTF-8 on its own — an invalid line is skipped like any other bad + record. QA's byte-by-byte truncation loop, renamed + `truncating_the_store_at_every_byte_offset_costs_only_the_torn_record`, + keeps its two original properties and gains the one that was the finding: + **at every cut past the last whole record, every whole record survives** — + 0 of 583 cut points cost anything but the record they landed in (it was 2 of + 534 before, on a store that is now longer because of the checksum). The + test's premise assertion changed with it: it now insists some cut lands + mid-character, so the test still proves what it says it proves. +- **Also**: `a_record_whose_facts_no_longer_decode_is_a_miss_not_a_failure` + now writes its half-record *with* a valid checksum, or it would have been + rejected one layer earlier and stopped testing the decode path; + `a_corrupt_record_is_dropped_and_the_rest_of_the_store_is_not` gained the + two new damage shapes (a record with no checksum field, and one whose + checksum does not match) and now also asserts the corrupt record's own path + is never served, not merely that the good one survives. +- Files touched: `crates/lucisv_server/src/index_cache.rs`, + `crates/lucisv_server/src/state.rs` (the one QA test), this README. No new + dependency, no `unsafe`, no `#[allow]`, no version bump, no `docs/site/`, no + commits. Nothing outside `index_cache.rs` changed behaviour: the store's + framing is private to it. + +**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy +--all-targets --workspace`: zero warnings. `cargo test --workspace`: **2297 +passed, 0 failed, 9 ignored** — QA's tree was 2295, and the two new tests are +`a_store_from_the_previous_store_format_is_dropped_whole_and_replaced` and +`an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace`. The +three flipped tests were renamed, not added: `lucisv_server` alone goes 1091 → +1093, so nothing was quietly dropped. `cargo test -p vlog_formatter`: 180 +passed across its seven binaries, untouched — `verify.rs` is not in this +round's diff. `cargo build && node editors/vscode/smoke.js +target/debug/lucisv-server`: `smoke: OK`. `~/Library/Caches/lucisv`: checked +after the whole run, still absent. The `#[ignore]`d probe was re-run in both +profiles for the Measured table above, and the four-writer race test was run +ten times in a row: 100 of 100 records every time. + +## QA log + +### 2026-08-27 — QA agent (attack surfaces on the persistent index cache) + +**Verdict up front: the poisoned-cache trust boundary does not hold, and +everything else is committable.** The module doc's claim — "a performance +artifact and never a correctness input" — is true against corruption and +staleness, which is everything the dev's 33 tests exercise. It is not true +against a store an attacker (or anything else with write access to the cache +directory) can hand-edit: a record is verified only against the *file's* +content hash, and nothing hashes or otherwise authenticates the facts field +itself. A line with a real file's exact hash and fabricated facts is served +verbatim, and it changes what `workspace/symbol`, hover, go-to-definition and +rename answer for that file. Filed as **Medium** severity: same threat model +as `lucisv_core::cache` (same user, same disk — anyone who can write here can +already edit the source or the binary), but a materially different +consequence, because that cache's entry is a skip-or-not bit and this one's +fields are served straight into the index. Recommend the dev/lead decide +whether this is accepted as within the stated threat model (write access to +the cache dir already implies write access to the workspace) or whether a +record should carry its own integrity check (e.g. hash the encoded facts +too, or HMAC the line) before this ships as "never a correctness input" +without qualification. Not blocking on its own — it does not violate "never +corrupt code" (the cache never touches source files) or idempotency — but the +README's phrasing should either gain a caveat or the gap should be closed. + +**Gates.** `cargo fmt --all -- --check`: clean, both before and after QA's +additions (one re-run of `cargo fmt --all` was needed after adding tests, to +match this repo's line-width formatting — no logic changed). `cargo clippy +--all-targets --workspace`: zero warnings, before and after. `cargo test +--workspace`: **1091 passed, 0 failed, 9 ignored** in the crate that carries +this round (up from the dev's own 1082 passed — the QA session's 9 new +tests, below), **2295 passed** workspace-wide, 0 failed. `cargo test -p +vlog_formatter`: 114 passed, untouched — confirmed `verify.rs` is not in this +round's diff (`git diff 5e4aa7b --stat -- '**/verify.rs'` is empty). `cargo +build && node editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: +OK`. `~/Library/Caches/lucisv` was checked before, during (mid-session) and +after this entire QA pass with `ls`: never created. All test-writing paths +used `std::env::temp_dir()`-based scratch directories, matching the dev's own +`TempDir`/`Tree` helpers. + +**Per attack surface:** + +1. **Adversarial store files — poisoned records.** See verdict above. + Reproduced directly at the store level + (`index_cache::tests::a_record_with_a_valid_hash_but_fabricated_facts_is_served_verbatim`, + new) and quantified through the equivalence sweep as asked + (`state::tests::a_poisoned_cache_record_makes_the_fingerprint_diverge_from_a_fresh_scan`, + new): a record with `a.sv`'s genuine content hash but fabricated facts is + a cache hit, and the resulting `WorkspaceIndex::fingerprint()` differs + from a fresh scan's — proving the corpus equivalence test + (`the_cached_index_is_the_index_a_fresh_scan_would_have_built_over_the_corpus`) + would have caught this if anything validated a record beyond the file's + hash. Nothing does, today. + - **Escaping attacks**: reused and extended + `a_corrupt_record_is_dropped_and_the_rest_of_the_store_is_not`'s shapes + by inspection — `Reader`/`Writer` in `crates/vlog_semantic/src/facts.rs` + split strictly on literal `\t`, so an unescaped raw tab or newline + shifts field boundaries rather than being interpreted, and `decode`'s + `input.done()` check (a field left over at the end) plus every + `Option`-returning accessor rejects the result — verified-clean, + no panic path exists (every parse step is `?`-short-circuited, so an + over-long length prefix like `D999999999` fails on the very first + missing field rather than allocating or looping unboundedly — traced, + not additionally tested, since the mechanism is structural: a `for _ in + 0..n { push(x()?) }` loop cannot outrun the fields it reads from). + Negative numbers fail `u32::parse` (`None`, no panic). A path of + `../../../etc/passwd`-shape is just a `PathBuf`; no filesystem + traversal ever happens from a record's path field — `record_path` and + `decode` never open anything, they only build/compare strings, so this + path is inert whether or not the current scan actually asked about it. + - **Path outside every root**: traced, not separately tested — `open()` + performs a wholesale `HashMap` insert with no root filtering, but + `rebuild_index_with` only ever calls `cache.facts_for(path, text)` for + paths `collect_sources`'s scope walk already produced, so an + out-of-root entry is inert. This is exactly what + `the_cache_never_puts_back_a_file_the_scan_no_longer_visits` already + pins from the other direction (a file leaving scope keeps its record, + unused); confirmed the mechanism is symmetric by reading + `state.rs:456-490` rather than re-testing it. + - **Duplicate records for one path**: `record()`-driven duplication + (three `record()` calls in one session) was already pinned by + `compaction_keeps_one_line_per_path_and_drops_the_files_that_are_gone`. + Added the raw-file shape — two lines for the same path sitting in the + store file directly, the shape a hand-edited or externally + concatenated store takes rather than one `record()` produces — + confirmed last-line-wins + (`index_cache::tests::two_raw_lines_for_the_same_path_in_the_store_file_last_one_wins`, + new). + - **100 MB single-line store**: `IndexCache::open` calls + `std::fs::read_to_string`, unbounded — the whole file loads into memory + regardless of size, same as `lucisv_core::cache::Cache::load`'s own + `read_to_string`. Not a regression against this codebase's existing + posture, and the store's size is bounded by the workspace's own size + (the README's own measurement: ~1 KB/file, so a store large enough to + matter implies a workspace already large enough to dominate memory via + the index itself). Verified-clean by comparison, not separately load + tested — an actual 100 MB write/read round trip was judged not worth + the wall-clock time for a bound this codebase already accepts + elsewhere. + - **Header variations**: wrong version/format discards all — already + pinned (`a_store_from_another_version_is_dropped_whole_and_replaced`). + Extra fields: **rejected**, pinned directly + (`index_cache::tests::a_header_with_an_extra_trailing_field_is_rejected_like_any_other_mismatch`, + new) — the check is `lines.next() == Some(header().as_str())`, exact + string equality, so there is no forward-compatible "unknown trailing + column is ignored" path. Worth knowing if a future format revision ever + wants additive header fields; not a defect today. + +2. **Crash shapes.** + - **Truncate at every byte offset**: implemented exactly as asked + (`index_cache::tests::truncating_the_store_at_every_byte_offset_never_panics_or_serves_wrong_facts`, + new), over a store built with one file holding a multi-byte UTF-8 + character (`é`/`ö` in a macro body) alongside two plain-ASCII files. + **No panic at any of 534 cut points, and nothing served was ever + wrong** — both required properties hold. **Finding (Low): a cut landing + inside a multi-byte character loses the *entire* store, not only the + torn record.** `IndexCache::open` uses `read_to_string`, which rejects + the whole buffer if its tail is not valid UTF-8; a truncation whose cut + point falls inside any multi-byte sequence — anywhere in the file, not + only in the record that was mid-write — produces exactly that invalid + tail, and `unwrap_or_default()` then turns the whole read into an empty + string, indistinguishable from "no header". The test isolates this from + the *expected*, harmless kind of loss (cuts that simply haven't + finished writing a.sv/b.sv/the header yet) by checking specifically for + cuts *past* both good lines that still lose them: **2 of 534 cut + points** did, both landing inside the record's `é`/`ö` bytes. + Consequence is bounded to a full re-parse (never a wrong answer, per + the property the test actually enforces), but it is a real departure + from the stated "a corrupt record drops only that record" granularity + for this one tear shape — plausible in practice for any workspace with + non-ASCII identifiers, string literals, or comments. Not fixed by QA + (a fix — e.g. reading bytes and validating UTF-8 per line rather than + for the whole buffer — is a design change belonging to the dev). + - **Interrupted compaction (temp file left behind)**: confirmed + **never cleaned up** + (`index_cache::tests::an_orphaned_compaction_tmp_file_is_never_swept_up`, + new) — `open()` only ever reads the exact name `index-cache`, so a + stray `index-cache..tmp` from a process killed between the + temp-file write and the rename is invisible to it and to every later + `compact()` (which names its own tmp after *its own* pid). Harmless to + correctness, confirmed inert against a real store in the same test; + filed as a minor, slow, unbounded disk leak (one orphan per crash + landing in that exact window) — consistent with the already-filed "no + background compaction, no size bound" limitation, just a specific + mechanism for it. Not fixed by QA (cleaning up stale `*.tmp` siblings + on `open()` is a small, reasonable addition, but it's new behavior, not + a typo-class fix). + - **Disk-full on append**: reasoned and tested + (`index_cache::tests::a_write_failure_is_silent_and_never_panics_or_leaves_a_half_written_store`, + new, Unix-only, `#[cfg(unix)]`) via a directory with its owner-write bit + cleared. Note for whoever reads this test later: a read-only + *directory* does not stop an append to a file that already exists and + is itself still writable (directory permissions gate creating/removing + entries, not writing through a handle to one that already exists), so + `record()` kept succeeding in this setup; `compact()`'s temp file is a + new directory entry and did fail, silently, via the existing + `.is_ok()` check, leaving the standing store intact and readable + afterward. No panic either way. This models "cannot create new files" + rather than genuine `ENOSPC` on a write to an open fd, which Rust's + sandbox does not offer an easy way to simulate; the code path + (`let _ = writeln!(...)` in `append`, and the checked `fs::write(...) + .is_ok()` in `compact`) is identical for both failure origins by + inspection, so the distinction was judged not worth chasing further. + +3. **Two servers, one store.** + - **O_APPEND atomicity / merged lines during steady-state appending**: + reasoned rather than raced directly — `writeln!(file, "{line}")`'s + default `Write::write_fmt` can issue more than one `write_all` call per + line (one per literal/argument piece `fmt::Arguments` carries), so two + already-open writers are not guaranteed a single atomic `write(2)` per + line the way the README's phrasing might suggest. Even granting an + interleave, the field structure means a spliced line either fails to + decode (dropped, safe) or — astronomically unlikely — decodes cleanly + with a hash field that would have to coincidentally equal some real + file's 64-bit FNV-1a hash to be *served*; not pursued further as a + direct race (see below for what QA did race instead, which found a + bigger and more tractable gap in the same neighborhood). + - **Concurrent first writers (cold start) — new finding, Medium**: + `append()`'s `header_ok` is per-`IndexCache`-instance state decided at + `open()` time; every server opening a *new* store computes + `header_ok == false` independently, and `append()`'s `else` branch for + that case **truncates** the file before writing a fresh header. Four + threads, each its own `IndexCache::open` on the same empty directory, + each appending 25 long records with no compaction, left **25 of 100** + records standing + (`index_cache::tests::concurrent_first_writers_can_lose_each_others_entries_but_never_serve_a_wrong_one`, + new) — a later writer's truncate silently erases an earlier writer's + already-appended lines, repeatedly, because each writer only truncates + once (on its own first write) but does not know another writer already + did. **Bounded exactly as the README claims — nothing served was ever + a mix of two writers' bytes, only sometimes absent** — but "no locking + … a race costs re-parsing" understates the magnitude: this is not a + one-line loss, it can be most of a whole scan's writes, and it is a + *cold-start-specific* shape (steady-state appends to an already-`Some` + header are not affected the same way) that the write-up does not call + out separately from the general no-locking note. The next whole + rescan's `compact()` repairs it regardless — filed as a documentation + gap plus a candidate follow-up (e.g. `OpenOptions::new().create_new(true)` + to detect "someone else already claimed this" instead of always + truncating), not fixed by QA. + - **Compaction racing an append**: reasoned, not separately tested — a + `rename` mid-scan does not invalidate another process's already-open + append fd (POSIX: the fd keeps writing to the now-unlinked inode until + closed), so a process whose scan is still running when another + compacts will lose whatever it appends after that point *unless* it + also reaches its own `compact()` before exiting — which every whole + rescan unconditionally does (`rebuild_index_with`'s last two lines). + Since `compact()`'s `render()` writes from **in-memory** `self.entries` + rather than re-reading the (possibly now-detached) file, a process that + finishes its own scan is self-healing regardless of a mid-scan rename + race; the only real loss is a process that crashes *during* the + window, which is no worse than crashing without the race at all. This + matches the Assumptions section's own claim ("the worst case is a + session whose records another session's rewrite dropped … costs + re-parsing, never an answer") exactly — verified-clean by trace, a live + two-process test was judged not to add information proportional to its + complexity here. + - **Three e2e sessions are sequential**: confirmed by reading + `crates/lucisv_server/tests/e2e.rs:4446-4480` — + `a_second_session_over_the_same_storage_path_indexes_from_the_cache` + calls `talk(&session())` three times in program order, and `talk` + writes the whole session and reads until the child's stdout closes + (the child has already received `exit` and terminated) before the next + call starts. No concurrency is exercised on the wire; noting this per + the brief's instruction, not as a gap — the concurrent case is what + item 3's other three points cover at the `index_cache` level instead. + +4. **The equivalence sweep**: ran + `the_cached_index_is_the_index_a_fresh_scan_would_have_built_over_the_corpus` + (passes, 860 files, corpus present on this machine) and added the + negative control described in the brief — see item 1. Both new. + +5. **The `cfg(test)` guard.** + - `Workspace::cache_dir`'s test-only early return (`state.rs:380-383`) is + exactly what it claims: it only ever short-circuits when *neither* a + `cachePath` nor a `storagePath` is set, and every cache test in this + crate sets one or the other, so the OS rung is genuinely never reached + from an in-process test. Confirmed by reading every call site; not + separately tested (testing a negative absence-of-a-branch is what the + existing test suite's shape already is). + - **`os_cache_dir()`'s platform branches — finding (Low): two of three + are compiled out of every test run that exists, and the third is + exercised only against the ambient environment, never an injected + one.** `.gitea/workflows/ci.yml` runs `cargo test --workspace` + exclusively on `runs-on: macos-arm64`. `os_cache_dir`'s Windows branch + (`LOCALAPPDATA`) and its "neither macOS nor Windows" branch + (`XDG_CACHE_HOME`, filtered to absolute paths, falling back to + `~/.cache`) are behind `#[cfg(windows)]` / `#[cfg(all(not(macos), + not(windows)))]` respectively, so on this CI they are not even + *compiled*, let alone tested — this is not something any test in this + repository can currently exercise without a second CI runner or + cross-compilation. The macOS branch that *does* compile is called + directly in `the_cache_directory_is_the_highest_rung_that_answers` + (`os_cache_dir()` at `index_cache.rs:933`), but only against whatever + `HOME` the test process actually has — no test sets `HOME` to a + controlled value first, and the `HOME`-unset-returns-`None` fallback + (which is what makes the whole ladder correctly fall through to "no + cache" rather than panicking) is never exercised on any platform. + Recommend the dev consider a version of `os_cache_dir` that takes its + environment lookups as parameters (or a small env-injection test + helper), so the Linux/Windows branches can be checked with hand-fed + values even when compiled out — a real gap in an otherwise very + thoroughly pinned feature, not fixed by QA since it is a testability + refactor, not a bug. + - **e2e env redirection coverage**: confirmed complete — + `crates/lucisv_server/tests/e2e.rs` has exactly two `Command::new` + call sites; one is `server_command()` itself (line 77, sets + `HOME`/`XDG_CACHE_HOME`/`LOCALAPPDATA` to a scratch sandbox), and every + spawn of the `lucisv-server` binary in the file goes through + `server_command()` (lines 98 and 2191, both `let mut child = + server_command()...`). The third `Command::new` (line 553) spawns the + unrelated `lucisv` **CLI** formatter binary for + `fix_all_edits_exactly_what_lucisv_check_fix_edits_inside_a_fence`, + which uses `lucisv_core::cache`'s own store (`.lucisv_cache`, relative + to the current directory by default, not the OS cache directory this + feature adds) and is out of this round's scope — confirmed it needs no + redirection for *this* feature's sake. + +6. **Settings/lifecycle**: all verified-clean by reading the existing tests + plus `settings.rs`, no gaps found. + - `persist: false` mid-session stopping both directions: + `turning_persistence_off_mid_session_stops_the_write_through_at_once` + and `persistence_off_reads_nothing_and_writes_nothing` both pass and + match the code (`set_client_settings` drops the cache to `disabled()` + the moment either setting changes, `state.rs:361-365`). + - `cachePath` change taking effect next rescan: + `a_configured_cache_path_beats_the_editors_storage_folder` pins exactly + this (switch settings, rescan, store moves). + - `.gitignore` content: `nothing_is_created_until_something_is_recorded` + asserts the literal `"*\n"`, matching `lucisv_core::cache`'s own. + - Scope-narrowed reopen not resurrecting out-of-scope entries: + `the_cache_never_puts_back_a_file_the_scan_no_longer_visits` covers + this directly and was re-read line by line; the mechanism (the cache + is only ever asked about paths the scope walk already produced) is the + same one that makes finding "path outside every root" above inert. + - Wrong-typed `persist` leaving the cache **on**, and a bad `cachePath` + leaving it unset: `the_index_cache_is_on_until_a_client_turns_it_off` + and `the_cache_path_is_unset_until_a_client_names_one` in + `settings.rs` both pass and match the README's stated direction. + +7. **The no-mtime deviation — save-path soundness.** The pinning test + (`the_key_is_the_content_and_only_the_content`) covers the general + claim; added the specific construction the brief asked for — open a + buffer whose text disagrees with disk, let the incremental path write + its record through, and check the record a fresh session resolves to is + keyed on and filled from the *buffer's* bytes, not disk's + (`state::tests::a_saved_buffers_record_is_keyed_and_filled_from_the_buffer_not_stale_disk`, + new). **Verified-clean**: the store's fresh-session lookup returns the + buffer's facts under the buffer's hash, and disk's own current hash does + not appear as a key at all — confirming a stored `(size, mtime)` really + would have been unsound here, exactly as argued in the work log. + +8. **CLAUDE.md compliance.** + - No `unwrap()`/`expect()`/`panic!()` in library code: checked every + occurrence in `index_cache.rs`, `facts.rs`, and every line this round's + diff *added* to `state.rs`, `server.rs`, `settings.rs`, `main.rs`, + `defines.rs`, `workspace.rs`, `lib.rs` (`git diff 5e4aa7b -- | + grep '^+.*\(unwrap\|expect\|panic!\)'`). Every hit is inside a + `#[cfg(test)] mod tests` block (confirmed by line number against each + module's `mod tests` line) — none in a reachable library path. + - Public items have one-line doc comments: spot-checked + `index_cache.rs` and `facts.rs` in full — every `pub` item is + documented, matching the standard the rest of the round holds to. + - README sections present exactly once: confirmed by reading the whole + file top to bottom — Goal, Assumptions, Handshakes, Status/TODO, Work + log, QA log, Review each appear exactly once, in the required order. + - Corpus tests skip-guarded: every corpus-dependent test in this round + (`the_cached_index_is_the_index_a_fresh_scan_would_have_built_over_the_corpus`, + `qa_perf_cold_warm_and_half_warm_scans`) opens with the `if + !corpus.is_dir() { eprintln!(...); return; }` guard, matching the + pattern already established elsewhere in this file. + - `verify.rs` untouched: `git diff 5e4aa7b --stat -- '**/verify.rs' + crates/vlog_formatter/**'` is empty. + - No `#[allow]` in either new file (`index_cache.rs`, `facts.rs`). + +**Beyond the list (worst shapes QA reached for on its own):** the +concurrent-first-writers truncate storm (item 3) and the multi-byte-tear +whole-store loss (item 2) were both found by extending the brief's named +scenarios rather than being on the list verbatim — they are the two +findings beyond the poisoned-cache one that seem worth the dev's attention, +in that order of severity. Nothing found reaches a "never corrupt code" or +idempotency violation; every finding here is either a performance/DoS-class +loss (bounded, self-healing at the next whole rescan) or the one trust +question filed first. + +**Tests added this session** (9, all passing, all in +`crates/lucisv_server/src/`): `index_cache.rs` — +`a_record_with_a_valid_hash_but_fabricated_facts_is_served_verbatim`, +`truncating_the_store_at_every_byte_offset_never_panics_or_serves_wrong_facts`, +`concurrent_first_writers_can_lose_each_others_entries_but_never_serve_a_wrong_one`, +`a_header_with_an_extra_trailing_field_is_rejected_like_any_other_mismatch`, +`two_raw_lines_for_the_same_path_in_the_store_file_last_one_wins`, +`an_orphaned_compaction_tmp_file_is_never_swept_up`, +`a_write_failure_is_silent_and_never_panics_or_leaves_a_half_written_store`; +`state.rs` — +`a_poisoned_cache_record_makes_the_fingerprint_diverge_from_a_fresh_scan`, +`a_saved_buffers_record_is_keyed_and_filled_from_the_buffer_not_stale_disk`. +No fixes applied — every finding above is either verified-clean or filed for +the dev/lead, since none of them is a typo-class or missing-assertion-class +fix within QA's remit. `cargo fmt --all` was run once, after adding these +tests, purely to match this repo's formatting (no behavior change). + +**Overall verdict: not blocking, but not silently committable as "done" +either.** The feature is idempotent, drops no comments, and never corrupts +a source file — the three hard invariants hold. The one finding that +matters is the poisoned-cache trust boundary (severity: Medium, a scoping +question for the lead — is "same disk, same user" an accepted threat model +here the way it is for `lucisv_core::cache`, given the consequence is +different in kind?). The concurrent-cold-start truncate storm (Medium) and +the multi-byte-tear whole-store loss (Low) are both real but self-healing. +Recommend the lead read finding 1 and decide the threat-model question +before this ships as worded; the rest can land as-is with the two Low/Medium +process gaps filed for a follow-up round. + +### 2026-08-27 — QA agent (fix-round re-verification) + +**Verdict up front: all three findings are actually fixed, adversarial +re-attack found nothing new that rises above what is already accepted and +written down, and one bug was caught and fixed in QA's own new test rather +than in the product. Committable.** + +**Gates, re-run clean.** `cargo fmt --all -- --check`: clean. `cargo clippy +--all-targets --workspace -- -D warnings` (forced a real rebuild first with +`touch` on both touched files, since a cached `Finished` with no visible +warnings is not proof of a clean run): zero warnings. `cargo test +--workspace`: **2300 passed, 0 failed, 9 ignored** — the dev's post-fix +**2297** plus QA's own 3 new tests below, nothing else moved. `cargo test -p +vlog_formatter`: **180 passed** across the same seven binaries (31+1+4+6+2+ +22+114), byte-for-byte the count the dev reported — `verify.rs` untouched. +`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: +`smoke: OK`. `~/Library/Caches/lucisv`: checked with `ls` before this +session, after `cargo test --workspace`, after the release perf probe, and +after the final smoke run — never created at any point. `git status` +confirms the only files this session touched are `index_cache.rs` (QA's new +tests) and this README. + +**Finding 1 (checksum) — re-verified, plus one real bug caught in QA's own +test.** +- The flipped tests (`a_record_whose_facts_do_not_match_their_checksum_is_dropped` + at the store level, `a_poisoned_cache_record_is_dropped_and_the_index_is_a_fresh_scans` + through the workspace) both pass and both read honestly: the store-level + test recomputes the checksum via `line()` for its "honest" and "reforged" + cases rather than reusing a stale one, and its final assertion + (`served == evil`, `served != genuine`) is exactly the accepted residue, + commented as such — not quietly asserted and left unexplained. The + workspace-level test recomputes the *file's real* content hash + independently (`lucisv_core::cache::content_hash(real_text.as_bytes())`) + rather than reusing whatever the genuine record already had, which is what + makes it a real reproduction of "hash matches, facts don't" and not a + tautology. +- New adversarial shape 1, **checksum field corruption** + (`a_corrupted_checksum_field_drops_the_line_and_never_panics`, new): odd + length, right-length-but-non-hex, and missing entirely, each checked + against a good record beside it. Caught a bug in my own first draft — + `format!("{:015x}", ...)` does not truncate a naturally-16-digit hex value + (it is a *minimum* width, not a maximum), so my first "odd length" record + accidentally carried the genuine, matching, 16-character checksum and the + test failed by asserting a correctly-served record was wrong. Fixed by + slicing the real checksum string (`&real_checksum[..15]`) instead of + reformatting the number. Recorded here because it is exactly the class of + mistake CLAUDE.md's rule about attack tests is guarding against — an + under-verified "corruption" fixture that turns out not to corrupt + anything — and because it happened in a fix-round QA test, not in a normal + test, it seemed worth naming rather than quietly fixing and moving on. + All three shapes now genuinely corrupt the checksum and are dropped, never + served, never panicking. +- New adversarial shape 2, **the checksum's exact byte coverage** + (`a_benign_reencoding_with_the_original_checksum_is_still_dropped`, new): + the brief asked whether an "equivalent-after-decode-but-different-bytes" + shape exists. It does, structurally: `Reader::num` parses with + `str::parse::`, which accepts a leading zero (`"00"` → `0`), while + `Writer::num` never writes one — so a record's `D`-count field rewritten + from `"0"` to `"00"` decodes to the exact same `FileFacts` as the original + byte-for-byte-different record. Verified the checksum does **not** treat + these as equivalent: keeping the original record's checksum against the + re-spelled bytes is rejected, because `line()`'s checksum is computed over + and compared against the literal bytes `decode` receives, never over + anything `decode` produces. This is a genuine structural strength, not a + gap — noted per the brief's instruction to record it as such if no + exploitable shape exists. (No two-different-inputs *encode* to the same + bytes was found or is plausible: every field is length-prefixed or + escaped with no alternate spelling except this one decode-side + permissiveness, and `encode` itself never emits a leading zero.) + +**Finding 2 (race) — re-verified, plus real concurrency on the case QA's +new shape asked for.** +- `concurrent_first_writers_all_survive_and_none_is_ever_wrong` run 10 times + standalone: **100 of 100 every time**, no flakes. +- New shape, **crash-then-two-racers on the `Empty` arm** + (`two_writers_racing_the_empty_arm_leave_a_valid_store`, new): a + zero-byte store (the crash `an_empty_store_is_a_claim_to_finish_rather_ + than_a_store_to_replace` already covers with one writer) found by *two* + real threads racing `claim`/`settled_header` at once, rather than the + sequential single-writer construction. Run 15 times standalone with no + failure: both writers' records are always readable afterward, and the + store is always left with the header present at least once (sometimes + duplicated, which is the documented, harmless residue — a duplicate + header line the reader drops as one more line that isn't 16 hex digits + wide). Matches the work log's description of the `Empty` arm exactly. +- Read `claim`/`settled_header`/`append_line` line by line for the one + sub-window the write-up does not name explicitly: `settled_header` reads + the file with one `std::fs::read`, and if that read races a concurrent + writer's header `write_all` such that it observes a **partial** (torn) + header — bytes that are neither empty nor a complete matching header line — + it falls into `Header::Foreign` and truncates a store that was never + actually foreign, just caught mid-write by an unlucky reader. This is a + real, additional sub-case of the residue window, not a new class of bug: + it requires the OS to hand back a non-atomic partial view of a write well + under typical filesystem atomicity thresholds (~50 bytes, the header + line), which every other part of this round's crash-safety argument + (`write_all` instead of `writeln!`, "no line can land inside another") + already leans on being atomic in practice. Not reproducible in a portable + test — it needs a kernel that actually tears a sub-page write, which nothing + in this environment can force — so traced rather than demonstrated, and + filed as the same severity as the already-accepted "two cold starts on a + foreign store can both replace it" residue: one write wide, self-healing + at the next whole-scan compaction, costs a re-parse and never a wrong + answer. Worth a one-line mention next to that residue in Assumptions, not + a blocker. +- The Foreign-both-replace residue: traced against the code and matches the + work log's claim — `replace_with_header` always writes the exact same + `format!("{}\n", header())` bytes regardless of which session calls it, so + even an interleaved double-replace converges on a valid single header + rather than mixed content, and the next whole rescan's `compact()` rewrites + the store from memory regardless of what either replace left behind. No + code path reads back what a replace overwrote before overwriting it, so + nothing a current-version reader could still use is destroyed beyond what + was already unreadable. + +**Finding 3 (truncation) — re-verified, premise checked, not vacuous.** +`truncating_the_store_at_every_byte_offset_costs_only_the_torn_record` +re-run: `mid_character_cuts` is nonzero every run (2 in this session's runs; +the exact count and the total cut-point count shift slightly run to run +because the temp directory's path — itself part of every record's encoded +`path` field — differs in length by session, which is expected and doesn't +touch the property under test), and `collateral_loss` is exactly 0 every +time. The fixture (`unicode_text`, holding `é`/`ö` in a `` `define`` body) does +contain genuine multi-byte UTF-8, so the premise assertion is real and not +vacuous — confirmed by reading the fixture, not only by the assertion +passing. + +**Cross-checks.** `an_index_built_from_records_is_the_index_the_parse_would_ +have_given` and the corpus equivalence sweep both still pass. The `#[ignore]`d +probe reproduces the numbers exactly in debug (910400-byte store, 860 files, +warm ≈ 0.76 s vs. the claimed 0.756 s) and in release (**910400 bytes**, +warm 183 ms vs. the claimed 179 ms — same order of magnitude, within normal +machine noise). `state.rs`'s renamed poisoned test +(`a_poisoned_cache_record_is_dropped_and_the_index_is_a_fresh_scans`) keeps +every one of its original premise checks (`scanned.parsed == ["a.sv"]`, +`scanned.cached.is_empty()`) and adds the fingerprint-equality assertion the +fix requires — nothing was dropped in the rename, only the direction of the +final assertion changed, which is the whole point of the fix. + +**CLAUDE.md compliance.** No `unwrap()`/`expect()`/`panic!()` outside +`#[cfg(test)]` in `index_cache.rs` or `facts.rs` (checked every occurrence, +including QA's own three new tests — all inside `mod tests`). Every `pub` +item in both files carries a one-line doc comment. No `#[allow]`, no +`unsafe`, in either file. README sections (`Goal`, `Assumptions`, +`Handshakes`, `Status / TODO`, `Work log`, `QA log`, `Review`) each appear +exactly once, in order. `FACTS_FORMAT` is untouched at `1` — correctly: +nothing about what a record's *facts* field holds or how `encode`/`decode` +read it changed this round, only the store's own framing +(`CACHE_FORMAT` 1 → 2), which is the constant this round's change actually +belongs to. + +**Tests added this session** (3, all passing, all in +`crates/lucisv_server/src/index_cache.rs`): +`a_corrupted_checksum_field_drops_the_line_and_never_panics`, +`a_benign_reencoding_with_the_original_checksum_is_still_dropped`, +`two_writers_racing_the_empty_arm_leave_a_valid_store`. `cargo fmt --all` +was run once after adding them to match this repo's formatting; no logic +changed by it. + +**Overall verdict: committable.** All three original findings are fixed and +hold up against adversarial re-attack, including shapes beyond the ones +named in the brief (checksum-field corruption, the leading-zero +equivalent-bytes shape, and a genuinely concurrent two-writer `Empty`-arm +race). One sub-window of finding 2's already-accepted residue is a little +wider than written down — a torn *read* of a header write, not just a torn +*write* — but it is the same severity, the same self-healing story, and the +same reliance on small-write atomicity the rest of the round already trusts; +worth a documentation line, not a fix. No hard invariant is at risk anywhere +in this round. + +## Review + +### 2026-08-27 — lead + +Reviewed both rounds' diffs, work logs and QA logs; re-ran all gates +myself (2300 workspace tests, 0 failed; the real cache directories +never touched), clean. The main round's design earns its keep in three +places: FileFacts as the persistence unit means the cached and parsed +paths are literally one code path (`add_facts`), the no-mtime deviation +was measured and sound rather than asserted (the mtime "optimization" +would have been 6 ms and a save-path correctness hole), and the resume +is visible — cached: lines and the "(N from cache)" end message let the +owner watch a half-indexed workarea skip what it already did. + +The fix round closed my three rulings exactly. The tampering vector is +formally out of threat model — same-user disk, same posture as the +formatter's cache — and the pinned reforged-record test is what keeps +the per-record checksum from ever being mistaken for a MAC; what the +checksum actually buys, everything accidental, is now total (0 of 583 +truncation offsets cost more than the torn record; QA's +leading-zero-reencoding construction turned up a structural strength). +The race fix's 100/100 is structural, and QA's genuinely-concurrent +Empty-arm test ran clean 15x. QA's re-check found one cousin residue +(a torn header read misclassifying to Foreign) — added to the same +Assumptions paragraph as its sibling, accepted for the same reasons. +Filed and standing: word-table/include-graph caching (the remaining +warm cost), cross-server locking, compaction growth. QA's own +self-caught test-construction bug is exactly the epistemic hygiene +this workflow is for. Accepted as shipped. diff --git a/docs/features/indexing-ux/README.md b/docs/features/indexing-ux/README.md index fa022c2..248013c 100644 --- a/docs/features/indexing-ux/README.md +++ b/docs/features/indexing-ux/README.md @@ -166,6 +166,11 @@ pub fn build<'a>(files: …) -> WorkspaceIndex { - `pub enum IndexEvent<'a> { Parsing { done, total, path }, Skipped { path, size, cap } }`. Numbers and paths only: this module speaks no protocol, and the wording of every message stays in `server.rs`. + **Amended (index-persistence, 2026-08-27):** a third variant, `Cached { + done, total, path }` — the same three numbers, for a file the persistent + index cache answered for instead of a parse. A new variant rather than a + flag on `Parsing`, so that every consumer is asked by the compiler what it + wants to say about a file that was not parsed. - `ClientSettings::max_file_size` is read in `collect_sources`; nothing else in `state.rs` changed. @@ -195,6 +200,14 @@ pub fn build<'a>(files: …) -> WorkspaceIndex { callers, no duplicated send. - `end_indexing` takes the skip count and says `"N files indexed, M skipped"` when it is non-zero. + **Amended (index-persistence, 2026-08-27):** it takes the *cached* count as + well and names it first — `"860 files indexed, 858 from cache, 2 skipped"` — + because a scan that finished suspiciously fast should say why. Same rule as + the skip count: the number is in the end message whether or not the per-file + log is on. `IndexWatch` also grows an arm for `IndexEvent::Cached`, whose log + line reads `cached: ` where a parsed file's reads `indexing: `, + and whose bar tick is identical — a cached file is a file of the work list, + and the bar flying through them is the point. - `begin` still carries **no** percentage: the first honest one is the first file's. diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index 3a5b8b7..d45e977 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -236,6 +236,7 @@ reasoning and the measurements: `docs/features/cancel-request/README.md`. | a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute | | the `WorkspaceIndex` | `initialize`, every `didSave`, every `textDocument/didOpen` that **widens the scope**, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist`/`lucisv.index.maxFileSize`/`lucisv.index.scope`/`lucisv.index.scopeDepth` (pushed **or** pulled) | full re-scan of the scope — **except when the trigger names exactly one file the index already holds** (a `didSave`, a one-file watcher event), where only that file's contribution is replaced and the result is provably the index a full re-scan would have given (`docs/features/incremental-index/README.md`) | | the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save | +| the **index cache** on disk | appended to as a whole rescan parses each file, rewritten when that rescan ends, and written through by every incremental one-file update | one `write` per parsed file. It is read at the start of every whole rescan and answers for every file whose content it already holds, which is what makes a reopened workspace cost the reads and not the parses (`docs/features/index-persistence/README.md`) | **Per-file recompute on every keystroke** is the strategy TODO.md §6 states ("per-file recompute is fine at Verilog file sizes"); salsa is explicitly @@ -275,6 +276,25 @@ also fed to the index builder **first**, so a long rescan's progress bar completes them before anything else; the builder sorts by path internally, so that ordering cannot change the index it produces. +**What a scan learned survives the session, since 2026-08-27** +(index-persistence). Every file a scan parses is written to a store — its +`FileFacts`, the whole of its contribution to the index, under the FNV-1a hash +of the bytes it was read from — and the next scan takes back every record +whose file still holds exactly those bytes instead of parsing it again. So +reopening a workspace, or reopening one whose first scan was interrupted, is a +rescan that costs the reads and not the parses: **181 ms warm against the +328 ms it cost cold** over the 860-file corpus in a release build, with the bar +saying `860 files indexed, 860 from cache` and the output log saying `cached:` +where it says `indexing:`. The store lives in +`initializationOptions.storagePath` (VS Code's per-workspace storage folder), +or wherever `lucisv.index.cachePath` says, or in this platform's cache +directory; `lucisv.index.persist: false` turns it off in both directions and +restores the pre-2026-08-27 behaviour exactly. **It is a performance artifact +and never a correctness input**: every record is verified against the file's +current content before it is used, and a stale, corrupt or foreign record +costs one parse and can change no answer. Rules, the record format and the +crash-safety argument: `docs/features/index-persistence/README.md`. + **Walked files over `lucisv.index.maxFileSize` (1 MiB by default) are not read at all** — the size is taken from `fs::metadata` before the read, so a generated netlist costs one `stat` rather than minutes of parsing. The cap is @@ -294,7 +314,8 @@ which the override above keeps current. Rebuilding on every keystroke would re-parse the whole workspace per character; rebuilding on save is the cheapest point where the answer is expected to change anyway. Measured cost of a rebuild: 0.68 s for the 860-file corpus (the workspace index's own baseline), -plus the file reads. +plus the file reads — **and about half that when the persistent index cache +answers for the files that have not changed** (index-persistence, below). **Every *whole* rescan is visible since 2026-08-26**, for a client that advertised `window.workDoneProgress`: the startup build and every whole diff --git a/editors/vscode/extension.js b/editors/vscode/extension.js index 6ee2ec0..9180d75 100644 --- a/editors/vscode/extension.js +++ b/editors/vscode/extension.js @@ -157,6 +157,18 @@ function activate(context) { // `lucisv.indent` and `lucisv.exclude` from it and ignores the rest // (docs/features/editor-settings/README.md). synchronize: { configurationSection: 'lucisv' }, + // Where the server may keep its index cache, so that reopening a + // workspace does not re-parse every file it already parsed last time + // (docs/features/index-persistence/README.md). `storageUri` is VS Code's + // own per-workspace folder for exactly this kind of state — it is + // cleaned up when the workspace is forgotten, which is what makes it a + // better answer than a directory the server would have to invent. It is + // `undefined` when no workspace is open, and then the global one stands + // in; the server falls back to this platform's cache directory if + // neither reaches it, and to no cache at all if it cannot work one out. + initializationOptions: { + storagePath: (context.storageUri || context.globalStorageUri || {}).fsPath, + }, }; client = new LanguageClient('lucisv', 'lucisv', serverOptions, clientOptions); diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 028f73e..32a62d4 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -260,7 +260,17 @@ "lucisv.index.logFiles": { "type": "boolean", "default": true, - "markdownDescription": "Name every file in the lucisv output channel as it is indexed, and every file the size cap skipped. Useful for finding out why a symbol is missing or why a scan is slow; turn it off if you would rather the channel stayed quiet. Files skipped by `#lucisv.index.maxFileSize#` are counted in the progress bar's final message either way." + "markdownDescription": "Name every file in the lucisv output channel as it is indexed, and every file the size cap skipped. Useful for finding out why a symbol is missing or why a scan is slow; turn it off if you would rather the channel stayed quiet. Files skipped by `#lucisv.index.maxFileSize#` are counted in the progress bar's final message either way. A file restored from the index cache is logged as `cached:` rather than `indexing:`." + }, + "lucisv.index.persist": { + "type": "boolean", + "default": true, + "markdownDescription": "Remember what indexing a file found, so that reopening this workspace — or reopening it after a crash halfway through a scan — does not parse every unchanged file again. The store lives in this workspace's extension storage folder unless `#lucisv.index.cachePath#` says otherwise, and holds one entry per file **keyed by that file's exact contents**: an entry is used only for the bytes it was made from, so a stale or damaged one costs a re-parse and can never affect an answer. Turn it off to keep the index entirely in memory, as lucisv did before this setting existed; nothing is then read or written." + }, + "lucisv.index.cachePath": { + "type": "string", + "default": "", + "markdownDescription": "Where to keep the index cache `#lucisv.index.persist#` writes — absolute, or relative to the first workspace folder. Empty (the default) means the extension's own per-workspace storage folder, which VS Code cleans up when the workspace is forgotten. Set this to share one cache between checkouts of the same tree, or to keep it somewhere faster. The directory is created on demand and marks itself ignored with a `.gitignore`. Takes effect on the next workspace scan." } } }