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 untracked files: not in `HEAD`, so absent from
362 // `committed.blobs` above. A gitignore-aware walk finds them so the
363 // working-tree `sync`/`check`/`review` see new work that isn't staged yet.
364 // They count as dirty (so the preview re-runs when they change) and add to
365 // the blob total (they are genuinely new blobs, not edits of existing ones).
366 for path in repo.untracked_files()? {
367 match std::fs::read(workdir.join(&path)) {
368 Ok(bytes) => {
369 let woid = repo.blob_oid(&bytes)?;
370 by_path.insert(path.clone(), extractor.extract(&path, &woid, &bytes));
371 dirty.insert((path, woid));
372 }
373 // Raced away between the walk and the read — nothing to add.
374 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
375 Err(e) => return Err(e.into()),
376 }
377 }
378 }
379
380 // The blob total is the file count of the *overlaid* graph — committed files,
381 // minus working-tree deletions, plus untracked additions — not the committed
382 // baseline, so it stays consistent whether files were added or removed.
383 let total = by_path.len();
384
385 // Encode the dirty set into the sync state so repeated identical previews
386 // no-op, but any committed change (which alters the plain tree id) does not.
387 let state = if dirty.is_empty() {
388 tree.clone()
389 } else {
390 let mut buf = String::new();
391 for (path, marker) in &dirty {
392 buf.push_str(path);
393 buf.push('\0');
394 buf.push_str(marker);
395 buf.push('\n');
396 }
397 format!("{tree}:dirty:{:016x}", fnv1a64(buf.as_bytes()))
398 };
399 let dirty_count = dirty.len();
400
401 // A dirty-set hash computed for another tree says nothing about this one, so
402 // a foreign store may never no-op here (issue #330).
403 let foreign = foreign_worktree(store, repo)?;
404 if foreign.is_none() && store.sync_state()?.as_deref() == Some(state.as_str()) {
405 return Ok(SyncReport {
406 no_op: true,
407 blobs_total: total,
408 blobs_dirty: dirty_count,
409 nodes: store.node_count()?,
410 edges: store.edge_count()?,
411 tree,
412 ..SyncReport::default()
413 });
414 }
415
416 let mut assembled = flatten(by_path);
417 resolve_calls(&mut assembled);
418 append_submodule_nodes(repo.submodules()?, &mut assembled);
419 store.reconcile(&assembled, Some(&state))?;
420 store.set_synced_worktree(&worktree_id(repo))?;
421
422 Ok(SyncReport {
423 no_op: false,
424 blobs_total: total,
425 blobs_extracted: committed.extracted,
426 blobs_cached: committed.cached,
427 blobs_dirty: dirty_count,
428 nodes: store.node_count()?,
429 edges: store.edge_count()?,
430 tree,
431 rebuilt_from_foreign_worktree: foreign,
432 })
433}
434
435/// Sync `store` to the **git index** — the staged tree that a commit would
436/// record. Unlike [`sync_worktree`] (files on disk) this reads each staged blob
437/// by its index object id, so it validates *exactly what is about to be
438/// committed* (partially-staged changes and all). New staged files are included;
439/// unstaged working-tree edits are not. Backs the index-aware pre-commit gate.
440///
441/// # Errors
442/// Returns a [`SyncError`] if git access, extraction caching, or the store
443/// reconcile fails.
444pub fn sync_index(
445 store: &mut Store,
446 repo: &Repo,
447 cache: &ObjectCache,
448 extractor: &dyn Extractor,
449) -> Result<SyncReport, SyncError> {
450 let staged = repo.index_files()?;
451 // A stable state id over the staged (path, oid) set, in its own `index:`
452 // namespace so it never collides with a committed tree id or a worktree dirty
453 // marker — repeated identical index syncs then no-op, while any staged change
454 // does not.
455 let mut buf = String::new();
456 for blob in &staged {
457 buf.push_str(&blob.path);
458 buf.push('\0');
459 buf.push_str(&blob.oid);
460 buf.push('\n');
461 }
462 let state = format!("index:{:016x}", fnv1a64(buf.as_bytes()));
463
464 // An index hash from another tree describes another index (issue #330).
465 let foreign = foreign_worktree(store, repo)?;
466 if foreign.is_none() && store.sync_state()?.as_deref() == Some(state.as_str()) {
467 return Ok(SyncReport {
468 no_op: true,
469 blobs_total: staged.len(),
470 nodes: store.node_count()?,
471 edges: store.edge_count()?,
472 tree: state,
473 ..SyncReport::default()
474 });
475 }
476
477 let extracted = extract_blobs(repo, cache, extractor, staged)?;
478 let total = extracted.by_path.len();
479 let mut assembled = flatten(extracted.by_path);
480 resolve_calls(&mut assembled);
481 // Index mode is "exactly what a commit would record", so submodule pins come
482 // from the *staged* gitlinks, not `HEAD` — a staged bump is reflected.
483 append_submodule_nodes(repo.index_submodules()?, &mut assembled);
484 store.reconcile(&assembled, Some(&state))?;
485 store.set_synced_worktree(&worktree_id(repo))?;
486
487 Ok(SyncReport {
488 no_op: false,
489 blobs_total: total,
490 blobs_extracted: extracted.extracted,
491 blobs_cached: extracted.cached,
492 blobs_dirty: 0,
493 nodes: store.node_count()?,
494 edges: store.edge_count()?,
495 tree: state,
496 rebuilt_from_foreign_worktree: foreign,
497 })
498}
499
500/// Extract a repo's **derived graph at an arbitrary commit/tree `rev`** into
501/// `store`, replacing its contents — the same content-addressed extraction as
502/// [`sync`], but for a historical point rather than `HEAD`. Because extraction is
503/// keyed by `(path, blob oid, env)`, every blob unchanged versus another synced
504/// point is a cache hit, so resolving an older version only re-does what differs.
505///
506/// This backs **version-pin resolution** (ADR-0009 step 8): to resolve a spoke's
507/// cross-repo reference against the hub *version it deploys* (a submodule sha,
508/// an image tag → commit), extract the hub at that `rev` into an ephemeral store
509/// and resolve there. It populates the derived layer only (config keys, symbols,
510/// calls); authored/import layers are not re-applied, since this is a read-only
511/// resolution snapshot. No sync-state is recorded (`tree` carries `rev` for the
512/// report only).
513///
514/// # Errors
515/// Returns [`SyncError`] on git access, extraction caching, or store failure.
516pub fn sync_tree(
517 store: &mut Store,
518 repo: &Repo,
519 cache: &ObjectCache,
520 extractor: &dyn Extractor,
521 rev: &str,
522) -> Result<SyncReport, SyncError> {
523 let extracted = extract_blobs(repo, cache, extractor, repo.blobs_at(rev)?)?;
524 let mut assembled = flatten(extracted.by_path);
525 resolve_calls(&mut assembled);
526 append_submodule_nodes(repo.submodules_at(rev)?, &mut assembled);
527 let total = file_count(&assembled);
528 store.rebuild(&assembled, None)?;
529 Ok(SyncReport {
530 no_op: false,
531 blobs_total: total,
532 blobs_extracted: extracted.extracted,
533 blobs_cached: extracted.cached,
534 blobs_dirty: 0,
535 nodes: store.node_count()?,
536 edges: store.edge_count()?,
537 tree: rev.to_owned(),
538 // A historical-rev store deliberately records no synced state at all
539 // (`rebuild(.., None)` clears the row), so it is stamped with no tree
540 // either — it is a scratch view of a commit, not of a working tree.
541 rebuilt_from_foreign_worktree: None,
542 })
543}
544
545/// The committed fact sets for the `HEAD` tree, one per path, plus the blob list
546/// (for overlay comparison) and cache-hit/miss counts.
547struct Committed {
548 blobs: Vec<crate::BlobRef>,
549 by_path: BTreeMap<String, FactSet>,
550 extracted: usize,
551 cached: usize,
552}
553
554/// Extract (or load from cache) the fact set for every blob in the `HEAD` tree.
555fn extract_committed(
556 repo: &Repo,
557 cache: &ObjectCache,
558 extractor: &dyn Extractor,
559) -> Result<Committed, SyncError> {
560 extract_blobs(repo, cache, extractor, repo.walk_blobs()?)
561}
562
563/// Extract (or load from cache) the fact set for each blob in `blobs` — the
564/// shared core of [`extract_committed`] and [`sync_index`], differing only in
565/// which tree the blob list comes from (`HEAD` vs the git index).
566fn extract_blobs(
567 repo: &Repo,
568 cache: &ObjectCache,
569 extractor: &dyn Extractor,
570 blobs: Vec<crate::BlobRef>,
571) -> Result<Committed, SyncError> {
572 let mut by_path = BTreeMap::new();
573 let mut extracted = 0usize;
574 let mut cached = 0usize;
575
576 // Extraction output depends on runtime state beyond (path, bytes): which
577 // image models are installed, and the extractor's ingestion toggles. The
578 // extractor folds both into a single tag for the cache key. Computed once
579 // per sync.
580 let env = extractor.env_tag();
581
582 for blob in &blobs {
583 // Extraction is a function of (path, blob bytes) and — with `image-ocr`
584 // — the OCR model environment (`env`), never blob id alone: node keys are
585 // path-scoped (e.g. `file:<path>`), so the same blob content at two
586 // different paths yields different facts. Key the cache by (path, oid,
587 // env) so duplicate-content files (e.g. empty files, which git dedupes to
588 // one oid) never collide, the same path+oid in another branch/worktree
589 // still hits, and installing/upgrading OCR models re-extracts images.
590 let key = cache_key(&blob.path, &blob.oid, env);
591 let facts = if let Some(facts) = cache.get(&key)? {
592 cached += 1;
593 facts
594 } else {
595 let bytes = repo.read_blob(&blob.oid)?;
596 let facts = extractor.extract(&blob.path, &blob.oid, &bytes);
597 cache.put(&key, &facts)?;
598 extracted += 1;
599 facts
600 };
601 by_path.insert(blob.path.clone(), facts);
602 }
603
604 Ok(Committed {
605 blobs,
606 by_path,
607 extracted,
608 cached,
609 })
610}
611
612/// Concatenate per-path fact sets into one assembled fact set.
613fn flatten(by_path: BTreeMap<String, FactSet>) -> FactSet {
614 let mut assembled = FactSet::new();
615 for facts in by_path.into_values() {
616 assembled.nodes.extend(facts.nodes);
617 assembled.edges.extend(facts.edges);
618 }
619 assembled
620}
621
622/// The `NodeKind::Other` token for a submodule-pin node (`submodule:<path>`).
623pub(crate) const SUBMODULE_KIND: &str = "submodule";
624
625/// Append the given submodule-pin nodes to `assembled`, replacing any already
626/// present. `subs` is the caller's source-appropriate list — `repo.submodules()`
627/// (the `HEAD` tree) for committed/worktree syncs, `repo.index_submodules()` (the
628/// staged gitlinks) for the index-aware pre-commit gate. A submodule pin is a
629/// **tree-level** derived fact (a gitlink + its `.gitmodules` URL, ADR-0009), not
630/// a per-blob one, so it is recomputed on every sync rather than cached. Removing
631/// any existing submodule nodes first makes the
632/// incremental path — which reconstructs derived nodes from the store — produce
633/// exactly the full sync's result: an unchanged pin re-adds identically, a bumped
634/// pin's new sha wins, and a removed submodule leaves none behind. The nodes carry
635/// `path = .gitmodules` (so a `.gitmodules` deletion drops them) and stand alone
636/// (no edges — nothing in the graph is their guaranteed endpoint).
637fn append_submodule_nodes(subs: Vec<crate::Submodule>, assembled: &mut FactSet) {
638 let kind = NodeKind::Other(SUBMODULE_KIND.to_owned());
639 assembled.nodes.retain(|n| n.kind != kind);
640 for sm in subs {
641 let key = format!("submodule:{}", sm.path);
642 let mut node = Node::new(key, kind.clone(), sm.path.clone());
643 node.path = Some(".gitmodules".to_owned());
644 node.provenance = Provenance::Derived;
645 node.meta = serde_json::json!({ "path": sm.path, "url": sm.url, "sha": sm.sha });
646 assembled.nodes.push(node);
647 }
648}
649
650/// The number of source files reflected in an assembled fact set (one `File`
651/// node per extracted blob). Both the full and incremental sync paths derive
652/// `SyncReport::blobs_total` from the *assembled graph* this way — not from the
653/// raw blob list — so the two paths report the same total for the same tree (the
654/// graphs are identical; see the equivalence test).
655fn file_count(facts: &FactSet) -> usize {
656 facts
657 .nodes
658 .iter()
659 .filter(|n| n.kind == NodeKind::File)
660 .count()
661}
662
663/// Resolve the per-function call records (`meta.calls`) accumulated during
664/// extraction into `calls` edges, now that every file's symbols are present.
665///
666/// Resolution is deliberately conservative — it links a call only when the target
667/// is **unambiguous** — but scope-aware: a callee descriptor may carry the
668/// immediate qualifier the call site provided (`b::foo`, `Type::assoc`,
669/// `Self::method`; see [`crate::extract`]). A call resolves when either
670///
671/// 1. its simple name is unique across the whole tree (the base case), or
672/// 2. its name is ambiguous but a qualifier picks out **exactly one** matching
673/// function — the one whose immediate scope segment equals that qualifier
674/// (with `Self` bound to the caller's own impl type).
675///
676/// This never links a name it could not before (it is a strict superset), and it
677/// still refuses to guess when a qualifier leaves more than one candidate. Runs at
678/// assembly time — not per blob — since a single blob cannot see other files.
679fn resolve_calls(facts: &mut FactSet) {
680 // Simple function name → the keys of functions with that name.
681 let mut by_name: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
682 for n in &facts.nodes {
683 if n.kind == NodeKind::Fn {
684 by_name
685 .entry(n.name.as_str())
686 .or_default()
687 .push(n.key.as_str());
688 }
689 }
690
691 // Collect (caller, callee) pairs; BTreeSet dedupes and orders them.
692 let mut resolved: BTreeSet<(String, String)> = BTreeSet::new();
693 for n in &facts.nodes {
694 if n.kind != NodeKind::Fn {
695 continue;
696 }
697 let Some(calls) = n.meta.get("calls").and_then(|v| v.as_array()) else {
698 continue;
699 };
700 // The caller's own type (for binding `Self::` calls) is the scope segment
701 // immediately before its name in its key, if it is a method.
702 let caller_self = self_type_of(&n.key);
703 for descriptor in calls.iter().filter_map(|v| v.as_str()) {
704 let (qualifier, name) = split_callee(descriptor);
705 let Some(candidates) = by_name.get(name) else {
706 continue;
707 };
708 let target = if candidates.len() == 1 {
709 // Unambiguous by simple name — the base case (unchanged behaviour).
710 Some(candidates[0])
711 } else if let Some(q) = qualifier {
712 // Ambiguous name; try the qualifier. `Self` binds to the caller's
713 // impl type — a free function has none, so such a call stays open.
714 let want = if q == "Self" { caller_self } else { Some(q) };
715 want.and_then(|want| unique_in_scope(candidates, want, name))
716 } else {
717 None
718 };
719 if let Some(dst) = target {
720 resolved.insert((n.key.clone(), dst.to_owned()));
721 }
722 }
723 }
724
725 for (src, dst) in resolved {
726 facts.edges.push(Edge::derived(src, dst, EdgeKind::Calls));
727 }
728}
729
730/// The qualified suffix of a symbol key (`sym:<lang>:<path>#<qualified>` →
731/// `<qualified>`), i.e. the scope-segment path within its file.
732fn qualified_suffix(key: &str) -> &str {
733 key.rsplit_once('#').map_or(key, |(_, q)| q)
734}
735
736/// The caller's own type for binding a `Self::` call: the scope segment
737/// immediately before the function's name in its key (`Type::method` → `Type`),
738/// or `None` for a free function (no enclosing type).
739fn self_type_of(key: &str) -> Option<&str> {
740 let mut segs = qualified_suffix(key).rsplit("::");
741 segs.next()?; // the function's own name
742 segs.next() // the enclosing scope segment, if any
743}
744
745/// The single candidate whose immediate scope segment is `want` (so its key ends
746/// with the `want::name` segment pair), or `None` when zero or several match —
747/// segment-aware so `T::m` matches `a::T::m` but never `XT::m`.
748fn unique_in_scope<'a>(candidates: &[&'a str], want: &str, name: &str) -> Option<&'a str> {
749 let mut hit = None;
750 for &key in candidates {
751 let mut segs = qualified_suffix(key).rsplit("::");
752 if segs.next() == Some(name) && segs.next() == Some(want) {
753 if hit.is_some() {
754 return None; // more than one match at this scope — refuse to guess
755 }
756 hit = Some(key);
757 }
758 }
759 hit
760}
761
762/// Split a `meta.calls` descriptor into its immediate qualifier and simple name:
763/// `b::foo` → `(Some("b"), "foo")`, `foo` → `(None, "foo")`.
764fn split_callee(descriptor: &str) -> (Option<&str>, &str) {
765 match descriptor.rsplit_once("::") {
766 Some((qualifier, name)) => (Some(qualifier), name),
767 None => (None, descriptor),
768 }
769}
770
771/// Content-addressed cache key for a blob at a given path: the blob oid (kept
772/// as the leading, well-distributed shard) suffixed with a stable 64-bit hash of
773/// the path, the [`crate::extract::EXTRACT_VERSION`], and the extractor
774/// environment tag `env` (the installed media-model — OCR + vision + audio —
775/// identity; `0` when no media model is active — see
776/// [`crate::extract::media_env_tag`]). Sharing across branches/worktrees is
777/// preserved (same path+oid+version+env → same key) while duplicate content at
778/// distinct paths stays distinct; bumping the extractor version *or* changing the
779/// installed media models retires old entries so a re-extraction is forced.
780fn cache_key(path: &str, oid: &str, env: u64) -> String {
781 format!(
782 "{oid}-{:016x}-v{}-e{env:016x}",
783 fnv1a64(path.as_bytes()),
784 crate::extract::EXTRACT_VERSION,
785 )
786}
787
788/// How many superseded extractor generations [`sweep_superseded`] keeps behind
789/// the current one by default: **one**.
790///
791/// Not clutter, and not free — it is a trade against the one workflow this
792/// project actually has. Roteiro is developed *inside* the repository it indexes,
793/// so a branch that bumps [`crate::extract::EXTRACT_VERSION`] and the `main` it
794/// will merge into share one `.git/roteiro` (the cache is under the **common**
795/// git dir). With no retention, one maintenance pass on the branch deletes
796/// `main`'s whole live set, and every switch back pays a full cold extraction;
797/// keeping the previous generation makes that switch free. Rolling a release back
798/// one version gets the same protection as a side effect.
799///
800/// It is bounded, which is the part that matters: the complaint being answered
801/// (#387) is *unbounded* accumulation — four generations resident and counting —
802/// and the steady state here is two, whatever happens next.
803pub const DEFAULT_KEEP_GENERATIONS: u32 = 1;
804
805/// Delete the object-cache entries left behind by **superseded** extractor
806/// generations, keeping the current one and `keep_generations` behind it.
807///
808/// # Why a sweep and not a byte budget
809///
810/// Because a proof is available here and nowhere else. [`cache_key`] writes the
811/// extractor generation into every key, and that generation only ever moves
812/// forward, so an entry tagged with an older one *cannot be asked for* by any
813/// binary at or beyond the current generation — no bookkeeping, no recency, no
814/// guessing. A byte budget (the Stage 25 / `rto-llama` `ModelCache` precedent,
815/// ported to disk by [`crate::Store::sweep_agent_cache`]) would have had to
816/// invent an ordering over live entries and would then evict *reachable* ones by
817/// design: on a cache shared by every worktree that means one worktree silently
818/// paying for another's working set, and it would need a last-used column this
819/// store has no clock to fill (ADR-0013 §3). It buys a bound this does not give —
820/// the live set itself is unbounded, and a repository large enough for that to
821/// hurt still needs one. That is a second policy on top of this one, not an
822/// alternative to it, and nothing has yet measured a need for it.
823///
824/// # What "superseded" is allowed to mean
825///
826/// **Only the generation**, i.e. [`crate::extract::EXTRACT_BASE_VERSION`]. The
827/// other two things folded into a key are deliberately *not* eligible:
828///
829/// - The **feature namespace** ([`crate::extract::FEATURE_NAMESPACE_STRIDE`] and
830/// above). A default build and an `--all-features` build write different
831/// `EXTRACT_VERSION`s at the *same* generation, and both are live at once —
832/// `cargo test --workspace` and `cargo test --all-features` on one repository
833/// are exactly that. Sweeping on the whole version number would have each build
834/// delete the other's cache on sight, and the two would take turns
835/// re-extracting for ever. So the namespace is masked off, and every namespace
836/// at a kept generation is kept.
837/// - The **environment tag** (`-e…`: the installed media-model and ingestion
838/// identity). It is a hash — unordered, so no tag can be shown to supersede
839/// another, and several are legitimately live at once (a build without
840/// `image-ocr` tags `0`; a build with it and a model installed does not).
841/// Reclaiming those would need the ordering the paragraph above rejected. They
842/// are left alone, and the cost of that is stated rather than hidden: env churn
843/// *within* one generation is not reclaimed by this pass.
844///
845/// # Why this is safe while other worktrees are live
846///
847/// The rule reads only the key, never the repository — so it does not need to
848/// know what any other worktree has checked out, and cannot be wrong about it. A
849/// reachability rule phrased over *blob ids* would need exactly that knowledge,
850/// and would be the dangerous version of this function: an oid unreachable from
851/// one worktree's `HEAD` is routinely live in another's. This one never asks.
852///
853/// Its only cross-worktree effect is on a worktree running an **older** binary,
854/// which it can cost a re-extraction and nothing else — the cache is derived, so
855/// a miss is slow, never wrong. The asymmetry runs one way: an entry from a
856/// *newer* generation than the sweeper's is retained, because `generation >=
857/// oldest_kept` holds for anything ahead. Two binaries of different ages can
858/// therefore never take turns deleting each other's work.
859///
860/// # Errors
861/// Returns [`CacheError`] if the cache cannot be listed. See
862/// [`ObjectCache::sweep`] for what a failure to delete an individual entry does
863/// (it is counted, not raised).
864pub fn sweep_superseded(
865 cache: &ObjectCache,
866 keep_generations: u32,
867) -> Result<ReclaimReport, CacheError> {
868 let current = crate::extract::EXTRACT_BASE_VERSION;
869 let oldest_kept = current.saturating_sub(keep_generations);
870
871 // The predicate is the only thing that ever classifies an entry, and it runs
872 // exactly once per scanned entry — so tallying here is the one place the
873 // reason for a retention is known, and it costs nothing extra. Counting it
874 // afterwards would mean a second walk, and reconstructing it in the caller
875 // would mean a second copy of this rule.
876 let current_kept = Cell::new(0);
877 let recent_kept = Cell::new(0);
878 let ahead_kept = Cell::new(0);
879 let unrecognised_kept = Cell::new(0);
880 let tally = |counter: &Cell<usize>| counter.set(counter.get() + 1);
881
882 let sweep = cache.sweep(&|key| match key_generation(key) {
883 // Not a key this module writes — a foreign or future format. Unreadable
884 // is not the same as unreachable, and only one of the two may be deleted.
885 None => {
886 tally(&unrecognised_kept);
887 true
888 }
889 Some(generation) if generation > current => {
890 tally(&ahead_kept);
891 true
892 }
893 Some(generation) if generation == current => {
894 tally(¤t_kept);
895 true
896 }
897 Some(generation) if generation >= oldest_kept => {
898 tally(&recent_kept);
899 true
900 }
901 Some(_) => false,
902 })?;
903
904 let report = ReclaimReport {
905 kept_current: current_kept.get(),
906 kept_recent: recent_kept.get(),
907 kept_ahead: ahead_kept.get(),
908 kept_unrecognised: unrecognised_kept.get(),
909 sweep,
910 };
911 debug_assert_eq!(
912 report.kept_total(),
913 report.sweep.retained,
914 "every retained entry is retained for exactly one of the four reasons",
915 );
916 Ok(report)
917}
918
919/// What one [`sweep_superseded`] pass did — and, for everything it kept, **why**.
920///
921/// The four `kept_*` counts exist because the retention rule keeps more than the
922/// obvious class, and a summary that named only the obvious one would describe an
923/// irreversible operation inaccurately. They partition [`ObjectSweep::retained`]:
924/// each retained entry falls into exactly one, and their sum is that total.
925#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
926pub struct ReclaimReport {
927 /// The underlying pass: what was scanned, freed, and left on disk.
928 pub sweep: ObjectSweep,
929 /// Kept at **this build's own generation** — the live set, the thing a sweep
930 /// exists to not touch.
931 pub kept_current: usize,
932 /// Kept at an **older** generation still inside the `keep_generations`
933 /// window. Unreachable by this build; deliberate insurance for the binary a
934 /// generation behind that shares this cache (see
935 /// [`DEFAULT_KEEP_GENERATIONS`]).
936 pub kept_recent: usize,
937 /// Kept because it belongs to a generation **ahead** of this build — another
938 /// worktree, or a colleague, running a newer binary against the same shared
939 /// cache. Never swept, which is what stops two binaries of different ages
940 /// taking turns deleting each other's work.
941 pub kept_ahead: usize,
942 /// Kept because `key_generation` could not read a generation out of the key
943 /// at all. Doubt retains, always — but a non-zero count here is worth
944 /// investigating rather than absorbing into a total, because it is either a
945 /// format this build no longer writes or a bug in the parser, and both are
946 /// things a reader would want to know their cache is holding.
947 pub kept_unrecognised: usize,
948}
949
950impl ReclaimReport {
951 /// The four `kept_*` counts summed — equal to [`ObjectSweep::retained`].
952 #[must_use]
953 pub fn kept_total(&self) -> usize {
954 self.kept_current + self.kept_recent + self.kept_ahead + self.kept_unrecognised
955 }
956}
957
958/// The extractor **generation** encoded in a [`cache_key`] key, or `None` if the
959/// key does not carry one in the exact shape `cache_key` writes.
960///
961/// The parse is strict on purpose: this is the predicate a delete hangs off, so
962/// every doubt has to resolve to `None`, which retains. It therefore requires the
963/// whole `-v<digits>-e<16 hex digits>` tail, rejects a sign that `u32::from_str`
964/// would otherwise accept (`+12`), and rejects an environment tag of the wrong
965/// width — anything merely *shaped like* a key is left alone.
966fn key_generation(key: &str) -> Option<u32> {
967 let (head, env) = key.rsplit_once("-e")?;
968 if env.len() != 16 || !env.bytes().all(|b| b.is_ascii_hexdigit()) {
969 return None;
970 }
971 let (_, version) = head.rsplit_once("-v")?;
972 if version.is_empty() || !version.bytes().all(|b| b.is_ascii_digit()) {
973 return None;
974 }
975 // Mask off the feature namespace; what remains is the generation. Sound while
976 // the base stays below the stride, which `extract.rs` asserts at compile time.
977 Some(version.parse::<u32>().ok()? % crate::extract::FEATURE_NAMESPACE_STRIDE)
978}
979
980/// FNV-1a (64-bit). Dependency-free and deterministic; used only to derive
981/// cache filenames, so it needs no cryptographic properties.
982fn fnv1a64(bytes: &[u8]) -> u64 {
983 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
984 for &b in bytes {
985 hash ^= u64::from(b);
986 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
987 }
988 hash
989}
990
991#[cfg(test)]
992mod tests {
993 use super::{ObjectCache, cache_key, key_generation, resolve_calls};
994 use crate::{EdgeKind, FactSet, Node, NodeKind};
995
996 fn fn_node(key: &str, name: &str, calls: &[&str]) -> Node {
997 let mut n = Node::new(key, NodeKind::Fn, name);
998 if !calls.is_empty() {
999 n.meta = serde_json::json!({ "calls": calls });
1000 }
1001 n
1002 }
1003
1004 #[test]
1005 fn resolve_calls_links_unique_names_only() {
1006 let mut fs = FactSet::new()
1007 .with_node(fn_node(
1008 "sym:rust:a.rs#caller",
1009 "caller",
1010 &["target", "dup", "missing"],
1011 ))
1012 .with_node(fn_node("sym:rust:a.rs#target", "target", &[]))
1013 // Two functions named `dup` → ambiguous, must not be linked.
1014 .with_node(fn_node("sym:rust:a.rs#dup", "dup", &[]))
1015 .with_node(fn_node("sym:rust:b.rs#dup", "dup", &[]));
1016
1017 resolve_calls(&mut fs);
1018
1019 let calls: Vec<_> = fs
1020 .edges
1021 .iter()
1022 .filter(|e| e.kind == EdgeKind::Calls)
1023 .collect();
1024 assert_eq!(
1025 calls.len(),
1026 1,
1027 "only the unambiguous, known callee is linked"
1028 );
1029 assert_eq!(calls[0].src, "sym:rust:a.rs#caller");
1030 assert_eq!(calls[0].dst, "sym:rust:a.rs#target");
1031 }
1032
1033 #[test]
1034 fn cache_key_separates_paths_but_is_stable() {
1035 let oid = "abc123";
1036 // Same path + oid + env is stable across calls.
1037 assert_eq!(cache_key("src/a.rs", oid, 0), cache_key("src/a.rs", oid, 0));
1038 // Same blob content (oid) at two different paths must not collide.
1039 assert_ne!(cache_key("src/a.rs", oid, 0), cache_key("src/b.rs", oid, 0));
1040 // Different content at the same path differs too.
1041 assert_ne!(
1042 cache_key("src/a.rs", "aaa", 0),
1043 cache_key("src/a.rs", "bbb", 0)
1044 );
1045 // A different extractor environment (e.g. OCR models installed) differs,
1046 // so image facts are re-extracted when the models change.
1047 assert_ne!(
1048 cache_key("src/a.rs", oid, 0),
1049 cache_key("src/a.rs", oid, 42)
1050 );
1051 // Key stays sharded on the oid so the cache's 2-char shard is well spread.
1052 assert!(cache_key("src/a.rs", oid, 0).starts_with("abc123-"));
1053 // The extractor version is folded in, so a bump retires old entries.
1054 assert!(
1055 cache_key("src/a.rs", oid, 0)
1056 .contains(&format!("-v{}", crate::extract::EXTRACT_VERSION))
1057 );
1058 }
1059
1060 /// The sweep predicate's one input. The round trip is what makes the sweep
1061 /// safe: a key this module just wrote must decode to *this* generation, or a
1062 /// pass at the current version would delete its own live entries.
1063 #[test]
1064 fn key_generation_round_trips_the_key_this_module_writes() {
1065 let key = cache_key("src/a.rs", "abc123", 0);
1066 assert_eq!(
1067 key_generation(&key),
1068 Some(crate::extract::EXTRACT_BASE_VERSION),
1069 "a key written now decodes to the current generation: {key}",
1070 );
1071 // …and so does the same generation in another feature build's namespace,
1072 // which is the whole reason the namespace is masked off rather than
1073 // compared. Both are live at once on a machine that runs the default and
1074 // `--all-features` test suites over one repository.
1075 let base = crate::extract::EXTRACT_BASE_VERSION;
1076 for namespace in [100, 200, 300, 400, 500, 600, 700] {
1077 let other = format!(
1078 "abc123-0000000000000000-v{}-e0000000000000000",
1079 base + namespace
1080 );
1081 assert_eq!(
1082 key_generation(&other),
1083 Some(base),
1084 "namespace {namespace} is not a different generation",
1085 );
1086 }
1087 }
1088
1089 /// Every doubt resolves to `None`, and `None` retains. These are the strings
1090 /// that must *not* be read as a generation — each one would otherwise put a
1091 /// file nobody can identify in reach of a delete.
1092 #[test]
1093 fn key_generation_refuses_anything_it_did_not_write() {
1094 for not_a_key in [
1095 "",
1096 "abc123", // no tail at all
1097 "abc123-0000000000000000-v12", // no env tag
1098 "abc123-0000000000000000-e0000000000000000", // no version tag
1099 "abc123-0000000000000000-v12-e00000000000000", // env too short
1100 "abc123-0000000000000000-v12-e00000000000000000", // env too long
1101 "abc123-0000000000000000-v12-egggggggggggggggg", // env not hex
1102 "abc123-0000000000000000-v+12-e0000000000000000", // `+12` parses as 12
1103 "abc123-0000000000000000-v-e0000000000000000", // empty version
1104 "abc123-0000000000000000-v1 2-e0000000000000000", // not all digits
1105 "abc123-0000000000000000-v99999999999-e0000000000000000", // overflows u32
1106 ] {
1107 assert_eq!(
1108 key_generation(not_a_key),
1109 None,
1110 "`{not_a_key}` must not be read as a generation",
1111 );
1112 }
1113 }
1114
1115 /// The sweep's contract, on a cache holding one entry per generation and
1116 /// namespace: the current generation survives in **every** namespace, the
1117 /// retained generations survive, older ones go, and a *newer* one — written
1118 /// by a binary ahead of this one sharing the same common git dir — is never
1119 /// touched, whatever the retention.
1120 #[test]
1121 fn sweep_superseded_keeps_current_future_and_kept_generations() {
1122 let base = crate::extract::EXTRACT_BASE_VERSION;
1123 let dir = std::env::temp_dir().join(format!("roteiro-gc-{}", std::process::id()));
1124 std::fs::remove_dir_all(&dir).ok();
1125 let cache = ObjectCache::open(&dir).expect("open");
1126
1127 let key = |version: u32| format!("abc123-0000000000000000-v{version}-e0000000000000000");
1128 let ancient = key(base - 2);
1129 let previous = key(base - 1);
1130 let current = key(base);
1131 let current_all_features = key(base + 700);
1132 let future = key(base + 1);
1133 let foreign = "not-a-roteiro-cache-key".to_owned();
1134 for k in [
1135 &ancient,
1136 &previous,
1137 ¤t,
1138 ¤t_all_features,
1139 &future,
1140 &foreign,
1141 ] {
1142 cache.put(k, &FactSet::new()).expect("put");
1143 }
1144
1145 // Keeping one generation back: only `base - 2` is unreachable.
1146 let swept =
1147 super::sweep_superseded(&cache, super::DEFAULT_KEEP_GENERATIONS).expect("sweep");
1148 assert_eq!(swept.sweep.removed, 1, "{swept:?}");
1149 // Retention is not one class, and the report says which. Two entries sit
1150 // at this generation (the two namespaces), one behind it, one ahead of
1151 // it, and one key that does not parse — each counted under its own
1152 // reason, because a summary that folded them together would describe an
1153 // irreversible operation inaccurately.
1154 assert_eq!(
1155 (
1156 swept.kept_current,
1157 swept.kept_recent,
1158 swept.kept_ahead,
1159 swept.kept_unrecognised,
1160 ),
1161 (2, 1, 1, 1),
1162 "{swept:?}",
1163 );
1164 assert_eq!(
1165 swept.kept_total(),
1166 swept.sweep.retained,
1167 "the four reasons must partition the retained total: {swept:?}",
1168 );
1169 assert!(!cache.contains(&ancient));
1170 for k in [
1171 &previous,
1172 ¤t,
1173 ¤t_all_features,
1174 &future,
1175 &foreign,
1176 ] {
1177 assert!(cache.contains(k), "`{k}` must survive a keep-1 sweep");
1178 }
1179
1180 // Keeping none: the previous generation goes too, and nothing else does.
1181 let swept = super::sweep_superseded(&cache, 0).expect("sweep");
1182 assert_eq!(swept.sweep.removed, 1, "{swept:?}");
1183 assert!(!cache.contains(&previous));
1184 for k in [¤t, ¤t_all_features, &future, &foreign] {
1185 assert!(cache.contains(k), "`{k}` must survive a keep-0 sweep");
1186 }
1187
1188 // A repeat pass is a no-op: nothing reachable is ever swept "eventually".
1189 let swept = super::sweep_superseded(&cache, 0).expect("sweep");
1190 assert_eq!(swept.sweep.removed, 0, "{swept:?}");
1191 assert_eq!(swept.sweep.retained, 4, "{swept:?}");
1192
1193 std::fs::remove_dir_all(&dir).expect("cleanup");
1194 }
1195}