artifactize-core 0.28.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
mod states;
mod view;
pub use states::{ArtifactCondition, EvalCondition, VerifyAction};
#[cfg(test)]
mod tests;

use std::{
    collections::{BTreeMap, BTreeSet},
    path::Path,
};

use serde::Serialize;
use tokio_util::sync::CancellationToken;

use crate::{
    cache,
    config::{ArtifactName, Eval, EvalId, Profile, read_workspace_declarations},
    graph::{Evidence, Graph, Readiness},
    project::VerifyOptions,
    remote::Session,
    store::{self, Claim, LastRequest},
};

use super::selection::Selection;

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StatusView {
    pub selection: Selection,
    pub recursive: bool,
    pub force: bool,
    pub selected_eval_ids: Vec<crate::config::EvalId>,
    pub included_eval_ids: Vec<crate::config::EvalId>,
    pub satisfied: bool,
    pub obligations: Vec<crate::config::ArtifactName>,
    pub artifacts: Vec<ArtifactState>,
    pub evals: Vec<EvalState>,
    pub counts: Counts,
    /// Saved records that did not decode in the newest attempts in the required scope.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub unreadable: Vec<store::Unreadable>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ArtifactState {
    #[serde(with = "crate::platform::path_serde")]
    pub definition: std::path::PathBuf,
    pub target_missing: bool,
    pub id: crate::config::ArtifactName,
    pub kind: crate::config::ArtifactKind,
    pub path: crate::config::Target,
    pub tags: Vec<String>,
    pub state: ArtifactCondition,
    pub reason: String,
    pub eval_ids: Vec<crate::config::EvalId>,
    pub passed: usize,
    pub total: usize,
    pub satisfied: bool,
    pub obligations: Vec<crate::config::ArtifactName>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EvalState {
    pub id: crate::config::EvalId,
    pub target: crate::config::ArtifactName,
    pub title: String,
    pub profile: Profile,
    pub selected: bool,
    pub included: bool,
    pub force: bool,
    pub state: EvalCondition,
    pub action: VerifyAction,
    pub reason: String,
    pub blocked_by: Vec<crate::store::Blocker>,
    pub obligations: Vec<crate::config::ArtifactName>,
    /// The Eval definition hash: the evaluation criteria the key covers.
    pub eval_def_hash: crate::types::DefinitionHash,
    /// The target's current fingerprint; null without one.
    pub fingerprint: Option<crate::types::Fingerprint>,
    /// Each Artifact the eval depends on, with its current fingerprint or null without one.
    pub fingerprints: BTreeMap<crate::config::ArtifactName, Option<crate::types::Fingerprint>>,
    /// The reuse key composed of the hash and the fingerprints; null when one is missing.
    pub key: Option<crate::types::ReuseKey>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last: Option<LastRequest>,
    /// Why the key no longer matches the newest cached result for this Eval definition: the
    /// target's changed files and the dependency Artifacts whose fingerprints changed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub changes: Option<cache::Changes>,
}

#[derive(Debug, Default, Serialize)]
pub struct Counts {
    pub artifacts: BTreeMap<ArtifactCondition, usize>,
    pub evals: BTreeMap<EvalCondition, usize>,
    pub execute: usize,
    pub reuse: usize,
    pub wait: usize,
    pub blocked: usize,
}

/// All effects needed by the status projection have finished before this is assembled.
struct Snapshot<'a> {
    required: &'a BTreeSet<&'a ArtifactName>,
    evals: &'a [&'a Eval],
    input_errors: &'a BTreeMap<&'a ArtifactName, String>,
    selected_eval_ids: &'a [crate::config::EvalId],
    included_eval_ids: &'a [crate::config::EvalId],
    fingerprints: &'a BTreeMap<&'a crate::config::ArtifactName, cache::PreparedFingerprint>,
    known: &'a Known<'a>,
}

/// What the store and the remote review store say about the keys a scan computed so far.
#[derive(Default)]
struct Known<'c> {
    cached: BTreeMap<crate::config::EvalId, Claim>,
    previous: BTreeMap<(crate::config::EvalId, crate::types::DefinitionHash), store::Execution>,
    latest: BTreeMap<crate::config::EvalId, LastRequest>,
    deferred: BTreeSet<EvalId>,
    unreadable: Vec<store::Unreadable>,
    /// Every key computed so far, by eval.
    keys: BTreeMap<&'c crate::config::EvalId, cache::Key>,
}

