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