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, selection::select_profiles},
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 config = select_profiles(
163        config,
164        selection,
165        options.profile.as_ref(),
166        options.recursive,
167    )?;
168    let graph = Graph::new(&config).map_err(|error| error.to_string())?;
169    let selected = selection.resolve(&config)?;
170    let required: BTreeSet<_> = graph
171        .dependency_closure(&selected.roots)
172        .map_err(|error| error.to_string())?
173        .into_iter()
174        .collect();
175    let selected_eval_ids: Vec<_> = selected.evals.iter().map(|eval| eval.id.clone()).collect();
176    let included_eval_ids: Vec<_> = selection
177        .included_evals(&config, options.recursive)?
178        .iter()
179        .map(|eval| eval.id.clone())
180        .collect();
181    let state = store::state_dir(state_dir)?;
182    // Read-only: a store record that completed after the local latest counts as reuse without
183    // being mirrored, as verify would take it before claiming. --force reads nothing from the
184    // store, so its prediction has none.
185    let remote = if options.force {
186        None
187    } else {
188        Session::open(Some(&state), Some(&config.root))?
189    };
190    let scope = Scope {
191        config: &config,
192        graph: &graph,
193        selection,
194        options,
195        required: &required,
196        selected_eval_ids: &selected_eval_ids,
197        included_eval_ids: &included_eval_ids,
198        state: &state,
199        remote: remote.as_deref(),
200    };
201    // Availability is already projected onto the affected evals as PREPARATION_FAILED.
202    // Do not let preparing that target discard the other evals' read-only forecasts.
203    let targets = cache::fingerprint_targets(&config, &required)
204        .into_iter()
205        .filter(|name| config.artifacts[*name].target_error.is_none())
206        .collect();
207    let fingerprints = match publish {
208        None => {
209            cache::prepare(&config, targets, &state, &parallelism, cancellation.clone()).await?
210        }
211        Some(publish) => {
212            scope
213                .progressively(targets, &parallelism, cancellation.clone(), publish)
214                .await?
215        }
216    };
217    // Read once every fingerprint is in, so a Run that ended meanwhile counts.
218    let known = scope.read(&fingerprints).await?;
219    if cancellation.is_cancelled() {
220        return Err("Project preparation was cancelled.".into());
221    }
222    let view = scope.assemble(&fingerprints, &known)?;
223    Ok((view, known.cached))
224}
225
226/// What one scan reads against.
227struct Scope<'a> {
228    config: &'a crate::config::RepoConfig,
229    graph: &'a Graph<'a>,
230    selection: &'a Selection,
231    options: &'a VerifyOptions,
232    required: &'a BTreeSet<&'a crate::config::ArtifactName>,
233    selected_eval_ids: &'a [crate::config::EvalId],
234    included_eval_ids: &'a [crate::config::EvalId],
235    state: &'a Path,
236    remote: Option<&'a Session>,
237}
238
239type Fingerprints<'a> = BTreeMap<&'a crate::config::ArtifactName, cache::PreparedFingerprint>;
240
241impl<'a> Scope<'a> {
242    /// Prepare the fingerprints, handing `publish` what is known each time some come in: first
243    /// the graph with every eval being checked, then each action as soon as it cannot change.
244    async fn progressively(
245        &self,
246        targets: BTreeSet<&'a crate::config::ArtifactName>,
247        parallelism: &cache::Parallelism,
248        cancellation: CancellationToken,
249        publish: Publish<'_>,
250    ) -> Result<Fingerprints<'a>, String> {
251        let mut fingerprints = Fingerprints::new();
252        let first = Known::default();
253        publish(Progress {
254            view: self.assemble(&fingerprints, &first)?,
255            cached: &first.cached,
256            checking: self.checking(&fingerprints, &first.cached),
257        });
258        let mut known = self.read(&fingerprints).await?;
259        let (ready, mut arrived) = tokio::sync::mpsc::unbounded_channel();
260        // A failed store read stops the fingerprints nobody would read any more.
261        let preparation = cancellation.child_token();
262        // Dependency first: an eval's action is known once its gates' are, so what is upstream
263        // is fingerprinted first and the graph fills in from there.
264        let targets = self
265            .graph
266            .components()
267            .iter()
268            .flat_map(|component| &component.artifacts)
269            .filter_map(|id| targets.get(*id).copied());
270        let preparing = cache::prepare_each(
271            self.config,
272            targets,
273            self.state,
274            parallelism,
275            preparation.clone(),
276            move |id, fingerprint| {
277                let _ = ready.send((id, fingerprint));
278            },
279        );
280        let publishing = async {
281            while let Some((id, fingerprint)) = arrived.recv().await {
282                let started = tokio::time::Instant::now();
283                fingerprints.insert(id, fingerprint);
284                while let Ok((id, fingerprint)) = arrived.try_recv() {
285                    fingerprints.insert(id, fingerprint);
286                }
287                self.absorb(&mut known, &fingerprints).await?;
288                publish(Progress {
289                    view: self.assemble(&fingerprints, &known)?,
290                    cached: &known.cached,
291                    checking: self.checking(&fingerprints, &known.cached),
292                });
293                // Publishing takes from the fingerprints' time: leave them as long again.
294                tokio::time::sleep(started.elapsed()).await;
295            }
296            Ok::<_, String>(())
297        };
298        let publishing = async {
299            let published = publishing.await;
300            if published.is_err() {
301                preparation.cancel();
302            }
303            published
304        };
305        let (prepared, published) = tokio::join!(preparing, publishing);
306        prepared?;
307        published?;
308        Ok(fingerprints)
309    }
310
311    /// What the store says about `fingerprints`, read afresh.
312    async fn read(&self, fingerprints: &Fingerprints<'a>) -> Result<Known<'a>, String> {
313        let mut known = Known {
314            latest: store::read_latest_requests(self.state, &self.config.root).await?,
315            waiting: store::read_waiting(self.state, Some(&self.config.root)).await?,
316            unreadable: store::read_unreadable(self.state, Some(&self.config.root)).await?,
317            ..Known::default()
318        };
319        self.absorb(&mut known, fingerprints).await?;
320        Ok(known)
321    }
322
323    /// Look up the keys `fingerprints` complete that `known` has not looked up yet.
324    async fn absorb(
325        &self,
326        known: &mut Known<'a>,
327        fingerprints: &Fingerprints<'a>,
328    ) -> Result<(), String> {
329        let new: BTreeMap<&'a crate::config::EvalId, cache::Key> = self
330            .config
331            .evals
332            .iter()
333            .filter(|eval| !known.keys.contains_key(&eval.id))
334            .filter_map(|eval| {
335                Some((
336                    &eval.id,
337                    cache::eval_key(self.config, eval, fingerprints).ok()?,
338                ))
339            })
340            .collect();
341        let selected: BTreeSet<_> = self.selected_eval_ids.iter().collect();
342        let keys: BTreeMap<_, _> = new
343            .iter()
344            .filter(|(id, _)| !(self.options.force && selected.contains(**id)))
345            .map(|(id, key)| (*id, key))
346            .collect();
347        let mut cached = store::read_profiled_executions(
348            self.state,
349            self.config
350                .evals
351                .iter()
352                .filter_map(|eval| {
353                    keys.get(&eval.id).map(|key| {
354                        (
355                            eval.id.clone(),
356                            key.value.clone(),
357                            eval.declaration.profile().into(),
358                        )
359                    })
360                })
361                .collect(),
362        )
363        .await?;
364        if let Some(remote) = self.remote {
365            let all: Vec<_> = keys
366                .values()
367                .map(|key| key.value.clone())
368                .collect::<BTreeSet<_>>()
369                .into_iter()
370                .collect();
371            for execution in remote.lookup(&all).await? {
372                let key = execution.key.clone().expect("remote key");
373                for (id, _) in keys.iter().filter(|(_, candidate)| candidate.value == key) {
374                    let newer = match cached.get(*id) {
375                        Some(Claim::Reuse(local)) => execution.completed_after(local),
376                        _ => true,
377                    };
378                    if newer {
379                        cached.insert((*id).clone(), Claim::Reuse(Box::new(execution.clone())));
380                    }
381                }
382            }
383        }
384        // Explain changed keys against the newest cached result for the same Eval definition.
385        let stale: Vec<_> = keys
386            .iter()
387            .filter(|(id, _)| !matches!(cached.get(**id), Some(Claim::Reuse(_))))
388            .map(|(id, key)| ((*id).clone(), key.eval_def_hash.clone()))
389            .collect();
390        known
391            .previous
392            .extend(store::read_latest_cached(self.state, &stale).await?);
393        known.cached.extend(cached);
394        known.keys.extend(new);
395        Ok(())
396    }
397
398    fn assemble(
399        &self,
400        fingerprints: &Fingerprints<'a>,
401        known: &Known<'a>,
402    ) -> Result<StatusView, String> {
403        view::assemble(
404            self.config,
405            self.graph,
406            self.selection,
407            self.options,
408            Snapshot {
409                required: self.required,
410                selected_eval_ids: self.selected_eval_ids,
411                included_eval_ids: self.included_eval_ids,
412                fingerprints,
413                known,
414            },
415        )
416    }
417
418    /// The evals whose action may still change: a fingerprint their key needs is not in yet,
419    /// or, unless they reuse a result, the action of an eval they wait for may still change.
420    fn checking(
421        &self,
422        fingerprints: &Fingerprints<'a>,
423        cached: &BTreeMap<crate::config::EvalId, Claim>,
424    ) -> BTreeSet<&'a crate::config::EvalId> {
425        let evals: BTreeMap<_, _> = self
426            .config
427            .evals
428            .iter()
429            .map(|eval| (&eval.id, eval))
430            .collect();
431        let mut settled = BTreeSet::new();
432        let mut checking = BTreeSet::new();
433        // Dependency first, so an eval's gates are decided before it; gates in its own cycle
434        // are not, and the cycle stays being checked until every fingerprint is in.
435        for component in self.graph.components() {
436            for artifact in component
437                .artifacts
438                .iter()
439                .filter(|id| self.required.contains(*id))
440            {
441                for id in &self.graph.artifacts()[*artifact].evals {
442                    let keyed =
443                        cache::dependencies(self.config, evals[id])
444                            .into_iter()
445                            .all(|input| {
446                                self.config.artifacts[input].target_error.is_some()
447                                    || self.config.artifacts[input].fingerprint.is_none()
448                                    || fingerprints.contains_key(input)
449                            });
450                    let decided = keyed
451                        && (matches!(cached.get(*id), Some(Claim::Reuse(_)))
452                            || self
453                                .graph
454                                .gates(id)
455                                .iter()
456                                .all(|gate| settled.contains(gate)));
457                    if decided {
458                        settled.insert(*id);
459                    } else {
460                        checking.insert(*id);
461                    }
462                }
463            }
464        }
465        checking
466    }
467}
468
469impl Counts {
470    fn action(&mut self, action: VerifyAction) {
471        match action {
472            VerifyAction::Execute => self.execute += 1,
473            VerifyAction::Reuse => self.reuse += 1,
474            VerifyAction::Wait => self.wait += 1,
475            VerifyAction::Blocked => self.blocked += 1,
476        }
477    }
478}