/// What a scan knows part way: the status as far as its fingerprints go, the results it found
/// to reuse, and the evals whose action may still change.
pub(crate) type Publish<'p> = &'p mut (dyn FnMut(usize) + Send);

/// Prepare current fingerprints without executing evals or changing saved evidence.
pub async fn status(
    repo: &Path,
    state_dir: Option<&Path>,
    selection: &Selection,
    options: &VerifyOptions,
    cancellation: CancellationToken,
) -> Result<StatusView, String> {
    // Options are checked before anything is read.
    super::fingerprint_parallelism(options)?;
    let config = read_workspace_declarations(repo).map_err(|error| error.to_string())?;
    scan(config, state_dir, selection, options, cancellation, None)
        .await
        .map(|(view, _)| view)
}

/// [`status`] of a workspace configuration already read, with the claims it found by eval.
/// With `publish`, what it knows is handed there as its fingerprints come in.
pub(crate) async fn scan(
    mut config: crate::config::RepoConfig,
    state_dir: Option<&Path>,
    selection: &Selection,
    options: &VerifyOptions,
    cancellation: CancellationToken,
    publish: Option<Publish<'_>>,
) -> Result<(StatusView, BTreeMap<crate::config::EvalId, Claim>), String> {
    let parallelism = super::fingerprint_parallelism(options)?;
    // The forecast needs resolved declarations, not the expansion's syntax and sources.
    drop(config.program.take());
    crate::platform::release_free_memory();
    let graph = Graph::new(&config).map_err(|error| error.to_string())?;
    let plan = selection.plan(&config, &graph, options.recursive)?;
    let selected_eval_ids: Vec<_> = plan.selected.iter().map(|eval| eval.id.clone()).collect();
    let included_eval_ids: Vec<_> = plan.included.iter().map(|eval| eval.id.clone()).collect();
    let required = &plan.required;
    let evals = &plan.evals;
    let state = store::state_dir(state_dir)?;
    // Read-only: a store record that completed after the local latest counts as reuse without
    // being mirrored, as verify would take it before claiming. --force reads nothing from the
    // store, so its prediction has none.
    let remote = if options.force {
        None
    } else {
        Session::open(Some(&state), Some(&config.root))?
    };
    let targets: BTreeSet<_> = evals
        .iter()
        .flat_map(|eval| cache::dependencies(&config, eval))
        .collect();
    let input_errors = targets
        .union(required)
        .filter_map(|name| {
            crate::scope::validate_file_target(&config.root, &config.artifacts[*name])
                .err()
                .map(|error| (*name, error.to_string()))
        })
        .collect::<BTreeMap<_, _>>();
    let projection = graph.projection(required);
    let scope = Scope {
        config: &config,
        graph: &graph,
        selection,
        options,
        required,
        evals,
        input_errors: &input_errors,
        projection: &projection,
        selected_eval_ids: &selected_eval_ids,
        included_eval_ids: &included_eval_ids,
        state: &state,
        remote: remote.as_deref(),
    };
    // Availability is already projected onto the affected evals as PREPARATION_FAILED.
    // Do not let preparing that target discard the other evals' read-only forecasts.
    let targets: Vec<_> = targets
        .into_iter()
        .filter(|name| {
            !input_errors.contains_key(name) && config.artifacts[*name].fingerprint.is_some()
        })
        .collect();
    let mut fingerprints = Fingerprints::new();
    let mut left = targets.len();
    let mut publish = publish;
    if let Some(publish) = &mut publish {
        publish(left);
    }
    let inputs = cache::Inputs::new(&config, evals)?;
    inputs
        .prepare_each(
            targets,
            &state,
            &parallelism,
            cancellation.clone(),
            |id, fingerprint| {
                fingerprints.insert(id, fingerprint);
                left -= 1;
                if let Some(publish) = &mut publish {
                    publish(left);
                }
            },
        )
        .await?;
    drop(inputs);
    // Read once every fingerprint is in, so a Run that ended meanwhile counts.
    let known = scope.read(&fingerprints).await?;
    if cancellation.is_cancelled() {
        return Err("Project preparation was cancelled.".into());
    }
    let view = scope.assemble(&fingerprints, &known);
    Ok((view, known.cached))
}

/// What one scan reads against.
struct Scope<'a> {
    config: &'a crate::config::RepoConfig,
    graph: &'a Graph<'a>,
    projection: &'a crate::graph::Projection<'a, 'a>,
    selection: &'a Selection,
    options: &'a VerifyOptions,
    required: &'a BTreeSet<&'a ArtifactName>,
    evals: &'a [&'a Eval],
    input_errors: &'a BTreeMap<&'a ArtifactName, String>,
    selected_eval_ids: &'a [crate::config::EvalId],
    included_eval_ids: &'a [crate::config::EvalId],
    state: &'a Path,
    remote: Option<&'a Session>,
}

