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 #[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 pub eval_def_hash: crate::types::DefinitionHash,
80 pub fingerprint: Option<crate::types::Fingerprint>,
82 pub fingerprints: BTreeMap<crate::config::ArtifactName, Option<crate::types::Fingerprint>>,
84 pub key: Option<crate::types::ReuseKey>,
86 #[serde(skip_serializing_if = "Option::is_none")]
87 pub last: Option<LastRequest>,
88 #[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
104struct 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#[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 keys: BTreeMap<&'c crate::config::EvalId, cache::Key>,
125}
126
127pub(crate) type Publish<'p> = &'p mut (dyn FnMut(usize) + Send);
130
131pub async fn status(
133 repo: &Path,
134 state_dir: Option<&Path>,
135 selection: &Selection,
136 options: &VerifyOptions,
137 cancellation: CancellationToken,
138) -> Result<StatusView, String> {
139 super::fingerprint_parallelism(options)?;
141 let config = read_workspace_declarations(repo).map_err(|error| error.to_string())?;
142 scan(config, state_dir, selection, options, cancellation, None)
143 .await
144 .map(|(view, _)| view)
145}
146
147pub(crate) async fn scan(
150 mut config: crate::config::RepoConfig,
151 state_dir: Option<&Path>,
152 selection: &Selection,
153 options: &VerifyOptions,
154 cancellation: CancellationToken,
155 publish: Option<Publish<'_>>,
156) -> Result<(StatusView, BTreeMap<crate::config::EvalId, Claim>), String> {
157 let parallelism = super::fingerprint_parallelism(options)?;
158 drop(config.program.take());
160 crate::platform::release_free_memory();
161 let graph = Graph::new(&config).map_err(|error| error.to_string())?;
162 let plan = selection.plan(&config, &graph, options.recursive)?;
163 let selected_eval_ids: Vec<_> = plan.selected.iter().map(|eval| eval.id.clone()).collect();
164 let included_eval_ids: Vec<_> = plan.included.iter().map(|eval| eval.id.clone()).collect();
165 let required = &plan.required;
166 let evals = &plan.evals;
167 let state = store::state_dir(state_dir)?;
168 let remote = if options.force {
172 None
173 } else {
174 Session::open(Some(&state), Some(&config.root))?
175 };
176 let targets: BTreeSet<_> = evals
177 .iter()
178 .flat_map(|eval| cache::dependencies(&config, eval))
179 .collect();
180 let input_errors = targets
181 .union(required)
182 .filter_map(|name| {
183 crate::scope::validate_file_target(&config.root, &config.artifacts[*name])
184 .err()
185 .map(|error| (*name, error.to_string()))
186 })
187 .collect::<BTreeMap<_, _>>();
188 let projection = graph.projection(required);
189 let scope = Scope {
190 config: &config,
191 graph: &graph,
192 selection,
193 options,
194 required,
195 evals,
196 input_errors: &input_errors,
197 projection: &projection,
198 selected_eval_ids: &selected_eval_ids,
199 included_eval_ids: &included_eval_ids,
200 state: &state,
201 remote: remote.as_deref(),
202 };
203 let targets: Vec<_> = targets
206 .into_iter()
207 .filter(|name| {
208 !input_errors.contains_key(name) && config.artifacts[*name].fingerprint.is_some()
209 })
210 .collect();
211 let mut fingerprints = Fingerprints::new();
212 let mut left = targets.len();
213 let mut publish = publish;
214 if let Some(publish) = &mut publish {
215 publish(left);
216 }
217 let inputs = cache::Inputs::new(&config, evals)?;
218 inputs
219 .prepare_each(
220 targets,
221 &state,
222 ¶llelism,
223 cancellation.clone(),
224 |id, fingerprint| {
225 fingerprints.insert(id, fingerprint);
226 left -= 1;
227 if let Some(publish) = &mut publish {
228 publish(left);
229 }
230 },
231 )
232 .await?;
233 drop(inputs);
234 let known = scope.read(&fingerprints).await?;
236 if cancellation.is_cancelled() {
237 return Err("Project preparation was cancelled.".into());
238 }
239 let view = scope.assemble(&fingerprints, &known);
240 Ok((view, known.cached))
241}
242
243struct Scope<'a> {
245 config: &'a crate::config::RepoConfig,
246 graph: &'a Graph<'a>,
247 projection: &'a crate::graph::Projection<'a, 'a>,
248 selection: &'a Selection,
249 options: &'a VerifyOptions,
250 required: &'a BTreeSet<&'a ArtifactName>,
251 evals: &'a [&'a Eval],
252 input_errors: &'a BTreeMap<&'a ArtifactName, String>,
253 selected_eval_ids: &'a [crate::config::EvalId],
254 included_eval_ids: &'a [crate::config::EvalId],
255 state: &'a Path,
256 remote: Option<&'a Session>,
257}
258
259type Fingerprints<'a> = BTreeMap<&'a crate::config::ArtifactName, cache::PreparedFingerprint>;
260
261impl<'a> Scope<'a> {
262 async fn read(&self, fingerprints: &Fingerprints<'a>) -> Result<Known<'a>, String> {
264 let saved = store::read_attempts(
265 self.state,
266 &self.config.root,
267 self.evals.iter().map(|eval| eval.id.clone()).collect(),
268 )
269 .await?;
270 let mut known = Known {
271 latest: saved.latest,
272 unreadable: saved.unreadable,
273 ..Known::default()
274 };
275 self.absorb(&mut known, fingerprints).await?;
276 Ok(known)
277 }
278
279 async fn absorb(
281 &self,
282 known: &mut Known<'a>,
283 fingerprints: &Fingerprints<'a>,
284 ) -> Result<(), String> {
285 let new: BTreeMap<&'a crate::config::EvalId, cache::Key> = self
286 .evals
287 .iter()
288 .filter(|eval| !known.keys.contains_key(&eval.id))
289 .filter_map(|eval| {
290 Some((
291 &eval.id,
292 cache::eval_key(self.config, eval, fingerprints).ok()?,
293 ))
294 })
295 .collect();
296 let selected: BTreeSet<_> = self.selected_eval_ids.iter().collect();
297 let keys: BTreeMap<_, _> = new
298 .iter()
299 .filter(|(id, _)| !(self.options.force && selected.contains(**id)))
300 .map(|(id, key)| (*id, key))
301 .collect();
302 let mut cached = store::read_profiled_executions(
303 self.state,
304 self.evals
305 .iter()
306 .filter_map(|eval| {
307 keys.get(&eval.id).map(|key| {
308 (
309 eval.id.clone(),
310 key.value.clone(),
311 eval.declaration.profile().into(),
312 )
313 })
314 })
315 .collect(),
316 )
317 .await?;
318 if let Some(remote) = self.remote {
319 let all: Vec<_> = keys
320 .values()
321 .map(|key| key.value.clone())
322 .collect::<BTreeSet<_>>()
323 .into_iter()
324 .collect();
325 for execution in remote.lookup(&all).await? {
326 let key = execution.key.clone().expect("remote key");
327 for (id, _) in keys.iter().filter(|(_, candidate)| candidate.value == key) {
328 let newer = match cached.get(*id) {
329 Some(Claim::Reuse(local)) => execution.completed_after(local),
330 _ => true,
331 };
332 if newer {
333 cached.insert((*id).clone(), Claim::Reuse(Box::new(execution.clone())));
334 }
335 }
336 }
337 }
338 let stale: Vec<_> = keys
340 .iter()
341 .filter(|(id, _)| !matches!(cached.get(**id), Some(Claim::Reuse(_))))
342 .map(|(id, key)| ((*id).clone(), key.eval_def_hash.clone()))
343 .collect();
344 known
345 .previous
346 .extend(store::read_latest_cached(self.state, &stale).await?);
347 let deferred = store::read_deferred(
348 self.state,
349 &self.config.root,
350 cached
351 .iter()
352 .filter_map(|(id, claim)| match claim {
353 Claim::WaitHuman(execution) => Some((id.clone(), execution.clone())),
354 _ => None,
355 })
356 .collect(),
357 )
358 .await?;
359 known.deferred.extend(deferred);
360 known.cached.extend(cached);
361 known.keys.extend(new);
362 Ok(())
363 }
364
365 fn assemble(&self, fingerprints: &Fingerprints<'a>, known: &Known<'a>) -> StatusView {
366 view::assemble(
367 self.config,
368 self.graph,
369 self.projection,
370 self.selection,
371 self.options,
372 Snapshot {
373 required: self.required,
374 evals: self.evals,
375 input_errors: self.input_errors,
376 selected_eval_ids: self.selected_eval_ids,
377 included_eval_ids: self.included_eval_ids,
378 fingerprints,
379 known,
380 },
381 )
382 }
383}
384
385impl Counts {
386 fn action(&mut self, action: VerifyAction) {
387 match action {
388 VerifyAction::Execute => self.execute += 1,
389 VerifyAction::Reuse => self.reuse += 1,
390 VerifyAction::Wait => self.wait += 1,
391 VerifyAction::Blocked => self.blocked += 1,
392 }
393 }
394}