Skip to main content

artifactize_core/project/
verify.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    path::Path,
4    sync::Arc,
5};
6
7use tokio_util::sync::CancellationToken;
8
9use crate::{
10    broker::{self, now},
11    cache,
12    config::{ProfileKind, read_workspace_declarations},
13    graph::{EvalStatus, Evidence, Graph},
14    project::selection::Selection,
15    remote::Session,
16    store::{self, ExecutionOptions, Receipts, Request, Run, RunView},
17    workspace,
18};
19
20#[derive(Debug, Clone, Default)]
21pub struct VerifyOptions {
22    pub modes: crate::runs::RunModes,
23    /// Optional per-Run concurrency cap; absent admits every READY eval.
24    pub jobs: Option<usize>,
25    /// Fingerprints computed at once, in preparation and end-of-review rechecks; `None` uses
26    /// the available CPUs.
27    pub fingerprint_jobs: Option<usize>,
28    pub max_executions: Option<u64>,
29    /// Kinds whose evals only reuse a result, from the cache or the review store; one with
30    /// nothing to reuse is not executed, and the Run ends INCOMPLETE.
31    pub reuse_only: BTreeSet<ProfileKind>,
32    pub recursive: bool,
33    /// Force only explicitly selected Evals, never recursive dependencies.
34    pub force: bool,
35    /// What the requester is working on, shown with the Run; it changes nothing it does.
36    pub comment: Option<crate::types::RunComment>,
37}
38
39/// Submit to artifactize and observe settlement. Cancelling this future/token only stops watching.
40pub async fn verify(
41    repo: &Path,
42    state_dir: Option<&Path>,
43    selection: &Selection,
44    options: &VerifyOptions,
45    cancellation: CancellationToken,
46) -> Result<RunView, String> {
47    super::fingerprint_parallelism(options)?;
48    let context = crate::runs::Context::discover(repo, state_dir)?;
49    let observation = crate::runs::start(&context, selection, options, None).await?;
50    crate::runs::wait(&context, &observation.run, None, cancellation).await?;
51    crate::runs::view(&context, &observation.run).await
52}
53/// Validate declarations and reserve initial requests; fingerprints and remote I/O follow admission.
54pub(crate) async fn reserve(
55    repo: &Path,
56    state_dir: Option<&Path>,
57    selection: &Selection,
58    options: &VerifyOptions,
59    request_key: Option<&crate::types::RequestKey>,
60    request_args_hash: Option<&str>,
61    origin: &crate::runs::Origin,
62) -> Result<(crate::types::RunId, bool), String> {
63    if options.jobs == Some(0) {
64        return Err("jobs must be at least 1.".into());
65    }
66    let parallelism = super::fingerprint_parallelism(options)?;
67    let config = read_workspace_declarations(repo).map_err(|e| e.to_string())?;
68    let graph = Graph::new(&config).map_err(|e| e.to_string())?;
69    let plan = selection.plan(&config, &graph, options.recursive)?;
70    let selected_ids: BTreeSet<_> = plan.selected.iter().map(|eval| &eval.id).collect();
71    let mut definitions = store::definitions::Definitions::from_view(&crate::query::scoped_graph(
72        &config,
73        selection,
74        &graph,
75        plan.required.iter().copied(),
76    ))
77    .map_err(|error| error.to_string())?;
78    if plan.required.len() < config.artifacts.len() {
79        definitions.remember_scope(crate::config::DeclarationScope::of(
80            &config,
81            plan.required.iter().copied(),
82        ));
83    }
84    let state = store::state_dir(state_dir)?;
85    let _limits = crate::limits::Limits::read(&state)?;
86    let receipts = Receipts::open(&state, &config.root).await?;
87    let result = async {
88        let runs = workspace::prepare_directory(&state.join("runs"), &config.root)
89            .map_err(|e| e.to_string())?;
90        let directory =
91            crate::platform::private_tempdir_in("run-", &runs).map_err(|e| e.to_string())?;
92        let id = directory
93            .path()
94            .file_name()
95            .unwrap()
96            .to_str()
97            .expect("generated run directory names are ASCII")
98            .to_owned();
99        directory.keep().map_err(|e| e.to_string())?;
100        let run = Run {
101            modes: options.modes.clone(),
102            control: Some(crate::runs::Control::starting()?),
103            request_key: request_key.cloned(),
104            request_args_hash: request_args_hash.map(str::to_owned),
105            origin: Some(origin.clone()),
106            comment: options.comment.clone(),
107            id: id.parse()?,
108            repo_path: config.root.clone(),
109            repository: crate::repository::identify(&config.root),
110            state_dir: state,
111            state: crate::store::RunState::Running,
112            created_at: now(),
113            selection: selection.clone(),
114            definitions,
115            jobs: options.jobs,
116            fingerprint_jobs: Some(parallelism.limit()),
117            max_executions: options.max_executions,
118            executions_started: 0,
119            wait_timeout_ms: None,
120            wait_timed_out: false,
121            reuse_only: options.reuse_only.clone(),
122            recursive: options.recursive,
123            force: options.force,
124            validation: Default::default(),
125            stopped_backends: Vec::new(),
126            evidence: BTreeMap::new(),
127        };
128        let requests: Vec<_> = plan
129            .included
130            .iter()
131            .enumerate()
132            .map(|(ordinal, eval)| Request {
133                state: crate::store::RequestState::pending(
134                    crate::types::RequestStatus::Queued,
135                    None,
136                )
137                .expect("queued state"),
138                id: format!("{}-{}", run.id, ordinal + 1)
139                    .parse()
140                    .expect("generated request id is a safe segment"),
141                run_id: run.id.clone(),
142                eval_id: eval.id.clone(),
143                target: eval.target.clone(),
144                title: eval.declaration.title.clone(),
145                profile: (eval.declaration.profile()).into(),
146                requested_profile: (eval.declaration.profile()).into(),
147                eval_def_hash: cache::eval_definition_hash(&eval.declaration),
148                options: ExecutionOptions {
149                    mutex: eval.declaration.mutex.clone(),
150                    ..ExecutionOptions::new(eval.declaration.profile())
151                },
152                execution_id: None,
153                provenance: None,
154                usage: None,
155                reused_usage: None,
156                joined: false,
157                producer: None,
158                reviewer: None,
159                origin: None,
160                session_id: None,
161                session: None,
162                review_notes: None,
163                human_definition: None,
164                payload: eval.declaration.payload().into(),
165                references: eval.references.clone(),
166                deps: eval.deps.clone(),
167                force: options.force && selected_ids.contains(&eval.id),
168                fingerprint: None,
169                key: None,
170                fingerprints: Default::default(),
171                created_at: run.created_at,
172                started_at: None,
173                cwd: config.root.join(config.artifacts[&eval.target].folder()),
174                run_dir: None,
175                argv: None,
176                child: None,
177                blocked_reason: None,
178                blocked_by: Vec::new(),
179            })
180            .collect();
181        let id = receipts.reserve(&run, &requests).await?;
182        let accepted = id == run.id;
183        if !accepted {
184            let _ = std::fs::remove_dir(run.state_dir.join("runs").join(run.id.as_str()));
185        }
186        Ok((id, accepted))
187    }
188    .await;
189    let closed = receipts.close().await;
190    result.and_then(|reserved| closed.map(|()| reserved))
191}
192/// Keep the failure kind typed through execution; prefixes belong only to display.
193#[derive(Debug, thiserror::Error)]
194pub(crate) enum Error {
195    #[error("INPUT_CHANGED: {0}")]
196    InputChanged(String),
197    #[error("{0}")]
198    Preparation(String),
199}
200impl Error {
201    pub(crate) fn code(&self) -> crate::types::FailureCode {
202        match self {
203            Self::InputChanged(_) => crate::types::FailureCode::InputChanged,
204            Self::Preparation(_) => crate::types::FailureCode::PreparationFailed,
205        }
206    }
207}
208impl From<String> for Error {
209    fn from(message: String) -> Self {
210        Self::Preparation(message)
211    }
212}
213impl From<&str> for Error {
214    fn from(message: &str) -> Self {
215        Self::Preparation(message.into())
216    }
217}
218
219/// Execute exactly the admitted Run. Never reserve a second Run or substitute changed declarations.
220pub(crate) async fn execute(
221    mut run: Run,
222    receipts: &Receipts,
223    cancellation: CancellationToken,
224) -> Result<(), Error> {
225    let selection = &run.selection.clone();
226    let options = &VerifyOptions {
227        modes: run.modes.clone(),
228        jobs: run.jobs,
229        fingerprint_jobs: run.fingerprint_jobs,
230        max_executions: run.max_executions,
231        reuse_only: run.reuse_only.clone(),
232        recursive: run.recursive,
233        force: run.force,
234        comment: run.comment.clone(),
235    };
236    let repo = &run.repo_path;
237    let state_dir = Some(run.state_dir.as_path());
238    if options.jobs == Some(0) {
239        return Err("jobs must be at least 1.".into());
240    }
241    let parallelism = super::fingerprint_parallelism(options)?;
242    // The profiles read the environment the Run was submitted with, not this process's.
243    let accepted = Accepted::new(selection, std::mem::take(&mut run.definitions))?;
244    let state = store::state_dir(state_dir)?;
245    let limits = crate::limits::Limits::read(&state)?;
246    let runs =
247        workspace::prepare_directory(&state.join("runs"), repo).map_err(|e| e.to_string())?;
248    let inputs = {
249        let config = accepted.read(repo)?;
250        let graph = Graph::new(&config).map_err(|error| Error::InputChanged(error.to_string()))?;
251        let plan = accepted.plan(&config, &graph, options.recursive)?;
252        cache::Inputs::new(&config, &plan.evals)?
253    };
254    crate::platform::release_free_memory();
255    let prepared = inputs
256        .prepare(&runs, &parallelism, cancellation.clone())
257        .await?;
258    if cancellation.is_cancelled() {
259        return Err("Project preparation was cancelled.".into());
260    }
261    // The accepted declarations must still match at the execution boundary. The second
262    // expansion is also what the broker uses; no expanded graph was kept during fingerprinting.
263    let config = Arc::new(accepted.read(repo)?);
264    let graph = Graph::new(&config).map_err(|error| Error::InputChanged(error.to_string()))?;
265    let plan = accepted.plan(&config, &graph, options.recursive)?;
266    let required = &plan.required;
267    let fingerprints: BTreeMap<_, _> = prepared
268        .into_iter()
269        .map(|(id, value)| {
270            let (id, _) = config
271                .artifacts
272                .get_key_value(&id)
273                .expect("in accepted fingerprint scope");
274            (id, value)
275        })
276        .collect();
277    let keys: BTreeMap<_, _> = plan
278        .evals
279        .iter()
280        .filter_map(|eval| {
281            Some((
282                &eval.id,
283                cache::eval_key(&config, eval, &fingerprints).ok()?,
284            ))
285        })
286        .collect();
287    // The store is asked once for every key, and a record that completed after the local
288    // latest is mirrored into the local history before the Run claims anything. A forced Run
289    // reads nothing from the store, but publishes its results like any other.
290    let remote = Session::open(Some(&state), Some(&config.root))?;
291    // Results from a fake provider must never reach the shared review store.
292    if remote.is_some()
293        && let Some(variable) = crate::llm::active_test_endpoint()
294    {
295        return Err(format!(
296            "{variable} points Agent reviews at a local test endpoint; set ARTIFACTIZE_REMOTE=off so their results stay out of the review store."
297        ).into());
298    }
299    if let Some(remote) = &remote
300        && !options.force
301    {
302        remote
303            .refresh(
304                receipts,
305                keys.values().map(|key| key.value.clone()).collect(),
306            )
307            .await?;
308        // The store can take time: don't start an eval against a declaration changed since
309        // the execution-boundary read above.
310        accepted.recheck(repo)?;
311    }
312    let mut requests = store::read_run_requests_only(&state, &run.id).await?;
313    let included: BTreeMap<_, _> = plan.included.iter().map(|&eval| (&eval.id, eval)).collect();
314    for request in &mut requests {
315        request.fingerprint = fingerprints
316            .get(&request.target)
317            .map(|fingerprint| fingerprint.value.clone());
318        request.key = keys.get(&request.eval_id).map(|key| key.value.clone());
319        let eval = included.get(&request.eval_id)
320            .ok_or_else(|| {
321                format!(
322                    "Saved request {} in Run {} refers to Eval {}, which is missing from the workspace configuration.",
323                    request.id, request.run_id, request.eval_id
324                )
325            })?;
326        request.fingerprints = cache::dependencies(&config, eval)
327            .into_iter()
328            .filter_map(|name| {
329                fingerprints
330                    .get(name)
331                    .map(|fingerprint| (name.clone(), fingerprint.value.clone()))
332            })
333            .collect();
334        receipts.save_request(request).await?;
335    }
336    run.control.as_mut().expect("owned Run").activity = crate::runs::Activity::Executing;
337    receipts.save_run(&run).await?;
338    let mut evidence = match broker::schedule(
339        config.clone(),
340        &graph,
341        &plan.evals,
342        &fingerprints,
343        &keys,
344        &parallelism,
345        &limits,
346        &mut run,
347        &mut requests,
348        receipts,
349        remote.clone(),
350        cancellation.clone(),
351    )
352    .await
353    {
354        Ok(evidence) => evidence,
355        Err(error) => {
356            return Err(error.into());
357        }
358    };
359    let evaluation = graph.evaluate_for_run(&evidence, run.modes.speculate);
360    // Freeze cancellation once at settlement so the Run and its requests agree.
361    let cancelled = cancellation.is_cancelled();
362    let at = now();
363    for request in &mut requests {
364        // A cancelled Run withdraws its waiting sign-offs too, deferred ones included.
365        let withdrawn = request.status().is_human_wait() && cancelled;
366        if !withdrawn
367            && (evidence.contains_key(request.eval_id.as_str()) || request.status().is_human_wait())
368        {
369            continue;
370        }
371        let eval = &evaluation.evals[request.eval_id.as_str()];
372        if request.status() == crate::types::RequestStatus::Blocked && !cancelled {
373            // A block saved mid-Run named the causes known then; the settled Run names all.
374            if eval.status == EvalStatus::Blocked {
375                request.blocked_by = eval.blocked_by.iter().copied().map(Into::into).collect();
376                request.blocked_reason = Some(gate_reason(eval));
377            }
378            continue;
379        }
380        if cancelled {
381            request.state = crate::store::RequestState::failed(
382                "Run was cancelled.".into(),
383                Some(crate::types::FailureCode::Cancelled),
384                at,
385            );
386            evidence.insert(request.eval_id.clone(), Evidence::OperationalError);
387        } else if request.status() == crate::types::RequestStatus::BudgetExhausted
388            && eval.can_execute()
389        {
390            continue;
391        } else {
392            request.state =
393                crate::store::RequestState::pending(status(eval.status), request.completed_at())
394                    .expect("non-executed request state");
395            request.blocked_reason = Some(gate_reason(eval));
396        }
397    }
398    let evaluation = graph.evaluate_for_run(&evidence, run.modes.speculate);
399    let required_evals: Vec<_> = evaluation
400        .evals
401        .iter()
402        .filter(|(id, _)| required.contains(&graph.eval_target(id).unwrap()))
403        .collect();
404    let satisfied = required
405        .iter()
406        .all(|id| evaluation.artifacts[id.as_str()].satisfied());
407    let budget_exhausted = requests
408        .iter()
409        .any(|request| request.status() == crate::types::RequestStatus::BudgetExhausted);
410    // Only a --reuse-only eval that had nothing to reuse leaves stale evidence in a Run.
411    let not_reused = evidence
412        .values()
413        .filter(|evidence| matches!(evidence, Evidence::Stale))
414        .count();
415    run.state = terminal_state(
416        TerminalFacts {
417            required_evals: &required_evals,
418            satisfied,
419            required_have_review_basis: required.iter().all(|id| {
420                // A parent without evals of its own is reviewed through its parts.
421                let artifact = &graph.artifacts()[id.as_str()];
422                artifact.basis || !artifact.evals.is_empty() || !artifact.parts.is_empty()
423            }),
424            budget_error: budget_exhausted.then(|| broker::budget_reason(&run)),
425            not_reused,
426        },
427        at,
428        cancelled,
429    );
430    if cancelled {
431        run.control.as_mut().expect("owned Run").failure_code =
432            Some(crate::types::FailureCode::Cancelled);
433    }
434    use crate::config::Field;
435    run.validation = store::Validation(Some(store::ValidationSnapshot {
436        selection: Field::Value(store::definitions::SavedSelection {
437            known: run.selection.clone(),
438            extra: Default::default(),
439        }),
440        recursive: Field::Value(run.recursive),
441        force: Field::Value(run.force),
442        selected_eval_ids: Field::Value(plan.selected.iter().map(|eval| eval.id.clone()).collect()),
443        included_eval_ids: Field::Value(plan.included.iter().map(|eval| eval.id.clone()).collect()),
444        satisfied: Field::Value(satisfied && !cancelled),
445        obligations: Field::Value(
446            evaluation
447                .obligations
448                .iter()
449                .filter(|id| required.contains(*id))
450                .map(|id| (*id).clone())
451                .collect(),
452        ),
453        artifacts: Field::Value(
454            required
455                .iter()
456                .map(|id| {
457                    let artifact = &evaluation.artifacts[id.as_str()];
458                    let (fingerprint_kind, fingerprint) = fingerprints.get(id).map_or(
459                        (Field::Missing, Field::Missing),
460                        |fingerprint| {
461                            (
462                                config.artifacts[*id]
463                                    .fingerprint
464                                    .as_ref()
465                                    .map(crate::config::Fingerprint::kind)
466                                    .into(),
467                                Field::Value(fingerprint.value.clone()),
468                            )
469                        },
470                    );
471                    store::ArtifactValidation {
472                        id: (*id).clone(),
473                        status: Field::Value(artifact.status.into()),
474                        passed: Field::Value(artifact.passed as u64),
475                        total: Field::Value(artifact.total as u64),
476                        satisfied: Field::Value(artifact.satisfied()),
477                        fingerprint_kind,
478                        fingerprint,
479                        extra: Default::default(),
480                    }
481                })
482                .collect(),
483        ),
484        evals: Field::Value(
485            required_evals
486                .iter()
487                .map(|(id, eval)| store::EvalValidation {
488                    id: (*id).clone(),
489                    status: Field::Value(status(eval.status)),
490                    blocked_by: Field::Value(
491                        eval.blocked_by.iter().copied().map(Into::into).collect(),
492                    ),
493                    extra: Default::default(),
494                })
495                .collect(),
496        ),
497        extra: Default::default(),
498    }));
499    if cancelled {
500        receipts
501            .retire_worker(&run.id, crate::types::FailureCode::Cancelled)
502            .await?;
503    }
504    if run.modes.speculate
505        && let Some(remote) = remote
506    {
507        // A blocked result cannot be retracted from a team store. Publish survivors only
508        // after scheduling/withdrawal finishes, while the owned Run still owns failures.
509        run.control.as_mut().expect("owned Run").activity = crate::runs::Activity::Publishing;
510        let mut publishing = run.clone();
511        publishing.state = crate::store::RunState::Running;
512        receipts.save_run(&publishing).await?;
513        for request in &requests {
514            remote.publish_request(receipts, request).await?;
515        }
516    }
517    // The reuse history is collected once per Run, before it ends so that whoever waits for
518    // the end also sees a failure, which only warns.
519    if let Err(error) = store::history::collect(&run.state_dir).await {
520        use std::io::Write;
521        let _ = writeln!(std::io::stderr().lock(), "Cache GC failed: {error}");
522    }
523    receipts.finish(&run, &requests).await?;
524    // Saved Agent conversations past their size bound are collected; a failure only warns.
525    let state = run.state_dir.clone();
526    let bounds = limits.agent_sessions();
527    let collected = crate::task::joined(
528        tokio::task::spawn_blocking(move || crate::agent::session::collect(&state, bounds, false))
529            .await,
530    )
531    .map_err(|e| e.to_string())
532    .and_then(|collected| collected);
533    if let Err(error) = collected {
534        use std::io::Write;
535        let _ = writeln!(
536            std::io::stderr().lock(),
537            "Agent session collection failed: {error}"
538        );
539    }
540    Ok(())
541}
542
543struct TerminalFacts<'a, 'graph> {
544    required_evals: &'a [(
545        &'a crate::types::EvalId,
546        &'a crate::graph::EvalEvaluation<'graph>,
547    )],
548    satisfied: bool,
549    required_have_review_basis: bool,
550    budget_error: Option<String>,
551    not_reused: usize,
552}
553
554fn terminal_state(
555    facts: TerminalFacts<'_, '_>,
556    at: crate::types::Timestamp,
557    cancelled: bool,
558) -> store::RunState {
559    use store::RunState;
560    let TerminalFacts {
561        required_evals,
562        satisfied,
563        required_have_review_basis,
564        budget_error,
565        not_reused,
566    } = facts;
567    if cancelled {
568        RunState::Error {
569            at,
570            error: Some("Run was cancelled.".into()),
571        }
572    } else if let Some(error) = budget_error {
573        RunState::Incomplete {
574            at,
575            error: Some(error),
576        }
577    } else if not_reused > 0 {
578        RunState::Incomplete {
579            at,
580            error: Some(format!(
581                "{not_reused} eval{} had no result to reuse and {} not executed (--reuse-only).",
582                if not_reused == 1 { "" } else { "s" },
583                if not_reused == 1 { "was" } else { "were" }
584            )),
585        }
586    } else if required_evals
587        .iter()
588        .any(|(_, c)| c.status == EvalStatus::Error)
589    {
590        RunState::Error { at, error: None }
591    } else if required_evals
592        .iter()
593        .any(|(_, c)| c.status == EvalStatus::Red)
594    {
595        RunState::Red { at }
596    } else if required_evals
597        .iter()
598        .any(|(_, eval)| eval.status == EvalStatus::Deferred)
599        && required_evals
600            .iter()
601            .all(|(_, eval)| eval.status.passes_gate())
602        && required_have_review_basis
603    {
604        RunState::Yellow { at }
605    } else if satisfied {
606        RunState::Green { at }
607    } else {
608        RunState::Incomplete { at, error: None }
609    }
610}
611
612pub(crate) fn status(status: EvalStatus) -> crate::types::RequestStatus {
613    match status {
614        EvalStatus::Deferred => crate::types::RequestStatus::Deferred,
615        EvalStatus::Provisional => crate::types::RequestStatus::Provisional,
616        EvalStatus::Green => crate::types::RequestStatus::Green,
617        EvalStatus::Red => crate::types::RequestStatus::Red,
618        EvalStatus::Error => crate::types::RequestStatus::Error,
619        EvalStatus::Stale => crate::types::RequestStatus::Stale,
620        EvalStatus::Unreviewed => crate::types::RequestStatus::Unreviewed,
621        EvalStatus::Wait => crate::types::RequestStatus::WaitDependency,
622        EvalStatus::Blocked => crate::types::RequestStatus::Blocked,
623    }
624}
625
626/// The same gate explanation is saved during scheduling and at Run settlement.
627pub(crate) fn gate_reason(eval: &crate::graph::EvalEvaluation<'_>) -> String {
628    eval.blocked_reason().unwrap_or_else(|| {
629        format!(
630            "Waiting for current GREEN dependency evidence: {}",
631            eval.unmet_gates
632                .iter()
633                .map(ToString::to_string)
634                .collect::<Vec<_>>()
635                .join(", ")
636        )
637    })
638}
639
640/// A compact identity of the immutable admitted definitions. This lives only for the
641/// worker's lifetime; the published Run keeps the full definitions in its saved row.
642struct Accepted<'a> {
643    selection: &'a Selection,
644    environment: BTreeMap<String, Option<String>>,
645    scope: Option<crate::config::DeclarationScope>,
646    digest: [u8; 32],
647}
648
649impl<'a> Accepted<'a> {
650    fn new(
651        selection: &'a Selection,
652        mut saved: store::definitions::Definitions,
653    ) -> Result<Self, Error> {
654        let scope = saved.take_scope();
655        Ok(Self {
656            selection,
657            environment: saved.environment(),
658            scope,
659            digest: definitions_digest(&saved)?,
660        })
661    }
662
663    fn read(&self, repo: &Path) -> Result<crate::config::RepoConfig, Error> {
664        let environment = |name: &str| self.environment.get(name).cloned().flatten();
665        if let Some(scope) = &self.scope
666            && let Ok(mut config) = scope.read(repo, crate::config::Evals::All, &environment)
667        {
668            // Preserve the environment snapshot of the admitted Run, including variables
669            // belonging to profiles that the selected scope does not read.
670            if let Some(program) = &mut config.program {
671                Arc::make_mut(program)
672                    .environment
673                    .clone_from(&self.environment);
674            }
675            if let Ok(view) = crate::query::graph(&config, self.selection)
676                && self.check(&view).is_ok()
677            {
678                return Ok(config);
679            }
680        }
681        crate::config::read_workspace_declarations_with(repo, &environment)
682            .map_err(|error| Error::InputChanged(error.to_string()))
683    }
684
685    fn plan<'b>(
686        &self,
687        config: &'b crate::config::RepoConfig,
688        graph: &Graph<'b>,
689        recursive: bool,
690    ) -> Result<crate::project::selection::Plan<'b>, Error> {
691        let plan = self
692            .selection
693            .plan(config, graph, recursive)
694            .map_err(Error::InputChanged)?;
695        self.check(&crate::query::scoped_graph(
696            config,
697            self.selection,
698            graph,
699            plan.required.iter().copied(),
700        ))?;
701        Ok(plan)
702    }
703
704    fn recheck(&self, repo: &Path) -> Result<(), Error> {
705        let config = self.read(repo)?;
706        let view = crate::query::graph(&config, self.selection).map_err(Error::InputChanged)?;
707        self.check(&view)
708    }
709
710    fn check(&self, view: &crate::query::GraphView<'_>) -> Result<(), Error> {
711        let current = store::definitions::Definitions::from_view(view)
712            .map_err(|error| Error::InputChanged(error.to_string()))?;
713        if definitions_digest(&current)? != self.digest {
714            return Err(Error::InputChanged(
715                "declarations changed after acceptance.".into(),
716            ));
717        }
718        Ok(())
719    }
720}
721
722fn definitions_digest(definitions: &store::definitions::Definitions) -> Result<[u8; 32], Error> {
723    use sha2::{Digest, Sha256};
724    let graph = definitions
725        .graph()
726        .ok_or_else(|| Error::InputChanged("The Run has no saved declarations.".into()))?;
727    // Component numbers are positions in the caller's graph, not declarations. The
728    // Artifact parts, eval inputs and labeled relations already determine the components;
729    // a scope read and a workspace read may number the same component differently.
730    let identity = (
731        &graph.version,
732        &graph.repo_path,
733        &graph.selection,
734        &graph.artifacts,
735        &graph.evals,
736        &graph.relations,
737        &graph.extra,
738    );
739    let bytes =
740        serde_json::to_vec(&identity).map_err(|error| Error::InputChanged(error.to_string()))?;
741    Ok(Sha256::digest(bytes).into())
742}
743
744#[cfg(test)]
745mod tests;