type Fingerprints<'a> = BTreeMap<&'a crate::config::ArtifactName, cache::PreparedFingerprint>;

impl<'a> Scope<'a> {
    /// What the store says about `fingerprints`, read afresh.
    async fn read(&self, fingerprints: &Fingerprints<'a>) -> Result<Known<'a>, String> {
        let saved = store::read_attempts(
            self.state,
            &self.config.root,
            self.evals.iter().map(|eval| eval.id.clone()).collect(),
        )
        .await?;
        let mut known = Known {
            latest: saved.latest,
            unreadable: saved.unreadable,
            ..Known::default()
        };
        self.absorb(&mut known, fingerprints).await?;
        Ok(known)
    }

    /// Look up the keys `fingerprints` complete that `known` has not looked up yet.
    async fn absorb(
        &self,
        known: &mut Known<'a>,
        fingerprints: &Fingerprints<'a>,
    ) -> Result<(), String> {
        let new: BTreeMap<&'a crate::config::EvalId, cache::Key> = self
            .evals
            .iter()
            .filter(|eval| !known.keys.contains_key(&eval.id))
            .filter_map(|eval| {
                Some((
                    &eval.id,
                    cache::eval_key(self.config, eval, fingerprints).ok()?,
                ))
            })
            .collect();
        let selected: BTreeSet<_> = self.selected_eval_ids.iter().collect();
        let keys: BTreeMap<_, _> = new
            .iter()
            .filter(|(id, _)| !(self.options.force && selected.contains(**id)))
            .map(|(id, key)| (*id, key))
            .collect();
        let mut cached = store::read_profiled_executions(
            self.state,
            self.evals
                .iter()
                .filter_map(|eval| {
                    keys.get(&eval.id).map(|key| {
                        (
                            eval.id.clone(),
                            key.value.clone(),
                            eval.declaration.profile().into(),
                        )
                    })
                })
                .collect(),
        )
        .await?;
        if let Some(remote) = self.remote {
            let all: Vec<_> = keys
                .values()
                .map(|key| key.value.clone())
                .collect::<BTreeSet<_>>()
                .into_iter()
                .collect();
            for execution in remote.lookup(&all).await? {
                let key = execution.key.clone().expect("remote key");
                for (id, _) in keys.iter().filter(|(_, candidate)| candidate.value == key) {
                    let newer = match cached.get(*id) {
                        Some(Claim::Reuse(local)) => execution.completed_after(local),
                        _ => true,
                    };
                    if newer {
                        cached.insert((*id).clone(), Claim::Reuse(Box::new(execution.clone())));
                    }
                }
            }
        }
        // Explain changed keys against the newest cached result for the same Eval definition.
        let stale: Vec<_> = keys
            .iter()
            .filter(|(id, _)| !matches!(cached.get(**id), Some(Claim::Reuse(_))))
            .map(|(id, key)| ((*id).clone(), key.eval_def_hash.clone()))
            .collect();
        known
            .previous
            .extend(store::read_latest_cached(self.state, &stale).await?);
        let deferred = store::read_deferred(
            self.state,
            &self.config.root,
            cached
                .iter()
                .filter_map(|(id, claim)| match claim {
                    Claim::WaitHuman(execution) => Some((id.clone(), execution.clone())),
                    _ => None,
                })
                .collect(),
        )
        .await?;
        known.deferred.extend(deferred);
        known.cached.extend(cached);
        known.keys.extend(new);
        Ok(())
    }

    fn assemble(&self, fingerprints: &Fingerprints<'a>, known: &Known<'a>) -> StatusView {
        view::assemble(
            self.config,
            self.graph,
            self.projection,
            self.selection,
            self.options,
            Snapshot {
                required: self.required,
                evals: self.evals,
                input_errors: self.input_errors,
                selected_eval_ids: self.selected_eval_ids,
                included_eval_ids: self.included_eval_ids,
                fingerprints,
                known,
            },
        )
    }
}

impl Counts {
    fn action(&mut self, action: VerifyAction) {
        match action {
            VerifyAction::Execute => self.execute += 1,
            VerifyAction::Reuse => self.reuse += 1,
            VerifyAction::Wait => self.wait += 1,
            VerifyAction::Blocked => self.blocked += 1,
        }
    }
}