Files
lucisv/crates/vfmt_core/src/cache.rs
T
lucioandClaude Fable 5 003e0766e9 Add alignment inference and the format cache (round 17)
alignment: Verible-style alignment-intent inference for ANSI ports
(name column), named connections (paren column) and parameter items
(name and = columns). A group aligns iff the author asked: >=4
excess spaces somewhere, or the group already sits consistently at
one column -- single-space code keeps today's bytes exactly (zero
churn across all 397 pre-existing cases; corpus outcome TSV
byte-identical while 291/578 formattable files change content).
Fixed-point by construction: aligned output re-infers the same
targets, flush re-infers flush; the whole verdict is decided at
document-build time (a printer-side split diverged ibex_core.sv at
width 60 during development -- caught by a 2312-run config sweep and
redesigned). Groups break at comments/attributes/directives/blank
lines; a group that cannot fit falls back to flush whole, never
mixed. No lexer changes: name_span plus the source answers every
spacing question. QA's sabotage confirmed the runtime convergence
check catches the predicted flip-flop even with the unit test gone.

format-cache: warm runs skip verified-clean files. Key = (FNV-1a 64
content hash, resolved config values, vfmt version), path-keyed;
only the fixed-point verdict is ever cached, so --check/--diff can
never go stale and a hit can only skip work, never produce output.
One atomic text file in self-gitignoring .vfmt_cache/; --no-cache /
--cache-dir; 8-process concurrency clean. Warm corpus check: 2x at
default threads, 7.7x single-threaded.

