Skip to main content

artifactize_core/monitor/model/
states.rs

1//! Eval view states: what one tree row shows, derived from the saved definitions and the
2//! current request states with the readiness rules of [`crate::graph`].
3//!
4//! Each Eval has its own references and gates, and its target's children count as references;
5//! its own Artifact and that Artifact's cycle peers never gate it.
6use std::{
7    cell::RefCell,
8    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
9};
10
11use super::Saved;
12use crate::{
13    graph::EvalStatus,
14    store::RequestView,
15    types::{ArtifactName, EvalId, RequestStatus},
16};
17
18/// Where a done eval's GREEN came from.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum Source {
21    Executed,
22    Provisional,
23    Reused,
24    /// A saved result the Run used for an eval it has no request for.
25    Saved,
26}
27
28/// Why a queued eval has not started although nothing upstream holds it.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum Queue {
31    /// Ready, waiting for scheduler admission without a Run cap.
32    Ready,
33    /// Waiting for the Run's explicitly chosen `--jobs` cap.
34    Jobs,
35    /// Waiting for a backend slot (limits.json); holds the backend name.
36    Slot(crate::config::Backend),
37    /// Waiting for the running execution of the same reuse key.
38    Joined,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum Activity {
43    Running,
44    /// The claimant, when someone has claimed it.
45    Human(Option<crate::types::ReviewerId>),
46    Queued(Queue),
47}
48
49/// The Artifacts an eval waits for, most actionable first, and one level of root cause when
50/// every one of them is itself waiting: `(via, root)` reads "via waits for root".
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Waits {
53    pub artifacts: Vec<crate::types::ArtifactName>,
54    pub root: Option<(crate::types::ArtifactName, crate::types::ArtifactName)>,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum NotRun {
59    /// A finished Run ended while the eval still waited for these Artifacts.
60    Dependency(Waits),
61    Budget,
62    Stale,
63    Unreviewed,
64    /// The eval has no request in this Run.
65    Absent,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub enum EvalView {
70    Done(Source),
71    /// `verdict` is RED; otherwise an operational ERROR.
72    Failed {
73        verdict: bool,
74    },
75    InProgress(Activity),
76    /// Only while the Run is running.
77    WaitingOn(Waits),
78    /// Upstream failed with a RED verdict or is itself blocked.
79    BlockedBy(Vec<crate::types::ArtifactName>),
80    NotRun(NotRun),
81}
82
83/// Roll-up urgency, ordered from failed to done for eval rows and Artifact completions.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
85pub enum Rank {
86    Failed,
87    InProgress,
88    Blocked,
89    Waiting,
90    NotRun,
91    Done,
92}
93
94impl EvalView {
95    pub fn rank(&self) -> Rank {
96        match self {
97            Self::Failed { .. } => Rank::Failed,
98            Self::InProgress(_) => Rank::InProgress,
99            Self::BlockedBy(_) => Rank::Blocked,
100            Self::WaitingOn(_) => Rank::Waiting,
101            Self::NotRun(_) => Rank::NotRun,
102            Self::Done(_) => Rank::Done,
103        }
104    }
105}
106
107/// The most urgent kind of activity in an in-progress Artifact.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
109pub enum Busy {
110    Running,
111    Human,
112    Queued,
113}
114
115/// An Artifact's evaluation as a whole, as shown where another eval waits for it.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum Completion {
118    /// Every eval is done; also basis Artifacts and Artifacts without evals.
119    Complete,
120    InProgress(Busy),
121    /// Some eval waits, is blocked or did not run.
122    Waiting {
123        blocked: bool,
124    },
125    /// `verdict` when an eval is RED, otherwise only operational ERRORs.
126    Failed {
127        verdict: bool,
128    },
129}
130
131impl Completion {
132    /// Order of X: failed, in progress, waiting, complete; blocked completions still wait.
133    pub(super) fn rank(self) -> Rank {
134        match self {
135            Self::Failed { .. } => Rank::Failed,
136            Self::InProgress(_) => Rank::InProgress,
137            Self::Waiting { .. } => Rank::Waiting,
138            Self::Complete => Rank::Done,
139        }
140    }
141}
142
143/// One Artifact an eval depends on, with its current completion.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct Upstream {
146    pub artifact: crate::types::ArtifactName,
147    pub completion: Completion,
148}
149
150/// Per-Run index from saved definitions: display order, evals per Artifact and the
151/// Artifacts each eval depends on. Built in one pass over the definitions and requests.
152pub(super) struct Index<'a> {
153    pub order: Vec<&'a ArtifactName>,
154    position: HashMap<&'a ArtifactName, usize>,
155    requests: HashMap<&'a EvalId, &'a RequestView>,
156    pub evals: BTreeMap<&'a ArtifactName, Vec<&'a EvalId>>,
157    /// Eval → direct dependency Artifacts, in display order.
158    pub upstream: BTreeMap<&'a EvalId, Vec<&'a ArtifactName>>,
159    gates: BTreeMap<&'a EvalId, Vec<&'a EvalId>>,
160    execution_order: Vec<&'a EvalId>,
161    targets: BTreeMap<&'a EvalId, &'a ArtifactName>,
162    /// Artifact → its cycle peers (same component), by name.
163    pub peers: BTreeMap<&'a ArtifactName, Vec<&'a ArtifactName>>,
164    /// Artifact → the Artifacts it is directly composed of.
165    pub parts: BTreeMap<&'a ArtifactName, Vec<&'a ArtifactName>>,
166    pub cyclic: BTreeSet<&'a ArtifactName>,
167}
168
169type Component = crate::store::definitions::Component;
170
171fn members(component: &Component) -> Vec<&ArtifactName> {
172    component.artifacts.value().into_iter().flatten().collect()
173}
174
175impl<'a> Index<'a> {
176    pub fn new(saved: &Saved<'a>) -> Self {
177        let order = saved.artifact_ids();
178        let position: HashMap<_, _> = order
179            .iter()
180            .enumerate()
181            .map(|(index, id)| (*id, index))
182            .collect();
183        let mut requests = HashMap::new();
184        for view in saved.requests {
185            requests.entry(&view.request.eval_id).or_insert(view);
186        }
187        let definitions: HashMap<_, _> = saved
188            .eval_definitions()
189            .iter()
190            .map(|eval| (&eval.id, eval))
191            .collect();
192        // Saved Eval definitions targeting each Artifact, then requests without one.
193        let mut targets: HashMap<&ArtifactName, Vec<&EvalId>> = HashMap::new();
194        for eval in saved.eval_definitions() {
195            targets.entry(&eval.target).or_default().push(&eval.id);
196        }
197        for view in saved.requests {
198            let request = &view.request;
199            if !definitions.contains_key(&request.eval_id) {
200                let evals = targets.entry(&request.target).or_default();
201                if !evals.contains(&&request.eval_id) {
202                    evals.push(&request.eval_id);
203                }
204            }
205        }
206        let evals: BTreeMap<_, _> = order
207            .iter()
208            .map(|&artifact| {
209                let mut ids = targets.remove(artifact).unwrap_or_default();
210                ids.sort_unstable();
211                (artifact, ids)
212            })
213            .collect();
214        let components = saved.components();
215        let mut peers = BTreeMap::new();
216        let mut cyclic = BTreeSet::new();
217        for component in components {
218            let mut names = members(component);
219            names.sort_unstable();
220            for &artifact in &names {
221                peers.insert(
222                    artifact,
223                    names.iter().copied().filter(|id| *id != artifact).collect(),
224                );
225                if component.cyclic.value() == Some(&true) {
226                    cyclic.insert(artifact);
227                }
228            }
229        }
230        let targets: BTreeMap<_, _> = evals
231            .iter()
232            .flat_map(|(&target, ids)| ids.iter().map(move |&id| (id, target)))
233            .collect();
234        // An eval depends on what it references.
235        let inputs: BTreeMap<_, Vec<_>> = targets
236            .iter()
237            .map(|(&eval, _)| {
238                let deps: Vec<_> = definitions
239                    .get(eval)
240                    .and_then(|definition| definition.deps.value())
241                    .map(|deps| deps.iter().collect())
242                    .unwrap_or_else(|| {
243                        requests
244                            .get(eval)
245                            .map_or(Vec::new(), |view| view.request.deps.iter().collect())
246                    });
247                (eval, deps)
248            })
249            .collect();
250        let human = |eval: &EvalId| match requests.get(eval) {
251            Some(view) => view.request.profile.kind() == crate::config::ProfileKind::Human,
252            None => definitions
253                .get(eval)
254                .and_then(|definition| definition.declaration.value())
255                .and_then(|declaration| declaration.profile.value())
256                .is_some_and(|profile| {
257                    matches!(profile.known, crate::config::StoredProfile::Human { .. })
258                }),
259        };
260        let schedule =
261            crate::graph::schedule::Schedule::new(targets.iter().map(|(&eval, &target)| {
262                crate::graph::schedule::Input {
263                    id: eval,
264                    target,
265                    deps: inputs[eval].clone(),
266                    human: human(eval),
267                }
268            }));
269        let upstream = inputs
270            .into_iter()
271            .map(|(eval, mut deps)| {
272                deps.extend(schedule.gates[eval].iter().map(|gate| targets[gate]));
273                let mut deps: Vec<_> = deps
274                    .into_iter()
275                    .collect::<BTreeSet<_>>()
276                    .into_iter()
277                    .collect();
278                deps.sort_by_key(|id| position.get(id).copied().unwrap_or(usize::MAX));
279                (eval, deps)
280            })
281            .collect();
282        let execution_order = schedule.order;
283        Self {
284            order,
285            position,
286            requests,
287            evals,
288            upstream,
289            gates: schedule.gates,
290            execution_order,
291            targets,
292            peers,
293            parts: saved.parts(),
294            cyclic,
295        }
296    }
297}
298
299/// Lazily derived views over one Run, using the same Eval gates as live scheduling.
300pub(super) struct States<'a> {
301    run: &'a crate::store::Run,
302    #[cfg(any(test, feature = "test-support"))]
303    pub derivations: std::cell::Cell<usize>,
304    pub index: Index<'a>,
305    pub running: bool,
306    views: RefCell<HashMap<&'a EvalId, Option<EvalView>>>,
307    effective: RefCell<HashMap<&'a EvalId, Option<EvalStatus>>>,
308    completions: RefCell<HashMap<&'a ArtifactName, Completion>>,
309    waits: RefCell<HashMap<&'a ArtifactName, Vec<ArtifactName>>>,
310    held: HashMap<&'a EvalId, bool>,
311}
312
313impl<'a> States<'a> {
314    /// Derive every Artifact once, upstream before downstream, so each lookup afterwards
315    /// is memoized and no derivation recurses along a long dependency chain.
316    pub fn new(saved: &Saved<'a>) -> Self {
317        let run = &saved.run.run;
318        let mut states = Self {
319            run,
320            #[cfg(any(test, feature = "test-support"))]
321            derivations: std::cell::Cell::new(0),
322            index: Index::new(saved),
323            running: run.status().is_open(),
324            views: RefCell::new(HashMap::new()),
325            effective: RefCell::new(HashMap::new()),
326            completions: RefCell::new(HashMap::new()),
327            waits: RefCell::new(HashMap::new()),
328            held: HashMap::new(),
329        };
330        for &eval in &states.index.execution_order {
331            states.effective(eval);
332            let held = states.index.gates[eval].iter().any(|&gate| {
333                matches!(
334                    states.effective(gate),
335                    EvalStatus::Red | EvalStatus::Blocked | EvalStatus::Error
336                ) || states.held[gate]
337            });
338            states.held.insert(eval, held);
339        }
340        for artifact in states.upstream_first() {
341            states.completion(artifact);
342            states.waits_of(artifact);
343        }
344        states
345    }
346
347    /// Every Artifact after the Artifacts its evals depend on (an iterative depth-first
348    /// post-order; projected Artifact cycles may come either way).
349    fn upstream_first(&self) -> Vec<&'a ArtifactName> {
350        let mut done = HashSet::new();
351        let mut seen = HashSet::new();
352        let mut ordered = Vec::with_capacity(self.index.order.len());
353        for &start in &self.index.order {
354            if !seen.insert(start) {
355                continue;
356            }
357            let mut stack = vec![(start, self.dependencies(start), 0)];
358            while let Some((artifact, dependencies, next)) = stack.last_mut() {
359                if let Some(&dependency) = dependencies.get(*next) {
360                    *next += 1;
361                    if seen.insert(dependency) {
362                        let dependencies = self.dependencies(dependency);
363                        stack.push((dependency, dependencies, 0));
364                    }
365                } else {
366                    if done.insert(*artifact) {
367                        ordered.push(*artifact);
368                    }
369                    stack.pop();
370                }
371            }
372        }
373        ordered
374    }
375
376    fn dependencies(&self, artifact: &ArtifactName) -> Vec<&'a ArtifactName> {
377        let mut seen = HashSet::new();
378        self.evals(artifact)
379            .iter()
380            .flat_map(|eval| self.upstream(eval).iter().copied())
381            .filter(|name| seen.insert(*name))
382            .collect()
383    }
384
385    /// The Artifact id as borrowed from the index, for memo keys.
386    fn key(&self, artifact: &ArtifactName) -> Option<&'a ArtifactName> {
387        self.index
388            .position
389            .get_key_value(artifact)
390            .map(|(&id, _)| id)
391    }
392
393    pub fn request(&self, eval: &EvalId) -> Option<&'a RequestView> {
394        self.index.requests.get(eval).copied()
395    }
396
397    /// Evidence the graph used for an eval without a request in this Run: the Run's
398    /// record of saved results, or for older Runs the validation saved at their end.
399    fn outside(&self, eval: &EvalId) -> Option<RequestStatus> {
400        if let Some(status) = self.run.evidence.get(eval) {
401            return Some(*status);
402        }
403        let saved = self.run.validation.snapshot()?.evals.value()?;
404        let status = *saved
405            .iter()
406            .find(|saved| &saved.id == eval)?
407            .status
408            .value()?;
409        matches!(
410            status,
411            RequestStatus::Green | RequestStatus::Red | RequestStatus::Error | RequestStatus::Stale
412        )
413        .then_some(status)
414    }
415
416    pub fn evals(&self, artifact: &ArtifactName) -> &[&'a EvalId] {
417        self.index.evals.get(artifact).map_or(&[], Vec::as_slice)
418    }
419
420    pub fn upstream(&self, eval: &EvalId) -> &[&'a ArtifactName] {
421        self.index.upstream.get(eval).map_or(&[], Vec::as_slice)
422    }
423
424    fn position(&self, artifact: &ArtifactName) -> usize {
425        self.index
426            .position
427            .get(artifact)
428            .copied()
429            .unwrap_or(usize::MAX)
430    }
431
432    pub fn view(&self, eval: &'a EvalId) -> EvalView {
433        if let Some(view) = self.views.borrow().get(eval) {
434            // Artifact-level presentation can revisit an Eval through a projected cycle.
435            return view.clone().unwrap_or(EvalView::NotRun(NotRun::Unreviewed));
436        }
437        self.views.borrow_mut().insert(eval, None);
438        #[cfg(any(test, feature = "test-support"))]
439        self.derivations.set(self.derivations.get() + 1);
440        let view = self.derive(eval);
441        self.views.borrow_mut().insert(eval, Some(view.clone()));
442        view
443    }
444
445    /// The eval's status as `graph.rs` evaluates it for gates: a GREEN result whose own
446    /// gates are unmet still waits or is blocked, and never fulfils a downstream gate.
447    pub fn effective(&self, eval: &'a EvalId) -> EvalStatus {
448        if let Some(status) = self.effective.borrow().get(eval) {
449            // Eval gates are acyclic; a revisit cannot supply a verdict.
450            return status.unwrap_or(EvalStatus::Wait);
451        }
452        self.effective.borrow_mut().insert(eval, None);
453        #[cfg(any(test, feature = "test-support"))]
454        self.derivations.set(self.derivations.get() + 1);
455        let status = self.evaluate(eval);
456        self.effective.borrow_mut().insert(eval, Some(status));
457        status
458    }
459
460    /// `Graph::evaluate` over the saved snapshot: gate readiness first, then
461    /// the eval's own evidence.
462    fn evaluate(&self, eval: &'a EvalId) -> EvalStatus {
463        let request = self.request(eval).map(|view| &view.request);
464        let status = request
465            .map(|request| request.status())
466            .or_else(|| self.outside(eval));
467        let unmet: Vec<_> = self
468            .index
469            .gates
470            .get(eval)
471            .into_iter()
472            .flatten()
473            .map(|&gate| (gate, self.effective(gate)))
474            .filter(|(_, status)| !status.passes_gate())
475            .collect();
476        if unmet
477            .iter()
478            .any(|&(gate, status)| self.status_blocks(eval, gate, status))
479        {
480            return EvalStatus::Blocked;
481        }
482        if !unmet.is_empty() {
483            return EvalStatus::Wait;
484        }
485        match status {
486            Some(RequestStatus::Deferred) => EvalStatus::Deferred,
487            // A provisional result stands once nothing it relies on is pending any more.
488            Some(RequestStatus::Provisional) if self.pending(eval).is_empty() => EvalStatus::Green,
489            Some(RequestStatus::Provisional) => EvalStatus::Provisional,
490            Some(RequestStatus::Green) => EvalStatus::Green,
491            Some(RequestStatus::Red) => EvalStatus::Red,
492            Some(RequestStatus::Error) => EvalStatus::Error,
493            Some(RequestStatus::Stale) => EvalStatus::Stale,
494            _ => EvalStatus::Unreviewed,
495        }
496    }
497
498    fn met(&self, artifact: &ArtifactName) -> bool {
499        self.evals(artifact)
500            .iter()
501            .all(|eval| self.effective(eval) == EvalStatus::Green)
502    }
503
504    fn derive(&self, eval: &'a EvalId) -> EvalView {
505        let Some(view) = self.request(eval) else {
506            // A saved result the Run used without a request of its own.
507            return match self.outside(eval) {
508                Some(RequestStatus::Green) => EvalView::Done(Source::Saved),
509                Some(RequestStatus::Red) => EvalView::Failed { verdict: true },
510                Some(RequestStatus::Error) => EvalView::Failed { verdict: false },
511                Some(RequestStatus::Stale) => EvalView::NotRun(NotRun::Stale),
512                _ => EvalView::NotRun(NotRun::Absent),
513            };
514        };
515        let request = &view.request;
516        match request.status() {
517            RequestStatus::Provisional if self.effective(eval) == EvalStatus::Provisional => {
518                EvalView::Done(Source::Provisional)
519            }
520            RequestStatus::Provisional | RequestStatus::Green => {
521                EvalView::Done(if crate::query::reused(request) {
522                    Source::Reused
523                } else {
524                    Source::Executed
525                })
526            }
527            RequestStatus::Red => EvalView::Failed { verdict: true },
528            RequestStatus::Error => EvalView::Failed { verdict: false },
529            RequestStatus::Running => EvalView::InProgress(Activity::Running),
530            RequestStatus::WaitingHuman | RequestStatus::Deferred => EvalView::InProgress(
531                Activity::Human(view.claim.as_ref().map(|claim| claim.reviewer.clone())),
532            ),
533            RequestStatus::BudgetExhausted => EvalView::NotRun(NotRun::Budget),
534            RequestStatus::Stale => EvalView::NotRun(NotRun::Stale),
535            RequestStatus::Queued
536            | RequestStatus::WaitDependency
537            | RequestStatus::Unreviewed
538            | RequestStatus::Blocked => {
539                let unmet = self.unmet(eval);
540                let blocking: Vec<_> = unmet
541                    .iter()
542                    .filter(|artifact| self.gate_blocks(eval, artifact))
543                    .cloned()
544                    .collect();
545                if !blocking.is_empty() {
546                    return EvalView::BlockedBy(blocking);
547                }
548                if self.run.modes.speculate {
549                    return self.ready(view);
550                }
551                if !unmet.is_empty() {
552                    let waits = Waits {
553                        root: self.root(&unmet),
554                        artifacts: unmet,
555                    };
556                    return if self.running {
557                        EvalView::WaitingOn(waits)
558                    } else {
559                        EvalView::NotRun(NotRun::Dependency(waits))
560                    };
561                }
562                self.ready(view)
563            }
564        }
565    }
566
567    /// Nothing upstream holds the eval.
568    fn ready(&self, view: &RequestView) -> EvalView {
569        let request = &view.request;
570        if !self.running || request.status() != RequestStatus::Queued {
571            return EvalView::NotRun(NotRun::Unreviewed);
572        }
573        EvalView::InProgress(Activity::Queued(
574            if let Some(crate::store::QueueReason::Slot { backend }) = request.state.queue_reason()
575            {
576                Queue::Slot(backend.clone())
577            } else if request.execution_id.is_some() {
578                Queue::Joined
579            } else if self.run.jobs.is_some() {
580                Queue::Jobs
581            } else {
582                Queue::Ready
583            },
584        ))
585    }
586
587    /// The Artifacts of this Eval's gates that pass only provisionally: a sign-off not yet
588    /// submitted, or a result that relies on one.
589    fn pending(&self, eval: &EvalId) -> Vec<ArtifactName> {
590        let mut artifacts: Vec<_> = self
591            .index
592            .gates
593            .get(eval)
594            .into_iter()
595            .flatten()
596            .filter(|&&gate| {
597                matches!(
598                    self.effective(gate),
599                    EvalStatus::Deferred | EvalStatus::Provisional
600                )
601            })
602            .map(|gate| self.index.targets[gate])
603            .collect::<BTreeSet<_>>()
604            .into_iter()
605            .collect();
606        artifacts
607            .sort_by_key(|artifact| (self.completion(artifact).rank(), self.position(artifact)));
608        artifacts.into_iter().cloned().collect()
609    }
610
611    /// Only this Eval's gates contribute waits; its own Artifact and cycle peers never do.
612    fn unmet(&self, eval: &EvalId) -> Vec<ArtifactName> {
613        let mut artifacts: Vec<_> = self
614            .index
615            .gates
616            .get(eval)
617            .into_iter()
618            .flatten()
619            .filter(|&&gate| !self.effective(gate).passes_gate())
620            .map(|gate| self.index.targets[gate])
621            .collect::<BTreeSet<_>>()
622            .into_iter()
623            .collect();
624        artifacts
625            .sort_by_key(|artifact| (self.completion(artifact).rank(), self.position(artifact)));
626        artifacts.into_iter().cloned().collect()
627    }
628
629    fn views_of(&self, artifact: &ArtifactName) -> Vec<EvalView> {
630        self.evals(artifact)
631            .iter()
632            .map(|eval| self.view(eval))
633            .collect()
634    }
635
636    /// The Artifact's completion from its eval rows; done rows whose own gates are unmet
637    /// do not complete it. A part that is not complete keeps its parent from it too.
638    pub fn completion(&self, artifact: &ArtifactName) -> Completion {
639        if let Some(completion) = self.completions.borrow().get(artifact) {
640            return *completion;
641        }
642        let own = self.own_completion(artifact);
643        let completion = self
644            .index
645            .parts
646            .get(artifact)
647            .into_iter()
648            .flatten()
649            .map(|part| self.completion(part))
650            .chain([own])
651            .min_by_key(|completion| match completion {
652                Completion::Failed { verdict } => (completion.rank(), *verdict),
653                _ => (completion.rank(), true),
654            })
655            .expect("its own completion");
656        if let Some(id) = self.key(artifact) {
657            self.completions.borrow_mut().insert(id, completion);
658        }
659        completion
660    }
661
662    fn own_completion(&self, artifact: &ArtifactName) -> Completion {
663        let views = self.views_of(artifact);
664        let busy = views
665            .iter()
666            .filter_map(|view| match view {
667                EvalView::InProgress(Activity::Running) => Some(Busy::Running),
668                EvalView::InProgress(Activity::Human(_)) => Some(Busy::Human),
669                EvalView::InProgress(Activity::Queued(_)) => Some(Busy::Queued),
670                _ => None,
671            })
672            .min();
673        if views
674            .iter()
675            .any(|view| matches!(view, EvalView::Failed { .. }))
676        {
677            // ERROR before RED, like the Artifact's own row; blocking follows `blocks`.
678            Completion::Failed {
679                verdict: !views.contains(&EvalView::Failed { verdict: false }),
680            }
681        } else if let Some(busy) = busy {
682            Completion::InProgress(busy)
683        } else if views.iter().any(|view| !matches!(view, EvalView::Done(_))) || !self.met(artifact)
684        {
685            Completion::Waiting {
686                blocked: self.blocks(artifact)
687                    || views
688                        .iter()
689                        .any(|view| matches!(view, EvalView::BlockedBy(_))),
690            }
691        } else {
692            Completion::Complete
693        }
694    }
695
696    /// Group only this Eval's actual gates, never unrelated Evals on the same material.
697    fn gate_blocks(&self, eval: &EvalId, artifact: &ArtifactName) -> bool {
698        self.index
699            .gates
700            .get(eval)
701            .into_iter()
702            .flatten()
703            .filter(|gate| self.index.targets[*gate] == artifact)
704            .any(|&gate| self.status_blocks(eval, gate, self.effective(gate)))
705    }
706
707    /// A RED or blocked gate blocks; an ERROR blocks under `--speculate`, and always when the
708    /// gate is a machine eval of a Human eval's own Artifact.
709    fn status_blocks(&self, eval: &EvalId, gate: &EvalId, status: EvalStatus) -> bool {
710        match status {
711            EvalStatus::Red | EvalStatus::Blocked => true,
712            EvalStatus::Error => {
713                self.run.modes.speculate
714                    || self.index.targets.get(gate) == self.index.targets.get(eval)
715            }
716            _ => false,
717        }
718    }
719
720    /// Graph lights treat an external ERROR as held too, without treating cycle peers
721    /// or unrelated sibling Evals as gates.
722    pub fn held_for_run(&self, eval: &EvalId) -> bool {
723        self.held.get(eval).copied().unwrap_or(false)
724    }
725
726    /// The graph's Blocked readiness downstream: an effective RED or blocked eval.
727    fn blocks(&self, artifact: &ArtifactName) -> bool {
728        self.evals(artifact).iter().any(|eval| {
729            matches!(self.effective(eval), EvalStatus::Red | EvalStatus::Blocked)
730                || (self.run.modes.speculate && self.effective(eval) == EvalStatus::Error)
731        })
732    }
733
734    /// Done evals whose own gates are unmet: the Artifacts holding them back.
735    fn held(&self, artifact: &ArtifactName, blocked: bool) -> Vec<crate::types::ArtifactName> {
736        let mut x: Vec<crate::types::ArtifactName> = Vec::new();
737        for &eval in self.evals(artifact) {
738            let wanted = if blocked {
739                EvalStatus::Blocked
740            } else {
741                EvalStatus::Wait
742            };
743            if matches!(self.view(eval), EvalView::Done(_)) && self.effective(eval) == wanted {
744                for id in self.unmet(eval) {
745                    if (!blocked || self.gate_blocks(eval, &id)) && !x.contains(&id) {
746                        x.push(id);
747                    }
748                }
749            }
750            // A provisional result waits for the sign-offs it relies on.
751            if !blocked && self.effective(eval) == EvalStatus::Provisional {
752                for id in self.pending(eval) {
753                    if !x.contains(&id) {
754                        x.push(id);
755                    }
756                }
757            }
758        }
759        x
760    }
761
762    /// The Artifacts this Artifact's evals wait for, as one X list.
763    pub fn waits_of(&self, artifact: &ArtifactName) -> Vec<crate::types::ArtifactName> {
764        if let Some(x) = self.waits.borrow().get(artifact) {
765            return x.clone();
766        }
767        let mut x = self.held(artifact, false);
768        for view in self.views_of(artifact) {
769            if let EvalView::WaitingOn(waits) | EvalView::NotRun(NotRun::Dependency(waits)) = view {
770                for id in waits.artifacts {
771                    if !x.contains(&id) {
772                        x.push(id);
773                    }
774                }
775            }
776        }
777        x.sort_by_key(|id| (self.completion(id).rank(), self.position(id)));
778        if let Some(id) = self.key(artifact) {
779            self.waits.borrow_mut().insert(id, x.clone());
780        }
781        x
782    }
783
784    /// The Artifacts this Artifact's blocked evals are blocked by.
785    pub fn blockers_of(&self, artifact: &ArtifactName) -> Vec<crate::types::ArtifactName> {
786        let mut x = self.held(artifact, true);
787        for view in self.views_of(artifact) {
788            if let EvalView::BlockedBy(blockers) = view {
789                for id in blockers {
790                    if !x.contains(&id) {
791                        x.push(id);
792                    }
793                }
794            }
795        }
796        x
797    }
798
799    /// When every X is itself waiting, exactly one level of cause: what the first X waits for.
800    fn root(
801        &self,
802        x: &[crate::types::ArtifactName],
803    ) -> Option<(crate::types::ArtifactName, crate::types::ArtifactName)> {
804        if x.iter()
805            .any(|id| !matches!(self.completion(id), Completion::Waiting { blocked: false }))
806        {
807            return None;
808        }
809        let via = x.first()?.clone();
810        let cause = self.waits_of(&via).into_iter().next()?;
811        Some((via, cause))
812    }
813
814    /// Every dependency Artifact of the eval, unmet ones first in X order.
815    pub fn upstream_states(&self, eval: &EvalId) -> Vec<Upstream> {
816        let mut upstream: Vec<_> = self
817            .upstream(eval)
818            .iter()
819            .map(|artifact| Upstream {
820                artifact: (*artifact).clone(),
821                completion: self.completion(artifact),
822            })
823            .collect();
824        upstream.sort_by_key(|upstream| {
825            (
826                upstream.completion.rank(),
827                self.position(&upstream.artifact),
828            )
829        });
830        upstream
831    }
832}