Skip to main content

rto_graph/
sync.rs

1//! The incremental, content-addressed sync engine.
2//!
3//! `sync` brings a [`Store`] into agreement with the repository's `HEAD` tree.
4//! Extraction is the expensive part and is content-addressed by blob id, so only
5//! blobs whose content changed are re-extracted; the rest load from the
6//! [`ObjectCache`]. If the tree id is unchanged since the last sync, it is a
7//! no-op. The graph itself is reassembled from the (cached) per-blob fact sets
8//! and rebuilt in a single transaction — a deliberately simple DB-write model
9//! for this stage; incremental DB updates can come later.
10
11use std::cell::Cell;
12use std::collections::{BTreeMap, BTreeSet, HashSet};
13
14use crate::cache::{CacheError, ObjectCache, ObjectSweep};
15use crate::extract::Extractor;
16use crate::git::{GitError, Repo};
17use crate::store::StoreError;
18use crate::{Edge, EdgeKind, FactSet, Node, NodeKind, Provenance, Store};
19
20/// Errors raised while syncing.
21#[derive(Debug, thiserror::Error)]
22pub enum SyncError {
23    /// A store operation failed.
24    #[error(transparent)]
25    Store(#[from] StoreError),
26    /// A cache operation failed.
27    #[error(transparent)]
28    Cache(#[from] CacheError),
29    /// A git operation failed.
30    #[error(transparent)]
31    Git(#[from] GitError),
32    /// Reading a working-tree file failed (dirty overlay).
33    #[error("worktree io error: {0}")]
34    Io(#[from] std::io::Error),
35}
36
37/// A summary of the work a [`sync`] performed.
38#[derive(Debug, Clone, Default, serde::Serialize)]
39pub struct SyncReport {
40    /// Hex id of the synced `HEAD` tree.
41    pub tree: String,
42    /// Whether the tree was unchanged and nothing was done.
43    pub no_op: bool,
44    /// Source files reflected in the graph — one `File` node per extracted blob.
45    /// Derived from the assembled graph (not the raw tree walk) so full and
46    /// incremental syncs report the same total for the same tree.
47    pub blobs_total: usize,
48    /// Blobs that were extracted (cache misses).
49    pub blobs_extracted: usize,
50    /// Blobs served from the cache (cache hits).
51    pub blobs_cached: usize,
52    /// Working-tree files whose uncommitted content overrode the committed blob
53    /// (the dirty overlay); always zero for a committed-only [`sync`].
54    pub blobs_dirty: usize,
55    /// Nodes in the store after syncing.
56    pub nodes: u64,
57    /// Edges in the store after syncing.
58    pub edges: u64,
59    /// The working tree this graph previously described, when it was a
60    /// **different** one and the sync therefore rebuilt from scratch rather than
61    /// trusting the recorded state (issue #330).
62    ///
63    /// `None` on every ordinary sync. `Some(path)` is the loud half of the
64    /// guarantee: the answer was corrected rather than served, and the caller can
65    /// say *which* tree the store had been holding, so a stale store is never a
66    /// silent wrong answer nor an unexplained slow one.
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub rebuilt_from_foreign_worktree: Option<String>,
69}
70
71/// A stable identity for the working tree a graph is assembled from: the
72/// working-tree root, or the git dir for a bare repository.
73///
74/// The *path* is used rather than an opaque id because its whole job is to appear
75/// in a message naming the tree the store actually holds — an id the reader
76/// cannot act on would defeat the point. Linked worktrees have distinct roots, so
77/// this separates them; a plain branch switch within one tree does not change it,
78/// which is correct (the tree is the same, its content moved).
79#[must_use]
80pub fn worktree_id(repo: &Repo) -> String {
81    repo.workdir()
82        .unwrap_or_else(|| repo.git_dir())
83        .to_string_lossy()
84        .into_owned()
85}
86
87/// Decide whether `store`'s recorded sync state may be trusted for *this* tree.
88///
89/// Returns `Some(previous)` when the store was last assembled from a **different**
90/// working tree: its tree id, dirty-set hash and extraction env all describe
91/// someone else's tree, so no fast path may consult them and the caller must
92/// rebuild in full. `None` when the store belongs here or has never been stamped
93/// (unknown is adopted, not rebuilt — see [`Store::synced_worktree`]).
94///
95/// Rebuilding is cheap relative to being wrong: the object cache is shared across
96/// worktrees and already warm, so the re-extraction mostly hits it.
97fn foreign_worktree(store: &Store, repo: &Repo) -> Result<Option<String>, SyncError> {
98    let here = worktree_id(repo);
99    Ok(store.synced_worktree()?.filter(|prior| *prior != here))
100}
101
102/// Sync `store` to the repository's `HEAD` tree, extracting changed blobs with
103/// `extractor` and caching results in `cache`.
104///
105/// # Errors
106/// Returns a [`SyncError`] if git access, extraction caching, or the store
107/// rebuild fails.
108pub fn sync(
109    store: &mut Store,
110    repo: &Repo,
111    cache: &ObjectCache,
112    extractor: &dyn Extractor,
113) -> Result<SyncReport, SyncError> {
114    let tree = repo.head_tree_id()?;
115
116    // The extraction *identity*: the extractor code version (`EXTRACT_VERSION`,
117    // bumped when extraction output changes) plus its environment (installed image
118    // models + ingestion toggles). Both change what an unchanged file extracts to,
119    // and both are folded into the content-cache key — so this mirrors that key.
120    // Recorded with the tree so the next sync can tell whether reusing the stored
121    // facts (the incremental path) is sound; a binary upgrade that bumps the
122    // version, or a model change, invalidates it and forces a full re-extraction.
123    let env = format!(
124        "v{}-e{:016x}",
125        crate::extract::EXTRACT_VERSION,
126        extractor.env_tag()
127    );
128
129    // Nothing to do only when **both** the tree and the extraction identity are
130    // unchanged.
131    //
132    // The identity half is load-bearing, and its absence was a real hole: an
133    // `EXTRACT_VERSION` bump is supposed to guarantee that no user is served the
134    // previous version's facts, but a store already synced at the current `HEAD`
135    // returned `no_op` here before the identity was ever computed — so the new
136    // binary's facts appeared only once `HEAD` next moved. Enabling a feature that
137    // changes extraction output (`audio-metadata`, `pdf-text`, `image-ocr`) on a
138    // quiet repository therefore looked like it had done nothing at all. Every
139    // *other* consumer of the identity — the content-cache key, the incremental
140    // path below — already agreed on it; this one had simply never been asked.
141    //
142    // A store with no recorded identity (`None`) does not match, which is the safe
143    // direction: it re-extracts once and records one.
144    // …and only when the recorded state describes *this* working tree. A store
145    // assembled from another tree has a tree id, dirty hash and env that are all
146    // someone else's, so neither the no-op below nor the incremental diff may
147    // consult them: that is how a stale store reports "up to date" while holding
148    // a graph nobody is looking at (issue #330).
149    let foreign = foreign_worktree(store, repo)?;
150
151    if foreign.is_none()
152        && store.sync_state()?.as_deref() == Some(tree.as_str())
153        && store.sync_env()?.as_deref() == Some(env.as_str())
154    {
155        return Ok(SyncReport {
156            no_op: true,
157            nodes: store.node_count()?,
158            edges: store.edge_count()?,
159            tree,
160            ..SyncReport::default()
161        });
162    }
163
164    // Fast path: if the last sync was a committed one at a known tree with the
165    // same extraction identity, update only the paths that changed. Falls back to
166    // a full re-extraction on any doubt (no prior tree, identity changed, an
167    // unavailable diff, or a tree that is not ours).
168    if foreign.is_none()
169        && let Some(report) = try_incremental(store, repo, cache, extractor, &tree, &env)?
170    {
171        return Ok(report);
172    }
173
174    let committed = extract_committed(repo, cache, extractor)?;
175    let mut assembled = flatten(committed.by_path);
176    resolve_calls(&mut assembled);
177    append_submodule_nodes(repo.submodules()?, &mut assembled);
178    let total = file_count(&assembled);
179    store.reconcile(&assembled, Some(&tree))?;
180    store.set_sync_env(&env)?;
181    store.set_synced_worktree(&worktree_id(repo))?;
182
183    Ok(SyncReport {
184        no_op: false,
185        blobs_total: total,
186        blobs_extracted: committed.extracted,
187        blobs_cached: committed.cached,
188        blobs_dirty: 0,
189        nodes: store.node_count()?,
190        edges: store.edge_count()?,
191        tree,
192        rebuilt_from_foreign_worktree: foreign,
193    })
194}
195
196/// Attempt an incremental committed sync from the last-synced tree to `head_tree`.
197/// Returns `Ok(Some(report))` when it ran, `Ok(None)` when the fast path is not
198/// eligible (the caller then does a full sync).
199///
200/// It is sound because it produces the exact same **derived-only** graph a full
201/// sync would: it reconstructs the derived subgraph from the store (identified by
202/// the `Derived` provenance tag — unchanged paths' facts are a deterministic
203/// function of their unchanged blob content, so they equal a fresh extraction),
204/// drops the changed/deleted paths, extracts only the changed blobs, re-resolves
205/// cross-file `calls` globally, and feeds the result to the same [`Store::reconcile`]
206/// the full path uses. `check`/`reapply_imports` re-layer the authored/import
207/// facts afterward exactly as before — this only accelerates the derived layer.
208fn try_incremental(
209    store: &mut Store,
210    repo: &Repo,
211    cache: &ObjectCache,
212    extractor: &dyn Extractor,
213    head_tree: &str,
214    env: &str,
215) -> Result<Option<SyncReport>, SyncError> {
216    // Eligibility: a prior committed tree (a plain oid — worktree/index states
217    // carry a `:`-delimited marker), extracted under the same environment.
218    let Some(prior_tree) = store.sync_state()? else {
219        return Ok(None);
220    };
221    if prior_tree.contains(':') || store.sync_env()?.as_deref() != Some(env) {
222        return Ok(None);
223    }
224    // The prior tree object may have been pruned (gc); on any diff failure, fall
225    // back to the full path rather than guessing.
226    let Ok(diff) = repo.diff_trees(&prior_tree, head_tree) else {
227        return Ok(None);
228    };
229
230    // Reconstruct the derived subgraph from the store: every derived node, and
231    // every derived edge except `calls` (globally re-derived below from the full
232    // function set, since a changed file can flip name-resolution elsewhere).
233    let mut nodes: Vec<Node> = store.nodes_by_provenance(Provenance::Derived)?;
234    let mut edges: Vec<Edge> = store
235        .edges_by_provenance(Provenance::Derived)?
236        .into_iter()
237        .filter(|e| e.kind != EdgeKind::Calls)
238        .collect();
239
240    // Drop the changed and deleted paths' derived facts (their nodes, and any edge
241    // incident to them — per-blob derived edges are intra-file, so this is exact).
242    let touched: BTreeSet<&str> = diff
243        .changed
244        .iter()
245        .map(|b| b.path.as_str())
246        .chain(diff.deleted.iter().map(String::as_str))
247        .collect();
248    let dropped: HashSet<String> = nodes
249        .iter()
250        .filter(|n| n.path.as_deref().is_some_and(|p| touched.contains(p)))
251        .map(|n| n.key.clone())
252        .collect();
253    nodes.retain(|n| !dropped.contains(&n.key));
254    edges.retain(|e| !dropped.contains(&e.src) && !dropped.contains(&e.dst));
255
256    // Extract the changed blobs (cache-aware) and add their derived facts.
257    let env_tag = extractor.env_tag();
258    let mut extracted = 0usize;
259    let mut cached = 0usize;
260    for blob in &diff.changed {
261        let key = cache_key(&blob.path, &blob.oid, env_tag);
262        let facts = if let Some(facts) = cache.get(&key)? {
263            cached += 1;
264            facts
265        } else {
266            let bytes = repo.read_blob(&blob.oid)?;
267            let facts = extractor.extract(&blob.path, &blob.oid, &bytes);
268            cache.put(&key, &facts)?;
269            extracted += 1;
270            facts
271        };
272        nodes.extend(facts.nodes);
273        edges.extend(facts.edges);
274    }
275
276    // Prune orphaned import-target nodes — a path-less derived node (e.g.
277    // `import:rust:foo`) that no surviving edge references. A full sync emits it
278    // only while some file imports it, so dropping the now-unreferenced ones keeps
279    // the two paths identical.
280    let referenced: HashSet<&str> = edges
281        .iter()
282        .flat_map(|e| [e.src.as_str(), e.dst.as_str()])
283        .collect();
284    nodes.retain(|n| n.path.is_some() || referenced.contains(n.key.as_str()));
285
286    // Global call resolution over the full (reconstructed + changed) function set,
287    // then reconcile to derived-only — identical to what the full path produces.
288    let mut assembled = FactSet { nodes, edges };
289    resolve_calls(&mut assembled);
290    append_submodule_nodes(repo.submodules()?, &mut assembled);
291    let total = file_count(&assembled);
292    store.reconcile(&assembled, Some(head_tree))?;
293    store.set_sync_env(env)?;
294    // The caller only reaches here for a store that is ours, but it may predate
295    // the stamp — record it, or this path would leave it unstamped forever.
296    store.set_synced_worktree(&worktree_id(repo))?;
297
298    Ok(Some(SyncReport {
299        no_op: false,
300        blobs_total: total,
301        blobs_extracted: extracted,
302        blobs_cached: cached,
303        blobs_dirty: 0,
304        nodes: store.node_count()?,
305        edges: store.edge_count()?,
306        tree: head_tree.to_owned(),
307        // Unreachable with a foreign store: the caller skips this path entirely.
308        rebuilt_from_foreign_worktree: None,
309    }))
310}
311
312/// Sync `store` to the working tree: the committed `HEAD` state with uncommitted
313/// working-tree changes overlaid on top (a pre-commit preview).
314///
315/// Committed blobs come from the content-addressed cache as in [`sync`]; then
316/// each tracked file whose working copy differs from its committed blob is
317/// re-extracted in memory (never cached, since dirty content is not a git
318/// object), deleted files are dropped, and brand-new **untracked** files (found
319/// via a gitignore-aware dirwalk, [`Repo::untracked_files`]) are overlaid in.
320/// The recorded sync state encodes the dirty set, so a later committed [`sync`]
321/// correctly supersedes the overlay.
322///
323/// # Errors
324/// Returns a [`SyncError`] if git access, extraction caching, working-tree I/O,
325/// or the store rebuild fails.
326pub fn sync_worktree(
327    store: &mut Store,
328    repo: &Repo,
329    cache: &ObjectCache,
330    extractor: &dyn Extractor,
331) -> Result<SyncReport, SyncError> {
332    let tree = repo.head_tree_id()?;
333    let committed = extract_committed(repo, cache, extractor)?;
334    let mut by_path = committed.by_path;
335
336    // Overlay uncommitted edits to tracked files. A file is dirty when its
337    // working-copy content hashes to a different git blob id than the committed
338    // one; identical content hashes identically, so clean files are skipped.
339    let mut dirty: BTreeSet<(String, String)> = BTreeSet::new();
340    if let Some(workdir) = repo.workdir() {
341        for blob in &committed.blobs {
342            match std::fs::read(workdir.join(&blob.path)) {
343                Ok(bytes) => {
344                    let woid = repo.blob_oid(&bytes)?;
345                    if woid != blob.oid {
346                        by_path.insert(
347                            blob.path.clone(),
348                            extractor.extract(&blob.path, &woid, &bytes),
349                        );
350                        dirty.insert((blob.path.clone(), woid));
351                    }
352                }
353                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
354                    by_path.remove(&blob.path);
355                    dirty.insert((blob.path.clone(), "\0deleted".to_owned()));
356                }
357                Err(e) => return Err(e.into()),
358            }
359        }
360
361        // Overlay brand-new files — anything on disk that `HEAD` does not have.
362        //
363        // Two sources, and it needs both (#636). `untracked_files` classifies the
364        // working tree **against the index**, so it stops reporting a file the
365        // moment it is `git add`-ed; the committed blob list above comes from the
366        // `HEAD` tree, where a new file does not exist either. A **staged
367        // addition** is therefore in neither, and used to fall straight through
368        // this overlay — so `git add`, an action that moves a file *closer* to
369        // committed, deleted its node from the graph and dropped the
370        // `+N uncommitted` marker at the exact moment the tree differed most from
371        // `HEAD`. Adding the index entries that `HEAD` lacks closes the gap.
372        //
373        // Content still comes from **disk**, not from the staged blob: this is the
374        // worktree source, and a file edited after being staged must be read as it
375        // now stands.
376        //
377        // They count as dirty (so the preview re-runs when they change) and add to
378        // the blob total (they are genuinely new blobs, not edits of existing ones).
379        let head_paths: BTreeSet<&str> = committed.blobs.iter().map(|b| b.path.as_str()).collect();
380        let mut new_paths: BTreeSet<String> = repo.untracked_files()?.into_iter().collect();
381        for entry in repo.index_files()? {
382            if !head_paths.contains(entry.path.as_str()) {
383                new_paths.insert(entry.path);
384            }
385        }
386        for path in new_paths {
387            match std::fs::read(workdir.join(&path)) {
388                Ok(bytes) => {
389                    let woid = repo.blob_oid(&bytes)?;
390                    by_path.insert(path.clone(), extractor.extract(&path, &woid, &bytes));
391                    dirty.insert((path, woid));
392                }
393                // Raced away between the walk and the read — nothing to add.
394                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
395                Err(e) => return Err(e.into()),
396            }
397        }
398    }
399
400    // The blob total is the file count of the *overlaid* graph — committed files,
401    // minus working-tree deletions, plus untracked additions — not the committed
402    // baseline, so it stays consistent whether files were added or removed.
403    let total = by_path.len();
404
405    // Encode the dirty set into the sync state so repeated identical previews
406    // no-op, but any committed change (which alters the plain tree id) does not.
407    let state = if dirty.is_empty() {
408        tree.clone()
409    } else {
410        let mut buf = String::new();
411        for (path, marker) in &dirty {
412            buf.push_str(path);
413            buf.push('\0');
414            buf.push_str(marker);
415            buf.push('\n');
416        }
417        format!("{tree}:dirty:{:016x}", fnv1a64(buf.as_bytes()))
418    };
419    let dirty_count = dirty.len();
420
421    // A dirty-set hash computed for another tree says nothing about this one, so
422    // a foreign store may never no-op here (issue #330).
423    let foreign = foreign_worktree(store, repo)?;
424    if foreign.is_none() && store.sync_state()?.as_deref() == Some(state.as_str()) {
425        return Ok(SyncReport {
426            no_op: true,
427            blobs_total: total,
428            blobs_dirty: dirty_count,
429            nodes: store.node_count()?,
430            edges: store.edge_count()?,
431            tree,
432            ..SyncReport::default()
433        });
434    }
435
436    let mut assembled = flatten(by_path);
437    resolve_calls(&mut assembled);
438    append_submodule_nodes(repo.submodules()?, &mut assembled);
439    store.reconcile(&assembled, Some(&state))?;
440    store.set_synced_worktree(&worktree_id(repo))?;
441
442    Ok(SyncReport {
443        no_op: false,
444        blobs_total: total,
445        blobs_extracted: committed.extracted,
446        blobs_cached: committed.cached,
447        blobs_dirty: dirty_count,
448        nodes: store.node_count()?,
449        edges: store.edge_count()?,
450        tree,
451        rebuilt_from_foreign_worktree: foreign,
452    })
453}
454
455/// Sync `store` to the **git index** — the staged tree that a commit would
456/// record. Unlike [`sync_worktree`] (files on disk) this reads each staged blob
457/// by its index object id, so it validates *exactly what is about to be
458/// committed* (partially-staged changes and all). New staged files are included;
459/// unstaged working-tree edits are not. Backs the index-aware pre-commit gate.
460///
461/// # Errors
462/// Returns a [`SyncError`] if git access, extraction caching, or the store
463/// reconcile fails.
464pub fn sync_index(
465    store: &mut Store,
466    repo: &Repo,
467    cache: &ObjectCache,
468    extractor: &dyn Extractor,
469) -> Result<SyncReport, SyncError> {
470    let staged = repo.index_files()?;
471    // A stable state id over the staged (path, oid) set, in its own `index:`
472    // namespace so it never collides with a committed tree id or a worktree dirty
473    // marker — repeated identical index syncs then no-op, while any staged change
474    // does not.
475    let mut buf = String::new();
476    for blob in &staged {
477        buf.push_str(&blob.path);
478        buf.push('\0');
479        buf.push_str(&blob.oid);
480        buf.push('\n');
481    }
482    let state = format!("index:{:016x}", fnv1a64(buf.as_bytes()));
483
484    // An index hash from another tree describes another index (issue #330).
485    let foreign = foreign_worktree(store, repo)?;
486    if foreign.is_none() && store.sync_state()?.as_deref() == Some(state.as_str()) {
487        return Ok(SyncReport {
488            no_op: true,
489            blobs_total: staged.len(),
490            nodes: store.node_count()?,
491            edges: store.edge_count()?,
492            tree: state,
493            ..SyncReport::default()
494        });
495    }
496
497    let extracted = extract_blobs(repo, cache, extractor, staged)?;
498    let total = extracted.by_path.len();
499    let mut assembled = flatten(extracted.by_path);
500    resolve_calls(&mut assembled);
501    // Index mode is "exactly what a commit would record", so submodule pins come
502    // from the *staged* gitlinks, not `HEAD` — a staged bump is reflected.
503    append_submodule_nodes(repo.index_submodules()?, &mut assembled);
504    store.reconcile(&assembled, Some(&state))?;
505    store.set_synced_worktree(&worktree_id(repo))?;
506
507    Ok(SyncReport {
508        no_op: false,
509        blobs_total: total,
510        blobs_extracted: extracted.extracted,
511        blobs_cached: extracted.cached,
512        blobs_dirty: 0,
513        nodes: store.node_count()?,
514        edges: store.edge_count()?,
515        tree: state,
516        rebuilt_from_foreign_worktree: foreign,
517    })
518}
519
520/// Extract a repo's **derived graph at an arbitrary commit/tree `rev`** into
521/// `store`, replacing its contents — the same content-addressed extraction as
522/// [`sync`], but for a historical point rather than `HEAD`. Because extraction is
523/// keyed by `(path, blob oid, env)`, every blob unchanged versus another synced
524/// point is a cache hit, so resolving an older version only re-does what differs.
525///
526/// This backs **version-pin resolution** (ADR-0009 step 8): to resolve a spoke's
527/// cross-repo reference against the hub *version it deploys* (a submodule sha,
528/// an image tag → commit), extract the hub at that `rev` into an ephemeral store
529/// and resolve there. It populates the derived layer only (config keys, symbols,
530/// calls); authored/import layers are not re-applied, since this is a read-only
531/// resolution snapshot. No sync-state is recorded (`tree` carries `rev` for the
532/// report only).
533///
534/// # Errors
535/// Returns [`SyncError`] on git access, extraction caching, or store failure.
536pub fn sync_tree(
537    store: &mut Store,
538    repo: &Repo,
539    cache: &ObjectCache,
540    extractor: &dyn Extractor,
541    rev: &str,
542) -> Result<SyncReport, SyncError> {
543    let extracted = extract_blobs(repo, cache, extractor, repo.blobs_at(rev)?)?;
544    let mut assembled = flatten(extracted.by_path);
545    resolve_calls(&mut assembled);
546    append_submodule_nodes(repo.submodules_at(rev)?, &mut assembled);
547    let total = file_count(&assembled);
548    store.rebuild(&assembled, None)?;
549    Ok(SyncReport {
550        no_op: false,
551        blobs_total: total,
552        blobs_extracted: extracted.extracted,
553        blobs_cached: extracted.cached,
554        blobs_dirty: 0,
555        nodes: store.node_count()?,
556        edges: store.edge_count()?,
557        tree: rev.to_owned(),
558        // A historical-rev store deliberately records no synced state at all
559        // (`rebuild(.., None)` clears the row), so it is stamped with no tree
560        // either — it is a scratch view of a commit, not of a working tree.
561        rebuilt_from_foreign_worktree: None,
562    })
563}
564
565/// The committed fact sets for the `HEAD` tree, one per path, plus the blob list
566/// (for overlay comparison) and cache-hit/miss counts.
567struct Committed {
568    blobs: Vec<crate::BlobRef>,
569    by_path: BTreeMap<String, FactSet>,
570    extracted: usize,
571    cached: usize,
572}
573
574/// Extract (or load from cache) the fact set for every blob in the `HEAD` tree.
575fn extract_committed(
576    repo: &Repo,
577    cache: &ObjectCache,
578    extractor: &dyn Extractor,
579) -> Result<Committed, SyncError> {
580    extract_blobs(repo, cache, extractor, repo.walk_blobs()?)
581}
582
583/// Extract (or load from cache) the fact set for each blob in `blobs` — the
584/// shared core of [`extract_committed`] and [`sync_index`], differing only in
585/// which tree the blob list comes from (`HEAD` vs the git index).
586fn extract_blobs(
587    repo: &Repo,
588    cache: &ObjectCache,
589    extractor: &dyn Extractor,
590    blobs: Vec<crate::BlobRef>,
591) -> Result<Committed, SyncError> {
592    let mut by_path = BTreeMap::new();
593    let mut extracted = 0usize;
594    let mut cached = 0usize;
595
596    // Extraction output depends on runtime state beyond (path, bytes): which
597    // image models are installed, and the extractor's ingestion toggles. The
598    // extractor folds both into a single tag for the cache key. Computed once
599    // per sync.
600    let env = extractor.env_tag();
601
602    for blob in &blobs {
603        // Extraction is a function of (path, blob bytes) and — with `image-ocr`
604        // — the OCR model environment (`env`), never blob id alone: node keys are
605        // path-scoped (e.g. `file:<path>`), so the same blob content at two
606        // different paths yields different facts. Key the cache by (path, oid,
607        // env) so duplicate-content files (e.g. empty files, which git dedupes to
608        // one oid) never collide, the same path+oid in another branch/worktree
609        // still hits, and installing/upgrading OCR models re-extracts images.
610        let key = cache_key(&blob.path, &blob.oid, env);
611        let facts = if let Some(facts) = cache.get(&key)? {
612            cached += 1;
613            facts
614        } else {
615            let bytes = repo.read_blob(&blob.oid)?;
616            let facts = extractor.extract(&blob.path, &blob.oid, &bytes);
617            cache.put(&key, &facts)?;
618            extracted += 1;
619            facts
620        };
621        by_path.insert(blob.path.clone(), facts);
622    }
623
624    Ok(Committed {
625        blobs,
626        by_path,
627        extracted,
628        cached,
629    })
630}
631
632/// Concatenate per-path fact sets into one assembled fact set.
633fn flatten(by_path: BTreeMap<String, FactSet>) -> FactSet {
634    let mut assembled = FactSet::new();
635    for facts in by_path.into_values() {
636        assembled.nodes.extend(facts.nodes);
637        assembled.edges.extend(facts.edges);
638    }
639    assembled
640}
641
642/// The `NodeKind::Other` token for a submodule-pin node (`submodule:<path>`).
643pub(crate) const SUBMODULE_KIND: &str = "submodule";
644
645/// Append the given submodule-pin nodes to `assembled`, replacing any already
646/// present. `subs` is the caller's source-appropriate list — `repo.submodules()`
647/// (the `HEAD` tree) for committed/worktree syncs, `repo.index_submodules()` (the
648/// staged gitlinks) for the index-aware pre-commit gate. A submodule pin is a
649/// **tree-level** derived fact (a gitlink + its `.gitmodules` URL, ADR-0009), not
650/// a per-blob one, so it is recomputed on every sync rather than cached. Removing
651/// any existing submodule nodes first makes the
652/// incremental path — which reconstructs derived nodes from the store — produce
653/// exactly the full sync's result: an unchanged pin re-adds identically, a bumped
654/// pin's new sha wins, and a removed submodule leaves none behind. The nodes carry
655/// `path = .gitmodules` (so a `.gitmodules` deletion drops them) and stand alone
656/// (no edges — nothing in the graph is their guaranteed endpoint).
657fn append_submodule_nodes(subs: Vec<crate::Submodule>, assembled: &mut FactSet) {
658    let kind = NodeKind::Other(SUBMODULE_KIND.to_owned());
659    assembled.nodes.retain(|n| n.kind != kind);
660    for sm in subs {
661        let key = format!("submodule:{}", sm.path);
662        let mut node = Node::new(key, kind.clone(), sm.path.clone());
663        node.path = Some(".gitmodules".to_owned());
664        node.provenance = Provenance::Derived;
665        node.meta = serde_json::json!({ "path": sm.path, "url": sm.url, "sha": sm.sha });
666        assembled.nodes.push(node);
667    }
668}
669
670/// The number of source files reflected in an assembled fact set (one `File`
671/// node per extracted blob). Both the full and incremental sync paths derive
672/// `SyncReport::blobs_total` from the *assembled graph* this way — not from the
673/// raw blob list — so the two paths report the same total for the same tree (the
674/// graphs are identical; see the equivalence test).
675fn file_count(facts: &FactSet) -> usize {
676    facts
677        .nodes
678        .iter()
679        .filter(|n| n.kind == NodeKind::File)
680        .count()
681}
682
683/// Resolve the per-function call records (`meta.calls`) accumulated during
684/// extraction into `calls` edges, now that every file's symbols are present.
685///
686/// Resolution is deliberately conservative — it links a call only when the target
687/// is **unambiguous** — but scope-aware: a callee descriptor may carry the
688/// immediate qualifier the call site provided (`b::foo`, `Type::assoc`,
689/// `Self::method`; see [`crate::extract`]). A call resolves when either
690///
691/// 1. its simple name is unique across the whole tree (the base case), or
692/// 2. its name is ambiguous but a qualifier picks out **exactly one** matching
693///    function — the one whose immediate scope segment equals that qualifier
694///    (with `Self` bound to the caller's own impl type).
695///
696/// This never links a name it could not before (it is a strict superset), and it
697/// still refuses to guess when a qualifier leaves more than one candidate. Runs at
698/// assembly time — not per blob — since a single blob cannot see other files.
699fn resolve_calls(facts: &mut FactSet) {
700    // Simple function name → the keys of functions with that name.
701    let mut by_name: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
702    for n in &facts.nodes {
703        if n.kind == NodeKind::Fn {
704            by_name
705                .entry(n.name.as_str())
706                .or_default()
707                .push(n.key.as_str());
708        }
709    }
710
711    // Collect (caller, callee) pairs; BTreeSet dedupes and orders them.
712    let mut resolved: BTreeSet<(String, String)> = BTreeSet::new();
713    for n in &facts.nodes {
714        if n.kind != NodeKind::Fn {
715            continue;
716        }
717        let Some(calls) = n.meta.get("calls").and_then(|v| v.as_array()) else {
718            continue;
719        };
720        // The caller's own type (for binding `Self::` calls) is the scope segment
721        // immediately before its name in its key, if it is a method.
722        let caller_self = self_type_of(&n.key);
723        for descriptor in calls.iter().filter_map(|v| v.as_str()) {
724            let (qualifier, name) = split_callee(descriptor);
725            let Some(candidates) = by_name.get(name) else {
726                continue;
727            };
728            let target = if candidates.len() == 1 {
729                // Unambiguous by simple name — the base case (unchanged behaviour).
730                Some(candidates[0])
731            } else if let Some(q) = qualifier {
732                // Ambiguous name; try the qualifier. `Self` binds to the caller's
733                // impl type — a free function has none, so such a call stays open.
734                let want = if q == "Self" { caller_self } else { Some(q) };
735                want.and_then(|want| unique_in_scope(candidates, want, name))
736            } else {
737                None
738            };
739            if let Some(dst) = target {
740                resolved.insert((n.key.clone(), dst.to_owned()));
741            }
742        }
743    }
744
745    for (src, dst) in resolved {
746        facts.edges.push(Edge::derived(src, dst, EdgeKind::Calls));
747    }
748}
749
750/// The qualified suffix of a symbol key (`sym:<lang>:<path>#<qualified>` →
751/// `<qualified>`), i.e. the scope-segment path within its file.
752fn qualified_suffix(key: &str) -> &str {
753    key.rsplit_once('#').map_or(key, |(_, q)| q)
754}
755
756/// The caller's own type for binding a `Self::` call: the scope segment
757/// immediately before the function's name in its key (`Type::method` → `Type`),
758/// or `None` for a free function (no enclosing type).
759fn self_type_of(key: &str) -> Option<&str> {
760    let mut segs = qualified_suffix(key).rsplit("::");
761    segs.next()?; // the function's own name
762    segs.next() // the enclosing scope segment, if any
763}
764
765/// The single candidate whose immediate scope segment is `want` (so its key ends
766/// with the `want::name` segment pair), or `None` when zero or several match —
767/// segment-aware so `T::m` matches `a::T::m` but never `XT::m`.
768fn unique_in_scope<'a>(candidates: &[&'a str], want: &str, name: &str) -> Option<&'a str> {
769    let mut hit = None;
770    for &key in candidates {
771        let mut segs = qualified_suffix(key).rsplit("::");
772        if segs.next() == Some(name) && segs.next() == Some(want) {
773            if hit.is_some() {
774                return None; // more than one match at this scope — refuse to guess
775            }
776            hit = Some(key);
777        }
778    }
779    hit
780}
781
782/// Split a `meta.calls` descriptor into its immediate qualifier and simple name:
783/// `b::foo` → `(Some("b"), "foo")`, `foo` → `(None, "foo")`.
784fn split_callee(descriptor: &str) -> (Option<&str>, &str) {
785    match descriptor.rsplit_once("::") {
786        Some((qualifier, name)) => (Some(qualifier), name),
787        None => (None, descriptor),
788    }
789}
790
791/// Content-addressed cache key for a blob at a given path: the blob oid (kept
792/// as the leading, well-distributed shard) suffixed with a stable 64-bit hash of
793/// the path, the [`crate::extract::EXTRACT_VERSION`], and the extractor
794/// environment tag `env` (the installed media-model — OCR + vision + audio —
795/// identity; `0` when no media model is active — see
796/// [`crate::extract::media_env_tag`]). Sharing across branches/worktrees is
797/// preserved (same path+oid+version+env → same key) while duplicate content at
798/// distinct paths stays distinct; bumping the extractor version *or* changing the
799/// installed media models retires old entries so a re-extraction is forced.
800fn cache_key(path: &str, oid: &str, env: u64) -> String {
801    format!(
802        "{oid}-{:016x}-v{}-e{env:016x}",
803        fnv1a64(path.as_bytes()),
804        crate::extract::EXTRACT_VERSION,
805    )
806}
807
808/// How many superseded extractor generations [`sweep_superseded`] keeps behind
809/// the current one by default: **one**.
810///
811/// Not clutter, and not free — it is a trade against the one workflow this
812/// project actually has. Roteiro is developed *inside* the repository it indexes,
813/// so a branch that bumps [`crate::extract::EXTRACT_VERSION`] and the `main` it
814/// will merge into share one `.git/roteiro` (the cache is under the **common**
815/// git dir). With no retention, one maintenance pass on the branch deletes
816/// `main`'s whole live set, and every switch back pays a full cold extraction;
817/// keeping the previous generation makes that switch free. Rolling a release back
818/// one version gets the same protection as a side effect.
819///
820/// It is bounded, which is the part that matters: the complaint being answered
821/// (#387) is *unbounded* accumulation — four generations resident and counting —
822/// and the steady state here is two, whatever happens next.
823pub const DEFAULT_KEEP_GENERATIONS: u32 = 1;
824
825/// Delete the object-cache entries left behind by **superseded** extractor
826/// generations, keeping the current one and `keep_generations` behind it.
827///
828/// # Why a sweep and not a byte budget
829///
830/// Because a proof is available here and nowhere else. [`cache_key`] writes the
831/// extractor generation into every key, and that generation only ever moves
832/// forward, so an entry tagged with an older one *cannot be asked for* by any
833/// binary at or beyond the current generation — no bookkeeping, no recency, no
834/// guessing. A byte budget (the Stage 25 / `rto-llama` `ModelCache` precedent,
835/// ported to disk by [`crate::Store::sweep_agent_cache`]) would have had to
836/// invent an ordering over live entries and would then evict *reachable* ones by
837/// design: on a cache shared by every worktree that means one worktree silently
838/// paying for another's working set, and it would need a last-used column this
839/// store has no clock to fill (ADR-0013 §3). It buys a bound this does not give —
840/// the live set itself is unbounded, and a repository large enough for that to
841/// hurt still needs one. That is a second policy on top of this one, not an
842/// alternative to it, and nothing has yet measured a need for it.
843///
844/// # What "superseded" is allowed to mean
845///
846/// **Only the generation**, i.e. [`crate::extract::EXTRACT_BASE_VERSION`]. The
847/// other two things folded into a key are deliberately *not* eligible:
848///
849/// - The **feature namespace** ([`crate::extract::FEATURE_NAMESPACE_STRIDE`] and
850///   above). A default build and an `--all-features` build write different
851///   `EXTRACT_VERSION`s at the *same* generation, and both are live at once —
852///   `cargo test --workspace` and `cargo test --all-features` on one repository
853///   are exactly that. Sweeping on the whole version number would have each build
854///   delete the other's cache on sight, and the two would take turns
855///   re-extracting for ever. So the namespace is masked off, and every namespace
856///   at a kept generation is kept.
857/// - The **environment tag** (`-e…`: the installed media-model and ingestion
858///   identity). It is a hash — unordered, so no tag can be shown to supersede
859///   another, and several are legitimately live at once (a build without
860///   `image-ocr` tags `0`; a build with it and a model installed does not).
861///   Reclaiming those would need the ordering the paragraph above rejected. They
862///   are left alone, and the cost of that is stated rather than hidden: env churn
863///   *within* one generation is not reclaimed by this pass.
864///
865/// # Why this is safe while other worktrees are live
866///
867/// The rule reads only the key, never the repository — so it does not need to
868/// know what any other worktree has checked out, and cannot be wrong about it. A
869/// reachability rule phrased over *blob ids* would need exactly that knowledge,
870/// and would be the dangerous version of this function: an oid unreachable from
871/// one worktree's `HEAD` is routinely live in another's. This one never asks.
872///
873/// Its only cross-worktree effect is on a worktree running an **older** binary,
874/// which it can cost a re-extraction and nothing else — the cache is derived, so
875/// a miss is slow, never wrong. The asymmetry runs one way: an entry from a
876/// *newer* generation than the sweeper's is retained, because `generation >=
877/// oldest_kept` holds for anything ahead. Two binaries of different ages can
878/// therefore never take turns deleting each other's work.
879///
880/// # Errors
881/// Returns [`CacheError`] if the cache cannot be listed. See
882/// [`ObjectCache::sweep`] for what a failure to delete an individual entry does
883/// (it is counted, not raised).
884pub fn sweep_superseded(
885    cache: &ObjectCache,
886    keep_generations: u32,
887) -> Result<ReclaimReport, CacheError> {
888    let current = crate::extract::EXTRACT_BASE_VERSION;
889    let oldest_kept = current.saturating_sub(keep_generations);
890
891    // The predicate is the only thing that ever classifies an entry, and it runs
892    // exactly once per scanned entry — so tallying here is the one place the
893    // reason for a retention is known, and it costs nothing extra. Counting it
894    // afterwards would mean a second walk, and reconstructing it in the caller
895    // would mean a second copy of this rule.
896    let current_kept = Cell::new(0);
897    let recent_kept = Cell::new(0);
898    let ahead_kept = Cell::new(0);
899    let unrecognised_kept = Cell::new(0);
900    let tally = |counter: &Cell<usize>| counter.set(counter.get() + 1);
901
902    let sweep = cache.sweep(&|key| match key_generation(key) {
903        // Not a key this module writes — a foreign or future format. Unreadable
904        // is not the same as unreachable, and only one of the two may be deleted.
905        None => {
906            tally(&unrecognised_kept);
907            true
908        }
909        Some(generation) if generation > current => {
910            tally(&ahead_kept);
911            true
912        }
913        Some(generation) if generation == current => {
914            tally(&current_kept);
915            true
916        }
917        Some(generation) if generation >= oldest_kept => {
918            tally(&recent_kept);
919            true
920        }
921        Some(_) => false,
922    })?;
923
924    let report = ReclaimReport {
925        kept_current: current_kept.get(),
926        kept_recent: recent_kept.get(),
927        kept_ahead: ahead_kept.get(),
928        kept_unrecognised: unrecognised_kept.get(),
929        sweep,
930    };
931    debug_assert_eq!(
932        report.kept_total(),
933        report.sweep.retained,
934        "every retained entry is retained for exactly one of the four reasons",
935    );
936    Ok(report)
937}
938
939/// What one [`sweep_superseded`] pass did — and, for everything it kept, **why**.
940///
941/// The four `kept_*` counts exist because the retention rule keeps more than the
942/// obvious class, and a summary that named only the obvious one would describe an
943/// irreversible operation inaccurately. They partition [`ObjectSweep::retained`]:
944/// each retained entry falls into exactly one, and their sum is that total.
945#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
946pub struct ReclaimReport {
947    /// The underlying pass: what was scanned, freed, and left on disk.
948    pub sweep: ObjectSweep,
949    /// Kept at **this build's own generation** — the live set, the thing a sweep
950    /// exists to not touch.
951    pub kept_current: usize,
952    /// Kept at an **older** generation still inside the `keep_generations`
953    /// window. Unreachable by this build; deliberate insurance for the binary a
954    /// generation behind that shares this cache (see
955    /// [`DEFAULT_KEEP_GENERATIONS`]).
956    pub kept_recent: usize,
957    /// Kept because it belongs to a generation **ahead** of this build — another
958    /// worktree, or a colleague, running a newer binary against the same shared
959    /// cache. Never swept, which is what stops two binaries of different ages
960    /// taking turns deleting each other's work.
961    pub kept_ahead: usize,
962    /// Kept because `key_generation` could not read a generation out of the key
963    /// at all. Doubt retains, always — but a non-zero count here is worth
964    /// investigating rather than absorbing into a total, because it is either a
965    /// format this build no longer writes or a bug in the parser, and both are
966    /// things a reader would want to know their cache is holding.
967    pub kept_unrecognised: usize,
968}
969
970impl ReclaimReport {
971    /// The four `kept_*` counts summed — equal to [`ObjectSweep::retained`].
972    #[must_use]
973    pub fn kept_total(&self) -> usize {
974        self.kept_current + self.kept_recent + self.kept_ahead + self.kept_unrecognised
975    }
976}
977
978/// The extractor **generation** encoded in a [`cache_key`] key, or `None` if the
979/// key does not carry one in the exact shape `cache_key` writes.
980///
981/// The parse is strict on purpose: this is the predicate a delete hangs off, so
982/// every doubt has to resolve to `None`, which retains. It therefore requires the
983/// whole `-v<digits>-e<16 hex digits>` tail, rejects a sign that `u32::from_str`
984/// would otherwise accept (`+12`), and rejects an environment tag of the wrong
985/// width — anything merely *shaped like* a key is left alone.
986fn key_generation(key: &str) -> Option<u32> {
987    let (head, env) = key.rsplit_once("-e")?;
988    if env.len() != 16 || !env.bytes().all(|b| b.is_ascii_hexdigit()) {
989        return None;
990    }
991    let (_, version) = head.rsplit_once("-v")?;
992    if version.is_empty() || !version.bytes().all(|b| b.is_ascii_digit()) {
993        return None;
994    }
995    // Mask off the feature namespace; what remains is the generation. Sound while
996    // the base stays below the stride, which `extract.rs` asserts at compile time.
997    Some(version.parse::<u32>().ok()? % crate::extract::FEATURE_NAMESPACE_STRIDE)
998}
999
1000/// FNV-1a (64-bit). Dependency-free and deterministic; used only to derive
1001/// cache filenames, so it needs no cryptographic properties.
1002fn fnv1a64(bytes: &[u8]) -> u64 {
1003    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
1004    for &b in bytes {
1005        hash ^= u64::from(b);
1006        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
1007    }
1008    hash
1009}
1010
1011#[cfg(test)]
1012mod tests {
1013    use super::{ObjectCache, cache_key, key_generation, resolve_calls};
1014    use crate::{EdgeKind, FactSet, Node, NodeKind};
1015
1016    fn fn_node(key: &str, name: &str, calls: &[&str]) -> Node {
1017        let mut n = Node::new(key, NodeKind::Fn, name);
1018        if !calls.is_empty() {
1019            n.meta = serde_json::json!({ "calls": calls });
1020        }
1021        n
1022    }
1023
1024    #[test]
1025    fn resolve_calls_links_unique_names_only() {
1026        let mut fs = FactSet::new()
1027            .with_node(fn_node(
1028                "sym:rust:a.rs#caller",
1029                "caller",
1030                &["target", "dup", "missing"],
1031            ))
1032            .with_node(fn_node("sym:rust:a.rs#target", "target", &[]))
1033            // Two functions named `dup` → ambiguous, must not be linked.
1034            .with_node(fn_node("sym:rust:a.rs#dup", "dup", &[]))
1035            .with_node(fn_node("sym:rust:b.rs#dup", "dup", &[]));
1036
1037        resolve_calls(&mut fs);
1038
1039        let calls: Vec<_> = fs
1040            .edges
1041            .iter()
1042            .filter(|e| e.kind == EdgeKind::Calls)
1043            .collect();
1044        assert_eq!(
1045            calls.len(),
1046            1,
1047            "only the unambiguous, known callee is linked"
1048        );
1049        assert_eq!(calls[0].src, "sym:rust:a.rs#caller");
1050        assert_eq!(calls[0].dst, "sym:rust:a.rs#target");
1051    }
1052
1053    #[test]
1054    fn cache_key_separates_paths_but_is_stable() {
1055        let oid = "abc123";
1056        // Same path + oid + env is stable across calls.
1057        assert_eq!(cache_key("src/a.rs", oid, 0), cache_key("src/a.rs", oid, 0));
1058        // Same blob content (oid) at two different paths must not collide.
1059        assert_ne!(cache_key("src/a.rs", oid, 0), cache_key("src/b.rs", oid, 0));
1060        // Different content at the same path differs too.
1061        assert_ne!(
1062            cache_key("src/a.rs", "aaa", 0),
1063            cache_key("src/a.rs", "bbb", 0)
1064        );
1065        // A different extractor environment (e.g. OCR models installed) differs,
1066        // so image facts are re-extracted when the models change.
1067        assert_ne!(
1068            cache_key("src/a.rs", oid, 0),
1069            cache_key("src/a.rs", oid, 42)
1070        );
1071        // Key stays sharded on the oid so the cache's 2-char shard is well spread.
1072        assert!(cache_key("src/a.rs", oid, 0).starts_with("abc123-"));
1073        // The extractor version is folded in, so a bump retires old entries.
1074        assert!(
1075            cache_key("src/a.rs", oid, 0)
1076                .contains(&format!("-v{}", crate::extract::EXTRACT_VERSION))
1077        );
1078    }
1079
1080    /// The sweep predicate's one input. The round trip is what makes the sweep
1081    /// safe: a key this module just wrote must decode to *this* generation, or a
1082    /// pass at the current version would delete its own live entries.
1083    #[test]
1084    fn key_generation_round_trips_the_key_this_module_writes() {
1085        let key = cache_key("src/a.rs", "abc123", 0);
1086        assert_eq!(
1087            key_generation(&key),
1088            Some(crate::extract::EXTRACT_BASE_VERSION),
1089            "a key written now decodes to the current generation: {key}",
1090        );
1091        // …and so does the same generation in another feature build's namespace,
1092        // which is the whole reason the namespace is masked off rather than
1093        // compared. Both are live at once on a machine that runs the default and
1094        // `--all-features` test suites over one repository.
1095        let base = crate::extract::EXTRACT_BASE_VERSION;
1096        for namespace in [100, 200, 300, 400, 500, 600, 700] {
1097            let other = format!(
1098                "abc123-0000000000000000-v{}-e0000000000000000",
1099                base + namespace
1100            );
1101            assert_eq!(
1102                key_generation(&other),
1103                Some(base),
1104                "namespace {namespace} is not a different generation",
1105            );
1106        }
1107    }
1108
1109    /// Every doubt resolves to `None`, and `None` retains. These are the strings
1110    /// that must *not* be read as a generation — each one would otherwise put a
1111    /// file nobody can identify in reach of a delete.
1112    #[test]
1113    fn key_generation_refuses_anything_it_did_not_write() {
1114        for not_a_key in [
1115            "",
1116            "abc123",                                                 // no tail at all
1117            "abc123-0000000000000000-v12",                            // no env tag
1118            "abc123-0000000000000000-e0000000000000000",              // no version tag
1119            "abc123-0000000000000000-v12-e00000000000000",            // env too short
1120            "abc123-0000000000000000-v12-e00000000000000000",         // env too long
1121            "abc123-0000000000000000-v12-egggggggggggggggg",          // env not hex
1122            "abc123-0000000000000000-v+12-e0000000000000000",         // `+12` parses as 12
1123            "abc123-0000000000000000-v-e0000000000000000",            // empty version
1124            "abc123-0000000000000000-v1 2-e0000000000000000",         // not all digits
1125            "abc123-0000000000000000-v99999999999-e0000000000000000", // overflows u32
1126        ] {
1127            assert_eq!(
1128                key_generation(not_a_key),
1129                None,
1130                "`{not_a_key}` must not be read as a generation",
1131            );
1132        }
1133    }
1134
1135    /// The sweep's contract, on a cache holding one entry per generation and
1136    /// namespace: the current generation survives in **every** namespace, the
1137    /// retained generations survive, older ones go, and a *newer* one — written
1138    /// by a binary ahead of this one sharing the same common git dir — is never
1139    /// touched, whatever the retention.
1140    #[test]
1141    fn sweep_superseded_keeps_current_future_and_kept_generations() {
1142        let base = crate::extract::EXTRACT_BASE_VERSION;
1143        let dir = std::env::temp_dir().join(format!("roteiro-gc-{}", std::process::id()));
1144        std::fs::remove_dir_all(&dir).ok();
1145        let cache = ObjectCache::open(&dir).expect("open");
1146
1147        let key = |version: u32| format!("abc123-0000000000000000-v{version}-e0000000000000000");
1148        let ancient = key(base - 2);
1149        let previous = key(base - 1);
1150        let current = key(base);
1151        let current_all_features = key(base + 700);
1152        let future = key(base + 1);
1153        let foreign = "not-a-roteiro-cache-key".to_owned();
1154        for k in [
1155            &ancient,
1156            &previous,
1157            &current,
1158            &current_all_features,
1159            &future,
1160            &foreign,
1161        ] {
1162            cache.put(k, &FactSet::new()).expect("put");
1163        }
1164
1165        // Keeping one generation back: only `base - 2` is unreachable.
1166        let swept =
1167            super::sweep_superseded(&cache, super::DEFAULT_KEEP_GENERATIONS).expect("sweep");
1168        assert_eq!(swept.sweep.removed, 1, "{swept:?}");
1169        // Retention is not one class, and the report says which. Two entries sit
1170        // at this generation (the two namespaces), one behind it, one ahead of
1171        // it, and one key that does not parse — each counted under its own
1172        // reason, because a summary that folded them together would describe an
1173        // irreversible operation inaccurately.
1174        assert_eq!(
1175            (
1176                swept.kept_current,
1177                swept.kept_recent,
1178                swept.kept_ahead,
1179                swept.kept_unrecognised,
1180            ),
1181            (2, 1, 1, 1),
1182            "{swept:?}",
1183        );
1184        assert_eq!(
1185            swept.kept_total(),
1186            swept.sweep.retained,
1187            "the four reasons must partition the retained total: {swept:?}",
1188        );
1189        assert!(!cache.contains(&ancient));
1190        for k in [
1191            &previous,
1192            &current,
1193            &current_all_features,
1194            &future,
1195            &foreign,
1196        ] {
1197            assert!(cache.contains(k), "`{k}` must survive a keep-1 sweep");
1198        }
1199
1200        // Keeping none: the previous generation goes too, and nothing else does.
1201        let swept = super::sweep_superseded(&cache, 0).expect("sweep");
1202        assert_eq!(swept.sweep.removed, 1, "{swept:?}");
1203        assert!(!cache.contains(&previous));
1204        for k in [&current, &current_all_features, &future, &foreign] {
1205            assert!(cache.contains(k), "`{k}` must survive a keep-0 sweep");
1206        }
1207
1208        // A repeat pass is a no-op: nothing reachable is ever swept "eventually".
1209        let swept = super::sweep_superseded(&cache, 0).expect("sweep");
1210        assert_eq!(swept.sweep.removed, 0, "{swept:?}");
1211        assert_eq!(swept.sweep.retained, 4, "{swept:?}");
1212
1213        std::fs::remove_dir_all(&dir).expect("cleanup");
1214    }
1215}