Skip to main content

artifactize_core/monitor/model/
graph.rs

1//! A Run as a graph of Artifacts: one node per Artifact of the tree, with the Artifacts it is
2//! made of, one edge per Artifact an Artifact's evals depend on, each with one of six lights
3//! taken from the tree's own states.
4use std::collections::{BTreeMap, BTreeSet};
5
6use super::{
7    NodeId, Target,
8    states::{Activity, Busy, Completion, EvalView, NotRun},
9    tree::{Kind, Node, Tally},
10};
11use crate::types::ArtifactName;
12
13/// How a graph node or edge is lit. Declared in precedence order: an Artifact takes the first
14/// light any of its evals has (RED before ERROR before in progress before blocked before
15/// waiting before GREEN).
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub enum Light {
18    /// An eval's verdict is RED.
19    Red,
20    /// An eval failed operationally: ERROR, not a verdict.
21    Error,
22    /// Running, or waiting for its Human.
23    Active,
24    /// Cannot proceed: an upstream Artifact is RED, ERROR or itself blocked.
25    Blocked,
26    /// Runnable but still waiting: queued, for upstream Artifacts that are not done yet, or
27    /// not run in a finished Run.
28    Waiting,
29    /// Every eval is GREEN (an Artifact without evals is complete too).
30    Green,
31}
32
33impl From<Completion> for Light {
34    /// An upstream Artifact's light where the graph has not lit it (a cycle peer lit later).
35    fn from(completion: Completion) -> Self {
36        match completion {
37            Completion::Complete => Self::Green,
38            Completion::Failed { verdict: true } => Self::Red,
39            Completion::Failed { verdict: false } => Self::Error,
40            Completion::InProgress(Busy::Running | Busy::Human) => Self::Active,
41            Completion::InProgress(Busy::Queued) => Self::Waiting,
42            Completion::Waiting { blocked: true } => Self::Blocked,
43            Completion::Waiting { blocked: false } => Self::Waiting,
44        }
45    }
46}
47
48impl From<&EvalView> for Light {
49    fn from(view: &EvalView) -> Self {
50        match view {
51            EvalView::Done(_) => Self::Green,
52            EvalView::Failed { verdict: true } => Self::Red,
53            EvalView::Failed { verdict: false } => Self::Error,
54            EvalView::InProgress(Activity::Running | Activity::Human(_)) => Self::Active,
55            EvalView::BlockedBy(_) => Self::Blocked,
56            EvalView::InProgress(Activity::Queued(_))
57            | EvalView::WaitingOn(_)
58            | EvalView::NotRun(
59                NotRun::Dependency(_)
60                | NotRun::Budget
61                | NotRun::Stale
62                | NotRun::Unreviewed
63                | NotRun::Absent,
64            ) => Self::Waiting,
65        }
66    }
67}
68
69/// Gate failures come from the Eval-level schedule, never an Artifact-wide inference.
70fn eval_light(eval: &Node, view: &EvalView) -> Light {
71    if eval.held
72        && matches!(
73            view,
74            EvalView::WaitingOn(_) | EvalView::NotRun(NotRun::Dependency(_))
75        )
76    {
77        Light::Blocked
78    } else {
79        Light::from(view)
80    }
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct GraphNode {
85    /// The Artifact row's tree id, `a:<artifact>`.
86    pub id: NodeId,
87    pub name: ArtifactName,
88    pub light: Light,
89    /// How many of its evals are GREEN, of how many; `None` without evals of its own.
90    pub tally: Option<Tally>,
91    /// The Artifacts of the graph it is made of directly, by name.
92    pub parts: Vec<ArtifactName>,
93}
94
95/// `to`'s evals depend on `from`.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct GraphEdge {
98    pub from: ArtifactName,
99    pub to: ArtifactName,
100    /// The input Artifact's current light.
101    pub light: Light,
102}
103
104#[derive(Debug, Clone, Default, PartialEq, Eq)]
105pub struct Graph {
106    /// In the tree's order: upstream first where the graph allows.
107    pub nodes: Vec<GraphNode>,
108    /// By `to` in node order, then `from` in node order.
109    pub edges: Vec<GraphEdge>,
110}
111
112impl Graph {
113    /// Whether `other` has the same Artifacts, parts and edges in the same order, whatever their
114    /// lights: a view can keep where it placed them and only relight them.
115    pub fn same_shape(&self, other: &Self) -> bool {
116        self.nodes.len() == other.nodes.len()
117            && self.edges.len() == other.edges.len()
118            && self
119                .nodes
120                .iter()
121                .zip(&other.nodes)
122                .all(|(one, other)| one.id == other.id && one.parts == other.parts)
123            && self
124                .edges
125                .iter()
126                .zip(&other.edges)
127                .all(|(one, other)| one.from == other.from && one.to == other.to)
128    }
129}
130
131/// The graph of the Artifact rows of a Run's [`tree`](super::tree), lit upstream first in the
132/// tree's order.
133pub fn graph(tree: &[Node]) -> Graph {
134    let artifacts: Vec<(ArtifactName, &Node, Completion)> = tree
135        .iter()
136        .filter_map(|node| match node.kind {
137            Kind::Artifact { completion, .. } => match Target::from(&node.id) {
138                Target::Artifact(name) => Some((name, node, completion)),
139                _ => None,
140            },
141            Kind::Eval(_) => None,
142        })
143        .collect();
144    let mut lights: BTreeMap<ArtifactName, Light> = BTreeMap::new();
145    for (name, node, completion) in &artifacts {
146        // The first light of its evals in precedence order.
147        let evals = node
148            .children
149            .iter()
150            .filter_map(|eval| match &eval.kind {
151                Kind::Eval(view) => Some(eval_light(eval, view)),
152                Kind::Artifact { .. } => None,
153            })
154            .min()
155            .unwrap_or(Light::Green);
156        // Every eval done, yet graph.rs still holds them on their own gates, or a part
157        // is not done: not complete.
158        let light = match evals {
159            Light::Green => Light::from(*completion),
160            light => light,
161        };
162        lights.insert(name.clone(), light);
163    }
164    let position: BTreeMap<&ArtifactName, usize> = artifacts
165        .iter()
166        .enumerate()
167        .map(|(index, (name, _, _))| (name, index))
168        .collect();
169    let mut edges = Vec::new();
170    for (name, node, _) in &artifacts {
171        let upstream: BTreeSet<_> = node
172            .children
173            .iter()
174            .flat_map(|eval| eval.upstream.iter().map(|dependency| &dependency.artifact))
175            .collect();
176        for from in upstream {
177            let Some(&own) = lights.get(from).filter(|_| from != name) else {
178                continue;
179            };
180            edges.push(GraphEdge {
181                from: from.clone(),
182                to: name.clone(),
183                light: own,
184            });
185        }
186    }
187    edges.sort_by_key(|edge| (position[&edge.to], position[&edge.from]));
188    Graph {
189        nodes: artifacts
190            .into_iter()
191            .map(|(name, node, _)| GraphNode {
192                id: node.id.clone(),
193                light: lights[&name],
194                tally: node.tally,
195                parts: node
196                    .parts
197                    .iter()
198                    .filter(|part| lights.contains_key(*part))
199                    .cloned()
200                    .collect(),
201                name,
202            })
203            .collect(),
204        edges,
205    }
206}