Skip to main content

artifactize_core/project/
status.rs

1mod states;
2mod view;
3pub use states::{ArtifactCondition, EvalCondition, VerifyAction};
4#[cfg(test)]
5mod tests;
6
7use std::{
8    collections::{BTreeMap, BTreeSet},
9    path::Path,
10};
11
12use serde::Serialize;
13use tokio_util::sync::CancellationToken;
14
15use crate::{
16    cache,
17    config::{Profile, read_workspace_config},
18    graph::{Evidence, Graph, Readiness},
19    project::VerifyOptions,
20    remote::Session,
21    store::{self, Claim, LastRequest},
22};
23
24use super::selection::Selection;
25
26#[derive(Debug, Serialize)]
27#[serde(rename_all = "camelCase")]
28pub struct StatusView {
29    pub selection: Selection,
30    pub recursive: bool,
31    pub force: bool,
32    pub selected_eval_ids: Vec<crate::config::EvalId>,
33    pub included_eval_ids: Vec<crate::config::EvalId>,
34    pub satisfied: bool,
35    pub obligations: Vec<crate::config::ArtifactName>,
36    pub artifacts: Vec<ArtifactState>,
37    pub evals: Vec<EvalState>,
38    pub counts: Counts,
39    #[serde(skip_serializing_if = "Vec::is_empty")]
40    pub unreadable: Vec<store::Unreadable>,
41}
42
43#[derive(Debug, Serialize)]
44#[serde(rename_all = "camelCase")]
45pub struct ArtifactState {
46    #[serde(with = "crate::platform::path_serde")]
47    pub definition: std::path::PathBuf,
48    pub target_missing: bool,
49    pub id: crate::config::ArtifactName,
50    pub kind: crate::config::ArtifactKind,
51    pub path: crate::config::Target,
52    pub tags: Vec<String>,
53    pub state: ArtifactCondition,
54    pub reason: String,
55    pub eval_ids: Vec<crate::config::EvalId>,
56    pub passed: usize,
57    pub total: usize,
58    pub satisfied: bool,
59    pub obligations: Vec<crate::config::ArtifactName>,
60}
61
62#[derive(Debug, Serialize)]
63#[serde(rename_all = "camelCase")]
64pub struct EvalState {
65    pub id: crate::config::EvalId,
66    pub target: crate::config::ArtifactName,
67    pub title: String,
68    pub profile: Profile,
69    pub selected: bool,
70    pub included: bool,
71    pub force: bool,
72    pub state: EvalCondition,
73    pub action: VerifyAction,
74    pub reason: String,
75    pub blocked_by: Vec<crate::store::Blocker>,
76    pub obligations: Vec<crate::config::ArtifactName>,
77    /// The Eval definition hash: the evaluation criteria the key covers.
78    pub eval_def_hash: crate::types::DefinitionHash,
79    /// The target's current fingerprint; null without one.
80    pub fingerprint: Option<crate::types::Fingerprint>,
81    /// Each Artifact the eval depends on, with its current fingerprint or null without one.
82    pub fingerprints: BTreeMap<crate::config::ArtifactName, Option<crate::types::Fingerprint>>,
83    /// The reuse key composed of the hash and the fingerprints; null when one is missing.
84    pub key: Option<crate::types::ReuseKey>,
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub last: Option<LastRequest>,
87    /// Why the key no longer matches the newest cached result for this Eval definition: the
88    /// target's changed files and the dependency Artifacts whose fingerprints changed.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub changes: Option<cache::Changes>,
91}
92
93#[derive(Debug, Default, Serialize)]
94pub struct Counts {
95    pub artifacts: BTreeMap<ArtifactCondition, usize>,
96    pub evals: BTreeMap<EvalCondition, usize>,
97    pub execute: usize,
98    pub reuse: usize,
99    pub wait: usize,
100    pub blocked: usize,
101}
102
103/// All effects needed by the status projection have finished before this is assembled.
104struct Snapshot<'a> {
105    required: &'a BTreeSet<&'a crate::config::ArtifactName>,
106    selected_eval_ids: &'a [crate::config::EvalId],
107    included_eval_ids: &'a [crate::config::EvalId],
108    fingerprints: &'a BTreeMap<&'a crate::config::ArtifactName, cache::PreparedFingerprint>,
109    known: &'a Known<'a>,
110}
111
112/// What the store and the remote review store say about the keys a scan computed so far.
113#[derive(Default)]
114struct Known<'c> {
115    cached: BTreeMap<crate::config::EvalId, Claim>,
116    previous: BTreeMap<(crate::config::EvalId, crate::types::DefinitionHash), store::Execution>,
117    latest: BTreeMap<crate::config::EvalId, LastRequest>,
118    waiting: Vec<store::RequestView>,
119    unreadable: Vec<store::Unreadable>,
120    /// Every key computed so far, by eval.
121    keys: BTreeMap<&'c crate::config::EvalId, cache::Key>,
122}
123
124/// What a scan knows part way: the status as far as its fingerprints go, the results it found
125/// to reuse, and the evals whose action may still change.
126pub(crate) struct Progress<'a> {
127    pub view: StatusView,
128    pub cached: &'a BTreeMap<crate::config::EvalId, Claim>,
129    pub checking: BTreeSet<&'a crate::config::EvalId>,
130}
131
132/// Where a scan hands what it knows part way.
133pub(crate) type Publish<'p> = &'p mut (dyn for<'a> FnMut(Progress<'a>) + Send);
134
135/// Prepare current fingerprints without executing evals or changing saved evidence.
136pub async fn status(
137    repo: &Path,
138    state_dir: Option<&Path>,
139    selection: &Selection,
140    options: &VerifyOptions,
141    cancellation: CancellationToken,
142) -> Result<StatusView, String> {
143    // Options are checked before anything is read.
144    super::fingerprint_parallelism(options)?;
145    let config = read_workspace_config(repo).map_err(|error| error.to_string())?;
146    scan(config, state_dir, selection, options, cancellation, None)
147        .await
148        .map(|(view, _)| view)
149}
150
151/// [`status`] of a workspace configuration already read, with the claims it found by eval.
152/// With `publish`, what it knows is handed there as its fingerprints come in.
153pub(crate) async fn scan(
154    config: crate::config::RepoConfig,
155    state_dir: Option<&Path>,
156    selection: &Selection,
157    options: &VerifyOptions,
158    cancellation: CancellationToken,
159    publish: Option<Publish<'_>>,
160) -> Result<(StatusView, BTreeMap<crate::config::EvalId, Claim>), String> {
161    let parallelism = super::fingerprint_parallelism(options)?;
162    let graph = Graph::new(&config).map_err(|error| error.to_string())?;
163    let selected = selection.resolve(&config)?;
164    let required: BTreeSet<_> = graph
165        .dependency_closure(&selected.roots)
166        .map_err(|error| error.to_string())?
167        .into_iter()
168        .collect();
169    let selected_eval_ids: Vec<_> = selected.evals.iter().map(|eval| eval.id.clone()).collect();
170    let included_eval_ids: Vec<_> = selection
171        .included_evals(&config, options.recursive)?
172        .iter()
173        .map(|eval| eval.id.clone())
174        .collect();
175    let state = store::state_dir(state_dir)?;
176    // Read-only: a store record that completed after the local latest counts as reuse without
177    // being mirrored, as verify would take it before claiming. --force reads nothing from the
178    // store, so its prediction has none.
179    let remote = if options.force {
180        None
181    } else {
182        Session::open(Some(&state), Some(&config.root))?
183    };
184    let scope = Scope {
185        config: &config,
186        graph: &graph,
187        selection,
188        options,
189        required: &required,
190        selected_eval_ids: &selected_eval_ids,
191        included_eval_ids: &included_eval_ids,
192        state: &state,
193        remote: remote.as_deref(),
194    };
195    // Availability is already projected onto the affected evals as PREPARATION_FAILED.
196    // Do not let preparing that target discard the other evals' read-only forecasts.
197    let targets = cache::fingerprint_targets(&config, &required)
198        .into_iter()
199        .filter(|name| config.artifacts[*name].target_error.is_none())
200        .collect();
201    let fingerprints = match publish {
202        None => {
203            cache::prepare(&config, targets, &state, &parallelism, cancellation.clone()).await?
204        }
205        Some(publish) => {
206            scope
207                .progressively(targets, &parallelism, cancellation.clone(), publish)
208                .await?
209        }
210    };
211    // Read once every fingerprint is in, so a Run that ended meanwhile counts.
212    let known = scope.read(&fingerprints).await?;
213    if cancellation.is_cancelled() {
214        return Err("Project preparation was cancelled.".into());
215    }
216    let view = scope.assemble(&fingerprints, &known)?;
217    Ok((view, known.cached))
218}
219
220/// What one scan reads against.
221struct Scope<'a> {
222    config: &'a crate::config::RepoConfig,
223    graph: &'a Graph<'a>,
224    selection: &'a Selection,
225    options: &'a VerifyOptions,
226    required: &'a BTreeSet<&'a crate::config::ArtifactName>,
227    selected_eval_ids: &'a [crate::config::EvalId],
228    included_eval_ids: &'a [crate::config::EvalId],
229    state: &'a Path,
230    remote: Option<&'a Session>,
231}
232
233type Fingerprints<'a> = BTreeMap<&'a crate::config::ArtifactName, cache::PreparedFingerprint>;
234
235impl<'a> Scope<'a> {
236    /// Prepare the fingerprints, handing `publish` what is known each time some come in: first
237    /// the graph with every eval being checked, then each action as soon as it cannot change.
238    async fn progressively(
239        &self,
240        targets: BTreeSet<&'a crate::config::ArtifactName>,
241        parallelism: &cache::Parallelism,
242        cancellation: CancellationToken,
243        publish: Publish<'_>,
244    ) -> Result<Fingerprints<'a>, String> {
245        let mut fingerprints = Fingerprints::new();
246        let first = Known::default();
247        publish(Progress {
248            view: self.assemble(&fingerprints, &first)?,
249            cached: &first.cached,
250            checking: self.checking(&fingerprints, &first.cached),
251        });
252        let mut known = self.read(&fingerprints).await?;
253        let (ready, mut arrived) = tokio::sync::mpsc::unbounded_channel();
254        // A failed store read stops the fingerprints nobody would read any more.
255        let preparation = cancellation.child_token();
256        // Dependency first: an eval's action is known once its gates' are, so what is upstream
257        // is fingerprinted first and the graph fills in from there.
258        let targets = self
259            .graph
260            .components()
261            .iter()
262            .flat_map(|component| &component.artifacts)
263            .filter_map(|id| targets.get(*id).copied());
264        let preparing = cache::prepare_each(
265            self.config,
266            targets,
267            self.state,
268            parallelism,
269            preparation.clone(),
270            move |id, fingerprint| {
271                let _ = ready.send((id, fingerprint));
272            },
273        );
274        let publishing = async {
275            while let Some((id, fingerprint)) = arrived.recv().await {
276                let started = tokio::time::Instant::now();
277                fingerprints.insert(id, fingerprint);
278                while let Ok((id, fingerprint)) = arrived.try_recv() {
279                    fingerprints.insert(id, fingerprint);
280                }
281                self.absorb(&mut known, &fingerprints).await?;
282                publish(Progress {
283                    view: self.assemble(&fingerprints, &known)?,
284                    cached: &known.cached,
285                    checking: self.checking(&fingerprints, &known.cached),
286                });
287                // Publishing takes from the fingerprints' time: leave them as long again.
288                tokio::time::sleep(started.elapsed()).await;
289            }
290            Ok::<_, String>(())
291        };
292        let publishing = async {
293            let published = publishing.await;
294            if published.is_err() {
295                preparation.cancel();
296            }
297            published
298        };
299        let (prepared, published) = tokio::join!(preparing, publishing);
300        prepared?;
301        published?;
302        Ok(fingerprints)
303    }
304
305    /// What the store says about `fingerprints`, read afresh.
306    async fn read(&self, fingerprints: &Fingerprints<'a>) -> Result<Known<'a>, String> {
307        let mut known = Known {
308            latest: store::read_latest_requests(self.state, &self.config.root).await?,
309            waiting: store::read_waiting(self.state, Some(&self.config.root)).await?,
310            unreadable: store::read_unreadable(self.state, Some(&self.config.root)).await?,
311            ..Known::default()
312        };
313        self.absorb(&mut known, fingerprints).await?;
314        Ok(known)
315    }
316
317    /// Look up the keys `fingerprints` complete that `known` has not looked up yet.
318    async fn absorb(
319        &self,
320        known: &mut Known<'a>,
321        fingerprints: &Fingerprints<'a>,
322    ) -> Result<(), String> {
323        let new: BTreeMap<&'a crate::config::EvalId, cache::Key> = self
324            .config
325            .evals
326            .iter()
327            .filter(|eval| !known.keys.contains_key(&eval.id))
328            .filter_map(|eval| {
329                Some((
330                    &eval.id,
331                    cache::eval_key(self.config, eval, fingerprints).ok()?,
332                ))
333            })
334            .collect();
335        let selected: BTreeSet<_> = self.selected_eval_ids.iter().collect();
336        let keys: BTreeMap<_, _> = new
337            .iter()
338            .filter(|(id, _)| !(self.options.force && selected.contains(**id)))
339            .map(|(id, key)| (*id, key))
340            .collect();
341        let mut cached = store::read_profiled_executions(
342            self.state,
343            self.config
344                .evals
345                .iter()
346                .filter_map(|eval| {
347                    keys.get(&eval.id).map(|key| {
348                        (
349                            eval.id.clone(),
350                            key.value.clone(),
351                            eval.declaration.profile().into(),
352                        )
353                    })
354                })
355                .collect(),
356        )
357        .await?;
358        if let Some(remote) = self.remote {
359            let all: Vec<_> = keys
360                .values()
361                .map(|key| key.value.clone())
362                .collect::<BTreeSet<_>>()
363                .into_iter()
364                .collect();
365            for execution in remote.lookup(&all).await? {
366                let key = execution.key.clone().expect("remote key");
367                for (id, _) in keys.iter().filter(|(_, candidate)| candidate.value == key) {
368                    let newer = match cached.get(*id) {
369                        Some(Claim::Reuse(local)) => execution.completed_after(local),
370                        _ => true,
371                    };
372                    if newer {
373                        cached.insert((*id).clone(), Claim::Reuse(Box::new(execution.clone())));
374                    }
375                }
376            }
377        }
378        // Explain changed keys against the newest cached result for the same Eval definition.
379        let stale: Vec<_> = keys
380            .iter()
381            .filter(|(id, _)| !matches!(cached.get(**id), Some(Claim::Reuse(_))))
382            .map(|(id, key)| ((*id).clone(), key.eval_def_hash.clone()))
383            .collect();
384        known
385            .previous
386            .extend(store::read_latest_cached(self.state, &stale).await?);
387        known.cached.extend(cached);
388        known.keys.extend(new);
389        Ok(())
390    }
391
392    fn assemble(
393        &self,
394        fingerprints: &Fingerprints<'a>,
395        known: &Known<'a>,
396    ) -> Result<StatusView, String> {
397        view::assemble(
398            self.config,
399            self.graph,
400            self.selection,
401            self.options,
402            Snapshot {
403                required: self.required,
404                selected_eval_ids: self.selected_eval_ids,
405                included_eval_ids: self.included_eval_ids,
406                fingerprints,
407                known,
408            },
409        )
410    }
411
412    /// The evals whose action may still change: a fingerprint their key needs is not in yet,
413    /// or, unless they reuse a result, the action of an eval they wait for may still change.
414    fn checking(
415        &self,
416        fingerprints: &Fingerprints<'a>,
417        cached: &BTreeMap<crate::config::EvalId, Claim>,
418    ) -> BTreeSet<&'a crate::config::EvalId> {
419        let evals: BTreeMap<_, _> = self
420            .config
421            .evals
422            .iter()
423            .map(|eval| (&eval.id, eval))
424            .collect();
425        let mut settled = BTreeSet::new();
426        let mut checking = BTreeSet::new();
427        // Dependency first, so an eval's gates are decided before it; gates in its own cycle
428        // are not, and the cycle stays being checked until every fingerprint is in.
429        for component in self.graph.components() {
430            for artifact in component
431                .artifacts
432                .iter()
433                .filter(|id| self.required.contains(*id))
434            {
435                for id in &self.graph.artifacts()[*artifact].evals {
436                    let keyed =
437                        cache::dependencies(self.config, evals[id])
438                            .into_iter()
439                            .all(|input| {
440                                self.config.artifacts[input].target_error.is_some()
441                                    || self.config.artifacts[input].fingerprint.is_none()
442                                    || fingerprints.contains_key(input)
443                            });
444                    let decided = keyed
445                        && (matches!(cached.get(*id), Some(Claim::Reuse(_)))
446                            || self
447                                .graph
448                                .gates(id)
449                                .iter()
450                                .all(|gate| settled.contains(gate)));
451                    if decided {
452                        settled.insert(*id);
453                    } else {
454                        checking.insert(*id);
455                    }
456                }
457            }
458        }
459        checking
460    }
461}
462
463impl Counts {
464    fn action(&mut self, action: VerifyAction) {
465        match action {
466            VerifyAction::Execute => self.execute += 1,
467            VerifyAction::Reuse => self.reuse += 1,
468            VerifyAction::Wait => self.wait += 1,
469            VerifyAction::Blocked => self.blocked += 1,
470        }
471    }
472}