Skip to main content

mbx_cache_store/
lib.rs

1//! Store inspection and garbage collection.
2//!
3//! The store holds six trees: `cas/v1` for content-addressed objects,
4//! `action-results/v1` for the results that reference them, `task-manifests/v1`
5//! for the prediction index, `checkouts/v1` for the checkouts that have built
6//! each identity, `build-receipts/v1` for exact completed build closures, and
7//! `sessions/v1` for per-build event streams. Only the first two are collected
8//! for size; manifests and receipts are small, checkout records expire with
9//! their checkout claims, and session streams are bounded by age and count
10//! because they are history rather than cache content.
11
12mod events;
13
14use eyre::{Context, Result};
15use mbx_cache_core::{
16    ActionPrediction, CacheDigest, CacheDirectory, LocalCas, RemoteActionResult, RustcMetadata,
17    TaskActionManifest, is_task_identity, task_manifest_actions,
18};
19use serde::{Deserialize, Serialize};
20use std::collections::{BTreeMap, BTreeSet, HashSet};
21use std::path::{Component, Path, PathBuf};
22use std::time::{Duration, SystemTime, UNIX_EPOCH};
23
24const CAS_DIR: &str = "cas/v1";
25const ACTION_RESULTS_DIR: &str = "action-results/v1";
26const CHECKOUTS_DIR: &str = "checkouts/v1";
27const SWEEP_STAMP: &str = "gc/v1/last-sweep";
28const SWEEP_LOCK: &str = "gc/v1/sweep.lock";
29const CHECKOUT_RECORD_VERSION: u8 = 1;
30const BUILD_RECEIPTS_DIR: &str = "build-receipts/v1";
31const BUILD_RECEIPT_VERSION: u8 = 1;
32const EXPORT_MANIFEST: &str = "mbx-cache-export-v1.json";
33const EXPORT_VERSION: u8 = 2;
34const LEGACY_EXPORT_VERSION: u8 = 1;
35
36const SESSION_RETENTION: Duration = Duration::from_secs(7 * 24 * 60 * 60);
37const MAX_SESSIONS: usize = 256;
38
39/// How long a checkout's claim outlives the last build that renewed it.
40///
41/// Existence alone is not enough to keep a claim alive. An identity covers one
42/// exact command line against one exact lockfile, so a checkout that lives for
43/// years accumulates an identity per lockfile it ever had -- and every one of
44/// them would go on rooting the actions of a build nobody will run again.
45/// Without this bound the rooted set only grows, until everything is rooted and
46/// the ordering means nothing. A build renews the claims it uses, so anything
47/// this stale belongs to a command that has moved on.
48const CHECKOUT_RETENTION: Duration = Duration::from_secs(30 * 24 * 60 * 60);
49
50#[derive(Debug, Default, PartialEq, Eq)]
51pub struct StoreStats {
52    pub objects: u64,
53    pub object_bytes: u64,
54    pub action_results: u64,
55    pub action_result_bytes: u64,
56    pub live_checkouts: u64,
57    /// Claims that root nothing any more: a checkout that is gone, or one that
58    /// is still there but has not renewed this claim inside the retention
59    /// window. Reported as stale rather than gone because those are different
60    /// things and only one of them means the directory is missing.
61    pub stale_checkouts: u64,
62}
63
64impl StoreStats {
65    pub fn total_bytes(&self) -> u64 {
66        self.object_bytes.saturating_add(self.action_result_bytes)
67    }
68}
69
70#[derive(Debug, Default, PartialEq, Eq)]
71pub struct GcOutcome {
72    pub removed_objects: u64,
73    pub removed_action_results: u64,
74    pub removed_checkout_records: u64,
75    /// Event streams dropped on age or count. These bytes are not included in
76    /// `remaining_bytes` because session history is not cache content.
77    pub removed_session_streams: u64,
78    pub removed_bytes: u64,
79    pub remaining_bytes: u64,
80}
81
82#[derive(Debug, PartialEq, Eq)]
83pub struct ProjectUsage {
84    pub workspace_root: PathBuf,
85    pub identities: u64,
86    pub action_bytes: u64,
87    pub target_bytes: u64,
88    pub live: bool,
89}
90
91#[derive(Debug, PartialEq, Eq)]
92pub struct LargestEntry {
93    pub kind: &'static str,
94    pub path: PathBuf,
95    pub bytes: u64,
96}
97
98#[derive(Debug, Default, PartialEq, Eq)]
99pub struct VerifyOutcome {
100    pub checked_objects: u64,
101    pub checked_action_results: u64,
102    pub problems: Vec<PathBuf>,
103}
104
105#[derive(Debug, Default, PartialEq, Eq)]
106pub struct RemoveProjectOutcome {
107    pub removed_checkout_records: u64,
108}
109
110#[derive(Debug, Default, PartialEq, Eq)]
111pub struct TransferOutcome {
112    pub actions: u64,
113    pub objects: u64,
114    pub bytes: u64,
115}
116
117/// A cache import together with named higher-level CAS roots it carried.
118#[derive(Debug)]
119#[non_exhaustive]
120pub struct ImportOutcome {
121    pub transfer: TransferOutcome,
122    pub attachments: BTreeMap<String, CacheDigest>,
123}
124
125/// Extra CAS roots carried by a cache export for a higher-level transport.
126#[derive(Debug, Default)]
127pub struct ExportAdditions {
128    /// Stable names by which the importer can discover selected objects.
129    pub attachments: BTreeMap<String, CacheDigest>,
130    /// Every object the attachments reach, including the named objects.
131    pub objects: BTreeSet<CacheDigest>,
132}
133
134/// One Cargo workspace and the target directory recorded for its build.
135#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
136pub struct WorkspaceTarget {
137    pub workspace_root: PathBuf,
138    pub target_dir: PathBuf,
139}
140
141#[derive(Debug, Serialize, Deserialize)]
142#[serde(deny_unknown_fields)]
143struct ExportManifest {
144    version: u8,
145    tasks: Vec<TaskActionManifest>,
146    actions: Vec<CacheDigest>,
147    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
148    attachments: BTreeMap<String, CacheDigest>,
149    #[serde(default, skip_serializing_if = "Vec::is_empty")]
150    objects: Vec<CacheDigest>,
151}
152
153/// The exact cache predictions completed by one top-level build command.
154#[derive(Debug, Clone, Serialize, Deserialize)]
155#[serde(deny_unknown_fields)]
156struct BuildReceipt {
157    version: u8,
158    workspace_root: PathBuf,
159    identity: String,
160    completed_nanos: u64,
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    group: Option<String>,
163    predictions: Vec<ActionPrediction>,
164}
165
166/// Record an exact completed build for checkout and grouped exports.
167pub fn record_build_receipt(
168    store: &Path,
169    run: &str,
170    identity: &str,
171    workspace_root: &Path,
172    group: Option<&str>,
173    predictions: Vec<ActionPrediction>,
174) -> Result<()> {
175    if !is_task_identity(run) || !is_task_identity(identity) {
176        eyre::bail!("invalid build receipt identity");
177    }
178    if !(TaskActionManifest {
179        version: 1,
180        task: identity.to_owned(),
181        predictions: predictions.clone(),
182    })
183    .validate()
184    {
185        eyre::bail!("invalid build receipt prediction");
186    }
187    if let Some(group) = group {
188        validate_export_group(group)?;
189    }
190    let key = workspace_key(workspace_root);
191    let lock_path = store
192        .join(BUILD_RECEIPTS_DIR)
193        .join("locks")
194        .join(format!("{key}.lock"));
195    std::fs::create_dir_all(lock_path.parent().expect("receipt lock has a parent"))?;
196    let mut lock = fslock::LockFile::open(&lock_path)?;
197    lock.lock()?;
198    let completed_nanos = SystemTime::now()
199        .duration_since(UNIX_EPOCH)
200        .map(|elapsed| elapsed.as_nanos().try_into().unwrap_or(u64::MAX))
201        .unwrap_or_default();
202    let receipt = BuildReceipt {
203        version: BUILD_RECEIPT_VERSION,
204        workspace_root: workspace_root.to_path_buf(),
205        identity: identity.to_owned(),
206        completed_nanos,
207        group: group.map(str::to_owned),
208        predictions,
209    };
210    let bytes = serde_json::to_vec(&receipt)?;
211    write_atomic(&latest_receipt_path(store, workspace_root), &bytes)?;
212    if let Some(group) = group {
213        write_atomic(&group_receipt_path(store, group, run), &bytes)?;
214    }
215    Ok(())
216}
217
218fn workspace_key(workspace_root: &Path) -> String {
219    CacheDigest::blake3(workspace_root.to_string_lossy().as_bytes()).hash
220}
221
222fn latest_receipt_path(store: &Path, workspace_root: &Path) -> PathBuf {
223    store
224        .join(BUILD_RECEIPTS_DIR)
225        .join("checkouts")
226        .join(format!("{}.json", workspace_key(workspace_root)))
227}
228
229fn group_receipt_path(store: &Path, group: &str, run: &str) -> PathBuf {
230    store
231        .join(BUILD_RECEIPTS_DIR)
232        .join("groups")
233        .join(group_key(group))
234        .join(format!("{run}.json"))
235}
236
237fn group_key(group: &str) -> String {
238    CacheDigest::blake3(group.as_bytes()).hash
239}
240
241fn read_build_receipt(path: &Path) -> Option<BuildReceipt> {
242    let bytes = std::fs::read(path).ok()?;
243    let receipt = serde_json::from_slice::<BuildReceipt>(&bytes).ok()?;
244    let valid = TaskActionManifest {
245        version: 1,
246        task: receipt.identity.clone(),
247        predictions: receipt.predictions.clone(),
248    }
249    .validate();
250    (receipt.version == BUILD_RECEIPT_VERSION && valid).then_some(receipt)
251}
252
253fn validate_export_group(group: &str) -> Result<()> {
254    if group.is_empty() || group.len() > 256 || group.chars().any(char::is_control) {
255        eyre::bail!("invalid build export group");
256    }
257    Ok(())
258}
259
260/// Export the complete local cache closure of this checkout's most recent build.
261pub fn export_checkout(
262    store: &Path,
263    workspace_root: &Path,
264    archive: &Path,
265) -> Result<TransferOutcome> {
266    let receipt = read_build_receipt(&latest_receipt_path(store, workspace_root))
267        .filter(|receipt| receipt.workspace_root == workspace_root)
268        .ok_or_else(|| {
269            eyre::eyre!(
270                "no completed mbx build is recorded for {}",
271                workspace_root.display()
272            )
273        })?;
274    export_receipts(store, vec![receipt], archive, ExportAdditions::default())
275}
276
277/// Return the target directory recorded for this checkout's latest build.
278pub fn checkout_workspace_target(
279    store: &Path,
280    workspace_root: &Path,
281) -> Result<Option<WorkspaceTarget>> {
282    let Some(receipt) = read_build_receipt(&latest_receipt_path(store, workspace_root))
283        .filter(|receipt| receipt.workspace_root == workspace_root)
284    else {
285        return Ok(None);
286    };
287    Ok(workspace_target_for_receipt(store, &receipt))
288}
289
290/// Return every Cargo target represented by the pending receipts in a group.
291pub fn group_workspace_targets(store: &Path, group: &str) -> Result<Vec<WorkspaceTarget>> {
292    validate_export_group(group)?;
293    let root = store
294        .join(BUILD_RECEIPTS_DIR)
295        .join("groups")
296        .join(group_key(group));
297    let targets = walk_files(&root)?
298        .into_iter()
299        .filter_map(|entry| read_build_receipt(&entry.path))
300        .filter(|receipt| receipt.group.as_deref() == Some(group))
301        .filter_map(|receipt| workspace_target_for_receipt(store, &receipt))
302        .collect::<BTreeSet<_>>();
303    Ok(targets.into_iter().collect())
304}
305
306fn workspace_target_for_receipt(store: &Path, receipt: &BuildReceipt) -> Option<WorkspaceTarget> {
307    let record = read_checkout_record(&checkout_record_path(
308        store,
309        &receipt.identity,
310        &receipt.workspace_root,
311    ))?;
312    (record.workspace_root == receipt.workspace_root && record.target_dir != record.workspace_root)
313        .then_some(WorkspaceTarget {
314            workspace_root: record.workspace_root,
315            target_dir: record.target_dir,
316        })
317}
318
319/// Export one checkout's closure together with higher-level CAS attachments.
320pub fn export_checkout_with(
321    store: &Path,
322    workspace_root: &Path,
323    archive: &Path,
324    additions: ExportAdditions,
325) -> Result<TransferOutcome> {
326    let receipt = read_build_receipt(&latest_receipt_path(store, workspace_root))
327        .filter(|receipt| receipt.workspace_root == workspace_root)
328        .ok_or_else(|| {
329            eyre::eyre!(
330                "no completed mbx build is recorded for {}",
331                workspace_root.display()
332            )
333        })?;
334    export_receipts(store, vec![receipt], archive, additions)
335}
336
337/// Export the union of every completed build recorded under one CI group.
338pub fn export_group(store: &Path, group: &str, archive: &Path) -> Result<TransferOutcome> {
339    export_group_with(store, group, archive, ExportAdditions::default())
340}
341
342/// Export a grouped closure together with higher-level CAS attachments.
343pub fn export_group_with(
344    store: &Path,
345    group: &str,
346    archive: &Path,
347    additions: ExportAdditions,
348) -> Result<TransferOutcome> {
349    validate_export_group(group)?;
350    let root = store
351        .join(BUILD_RECEIPTS_DIR)
352        .join("groups")
353        .join(group_key(group));
354    let receipts = walk_files(&root)?
355        .into_iter()
356        .filter_map(|entry| read_build_receipt(&entry.path).map(|receipt| (entry.path, receipt)))
357        .filter(|(_, receipt)| receipt.group.as_deref() == Some(group))
358        .collect::<Vec<_>>();
359    if receipts.is_empty() {
360        eyre::bail!("no completed mbx builds are recorded for export group {group:?}");
361    }
362    let outcome = export_receipts(
363        store,
364        receipts
365            .iter()
366            .map(|(_, receipt)| receipt.clone())
367            .collect(),
368        archive,
369        additions,
370    )?;
371    // A receipt is a pending-export root. Retire only the files this export
372    // consumed, and only after its complete archive has been published. A
373    // concurrent build can add another uniquely named receipt to the group
374    // without this cleanup deleting work the archive did not include.
375    for (path, _) in receipts {
376        std::fs::remove_file(path)?;
377    }
378    let _ = std::fs::remove_dir(root);
379    Ok(outcome)
380}
381
382fn export_receipts(
383    store: &Path,
384    mut receipts: Vec<BuildReceipt>,
385    archive: &Path,
386    additions: ExportAdditions,
387) -> Result<TransferOutcome> {
388    receipts.sort_by_key(|receipt| receipt.completed_nanos);
389    let mut actions = BTreeSet::new();
390    let mut tasks = BTreeMap::new();
391    for receipt in receipts {
392        actions.extend(
393            receipt
394                .predictions
395                .iter()
396                .map(|prediction| prediction.action.clone()),
397        );
398        // One task manifest can carry only one action per invocation. The
399        // newest run of the same task is the useful prediction set to import;
400        // every older action remains in `actions` and therefore in the bundle.
401        tasks.insert(
402            receipt.identity.clone(),
403            TaskActionManifest {
404                version: 1,
405                task: receipt.identity,
406                predictions: receipt.predictions,
407            },
408        );
409    }
410    let tasks = tasks.into_values().collect::<Vec<_>>();
411    validate_export_additions(&additions)?;
412    let (mut objects, result_paths) = strict_closure(store, &actions)?;
413    let cas = LocalCas::new(store);
414    for digest in &additions.objects {
415        require_object(&cas, &mut objects, digest)?;
416    }
417    let parent = archive
418        .parent()
419        .filter(|parent| !parent.as_os_str().is_empty())
420        .unwrap_or_else(|| Path::new("."));
421    std::fs::create_dir_all(parent)?;
422    let temporary = tempfile::Builder::new()
423        .prefix(".mbx-export-")
424        .tempfile_in(parent)?;
425    let mut builder = tar::Builder::new(temporary.reopen()?);
426    append_bytes(
427        &mut builder,
428        Path::new(EXPORT_MANIFEST),
429        &serde_json::to_vec(&ExportManifest {
430            version: if additions.attachments.is_empty() && additions.objects.is_empty() {
431                LEGACY_EXPORT_VERSION
432            } else {
433                EXPORT_VERSION
434            },
435            tasks,
436            actions: actions.iter().cloned().collect(),
437            attachments: additions.attachments.clone(),
438            objects: additions.objects.iter().cloned().collect(),
439        })?,
440    )?;
441    for path in objects.iter().chain(result_paths.iter()) {
442        append_file(&mut builder, store, path)?;
443    }
444    builder.finish()?;
445    drop(builder);
446    temporary
447        .persist(archive)
448        .map_err(|error| error.error)
449        .wrap_err_with(|| format!("failed to publish {}", archive.display()))?;
450    let bytes = std::fs::metadata(archive)?.len();
451    Ok(TransferOutcome {
452        actions: actions.len() as u64,
453        objects: objects.len() as u64,
454        bytes,
455    })
456}
457
458/// Validate a cache export in isolation, then publish its objects and actions.
459pub fn import_archive(store: &Path, archive: &Path) -> Result<TransferOutcome> {
460    Ok(import_archive_with_attachments(store, archive)?.transfer)
461}
462
463/// Import a cache archive and return its named higher-level CAS roots.
464pub fn import_archive_with_attachments(store: &Path, archive: &Path) -> Result<ImportOutcome> {
465    let staging = tempfile::tempdir()?;
466    let file = std::fs::File::open(archive)
467        .wrap_err_with(|| format!("failed to open {}", archive.display()))?;
468    let mut bundle = tar::Archive::new(file);
469    let mut seen = BTreeSet::new();
470    for entry in bundle.entries()? {
471        let mut entry = entry?;
472        let entry_type = entry.header().entry_type();
473        if !entry_type.is_file() && !entry_type.is_gnu_sparse() {
474            eyre::bail!("cache export contains a non-file entry");
475        }
476        let path = entry.path()?.into_owned();
477        validate_archive_path(&path)?;
478        if !seen.insert(path.clone()) {
479            eyre::bail!("cache export contains duplicate entry {}", path.display());
480        }
481        let destination = staging.path().join(&path);
482        std::fs::create_dir_all(destination.parent().expect("entry has a parent"))?;
483        // `unpack` understands GNU sparse maps. A plain stream copy expands
484        // holes into physical zeroes, which is both slower and much larger for
485        // Rust artifacts containing sparse sections.
486        entry.unpack(&destination)?;
487    }
488    let manifest: ExportManifest =
489        serde_json::from_slice(&std::fs::read(staging.path().join(EXPORT_MANIFEST))?)?;
490    let actions = manifest.actions.iter().cloned().collect::<BTreeSet<_>>();
491    let task_identities = manifest
492        .tasks
493        .iter()
494        .map(|task| task.task.as_str())
495        .collect::<BTreeSet<_>>();
496    if !matches!(manifest.version, LEGACY_EXPORT_VERSION | EXPORT_VERSION)
497        || (manifest.version == LEGACY_EXPORT_VERSION
498            && (!manifest.attachments.is_empty() || !manifest.objects.is_empty()))
499        || manifest.tasks.is_empty()
500        || actions.len() != manifest.actions.len()
501        || task_identities.len() != manifest.tasks.len()
502        || manifest.tasks.iter().any(|task| !task.validate())
503        || manifest
504            .actions
505            .iter()
506            .any(|action| action.algorithm != "blake3" || action.validate().is_err())
507        || manifest.tasks.iter().any(|task| {
508            task.predictions
509                .iter()
510                .any(|prediction| !actions.contains(&prediction.action))
511        })
512        || manifest
513            .attachments
514            .keys()
515            .any(|name| !valid_attachment_name(name))
516        || manifest.attachments.values().any(|digest| {
517            digest.algorithm != "blake3"
518                || digest.validate().is_err()
519                || !manifest.objects.contains(digest)
520        })
521        || manifest.objects.iter().collect::<BTreeSet<_>>().len() != manifest.objects.len()
522        || manifest
523            .objects
524            .iter()
525            .any(|digest| digest.algorithm != "blake3" || digest.validate().is_err())
526    {
527        eyre::bail!("unsupported or invalid cache export manifest");
528    }
529    let (mut objects, result_paths) = strict_closure(staging.path(), &actions)
530        .wrap_err("cache export is incomplete or corrupt")?;
531    let staged_cas = LocalCas::new(staging.path());
532    for digest in &manifest.objects {
533        require_object(&staged_cas, &mut objects, digest)
534            .wrap_err("cache export attachment is incomplete or corrupt")?;
535    }
536
537    let cas = LocalCas::new(store);
538    for path in &objects {
539        let relative = path.strip_prefix(staging.path())?;
540        let source = staging.path().join(relative);
541        let digest = addressed_digest(staging.path(), &source, false)
542            .ok_or_else(|| eyre::eyre!("invalid cache object path {}", relative.display()))?;
543        cas.store_file(&digest, &source)?;
544    }
545    let action_cache = mbx_cache_core::LocalActionCache::new(store);
546    for path in &result_paths {
547        let result: RemoteActionResult = serde_json::from_slice(&std::fs::read(path)?)?;
548        action_cache.store(&result)?;
549    }
550    for task in manifest.tasks {
551        merge_imported_manifest(store, task)?;
552    }
553    Ok(ImportOutcome {
554        transfer: TransferOutcome {
555            actions: actions.len() as u64,
556            objects: objects.len() as u64,
557            bytes: std::fs::metadata(archive)?.len(),
558        },
559        attachments: manifest.attachments,
560    })
561}
562
563fn validate_export_additions(additions: &ExportAdditions) -> Result<()> {
564    if additions
565        .attachments
566        .keys()
567        .any(|name| !valid_attachment_name(name))
568        || additions
569            .attachments
570            .values()
571            .any(|digest| !additions.objects.contains(digest))
572        || additions
573            .objects
574            .iter()
575            .any(|digest| digest.algorithm != "blake3" || digest.validate().is_err())
576    {
577        eyre::bail!("invalid cache export attachment");
578    }
579    Ok(())
580}
581
582fn valid_attachment_name(name: &str) -> bool {
583    !name.is_empty()
584        && name.len() <= 128
585        && name
586            .bytes()
587            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
588}
589
590fn strict_closure(
591    store: &Path,
592    actions: &BTreeSet<CacheDigest>,
593) -> Result<(BTreeSet<PathBuf>, BTreeSet<PathBuf>)> {
594    let cas = LocalCas::new(store);
595    let action_cache = mbx_cache_core::LocalActionCache::new(store);
596    let mut objects = BTreeSet::new();
597    let mut results = BTreeSet::new();
598    let mut directories = BTreeSet::new();
599    for action in actions {
600        let result = action_cache
601            .find(action)?
602            .ok_or_else(|| eyre::eyre!("action result is missing for {}", action.hash))?;
603        results.insert(action_cache.path_for(action)?);
604        require_object(&cas, &mut objects, &result.action)?;
605        if let Some(metadata) = &result.metadata {
606            require_object(&cas, &mut objects, metadata)?;
607            let captured: CapturedOutput =
608                serde_json::from_slice(&std::fs::read(cas.path_for(metadata)?)?)
609                    .wrap_err("action metadata is invalid")?;
610            require_object(&cas, &mut objects, &captured.stdout)?;
611            require_object(&cas, &mut objects, &captured.stderr)?;
612        }
613        if let Some(root) = &result.output_root {
614            require_object(&cas, &mut objects, root)?;
615            let mut pending = vec![root.clone()];
616            while let Some(digest) = pending.pop() {
617                if !directories.insert(digest.clone()) {
618                    continue;
619                }
620                let directory: CacheDirectory =
621                    serde_json::from_slice(&std::fs::read(cas.path_for(&digest)?)?)
622                        .wrap_err("output directory is invalid")?;
623                for file in directory.files {
624                    require_object(&cas, &mut objects, &file.digest)?;
625                }
626                for child in directory.directories {
627                    require_object(&cas, &mut objects, &child.digest)?;
628                    pending.push(child.digest);
629                }
630            }
631        }
632    }
633    Ok((objects, results))
634}
635
636#[derive(Deserialize)]
637struct CapturedOutput {
638    stdout: CacheDigest,
639    stderr: CacheDigest,
640}
641
642fn merge_imported_manifest(destination: &Path, mut imported: TaskActionManifest) -> Result<()> {
643    let identity = imported.task.clone();
644    let destination_path = task_manifest_path(destination, &identity);
645    if let Ok(bytes) = std::fs::read(&destination_path)
646        && let Ok(existing) = serde_json::from_slice::<TaskActionManifest>(&bytes)
647        && existing.task == identity
648        && existing.validate()
649    {
650        let mut predictions = imported
651            .predictions
652            .into_iter()
653            .map(|prediction| (prediction.invocation.clone(), prediction))
654            .collect::<BTreeMap<_, _>>();
655        predictions.extend(
656            existing
657                .predictions
658                .iter()
659                .cloned()
660                .map(|prediction| (prediction.invocation.clone(), prediction)),
661        );
662        imported.predictions = predictions.into_values().collect();
663        if !imported.validate() {
664            return Ok(());
665        }
666    }
667    write_atomic(&destination_path, &serde_json::to_vec(&imported)?)
668}
669
670fn require_object(
671    cas: &LocalCas,
672    objects: &mut BTreeSet<PathBuf>,
673    digest: &CacheDigest,
674) -> Result<()> {
675    let path = cas
676        .find(digest)?
677        .ok_or_else(|| eyre::eyre!("cache object is missing for {}", digest.hash))?;
678    objects.insert(path);
679    Ok(())
680}
681
682fn task_manifest_path(store: &Path, identity: &str) -> PathBuf {
683    store
684        .join("task-manifests/v1")
685        .join(format!("{identity}.json"))
686}
687
688fn append_file(builder: &mut tar::Builder<std::fs::File>, root: &Path, path: &Path) -> Result<()> {
689    let name = path.strip_prefix(root)?;
690    builder.append_path_with_name(path, name)?;
691    Ok(())
692}
693
694fn append_bytes(
695    builder: &mut tar::Builder<std::fs::File>,
696    name: &Path,
697    bytes: &[u8],
698) -> Result<()> {
699    let mut header = tar::Header::new_gnu();
700    header.set_size(bytes.len() as u64);
701    header.set_mode(0o644);
702    header.set_cksum();
703    builder.append_data(&mut header, name, bytes)?;
704    Ok(())
705}
706
707fn validate_archive_path(path: &Path) -> Result<()> {
708    if path.as_os_str().is_empty()
709        || path.is_absolute()
710        || path
711            .components()
712            .any(|component| !matches!(component, Component::Normal(_)))
713    {
714        eyre::bail!("cache export contains unsafe path {}", path.display());
715    }
716    let text = path.to_string_lossy();
717    if text != EXPORT_MANIFEST
718        && !text.starts_with("cas/v1/")
719        && !text.starts_with("action-results/v1/")
720    {
721        eyre::bail!("cache export contains unexpected path {}", path.display());
722    }
723    Ok(())
724}
725
726/// One checkout's claim on the actions a build identity recorded.
727///
728/// The target directory is not read back by anything yet; it is recorded
729/// because it is the other half of what the shim mapped, and a record that
730/// names only half of it would have to be rewritten to answer where the
731/// artifacts went.
732#[derive(Debug, Clone, Serialize, Deserialize)]
733#[serde(deny_unknown_fields)]
734struct CheckoutRecord {
735    version: u8,
736    workspace_root: PathBuf,
737    target_dir: PathBuf,
738    updated_secs: u64,
739}
740
741/// Summarize what the store currently holds.
742pub fn stats(store: &Path) -> Result<StoreStats> {
743    let objects = walk_files(&store.join(CAS_DIR))?;
744    let results = walk_files(&store.join(ACTION_RESULTS_DIR))?;
745    let checkouts = scan_checkouts(store)?;
746    Ok(StoreStats {
747        objects: objects.len() as u64,
748        object_bytes: objects.iter().map(|entry| entry.size).sum(),
749        action_results: results.len() as u64,
750        action_result_bytes: results.iter().map(|entry| entry.size).sum(),
751        live_checkouts: checkouts.live_records,
752        stale_checkouts: checkouts.stale_records.len() as u64,
753    })
754}
755
756/// Size the target tree a checkout record names, if it names one.
757///
758/// A build with no target directory of its own -- one driven by make or CMake,
759/// which writes wherever it was told -- records the checkout in that field
760/// rather than inventing a directory. Walking it would report the whole source
761/// tree, `.git` included, as though it were build output.
762fn checkout_target_bytes(sizes: &mut BTreeMap<PathBuf, u64>, record: &CheckoutRecord) -> u64 {
763    if record.target_dir == record.workspace_root {
764        return 0;
765    }
766    cached_tree_bytes(sizes, &record.target_dir)
767}
768
769/// Attribute cache and target bytes to each recorded workspace.
770///
771/// Shared objects are counted for every workspace that can reach them. That
772/// makes each row answer "how much keeps this workspace warm" without
773/// pretending shared storage can be divided exactly between projects.
774pub fn projects(store: &Path) -> Result<Vec<ProjectUsage>> {
775    let mut projects: BTreeMap<PathBuf, (BTreeSet<String>, bool, u64)> = BTreeMap::new();
776    let mut target_sizes = BTreeMap::new();
777    let root = store.join(CHECKOUTS_DIR);
778    for identity_entry in read_dir_or_empty(&root)? {
779        let identity = identity_entry.file_name().to_string_lossy().into_owned();
780        if !is_task_identity(&identity) || !identity_entry.file_type()?.is_dir() {
781            continue;
782        }
783        for entry in walk_files(&identity_entry.path())? {
784            let Some(record) = read_checkout_record(&entry.path) else {
785                continue;
786            };
787            let project = projects.entry(record.workspace_root.clone()).or_default();
788            if claim_is_live(store, &record) {
789                project.0.insert(identity.clone());
790                project.1 = true;
791            }
792            project.2 = project
793                .2
794                .max(checkout_target_bytes(&mut target_sizes, &record));
795        }
796    }
797    let action_cache = mbx_cache_core::LocalActionCache::new(store);
798    let mut usages = Vec::new();
799    for (workspace_root, (identities, live, target_bytes)) in projects {
800        let mut paths = rooted_objects(store, &identities)?;
801        for identity in &identities {
802            for action in task_manifest_actions(store, identity).unwrap_or_default() {
803                if let Ok(path) = action_cache.path_for(&action) {
804                    paths.insert(path);
805                }
806            }
807        }
808        let action_bytes = paths
809            .iter()
810            .filter_map(|path| std::fs::metadata(path).ok())
811            .map(|metadata| metadata.len())
812            .sum();
813        usages.push(ProjectUsage {
814            workspace_root,
815            identities: identities.len() as u64,
816            action_bytes,
817            target_bytes,
818            live,
819        });
820    }
821    usages.sort_by(|left, right| {
822        right
823            .action_bytes
824            .saturating_add(right.target_bytes)
825            .cmp(&left.action_bytes.saturating_add(left.target_bytes))
826            .then_with(|| left.workspace_root.cmp(&right.workspace_root))
827    });
828    Ok(usages)
829}
830
831/// Return the largest blobs and action-result records in descending order.
832pub fn largest(store: &Path, limit: usize) -> Result<Vec<LargestEntry>> {
833    let mut entries = Vec::new();
834    for (kind, root, action_result) in [
835        ("object", store.join(CAS_DIR), false),
836        ("action result", store.join(ACTION_RESULTS_DIR), true),
837    ] {
838        entries.extend(
839            walk_files(&root)?
840                .into_iter()
841                .filter(|entry| addressed_digest(store, &entry.path, action_result).is_some())
842                .map(|entry| LargestEntry {
843                    kind,
844                    path: entry.path,
845                    bytes: entry.size,
846                }),
847        );
848    }
849    entries.sort_by(|left, right| {
850        right
851            .bytes
852            .cmp(&left.bytes)
853            .then_with(|| left.path.cmp(&right.path))
854    });
855    entries.truncate(limit);
856    Ok(entries)
857}
858
859/// Verify every addressable CAS object and action-result record.
860pub fn verify(store: &Path) -> Result<VerifyOutcome> {
861    let cas = LocalCas::new(store);
862    let action_cache = mbx_cache_core::LocalActionCache::new(store);
863    // Verification reports the store as it is on disk and removes nothing, so
864    // no object is pending removal the way one is mid-sweep.
865    let virtually_removed = HashSet::new();
866    let mut outcome = VerifyOutcome::default();
867    for entry in walk_files(&store.join(CAS_DIR))? {
868        let Some(digest) = addressed_digest(store, &entry.path, false) else {
869            continue;
870        };
871        outcome.checked_objects += 1;
872        if !matches!(cas.find(&digest), Ok(Some(_))) {
873            outcome.problems.push(entry.path);
874        }
875    }
876    for entry in walk_files(&store.join(ACTION_RESULTS_DIR))? {
877        let Some(digest) = addressed_digest(store, &entry.path, true) else {
878            continue;
879        };
880        outcome.checked_action_results += 1;
881        if !matches!(action_cache.find(&digest), Ok(Some(_)))
882            || action_result_is_dangling(&cas, &entry.path, &virtually_removed)?
883        {
884            outcome.problems.push(entry.path);
885        }
886    }
887    outcome.problems.sort();
888    Ok(outcome)
889}
890
891/// Remove checkout claims belonging to exactly one workspace.
892pub fn remove_project(store: &Path, workspace_root: &Path) -> Result<RemoveProjectOutcome> {
893    let mut outcome = RemoveProjectOutcome::default();
894    for entry in walk_files(&store.join(CHECKOUTS_DIR))? {
895        if read_checkout_record(&entry.path)
896            .is_some_and(|record| record.workspace_root == workspace_root)
897        {
898            std::fs::remove_file(&entry.path)?;
899            outcome.removed_checkout_records += 1;
900            if let Some(parent) = entry.path.parent() {
901                let _ = std::fs::remove_dir(parent);
902            }
903        }
904    }
905    match std::fs::remove_file(latest_receipt_path(store, workspace_root)) {
906        Ok(()) => {}
907        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
908        Err(error) => return Err(error.into()),
909    }
910    Ok(outcome)
911}
912
913/// Record that `workspace_root` built `identity`.
914///
915/// Identities are shared by every checkout of one dependency graph, so this is
916/// what later tells the collector whether anything still needs what a build
917/// cached: one file per checkout under the identity it built. Writing a whole
918/// file per checkout rather than merging a list into one keeps concurrent
919/// builds out of each other's way -- there is nothing to merge, so there is no
920/// lock and no lost update.
921///
922/// A build with no target directory of its own passes `workspace_root` for
923/// `target_dir`, which reads as "none" rather than as a tree to measure.
924pub fn record_checkout(
925    store: &Path,
926    identity: &str,
927    workspace_root: &Path,
928    target_dir: &Path,
929) -> Result<()> {
930    let record = CheckoutRecord {
931        version: CHECKOUT_RECORD_VERSION,
932        workspace_root: workspace_root.to_path_buf(),
933        target_dir: target_dir.to_path_buf(),
934        updated_secs: SystemTime::now()
935            .duration_since(UNIX_EPOCH)
936            .map(|since| since.as_secs())
937            .unwrap_or_default(),
938    };
939    let mut contents = serde_json::to_vec(&record)?;
940    contents.push(b'\n');
941    // Refreshed by every build and read back only as a last-used stamp, so a
942    // power cut costs one build's worth of recency, not a wait on the disk.
943    write_advisory(
944        &checkout_record_path(store, identity, workspace_root),
945        &contents,
946    )
947}
948
949fn checkout_record_path(store: &Path, identity: &str, workspace_root: &Path) -> PathBuf {
950    // The path is hashed rather than escaped: it is only ever compared against
951    // the same hash of the same path, and every filesystem in play disagrees
952    // about which characters a name may hold.
953    let key = CacheDigest::blake3(workspace_root.to_string_lossy().as_bytes()).hash;
954    store
955        .join(CHECKOUTS_DIR)
956        .join(identity)
957        .join(format!("{key}.json"))
958}
959
960/// Evict objects until the store fits within `max_bytes`.
961///
962/// Objects no live checkout can reach are evicted first, so deleting a worktree
963/// releases what only that worktree needed. Within each class eviction is
964/// least-recently-used by access time where the filesystem records it, falling
965/// back to modification time. A restore verifies the blob it serves, which
966/// means it reads the whole file and the access time is real -- but only where
967/// the mount records one, so the ordering is an approximation either way.
968/// Evicting a live object costs a recompile, never correctness.
969pub fn gc(store: &Path, max_bytes: u64) -> Result<GcOutcome> {
970    gc_with_mode(store, max_bytes, false)
971}
972
973/// Describe the collection `gc` would perform without changing the store.
974pub fn gc_dry_run(store: &Path, max_bytes: u64) -> Result<GcOutcome> {
975    gc_with_mode(store, max_bytes, true)
976}
977
978fn gc_with_mode(store: &Path, max_bytes: u64, dry_run: bool) -> Result<GcOutcome> {
979    let mut objects = walk_files(&store.join(CAS_DIR))?;
980    let results = walk_files(&store.join(ACTION_RESULTS_DIR))?;
981    let mut live_bytes = objects
982        .iter()
983        .chain(results.iter())
984        .map(|entry| entry.size)
985        .sum::<u64>();
986
987    let mut outcome = GcOutcome::default();
988
989    // Prune before deciding what is rooted, so a checkout deleted since the
990    // last sweep stops protecting its artifacts during this one.
991    let checkouts = scan_checkouts(store)?;
992    for path in &checkouts.stale_records {
993        if dry_run || matches!(remove(path)?, Removal::Removed) {
994            outcome.removed_checkout_records += 1;
995        }
996        // The identity directory is left behind empty otherwise. It may hold
997        // other checkouts, in which case this fails and that is the answer.
998        if !dry_run && let Some(parent) = path.parent() {
999            let _ = std::fs::remove_dir(parent);
1000        }
1001    }
1002
1003    let mut virtually_removed = HashSet::new();
1004    if live_bytes > max_bytes {
1005        // Reachability costs a read per action result and per output tree, so
1006        // it is computed only when something is actually about to be evicted.
1007        // Under budget a sweep stays a directory walk and nothing more.
1008        let mut rooted = rooted_objects(store, &checkouts.live_identities)?;
1009        // A grouped CI export deliberately retains the exact actions from
1010        // every command in the job. Later commands can replace the current
1011        // task-manifest prediction for the same invocation, but the earlier
1012        // receipt still has to remain exportable until the post-job step runs.
1013        // Receipt bookkeeping is not part of the cache budget, so consult it
1014        // only when a sweep is already necessary and root its object closure.
1015        rooted.extend(rooted_action_objects(
1016            store,
1017            grouped_receipt_actions(store)?,
1018        ));
1019        // `false` sorts first, so unrooted objects go before rooted ones and
1020        // each class goes oldest-first. A store with no records at all roots
1021        // nothing and this is exactly the LRU it was before.
1022        objects.sort_by_cached_key(|entry| (rooted.contains(&entry.path), entry.used));
1023        let evicted = evict_objects(&objects, &rooted, live_bytes, max_bytes, |path| {
1024            if dry_run {
1025                virtually_removed.insert(path.to_path_buf());
1026                Ok(Removal::Removed)
1027            } else {
1028                remove(path)
1029            }
1030        })?;
1031        live_bytes = evicted.remaining_bytes;
1032        outcome.removed_objects += evicted.removed_objects;
1033        outcome.removed_bytes += evicted.removed_bytes;
1034    }
1035
1036    // An action result whose objects are gone can only produce a miss, so drop
1037    // it rather than leave the index pointing at nothing. This runs whether or
1038    // not this call evicted anything, since another process may have, and a
1039    // store that is over budget on results alone still needs the sweep.
1040    let cas = LocalCas::new(store);
1041    for entry in &results {
1042        if action_result_is_dangling(&cas, &entry.path, &virtually_removed)? {
1043            match if dry_run {
1044                Removal::Removed
1045            } else {
1046                remove(&entry.path)?
1047            } {
1048                Removal::Removed => {
1049                    live_bytes = live_bytes.saturating_sub(entry.size);
1050                    outcome.removed_action_results += 1;
1051                    outcome.removed_bytes += entry.size;
1052                }
1053                Removal::Missing => live_bytes = live_bytes.saturating_sub(entry.size),
1054                Removal::Blocked => {}
1055            }
1056        }
1057    }
1058
1059    let sessions = prune_sessions(store, dry_run)?;
1060    outcome.removed_session_streams += sessions.removed_streams;
1061    outcome.removed_bytes += sessions.removed_bytes;
1062
1063    outcome.remaining_bytes = live_bytes;
1064    Ok(outcome)
1065}
1066
1067#[derive(Debug, Default, PartialEq, Eq)]
1068struct SessionPrune {
1069    removed_streams: u64,
1070    removed_bytes: u64,
1071}
1072
1073fn prune_sessions(store: &Path, dry_run: bool) -> Result<SessionPrune> {
1074    let mut prune = SessionPrune::default();
1075    let ids = events::session_ids(store);
1076    let surplus = ids.len().saturating_sub(MAX_SESSIONS);
1077    for (index, id) in ids.iter().enumerate() {
1078        let paths = events::session_paths(store, id);
1079        let metadata = match std::fs::metadata(&paths.events) {
1080            Ok(metadata) => metadata,
1081            Err(_) => continue,
1082        };
1083        let stale = metadata
1084            .modified()
1085            .ok()
1086            .and_then(|at| SystemTime::now().duration_since(at).ok())
1087            .is_some_and(|age| age > SESSION_RETENTION);
1088        if index >= surplus && !stale {
1089            continue;
1090        }
1091        if events::session_is_live(store, id) {
1092            continue;
1093        }
1094        if dry_run {
1095            prune.removed_streams += 1;
1096            prune.removed_bytes += metadata.len();
1097            continue;
1098        }
1099        if matches!(remove(&paths.events)?, Removal::Removed) {
1100            prune.removed_streams += 1;
1101            prune.removed_bytes += metadata.len();
1102            let _ = std::fs::remove_file(&paths.lock);
1103        }
1104    }
1105    if !dry_run {
1106        for lock in events::orphaned_locks(store) {
1107            let _ = std::fs::remove_file(lock);
1108        }
1109    }
1110    Ok(prune)
1111}
1112
1113/// Sweep the store if `interval` has passed since the last attempt.
1114///
1115/// The stamp is written before the sweep, not after. Two builds finishing
1116/// together should cost one sweep between them, and a sweep that dies partway
1117/// should wait its turn like any other rather than retry on every build.
1118pub fn sweep_if_due(store: &Path, max_bytes: u64, interval: Duration) -> Result<Option<GcOutcome>> {
1119    if !claim_sweep(store, interval)? {
1120        return Ok(None);
1121    }
1122    gc(store, max_bytes).map(Some)
1123}
1124
1125/// Atomically stamp a due sweep before its callers perform coordinated GC.
1126pub fn claim_sweep(store: &Path, interval: Duration) -> Result<bool> {
1127    let lock_path = store.join(SWEEP_LOCK);
1128    std::fs::create_dir_all(lock_path.parent().expect("sweep lock has a parent"))?;
1129    let mut lock = fslock::LockFile::open(&lock_path)?;
1130    lock.lock()?;
1131
1132    let stamp = store.join(SWEEP_STAMP);
1133    if let Ok(metadata) = std::fs::metadata(&stamp)
1134        && let Ok(modified) = metadata.modified()
1135        && let Ok(since) = modified.elapsed()
1136        && since < interval
1137    {
1138        return Ok(false);
1139    }
1140    write_atomic(&stamp, b"")?;
1141    Ok(true)
1142}
1143
1144/// What the checkout registry says about the identities in this store.
1145struct CheckoutScan {
1146    live_identities: BTreeSet<String>,
1147    live_records: u64,
1148    stale_records: Vec<PathBuf>,
1149}
1150
1151fn scan_checkouts(store: &Path) -> Result<CheckoutScan> {
1152    let root = store.join(CHECKOUTS_DIR);
1153    let mut scan = CheckoutScan {
1154        live_identities: BTreeSet::new(),
1155        live_records: 0,
1156        stale_records: Vec::new(),
1157    };
1158    let listing = match std::fs::read_dir(&root) {
1159        Ok(listing) => listing,
1160        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(scan),
1161        Err(error) => {
1162            return Err(error).wrap_err_with(|| format!("failed to read {}", root.display()));
1163        }
1164    };
1165    for entry in listing {
1166        let entry = entry?;
1167        let name = entry.file_name().to_string_lossy().into_owned();
1168        // Anything that is not a directory named for an identity was not written
1169        // by mbx. Both halves matter: `walk_files` tolerates only a missing
1170        // directory, so a plain file whose name happens to look like an identity
1171        // would fail the whole scan -- and that scan runs inside every sweep,
1172        // including the automatic one after a build.
1173        if !is_task_identity(&name) || !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
1174            continue;
1175        }
1176        for record in walk_files(&entry.path())? {
1177            match read_checkout_record(&record.path) {
1178                Some(checkout) if claim_is_live(store, &checkout) => {
1179                    scan.live_identities.insert(name.clone());
1180                    scan.live_records += 1;
1181                }
1182                Some(_) => scan.stale_records.push(record.path),
1183                // A record this build cannot read claims nothing, but it is not
1184                // evidence the checkout is gone either, so leave it alone.
1185                None => {}
1186            }
1187        }
1188    }
1189    Ok(scan)
1190}
1191
1192fn read_checkout_record(path: &Path) -> Option<CheckoutRecord> {
1193    let bytes = std::fs::read(path).ok()?;
1194    let record = serde_json::from_slice::<CheckoutRecord>(&bytes).ok()?;
1195    (record.version == CHECKOUT_RECORD_VERSION).then_some(record)
1196}
1197
1198/// Actions whose successful grouped export has not retired its receipts yet.
1199fn grouped_receipt_actions(store: &Path) -> Result<BTreeSet<CacheDigest>> {
1200    let root = store.join(BUILD_RECEIPTS_DIR).join("groups");
1201    Ok(walk_files(&root)?
1202        .into_iter()
1203        .filter_map(|entry| read_build_receipt(&entry.path))
1204        .flat_map(|receipt| receipt.predictions.into_iter())
1205        .map(|prediction| prediction.action)
1206        .collect())
1207}
1208
1209/// Whether a recorded claim still speaks for a checkout that is using this
1210/// store.
1211fn claim_is_live(store: &Path, record: &CheckoutRecord) -> bool {
1212    checkout_is_live_on(store, &record.workspace_root) && !claim_has_expired(record)
1213}
1214
1215fn claim_has_expired(record: &CheckoutRecord) -> bool {
1216    let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) else {
1217        return false;
1218    };
1219    now.as_secs()
1220        .saturating_sub(record.updated_secs)
1221        .gt(&CHECKOUT_RETENTION.as_secs())
1222}
1223
1224/// Whether the checkout a record names is still on disk.
1225///
1226/// Absence is believed only when the checkout is definitely absent and its
1227/// nearest existing ancestor is on the same filesystem as the store. Walking
1228/// all the way to that ancestor matters for worktree managers and temporary
1229/// directories, which commonly remove a checkout together with one or more of
1230/// its otherwise-empty parents.
1231///
1232/// A different filesystem can be a mount whose contents are temporarily
1233/// unavailable, so uncertainty there remains live. Errors are treated the same
1234/// way: being wrong in that direction only delays collection; the other way
1235/// round throws away a warm cache someone is still using.
1236pub fn checkout_is_live_on(store: &Path, workspace_root: &Path) -> bool {
1237    if !matches!(workspace_root.try_exists(), Ok(false)) {
1238        return true;
1239    }
1240
1241    let Ok(store_metadata) = std::fs::metadata(store) else {
1242        return true;
1243    };
1244    for ancestor in workspace_root.ancestors().skip(1) {
1245        match std::fs::metadata(ancestor) {
1246            Ok(ancestor_metadata) => {
1247                return !same_filesystem(store, &store_metadata, ancestor, &ancestor_metadata);
1248            }
1249            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1250            Err(_) => return true,
1251        }
1252    }
1253    true
1254}
1255
1256/// Whether a checkout is still on disk, corroborating absence through its
1257/// immediate parent.
1258///
1259/// Prefer [`checkout_is_live_on`] when an existing store or managed-target
1260/// root is available to distinguish deletion from an unavailable filesystem.
1261pub fn checkout_is_live(workspace_root: &Path) -> bool {
1262    let Some(parent) = workspace_root.parent() else {
1263        return true;
1264    };
1265    checkout_is_live_on(parent, workspace_root)
1266}
1267
1268#[cfg(unix)]
1269fn same_filesystem(
1270    _a_path: &Path,
1271    a: &std::fs::Metadata,
1272    _b_path: &Path,
1273    b: &std::fs::Metadata,
1274) -> bool {
1275    use std::os::unix::fs::MetadataExt as _;
1276    a.dev() == b.dev()
1277}
1278
1279#[cfg(windows)]
1280fn same_filesystem(
1281    a_path: &Path,
1282    _a: &std::fs::Metadata,
1283    b_path: &Path,
1284    _b: &std::fs::Metadata,
1285) -> bool {
1286    windows_volume_name(a_path).is_some_and(|volume| windows_volume_name(b_path) == Some(volume))
1287}
1288
1289#[cfg(windows)]
1290fn windows_volume_name(path: &Path) -> Option<Vec<u16>> {
1291    use std::os::windows::ffi::OsStrExt as _;
1292    use windows_sys::Win32::Storage::FileSystem::{
1293        GetVolumeNameForVolumeMountPointW, GetVolumePathNameW,
1294    };
1295
1296    let path = path
1297        .as_os_str()
1298        .encode_wide()
1299        .chain(Some(0))
1300        .collect::<Vec<_>>();
1301    // Both APIs document MAX_PATH-sized output buffers for volume paths and
1302    // names. Failure is uncertainty, which deliberately keeps the checkout
1303    // live.
1304    let mut mount = vec![0_u16; 261];
1305    // SAFETY: `path` is nul-terminated and `mount` is writable for the stated
1306    // number of UTF-16 code units.
1307    if unsafe { GetVolumePathNameW(path.as_ptr(), mount.as_mut_ptr(), mount.len() as u32) } == 0 {
1308        return None;
1309    }
1310    let mut volume = vec![0_u16; 261];
1311    // SAFETY: the successful call above left `mount` nul-terminated, and
1312    // `volume` is writable for the stated number of UTF-16 code units.
1313    if unsafe {
1314        GetVolumeNameForVolumeMountPointW(mount.as_ptr(), volume.as_mut_ptr(), volume.len() as u32)
1315    } == 0
1316    {
1317        return None;
1318    }
1319    volume.truncate(volume.iter().position(|unit| *unit == 0)?);
1320    Some(volume)
1321}
1322
1323#[cfg(not(any(unix, windows)))]
1324fn same_filesystem(
1325    _a_path: &Path,
1326    _a: &std::fs::Metadata,
1327    _b_path: &Path,
1328    _b: &std::fs::Metadata,
1329) -> bool {
1330    false
1331}
1332
1333/// CAS paths reachable from the builds that live checkouts still depend on.
1334///
1335/// Recursing into output trees is the point: the descriptor blobs are tiny and
1336/// the leaf artifacts are where the bytes are, so rooting that stopped at the
1337/// top level would protect nothing worth protecting. Every read here is
1338/// tolerant -- a blob that has already been evicted, or that no longer parses,
1339/// simply roots less, and rooting less can only mean collecting sooner.
1340fn rooted_objects(store: &Path, identities: &BTreeSet<String>) -> Result<HashSet<PathBuf>> {
1341    let mut actions = BTreeSet::new();
1342    for identity in identities {
1343        // One manifest this build cannot read is not worth abandoning a sweep
1344        // over. It roots nothing, which can only mean collecting sooner.
1345        let manifest_actions = match task_manifest_actions(store, identity) {
1346            Ok(actions) => actions,
1347            Err(error) => {
1348                log::debug!("could not read the manifest for {identity}: {error}");
1349                continue;
1350            }
1351        };
1352        actions.extend(manifest_actions);
1353    }
1354    Ok(rooted_action_objects(store, actions))
1355}
1356
1357/// Return every local CAS path needed to restore the supplied actions.
1358fn rooted_action_objects(
1359    store: &Path,
1360    actions: impl IntoIterator<Item = CacheDigest>,
1361) -> HashSet<PathBuf> {
1362    let cas = LocalCas::new(store);
1363    let mut rooted = HashSet::new();
1364    let mut visited = BTreeSet::new();
1365    for action in actions {
1366        let Some(result) = read_action_result(store, &action) else {
1367            continue;
1368        };
1369        root_digest(&cas, &mut rooted, &result.action);
1370        if let Some(metadata) = &result.metadata {
1371            root_digest(&cas, &mut rooted, metadata);
1372            // The metadata blob is a descriptor too: it names the captured
1373            // stdout and stderr, and a restore reads both. Stopping at the
1374            // descriptor would leave the diagnostics of every action
1375            // unrooted -- including the one empty blob that every silent
1376            // compilation shares, which is enough on its own to turn a
1377            // rooted hit back into a miss.
1378            if let Some(rustc) = read_rustc_metadata(&cas, metadata) {
1379                root_digest(&cas, &mut rooted, &rustc.stdout);
1380                root_digest(&cas, &mut rooted, &rustc.stderr);
1381            }
1382        }
1383        if let Some(output_root) = &result.output_root {
1384            root_digest(&cas, &mut rooted, output_root);
1385            root_tree(&cas, output_root, &mut rooted, &mut visited);
1386        }
1387    }
1388    rooted
1389}
1390
1391fn read_action_result(store: &Path, action: &CacheDigest) -> Option<RemoteActionResult> {
1392    let path = mbx_cache_core::LocalActionCache::new(store)
1393        .path_for(action)
1394        .ok()?;
1395    let bytes = std::fs::read(path).ok()?;
1396    serde_json::from_slice(&bytes).ok()
1397}
1398
1399fn root_tree(
1400    cas: &LocalCas,
1401    output_root: &CacheDigest,
1402    rooted: &mut HashSet<PathBuf>,
1403    visited: &mut BTreeSet<CacheDigest>,
1404) {
1405    let mut pending = vec![output_root.clone()];
1406    while let Some(digest) = pending.pop() {
1407        if !visited.insert(digest.clone()) {
1408            continue;
1409        }
1410        let Some(directory) = read_directory(cas, &digest) else {
1411            continue;
1412        };
1413        for file in &directory.files {
1414            root_digest(cas, rooted, &file.digest);
1415        }
1416        for child in &directory.directories {
1417            root_digest(cas, rooted, &child.digest);
1418            pending.push(child.digest.clone());
1419        }
1420    }
1421}
1422
1423fn read_rustc_metadata(cas: &LocalCas, digest: &CacheDigest) -> Option<RustcMetadata> {
1424    let bytes = std::fs::read(cas.path_for(digest).ok()?).ok()?;
1425    serde_json::from_slice(&bytes).ok()
1426}
1427
1428fn read_directory(cas: &LocalCas, digest: &CacheDigest) -> Option<CacheDirectory> {
1429    let bytes = std::fs::read(cas.path_for(digest).ok()?).ok()?;
1430    serde_json::from_slice(&bytes).ok()
1431}
1432
1433fn root_digest(cas: &LocalCas, rooted: &mut HashSet<PathBuf>, digest: &CacheDigest) {
1434    if let Ok(path) = cas.path_for(digest) {
1435        rooted.insert(path);
1436    }
1437}
1438
1439#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1440enum Removal {
1441    Removed,
1442    Missing,
1443    Blocked,
1444}
1445
1446fn remove(path: &Path) -> Result<Removal> {
1447    match std::fs::remove_file(path) {
1448        Ok(()) => Ok(Removal::Removed),
1449        // A concurrent build may have evicted or replaced it already.
1450        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Removal::Missing),
1451        // Windows refuses to unlink a file another process holds open, which is
1452        // what a concurrent build reading this blob looks like. Skipping it
1453        // leaves the store over budget until the next sweep; failing would
1454        // abandon the sweep and leave it over budget for longer.
1455        Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {
1456            log::debug!("could not evict {}: {error}", path.display());
1457            Ok(Removal::Blocked)
1458        }
1459        Err(error) => Err(error).wrap_err_with(|| format!("failed to evict {}", path.display())),
1460    }
1461}
1462
1463#[derive(Debug, Default, PartialEq, Eq)]
1464struct ObjectEvictions {
1465    removed_objects: u64,
1466    removed_bytes: u64,
1467    remaining_bytes: u64,
1468}
1469
1470/// Evict sorted objects without crossing the checkout-protection boundary
1471/// when an unrooted object cannot be removed.
1472fn evict_objects(
1473    objects: &[Entry],
1474    rooted: &HashSet<PathBuf>,
1475    mut live_bytes: u64,
1476    max_bytes: u64,
1477    mut remove_file: impl FnMut(&Path) -> Result<Removal>,
1478) -> Result<ObjectEvictions> {
1479    let mut outcome = ObjectEvictions::default();
1480    let mut blocked_unrooted = false;
1481    for entry in objects {
1482        if live_bytes <= max_bytes {
1483            break;
1484        }
1485        let is_rooted = rooted.contains(&entry.path);
1486        if is_rooted && blocked_unrooted {
1487            // A locked unrooted blob is temporarily part of the irreducible
1488            // store. Deleting a live checkout's artifacts in its place would
1489            // invert the protection ordering this collector promises.
1490            break;
1491        }
1492        match remove_file(&entry.path)? {
1493            Removal::Removed => {
1494                live_bytes = live_bytes.saturating_sub(entry.size);
1495                outcome.removed_objects += 1;
1496                outcome.removed_bytes += entry.size;
1497            }
1498            Removal::Missing => live_bytes = live_bytes.saturating_sub(entry.size),
1499            Removal::Blocked if !is_rooted => blocked_unrooted = true,
1500            Removal::Blocked => {}
1501        }
1502    }
1503    outcome.remaining_bytes = live_bytes;
1504    Ok(outcome)
1505}
1506
1507/// Whether an action result references an object the store no longer has.
1508///
1509/// The digests checked here are exactly the ones `LocalActionCache::store`
1510/// requires. If the sweep checked fewer, eviction could leave an entry that
1511/// cannot be republished -- `store` would reject the identical result for a
1512/// missing blob while the index still claimed to hold it.
1513///
1514/// Presence is all that is checked, not content. Verifying would re-hash a
1515/// large fraction of the store on every sweep, which a chore could afford and
1516/// an automatic sweep cannot; it would also refresh the access time of every
1517/// descriptor blob while leaving the artifacts alone, biasing the very
1518/// ordering this module depends on. A blob that is present but corrupt now
1519/// keeps its result and turns into a miss on restore, and both CAS write paths
1520/// republish over a corrupt blob rather than trusting it.
1521///
1522/// Only the top-level objects are checked; a result whose output tree lost a
1523/// nested object still restores as a miss, which is safe.
1524fn action_result_is_dangling(
1525    cas: &LocalCas,
1526    path: &Path,
1527    virtually_removed: &HashSet<PathBuf>,
1528) -> Result<bool> {
1529    let bytes = match std::fs::read(path) {
1530        Ok(bytes) => bytes,
1531        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
1532        Err(error) => {
1533            return Err(error).wrap_err_with(|| format!("failed to read {}", path.display()));
1534        }
1535    };
1536    // An unparseable result is already useless; the cache rejects it on read.
1537    let Ok(result) = serde_json::from_slice::<RemoteActionResult>(&bytes) else {
1538        return Ok(false);
1539    };
1540    for digest in [
1541        Some(&result.action),
1542        result.metadata.as_ref(),
1543        result.output_root.as_ref(),
1544    ]
1545    .into_iter()
1546    .flatten()
1547    {
1548        match cas.path_for(digest) {
1549            Ok(path) => {
1550                if virtually_removed.contains(&path) || !path.exists() {
1551                    return Ok(true);
1552                }
1553            }
1554            // A digest the CAS cannot even address is not one it can hold.
1555            Err(_) => return Ok(true),
1556        }
1557    }
1558    Ok(false)
1559}
1560
1561struct Entry {
1562    path: PathBuf,
1563    size: u64,
1564    used: SystemTime,
1565}
1566
1567fn walk_files(root: &Path) -> Result<Vec<Entry>> {
1568    let mut entries = Vec::new();
1569    let mut pending = vec![root.to_path_buf()];
1570    while let Some(directory) = pending.pop() {
1571        let listing = match std::fs::read_dir(&directory) {
1572            Ok(listing) => listing,
1573            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
1574            Err(error) => {
1575                return Err(error)
1576                    .wrap_err_with(|| format!("failed to read {}", directory.display()));
1577            }
1578        };
1579        for entry in listing {
1580            let entry = entry?;
1581            let metadata = match entry.metadata() {
1582                Ok(metadata) => metadata,
1583                // A concurrent build may be publishing into the store.
1584                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
1585                Err(error) => return Err(error.into()),
1586            };
1587            if metadata.is_dir() {
1588                pending.push(entry.path());
1589            } else if metadata.is_file() {
1590                let used = metadata
1591                    .accessed()
1592                    .or_else(|_| metadata.modified())
1593                    .unwrap_or(SystemTime::UNIX_EPOCH);
1594                entries.push(Entry {
1595                    path: entry.path(),
1596                    size: metadata.len(),
1597                    used,
1598                });
1599            }
1600        }
1601    }
1602    Ok(entries)
1603}
1604
1605fn read_dir_or_empty(root: &Path) -> Result<Vec<std::fs::DirEntry>> {
1606    match std::fs::read_dir(root) {
1607        Ok(entries) => entries
1608            .collect::<std::io::Result<Vec<_>>>()
1609            .map_err(Into::into),
1610        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
1611        Err(error) => Err(error).wrap_err_with(|| format!("failed to read {}", root.display())),
1612    }
1613}
1614
1615fn digest_from_path(path: &Path, action_result: bool) -> Option<CacheDigest> {
1616    let name = path.file_name()?.to_str()?;
1617    let name = if action_result {
1618        name.strip_suffix(".json")?
1619    } else {
1620        name
1621    };
1622    let (hash, size) = name.rsplit_once('-')?;
1623    let algorithm = path.parent()?.parent()?.file_name()?.to_str()?.to_string();
1624    let digest = CacheDigest {
1625        algorithm,
1626        hash: hash.to_string(),
1627        size: size.parse().ok()?,
1628    };
1629    digest.validate().ok()?;
1630    Some(digest)
1631}
1632
1633fn addressed_digest(store: &Path, path: &Path, action_result: bool) -> Option<CacheDigest> {
1634    let digest = digest_from_path(path, action_result)?;
1635    let canonical = if action_result {
1636        mbx_cache_core::LocalActionCache::new(store)
1637            .path_for(&digest)
1638            .ok()?
1639    } else {
1640        LocalCas::new(store).path_for(&digest).ok()?
1641    };
1642    (canonical == path).then_some(digest)
1643}
1644
1645fn cached_tree_bytes(cache: &mut BTreeMap<PathBuf, u64>, root: &Path) -> u64 {
1646    *cache
1647        .entry(root.to_path_buf())
1648        .or_insert_with(|| tree_bytes(root))
1649}
1650
1651fn tree_bytes(root: &Path) -> u64 {
1652    let Ok(root_metadata) = std::fs::metadata(root) else {
1653        return 0;
1654    };
1655    if root_metadata.is_file() {
1656        return root_metadata.len();
1657    }
1658    let Ok(entries) = std::fs::read_dir(root) else {
1659        return 0;
1660    };
1661    let mut bytes = 0_u64;
1662    let mut pending = entries
1663        .filter_map(std::result::Result::ok)
1664        .map(|entry| entry.path())
1665        .collect::<Vec<_>>();
1666    while let Some(path) = pending.pop() {
1667        let Ok(metadata) = std::fs::symlink_metadata(&path) else {
1668            continue;
1669        };
1670        if metadata.is_file() {
1671            bytes = bytes.saturating_add(metadata.len());
1672        } else if metadata.is_dir()
1673            && let Ok(entries) = std::fs::read_dir(path)
1674        {
1675            pending.extend(
1676                entries
1677                    .filter_map(std::result::Result::ok)
1678                    .map(|entry| entry.path()),
1679            );
1680        }
1681    }
1682    bytes
1683}
1684
1685#[cfg(test)]
1686#[path = "store_tests.rs"]
1687mod tests;
1688
1689/// [`write_atomic`] without the sync: for records every build rewrites and
1690/// that a torn or missing file only makes one build older.
1691fn write_advisory(path: &Path, contents: &[u8]) -> Result<()> {
1692    let parent = path
1693        .parent()
1694        .filter(|parent| !parent.as_os_str().is_empty())
1695        .ok_or_else(|| eyre::eyre!("path has no parent: {}", path.display()))?;
1696    std::fs::create_dir_all(parent)
1697        .wrap_err_with(|| format!("failed to create {}", parent.display()))?;
1698    let mut temporary = tempfile::Builder::new()
1699        .prefix(".mbx-")
1700        .tempfile_in(parent)?;
1701    use std::io::Write as _;
1702    temporary.write_all(contents)?;
1703    temporary
1704        .persist(path)
1705        .map_err(|error| error.error)
1706        .wrap_err_with(|| format!("failed atomic write: {}", path.display()))?;
1707    Ok(())
1708}
1709
1710fn write_atomic(path: &Path, contents: &[u8]) -> Result<()> {
1711    let parent = path
1712        .parent()
1713        .filter(|parent| !parent.as_os_str().is_empty())
1714        .ok_or_else(|| eyre::eyre!("path has no parent: {}", path.display()))?;
1715    std::fs::create_dir_all(parent)
1716        .wrap_err_with(|| format!("failed to create {}", parent.display()))?;
1717    let mut temporary = tempfile::Builder::new()
1718        .prefix(".mbx-")
1719        .tempfile_in(parent)?;
1720    use std::io::Write as _;
1721    temporary.write_all(contents)?;
1722    temporary.as_file_mut().sync_all()?;
1723    temporary
1724        .persist(path)
1725        .map_err(|error| error.error)
1726        .wrap_err_with(|| format!("failed atomic write: {}", path.display()))?;
1727    Ok(())
1728}