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