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