big_code_analysis/vcs/cache.rs
1//! Persistent change-history cache, keyed by `HEAD` SHA and repo identity
2//! (issue #334).
3//!
4//! Re-walking the in-window history on every `bca vcs` invocation is the
5//! dominant cost on large repositories, and CI re-runs differ only by the
6//! commits pushed since the last run. This module persists the **raw,
7//! pre-finalize event log** of a walk so a later run can *replay* it (the
8//! `replay` module) instead of re-walking, and *extend* it by walking only
9//! the new commits.
10//!
11//! # Why an event log rather than the finished [`HistoryIndex`](super::HistoryIndex)
12//!
13//! [`Stats`](super::stats::Stats) is the collapsed, *now-relative* output
14//! of [`Accumulator::finalize`](super::stats::Accumulator::finalize):
15//! the time windows are already applied and the per-commit detail is
16//! gone. It therefore cannot be merged with newer commits, nor
17//! re-windowed when wall-clock `now` advances. The cache instead stores
18//! one `CommitEvent` per in-window commit — the same data the walk
19//! folds — so replay reconstructs the index at the *current* `now`
20//! (correct windowing, no staleness) and incremental update is a plain
21//! splice of newer events onto cached ones.
22//!
23//! # Author privacy
24//!
25//! Authors are stored only as their **unkeyed** SHA-256
26//! [`hashed`](super::identity::AuthorId::hashed) digests, never plaintext:
27//! the cache must not write raw author emails to disk. Replay reconstructs
28//! identities with
29//! [`AuthorId::from_digest`](super::identity::AuthorId::from_digest),
30//! which preserves author counts, ownership, and the emitted hashes
31//! bit-for-bit (distinct emails yield distinct digests). The digest is a
32//! stable pseudonym, **not** anonymization — it is recoverable against a
33//! candidate email set; see [`hashed`](super::identity::AuthorId::hashed)
34//! for the threat model.
35//!
36//! The opt-in `--author-hash-key` hardening (issue #956) keys the *emitted*
37//! digest only, applied at finalization (like `--emit-author-details`), so
38//! it never changes what the cache stores: the cache holds the unkeyed
39//! inner digest and replaying it under any key reproduces a fresh walk's
40//! keyed output. The on-disk digest is therefore deliberately unkeyed; it
41//! is local-only and never published. See
42//! [`AuthorId::emit_hashed`](super::identity::AuthorId::emit_hashed).
43//!
44//! # Invalidation
45//!
46//! A cached entry is honoured only when its [`CACHE_SCHEMA_VERSION`],
47//! [`VCS_SCHEMA_VERSION`], [`RISK_SCORE_VERSION`], the `fingerprint` of
48//! the walk-affecting options, and the shallow state under which it was
49//! walked all match the current run; otherwise it is ignored and the
50//! history recomputed. Window changes alter the fingerprint, so they
51//! force a fresh walk, as the issue specifies. A shallow clone that is
52//! later deepened (`git fetch --unshallow`) leaves `HEAD` unmoved, so the
53//! entry key is unchanged; the shallow-state match in
54//! `HistoryCache::is_compatible` is what forces a re-walk to replace the
55//! truncated counts (issue #810). A corrupt or unreadable entry is
56//! silently ignored, never fatal.
57
58use std::collections::hash_map::DefaultHasher;
59use std::hash::{Hash, Hasher};
60use std::path::{Path, PathBuf};
61use std::sync::atomic::{AtomicU64, Ordering};
62
63use serde::{Deserialize, Serialize};
64
65use super::classify::Classification;
66use super::error::Error;
67use super::identity::AuthorId;
68use super::options::Options;
69use super::score::RISK_SCORE_VERSION;
70use super::stats::VCS_SCHEMA_VERSION;
71
72/// On-disk format version for the cache. Bump on any change to the
73/// `HistoryCache` / `CommitEvent` shape — and on any change to what a
74/// recorded event *means*, since an older entry is otherwise replayed
75/// under semantics it was not walked with.
76///
77/// Version 2 (#1265): [`BotFilter`](super::identity::BotFilter) became
78/// case-insensitive. The fingerprint hashes only the pattern *string*,
79/// so an event log walked under the case-sensitive matcher would
80/// otherwise replay with its excluded set intact — the same input
81/// answering differently depending on whether the cache was warm. The
82/// bump forces one benign cold walk.
83pub const CACHE_SCHEMA_VERSION: u32 = 2;
84
85/// Front-end control over the persistent cache for one build.
86///
87/// The default both enables caching and uses the platform default
88/// directory, so a front end opts *out* (rather than in) — matching the
89/// issue's `--no-cache` / `--clear-cache` flags.
90#[derive(Clone, Debug)]
91// Sealed like `Options`: external front ends construct via
92// `CacheConfig::default()` + field assignment so additive knobs stay
93// non-breaking (see STABILITY.md).
94#[non_exhaustive]
95pub struct CacheConfig {
96 /// Read from and write to the cache. `false` forces a fresh walk and
97 /// skips persistence (`--no-cache`).
98 pub enabled: bool,
99 /// Remove this repository's cache directory before building
100 /// (`--clear-cache`). Honoured even when `enabled` is `false`.
101 pub clear: bool,
102 /// Cache root directory. `None` selects the platform default (`default_cache_dir`)
103 /// (`--cache-dir` overrides it).
104 pub dir: Option<PathBuf>,
105}
106
107impl Default for CacheConfig {
108 fn default() -> Self {
109 Self {
110 enabled: true,
111 clear: false,
112 dir: None,
113 }
114 }
115}
116
117/// One commit's raw, pre-finalize contribution to the history, as the
118/// walk observed it. Stored newest-first so a replay folds commits in the
119/// same order a fresh walk would — keeping the floating-point entropy
120/// sums bit-identical.
121#[derive(Clone, Debug, Serialize, Deserialize)]
122pub(crate) struct CommitEvent {
123 /// Commit object id (hex), used to splice an incremental walk onto the
124 /// cached tail and to de-duplicate across the splice boundary.
125 pub oid: String,
126 /// Raw committer time in Unix seconds (unclamped). Replay clamps it to
127 /// the *current* `now` so a future-dated commit reads as "today" under
128 /// the new reference time, exactly as the live walk does.
129 pub time: i64,
130 /// Participating author identities as SHA-256 digests — never
131 /// plaintext (see the module docs).
132 pub authors: Vec<String>,
133 /// The commit message matched a bug-fix keyword.
134 #[serde(default, skip_serializing_if = "is_false")]
135 pub bug_fix: bool,
136 /// The commit message matched a security-fix keyword.
137 #[serde(default, skip_serializing_if = "is_false")]
138 pub security_fix: bool,
139 /// The commit is a revert / rollback.
140 #[serde(default, skip_serializing_if = "is_false")]
141 pub revert: bool,
142 /// Rename edges this commit introduced, as `(source, destination)`
143 /// repository-relative paths. Replayed newest-first to rebuild the
144 /// alias chain that attributes pre-rename edits to the current path —
145 /// the one signal that must survive across an incremental boundary
146 /// (a rename in a *new* commit re-homes edits in *cached* ones).
147 #[serde(default, skip_serializing_if = "Vec::is_empty")]
148 pub renames: Vec<(PathBuf, PathBuf)>,
149 /// Each touched text file's **location path at this commit** (before
150 /// alias resolution) and its added+deleted line churn.
151 pub touched: Vec<(PathBuf, u64)>,
152}
153
154/// Serde skip predicate: a `false` flag is omitted to keep the cache
155/// compact (most commits match no keyword class).
156#[allow(clippy::trivially_copy_pass_by_ref)]
157fn is_false(value: &bool) -> bool {
158 !*value
159}
160
161impl CommitEvent {
162 /// Reconstruct the participating identities from their stored digests.
163 #[must_use]
164 pub(crate) fn author_ids(&self) -> Vec<AuthorId> {
165 self.authors
166 .iter()
167 .map(|digest| AuthorId::from_digest(digest.clone()))
168 .collect()
169 }
170
171 /// The commit's keyword classification, rebuilt from the stored flags.
172 #[must_use]
173 pub(crate) fn classification(&self) -> Classification {
174 Classification {
175 bug_fix: self.bug_fix,
176 security_fix: self.security_fix,
177 revert: self.revert,
178 }
179 }
180}
181
182/// A persisted history walk: the event log plus the version stamps and
183/// fingerprint that decide whether it may be reused.
184#[derive(Clone, Debug, Serialize, Deserialize)]
185pub(crate) struct HistoryCache {
186 /// On-disk format version ([`CACHE_SCHEMA_VERSION`]).
187 pub cache_schema_version: u32,
188 /// Output-shape version the events were produced under.
189 pub vcs_schema_version: u32,
190 /// Composite-formula version the events were produced under.
191 pub risk_score_version: u32,
192 /// [`fingerprint`] of the walk-affecting options.
193 pub options_fingerprint: u64,
194 /// The `HEAD` (or `--ref`) object id the walk reached, hex-encoded.
195 pub head_sha: String,
196 /// The long-window cutoff (`now − long_window`) the events were walked
197 /// to. A later run whose own cutoff is *older* than this (wall-clock
198 /// time ran backwards) cannot reuse the entry — its window reaches
199 /// past the cached tail — and falls back to a fresh walk.
200 pub walk_long_boundary: i64,
201 /// Whether the walk was truncated by a shallow clone.
202 #[serde(default)]
203 pub truncated_shallow_clone: bool,
204 /// The per-commit event log, newest-first.
205 pub events: Vec<CommitEvent>,
206}
207
208impl HistoryCache {
209 /// Whether this entry may be reused by a run with the given option
210 /// fingerprint and current shallow state: the format, schema, score,
211 /// and option versions must all match the current build, and the
212 /// shallow state under which the entry was walked must match the
213 /// repository's current shallow state.
214 ///
215 /// The shallow guard prevents replaying a truncated event log after a
216 /// shallow clone is deepened (`git fetch --unshallow` leaves `HEAD`
217 /// unmoved, so the head SHA — and thus the entry key — is unchanged),
218 /// and prevents reporting a complete walk's counts under a now-shallow
219 /// clone as un-truncated (issue #810). A shallow-state mismatch forces
220 /// a fresh walk that produces the correct counts and truncation flag.
221 #[must_use]
222 pub(crate) fn is_compatible(&self, options_fingerprint: u64, current_shallow: bool) -> bool {
223 self.cache_schema_version == CACHE_SCHEMA_VERSION
224 && self.vcs_schema_version == VCS_SCHEMA_VERSION
225 && self.risk_score_version == RISK_SCORE_VERSION
226 && self.options_fingerprint == options_fingerprint
227 && self.truncated_shallow_clone == current_shallow
228 }
229}
230
231/// A stable 64-bit fingerprint of every option that changes *which
232/// commits the walk visits or how they are recorded* — the window
233/// lengths, traversal mode, merge/rename/bot toggles, the bot pattern,
234/// and the `--as-of` reference time.
235///
236/// Finalization-only knobs (`--risk-formula`, `--emit-author-details`,
237/// `--author-hash-key` (#956), `--include-deleted`, the bus-factor options)
238/// are deliberately excluded: they are applied at replay, so changing one
239/// reuses the same event log — including re-finalizing a cached walk under
240/// a different author-hash key without a re-walk.
241/// The file-type scope (`--file-types`, #576) is excluded for the same
242/// reason — the cached event log spans every touched file regardless of
243/// scope, and the scope is re-applied to the freshly-enumerated seed and
244/// at replay, so an entry stays reusable across scopes. The revision
245/// spelling is excluded too — the resolved [`head_sha`] keys the entry,
246/// so two refs naming the same commit share it.
247///
248/// [`head_sha`]: HistoryCache::head_sha
249///
250/// `DefaultHasher` is created with fixed keys, so the digest is stable
251/// across processes built with the same toolchain (its `SipHasher13`
252/// algorithm is not guaranteed stable across Rust releases — a bump
253/// shifts every fingerprint, which costs a benign cold walk, never a
254/// wrong hit). [`CACHE_SCHEMA_VERSION`] guards the *meaning* of the
255/// inputs, so the fingerprint need only be self-consistent within one
256/// format version.
257#[must_use]
258pub(crate) fn fingerprint(options: &Options) -> u64 {
259 let mut hasher = DefaultHasher::new();
260 options.long_window_secs.hash(&mut hasher);
261 options.recent_window_secs.hash(&mut hasher);
262 options.full_history.hash(&mut hasher);
263 options.include_merges.hash(&mut hasher);
264 options.follow_renames.hash(&mut hasher);
265 options.exclude_bots.hash(&mut hasher);
266 options.bot_pattern.hash(&mut hasher);
267 options.as_of.hash(&mut hasher);
268 hasher.finish()
269}
270
271/// The default cache root: `$XDG_CACHE_HOME/big-code-analysis/vcs`, or the
272/// platform equivalent (`%LOCALAPPDATA%` on Windows, `~/.cache` as the
273/// POSIX fallback). `None` when no home/cache location can be resolved, in
274/// which case caching is simply disabled rather than erroring.
275#[must_use]
276pub(crate) fn default_cache_dir() -> Option<PathBuf> {
277 let suffix = Path::new("big-code-analysis").join("vcs");
278 if let Some(xdg) = non_empty_env("XDG_CACHE_HOME") {
279 return Some(PathBuf::from(xdg).join(&suffix));
280 }
281 #[cfg(windows)]
282 if let Some(local) = non_empty_env("LOCALAPPDATA") {
283 return Some(PathBuf::from(local).join(&suffix));
284 }
285 let home = non_empty_env("HOME")?;
286 Some(PathBuf::from(home).join(".cache").join(&suffix))
287}
288
289/// Read an environment variable, treating an unset *or empty* value as
290/// absent (an empty `HOME` is as useless as a missing one).
291fn non_empty_env(key: &str) -> Option<std::ffi::OsString> {
292 std::env::var_os(key).filter(|value| !value.is_empty())
293}
294
295/// The per-repository sub-directory under `cache_root`, named by a hash of
296/// the repository's canonical path so distinct working trees never share a
297/// directory (and the same tree is stable across runs).
298#[must_use]
299pub(crate) fn repo_dir(cache_root: &Path, repo_canonical: &Path) -> PathBuf {
300 let mut hasher = DefaultHasher::new();
301 repo_canonical.hash(&mut hasher);
302 cache_root.join(format!("{:016x}", hasher.finish()))
303}
304
305/// The cache file for one `HEAD` SHA within a repository directory.
306#[must_use]
307pub(crate) fn entry_path(repo_dir: &Path, head_sha: &str) -> PathBuf {
308 repo_dir.join(format!("{head_sha}.json"))
309}
310
311/// Load a single cache entry, returning `None` for a missing, unreadable,
312/// or corrupt file (all non-fatal — the history is simply recomputed).
313#[must_use]
314pub(crate) fn load(path: &Path) -> Option<HistoryCache> {
315 let bytes = std::fs::read(path).ok()?;
316 serde_json::from_slice(&bytes).ok()
317}
318
319/// Load every entry in `repo_dir` whose versions, option fingerprint, and
320/// shallow state match the current run, paired with its file path. Used to
321/// find a prior entry whose `HEAD` is an ancestor of the current one for an
322/// incremental walk. A non-existent directory yields an empty list.
323#[must_use]
324pub(crate) fn load_compatible(
325 repo_dir: &Path,
326 options_fingerprint: u64,
327 current_shallow: bool,
328) -> Vec<(PathBuf, HistoryCache)> {
329 let Ok(entries) = std::fs::read_dir(repo_dir) else {
330 return Vec::new();
331 };
332 let mut out = Vec::new();
333 for entry in entries.flatten() {
334 let path = entry.path();
335 if path.extension().is_some_and(|ext| ext == "json")
336 && let Some(cache) = load(&path)
337 && cache.is_compatible(options_fingerprint, current_shallow)
338 {
339 out.push((path, cache));
340 }
341 }
342 out
343}
344
345/// Monotonic counter making concurrent temp-file names unique within a
346/// process; combined with the PID it avoids two writers colliding on the
347/// same temporary path before the atomic rename.
348static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
349
350/// Persist a cache entry atomically: write to a uniquely-named temporary
351/// file in the destination directory, then rename it over the target so a
352/// concurrent reader never observes a half-written file.
353///
354/// # Errors
355///
356/// Returns [`Error::Cache`] if the directory cannot be created or the
357/// file cannot be written or renamed.
358pub(crate) fn write_atomic(path: &Path, cache: &HistoryCache) -> Result<(), Error> {
359 let dir = path
360 .parent()
361 .ok_or_else(|| Error::Cache(format!("cache path {} has no parent", path.display())))?;
362 std::fs::create_dir_all(dir).map_err(|e| cache_io_err("create cache directory", dir, &e))?;
363
364 let unique = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
365 let tmp = dir.join(format!(".{}.{unique}.tmp", std::process::id()));
366 let json =
367 serde_json::to_vec(cache).map_err(|e| Error::Cache(format!("serializing cache: {e}")))?;
368 std::fs::write(&tmp, &json).map_err(|e| cache_io_err("write cache temp file", &tmp, &e))?;
369 std::fs::rename(&tmp, path).map_err(|e| {
370 // Best-effort cleanup of the orphaned temp file on a failed rename.
371 let _ = std::fs::remove_file(&tmp);
372 cache_io_err("rename cache file", path, &e)
373 })
374}
375
376/// Remove a repository's entire cache directory (`--clear-cache`). A
377/// missing directory is success, not an error.
378///
379/// # Errors
380///
381/// Returns [`Error::Cache`] if the directory exists but cannot be removed.
382pub(crate) fn clear_repo(repo_dir: &Path) -> Result<(), Error> {
383 match std::fs::remove_dir_all(repo_dir) {
384 Ok(()) => Ok(()),
385 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
386 Err(e) => Err(cache_io_err("clear cache directory", repo_dir, &e)),
387 }
388}
389
390/// Build an [`Error::Cache`] naming the failed operation and path.
391fn cache_io_err(action: &str, path: &Path, error: &std::io::Error) -> Error {
392 Error::Cache(format!("{action} {}: {error}", path.display()))
393}
394
395#[cfg(test)]
396#[path = "cache_tests.rs"]
397mod tests;