Skip to main content

artifactize_core/cache/
explain.rs

1//! Explain cache misses using the earlier execution's fingerprints and file manifest.
2
3use super::{Key, Manifest};
4use crate::{config::ArtifactName, store::Execution};
5use serde::Serialize;
6use std::collections::{BTreeMap, BTreeSet};
7
8/// Keep change explanations readable in CLI output; the complete path list remains in Changes.
9const MAX_SUMMARY_PATHS: usize = 10;
10
11/// Why the current key differs from an earlier cached result for the same eval and Eval
12/// definition.
13#[derive(Debug, Serialize)]
14#[serde(rename_all = "camelCase")]
15pub struct Changes {
16    pub since_run_id: crate::types::RunId,
17    /// The target's own files: `path` changed, `+path` added, `-path` removed; absent when
18    /// not comparable.
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub files: Option<Vec<String>>,
21    /// Dependency Artifacts: `name` changed, `+name` added, `-name` removed; absent when none
22    /// changed or not comparable.
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub dependencies: Option<Vec<String>>,
25    pub summary: String,
26}
27
28/// Explain a changed key against an earlier cached execution of the same Eval definition:
29/// which of the target's files changed, and which dependency Artifacts' fingerprints changed.
30pub fn changes(
31    previous: &Execution,
32    target: &ArtifactName,
33    current: &Key,
34    manifest: Option<&Manifest>,
35) -> Changes {
36    let mut parts = Vec::new();
37    let mut files = None;
38    if previous.fingerprints.get(target) != current.fingerprints.get(target) {
39        match previous.manifest.as_ref().zip(manifest) {
40            Some((old, new)) if old.inputs == new.inputs => files = Some(Vec::new()),
41            Some((old, new)) => {
42                files = old
43                    .files
44                    .as_ref()
45                    .zip(new.files.as_ref())
46                    .map(|(old, new)| diff(old, new));
47                match &files {
48                    Some(files) if !files.is_empty() => {
49                        let shown = files
50                            .iter()
51                            .take(MAX_SUMMARY_PATHS)
52                            .cloned()
53                            .collect::<Vec<_>>()
54                            .join(", ");
55                        parts.push(match files.len() {
56                            0..=MAX_SUMMARY_PATHS => format!("changed: {shown}"),
57                            total => {
58                                format!("changed: {shown} and {} more", total - MAX_SUMMARY_PATHS)
59                            }
60                        });
61                    }
62                    _ => parts.push("inputs changed".to_owned()),
63                }
64            }
65            None => parts.push("fingerprint changed".to_owned()),
66        }
67    }
68    let dependencies = (!previous.fingerprints.is_empty())
69        .then(|| {
70            let others = |map: &BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>| {
71                map.iter()
72                    .filter(|(name, _)| *name != target)
73                    .map(|(name, value)| (name.clone(), value.clone()))
74                    .collect::<BTreeMap<_, _>>()
75            };
76            diff(
77                &others(&previous.fingerprints),
78                &others(&current.fingerprints),
79            )
80        })
81        .filter(|dependencies| !dependencies.is_empty());
82    parts.extend(dependencies.iter().flatten().map(|dependency| {
83        if let Some(id) = dependency.strip_prefix('+') {
84            format!("dependency {id} added")
85        } else if let Some(id) = dependency.strip_prefix('-') {
86            format!("dependency {id} removed")
87        } else {
88            format!("dependency {dependency} changed")
89        }
90    }));
91    if parts.is_empty() {
92        parts.push("fingerprint changed".to_owned());
93    }
94    Changes {
95        since_run_id: previous.provenance.run_id.clone(),
96        files,
97        dependencies,
98        summary: parts.join("; "),
99    }
100}
101
102fn diff<K: Ord + std::fmt::Display, T: PartialEq>(
103    old: &BTreeMap<K, T>,
104    new: &BTreeMap<K, T>,
105) -> Vec<String> {
106    old.keys()
107        .chain(new.keys())
108        .collect::<BTreeSet<_>>()
109        .into_iter()
110        .filter_map(|key| match (old.get(key), new.get(key)) {
111            (Some(old), Some(new)) if old != new => Some(key.to_string()),
112            (None, Some(_)) => Some(format!("+{key}")),
113            (Some(_), None) => Some(format!("-{key}")),
114            _ => None,
115        })
116        .collect()
117}