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