Skip to main content

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