655 workspace tests. Dev: 2 Opus agents (both isolated their gates
from the other's churn via HEAD-reverted scratchpad copies); QA: 2
Sonnet agents; reviews in docs/features/{alignment,format-cache}/
README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-19 14:42:07 -07:00

415 lines
15 KiB
Rust

//! The "already formatted" cache: a per-path record of content that a
//! previous run verified is a fixed point, so a repeat run can skip the
//! file entirely.
//!
//! Only the *clean* verdict is ever stored — never an error and never
//! "would reformat" — so a stale, missing or wrong entry can only ever
//! cause work to be redone, never a diagnostic to be lost. See
//! `docs/features/format-cache/README.md` for the key, the storage
//! format and the collision posture.
use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
/// The default cache directory, resolved against the current directory.
pub const DEFAULT_DIR: &str = ".vfmt_cache";
/// The entry file inside the cache directory.
const FILE: &str = "cache";
/// vfmt's version, part of every entry: a new release may format the same
/// bytes differently, so another version's entries are ignored.
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// What one entry asserts about one path: this content, under these
/// settings, is already formatted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Entry {
/// FNV-1a hash of the file's bytes as they are on disk.
pub content: u64,
/// The `line-length` that verdict was reached under.
pub line_length: usize,
/// The `indent` that verdict was reached under.
pub indent: usize,
}
/// The cache for one run: loaded once at startup, written once at exit.
pub struct Cache {
/// Where to write at the end of the run; `None` when the cache is off.
path: Option<PathBuf>,
entries: HashMap<String, Entry>,
}
impl Cache {
/// Loads the cache stored in `dir`. Never fails: a missing, unreadable
/// or corrupt file simply yields an empty cache that the run rebuilds.
pub fn load(dir: &Path) -> Cache {
let path = dir.join(FILE);
let entries =
std::fs::read_to_string(&path).ok().and_then(|text| parse(&text)).unwrap_or_default();
Cache { path: Some(path), entries }
}
/// A cache that reads nothing and writes nothing (`--no-cache`).
pub fn disabled() -> Cache {
Cache { path: None, entries: HashMap::new() }
}
/// True when `path`'s current content was already verified formatted
/// under these settings by this version of vfmt.
pub fn is_clean(&self, path: &Path, entry: Entry) -> bool {
key(path).and_then(|k| self.entries.get(k)) == Some(&entry)
}
/// Records that `path` holds content that is a fixed point. A no-op
/// when the cache is off, or when the path cannot be stored.
pub fn record(&mut self, path: &Path, entry: Entry) {
if self.path.is_none() {
return;
}
if let Some(k) = key(path) {
self.entries.insert(k.to_string(), entry);
}
}
/// Writes the cache back, atomically. Failure is deliberately silent:
/// the cache is an optimization, and a run must not change its output
/// or its exit code because a directory happened to be read-only.
pub fn store(&self) {
let Some(path) = &self.path else { return };
let Some(dir) = path.parent() else { return };
if std::fs::create_dir_all(dir).is_err() {
return;
}
// Self-ignoring, the way cargo marks `target/`.
let ignore = dir.join(".gitignore");
if !ignore.exists() {
let _ = std::fs::write(&ignore, "*\n");
}
let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id()));
if std::fs::write(&tmp, self.render()).is_ok() && std::fs::rename(&tmp, path).is_err() {
let _ = std::fs::remove_file(&tmp);
}
}
/// The file's text: one line per entry, sorted by path so that two
/// runs over the same tree write byte-identical caches. Entries whose
/// file is gone are dropped, so the file cannot grow forever.
fn render(&self) -> String {
let mut paths: Vec<&String> = self.entries.keys().collect();
paths.sort();
let mut text = String::new();
for path in paths {
if !Path::new(path).exists() {
continue;
}
let entry = &self.entries[path];
let _ = writeln!(
text,
"{:016x}\t{}\t{}\t{VERSION}\t{path}",
entry.content, entry.line_length, entry.indent
);
}
text
}
}
/// FNV-1a, 64-bit. Hand-rolled because the hash is written to disk and
/// std's `DefaultHasher` is explicitly not stable across Rust releases;
/// FNV-1a is byte-exactly specified and needs no dependency.
pub fn content_hash(bytes: &[u8]) -> u64 {
const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const PRIME: u64 = 0x0000_0100_0000_01b3;
let mut hash = OFFSET;
for byte in bytes {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(PRIME);
}
hash
}
/// A path's key in the store, or `None` for one that cannot be written on
/// a line of text (not UTF-8, or containing a tab or newline). Such a file
/// is simply never cached.
fn key(path: &Path) -> Option<&str> {
let text = path.to_str()?;
if text.is_empty() || text.contains('\t') || text.contains('\n') {
return None;
}
Some(text)
}
/// Parses the store. `None` means "this file is not something vfmt wrote"
/// — one malformed line discards the whole cache, because partial trust in
/// a file already caught lying is not worth the branch. Entries from
/// another vfmt version are dropped individually; that is staleness, not
/// corruption.
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
let mut entries = HashMap::new();
for line in text.lines() {
let mut fields = line.splitn(5, '\t');
let content = u64::from_str_radix(fields.next()?, 16).ok()?;
let line_length = fields.next()?.parse().ok()?;
let indent = fields.next()?.parse().ok()?;
let version = fields.next()?;
let path = fields.next()?;
if path.is_empty() {
return None;
}
if version == VERSION {
entries.insert(path.to_string(), Entry { content, line_length, indent });
}
}
Some(entries)
}
#[cfg(test)]
mod tests {
use super::*;
/// A throwaway directory, removed on drop.
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!("vfmt-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 }
}
/// Creates a file so that `render`'s existence check keeps it.
fn file(&self, name: &str) -> PathBuf {
let path = self.path.join(name);
std::fs::write(&path, "x").expect("write file");
path
}
fn cache_text(&self) -> String {
std::fs::read_to_string(self.path.join(FILE)).expect("read cache")
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
fn entry(content: u64) -> Entry {
Entry { content, line_length: 100, indent: 2 }
}
#[test]
fn fnv_1a_matches_the_published_vectors() {
// The reference values for FNV-1a 64. If this ever changes, every
// cache on every machine silently invalidates — hence the test.
assert_eq!(content_hash(b""), 0xcbf2_9ce4_8422_2325);
assert_eq!(content_hash(b"a"), 0xaf63_dc4c_8601_ec8c);
assert_eq!(content_hash(b"foobar"), 0x8594_4171_f739_67e8);
}
#[test]
fn a_missing_cache_is_empty_not_an_error() {
let dir = TempDir::new("missing");
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(Path::new("a.sv"), entry(1)));
}
#[test]
fn entries_round_trip_through_the_file() {
let dir = TempDir::new("roundtrip");
let file = dir.file("a.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&file, entry(0xdead));
cache.store();
let reloaded = Cache::load(&dir.path);
assert!(reloaded.is_clean(&file, entry(0xdead)));
// Every field is part of the key.
assert!(!reloaded.is_clean(&file, entry(0xbeef)));
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
}
#[test]
fn the_file_is_sorted_and_carries_the_version() {
let dir = TempDir::new("format");
let b = dir.file("b.sv");
let a = dir.file("a.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&b, entry(2));
cache.record(&a, entry(1));
cache.store();
let text = dir.cache_text();
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 2, "{text}");
assert!(lines[0].ends_with("a.sv"), "sorted by path: {text}");
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
assert_eq!(
lines[0],
format!("{:016x}\t100\t2\t{VERSION}\t{}", 1, a.to_string_lossy()),
"{text}"
);
}
#[test]
fn the_cache_directory_ignores_itself() {
let dir = TempDir::new("selfignore");
let file = dir.file("a.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&file, entry(1));
cache.store();
assert_eq!(std::fs::read_to_string(dir.path.join(".gitignore")).unwrap(), "*\n");
}
#[test]
fn a_corrupt_file_is_ignored_wholesale() {
for corrupt in [
"garbage\n",
"not-hex\t100\t2\t0.2.0\t/a.sv\n",
"0000000000000001\twide\t2\t0.2.0\t/a.sv\n",
"0000000000000001\t100\t2\t0.2.0\n",
"0000000000000001\t100\t2\t0.2.0\t\n",
"\0\0\0\n",
] {
let dir = TempDir::new("corrupt");
let file = dir.file("a.sv");
// A good line first: a bad one anywhere discards all of them.
let good = format!("{:016x}\t100\t2\t{VERSION}\t{}\n", 1, file.to_string_lossy());
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
}
}
#[test]
fn another_versions_entry_is_dropped_but_not_fatal() {
let dir = TempDir::new("version");
let old = dir.file("old.sv");
let mine = dir.file("mine.sv");
let text = format!(
"{:016x}\t100\t2\t0.0.0-not-this-one\t{}\n{:016x}\t100\t2\t{VERSION}\t{}\n",
1,
old.to_string_lossy(),
2,
mine.to_string_lossy()
);
std::fs::write(dir.path.join(FILE), text).unwrap();
let cache = Cache::load(&dir.path);
assert!(!cache.is_clean(&old, entry(1)), "another version's entry must not be trusted");
assert!(cache.is_clean(&mine, entry(2)), "this version's entry survives alongside it");
// And it is not carried forward.
cache.store();
assert!(!dir.cache_text().contains("old.sv"));
}
#[test]
fn entries_for_deleted_files_are_pruned_on_write() {
let dir = TempDir::new("prune");
let kept = dir.file("kept.sv");
let gone = dir.file("gone.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&kept, entry(1));
cache.record(&gone, entry(2));
std::fs::remove_file(&gone).unwrap();
cache.store();
let text = dir.cache_text();
assert!(text.contains("kept.sv"), "{text}");
assert!(!text.contains("gone.sv"), "{text}");
}
#[test]
fn unvisited_entries_survive_a_later_run() {
let dir = TempDir::new("survive");
let first = dir.file("a.sv");
let second = dir.file("b.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&first, entry(1));
cache.store();
// A second run that only visits b.sv must not forget a.sv.
let mut cache = Cache::load(&dir.path);
cache.record(&second, entry(2));
cache.store();
let reloaded = Cache::load(&dir.path);
assert!(reloaded.is_clean(&first, entry(1)));
assert!(reloaded.is_clean(&second, entry(2)));
}
#[test]
fn a_disabled_cache_reads_and_writes_nothing() {
let dir = TempDir::new("disabled");
let file = dir.file("a.sv");
let mut warm = Cache::load(&dir.path);
warm.record(&file, entry(1));
warm.store();
let before = dir.cache_text();
let mut cache = Cache::disabled();
assert!(!cache.is_clean(&file, entry(1)), "--no-cache must not read");
cache.record(&file, entry(9));
cache.store();
assert_eq!(dir.cache_text(), before, "--no-cache must not write");
}
#[test]
fn nothing_is_created_when_the_cache_is_off() {
let dir = TempDir::new("nothing");
let cache = Cache::disabled();
cache.store();
assert!(!dir.path.join(FILE).exists());
assert!(!dir.path.join(".gitignore").exists());
}
#[test]
fn the_cache_directory_is_created_on_demand() {
let dir = TempDir::new("mkdir");
let file = dir.file("a.sv");
let nested = dir.path.join("deep/inner");
let mut cache = Cache::load(&nested);
cache.record(&file, entry(1));
cache.store();
assert!(Cache::load(&nested).is_clean(&file, entry(1)));
}
#[test]
fn no_temporary_file_is_left_behind() {
let dir = TempDir::new("tmp");
let file = dir.file("a.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&file, entry(1));
cache.store();
let leftovers: Vec<_> = std::fs::read_dir(&dir.path)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".tmp"))
.collect();
assert!(leftovers.is_empty(), "{leftovers:?}");
}
#[test]
fn a_path_that_cannot_be_stored_is_simply_not_cached() {
let dir = TempDir::new("weirdpath");
let weird = dir.path.join("a\tb.sv");
let mut cache = Cache::load(&dir.path);
cache.record(&weird, entry(1));
cache.store();
assert!(!Cache::load(&dir.path).is_clean(&weird, entry(1)));
}
}